Is this a safe use of eval?

Christian Heimes lists at cheimes.de
Thu Feb 24 06:32:44 EST 2011


Am 24.02.2011 10:01, schrieb Peter Otten:
> How do you prevent that a malicious source sends you
> 
> my_string = 'calc_area(__import__("os").system("rm important_file") or 100, 
> 200)'
> 
> instead?

By using something like
http://code.activestate.com/recipes/496746-restricted-safe-eval/ . With
a combination of AST inspection and restricted builtins you can create a
restricted eval function that e.g. doesn't allow function calls, raising
or excepting exceptions and prevents access to members with a leading _.

Christian




More information about the Python-list mailing list