eval(source, {'builtins': {}}) archived as Faq
Duncan Booth
duncan.booth at invalid.invalid
Fri Sep 29 03:34:17 EDT 2006
Erik Max Francis <max at alcyone.com> wrote:
> This is an _extremely_ bad idea. _Never_ use eval in a case where you
> are trying to validate input.
>
> >>> def e(source): return eval(source, {'builtins': {}})
> ...
> >>> e('__import__("sys").exit()')
>
> Oops, the interpreter exited.
I'm slightly surprised that nobody has yet pointed out that the OP failed
at the very first hurdle here. If you are going to do this dangerous trick
then 'builtins' should be spelled '__builtins__':
>>> def e(source): return eval(source, {'__builtins__': {}})
>>> e('__import__("sys").exit()')
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
e('__import__("sys").exit()')
File "<pyshell#8>", line 1, in e
def e(source): return eval(source, {'__builtins__': {}})
File "<string>", line 1, in <module>
NameError: name '__import__' is not defined
>>>
but it is still not going to stop nasty things happening, it just makes
them a little more complex:
>>> e("[ c for c in 1 .__class__.__bases__[0].__subclasses__() if
c.__name__=='Quitter'][0]('bang')()")
More information about the Python-list
mailing list