如何防止通过函数调用从exec,eval访问内置函数

时间:2017-01-20 07:55:31

标签: python

我有以下代码

+--------------+---------+------+-----+---------+-------+
| Field        | Type    | Null | Key | Default | Extra |
+--------------+---------+------+-----+---------+-------+
| productCode  | int(11) | YES  |     | NULL    |       |
| sales        | int(11) | YES  |     | NULL    |       |
| year         | int(11) | YES  |     | NULL    |       |
| month        | int(11) | YES  |     | NULL    |       |
| day          | int(11) | YES  |     | NULL    |       |
| aFewWeeks    | int(11) | YES  |     | NULL    |       |
| dayOfTheWeek | int(11) | YES  |     | NULL    |       |
+--------------+---------+------+-----+---------+-------+

当ai运行时,我仍然得到如下结果,但我期望在函数 foo 中,我无法像这些内置函数一样访问全局,本地或abs,任何一个人可以帮忙解释一下,谢谢。

+------------------+---------+------+-----+---------+-------+
| Field            | Type    | Null | Key | Default | Extra |
+------------------+---------+------+-----+---------+-------+
| productCode      | int(11) | YES  |     | NULL    |       |
| optimumInventory | int(11) | YES  |     | NULL    |       |
| productDate      | date    | YES  |     | NULL    |       |
+------------------+---------+------+-----+---------+-------+

1 个答案:

答案 0 :(得分:1)

因为foo标识符指向在受保护的bloc之外定义的函数。因此,它使用定义它的模块的全局字典,而不是传递给受限环境的模块。

要实际阻止函数内置访问,必须在exec bloc中定义函数:

source = """def foo(x):
    print "x is {}, a is {}".format(x,a)
    print "locals:" + '*' * 10
    print locals()
    print "globals:" + '*' * 10
    print globals()
    print abs(1)
foo(x)
"""

但是你遇到了另一个问题:当你删除了所有内置文件时,locals()没有globals()被定义,exec(source,{'__builtins__': None}, {'x': 1})将失败并且 NameError:全局名称&#39 ;当地人'未定义

所以你必须在__builtins__键下放置你想要保留的内置函数:

exec(source, {'a': 1, '__builtins__': {'locals': locals,
                       'globals': globals}}, {'x': 1})

然后你按预期得到:

x is 1, a is 1
locals:**********
{'x': 1}
globals:**********
{'a': 1, '__builtins__': {'globals': <built-in function globals>, 'locals': <built-in function locals>}}

Traceback (most recent call last):
  File "<pyshell#46>", line 2, in <module>
    'globals': globals}}, {'x': 1})
  File "<string>", line 8, in <module>
  File "<string>", line 7, in foo
NameError: global name 'abs' is not defined