Use eval() safely?

Dieter Maurer dieter at handshake.de
Wed Feb 24 10:11:25 CET 2010


Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> writes on 22 Feb 2010 06:07:05 GMT:
> ...
> It's *especially* not safe if you put nothing in the globals dict, 
> because Python kindly rectifies that by putting the builtins into it:
> 
> >>> eval("__builtins__.keys()", {}, {})
> ['IndexError', 'all', 'help', 'vars', ... 'OverflowError']
> 
> 
> >>> eval("globals()", {}, {})
> {'__builtins__': {...}}
> >>>
> >>> eval("globals()", {'__builtins__': None}, {})
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<string>", line 1, in <module>
> NameError: name 'globals' is not defined
> 
> So {'__builtins__': None} is safer than {}. Still not safe, exactly, but 
> safer. Or at least you make the Black Hats work harder before they own 
> your server :)

Using functionality introduced with the class/type homogenization,
it is quite easy to get access to the "file" type (even when "__builtins__"
is disabled). Having "file", arbitrary files can be read, written, destroyed...


Dieter



More information about the Python-list mailing list