Use eval() safely?

Gregory Ewing greg.ewing at canterbury.ac.nz
Mon Feb 22 06:45:40 CET 2010


W. Martin Borgert wrote:

> def myeval(untrustedinput):
>     return eval(untrustedinput, {"__builtins__": None},
>                 { "abs": abs, "sin": math.sin })
> 
> Is it possible to define functions or import modules from the
> untrusted input string?

This is NOT safe as it stands. It still isn't safe even if
you put nothing in the globals dict at all.

A couple of ways someone can do nasty things to you:

# Wipe out any file writable by the calling process
eval("[c for c in (0).__class__.__bases__[0].__subclasses__() if c.__name__ == 
'file'][0]('/my/precious/file', 'w')")

# Use up large amounts of memory and CPU time
eval("100000**100000")

-- 
Greg



More information about the Python-list mailing list