Is this a safe use of eval?
Frank Millman
frank at chagford.com
Thu Feb 24 08:24:51 EST 2011
"Christian Heimes" <lists at cheimes.de> wrote
> 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 _.
>
Thanks, Christian. I had a look at that recipe, but I must say that Paul's
suggestion is much simpler -
from ast import literal_eval
method_name = 'calc_area'
args = literal_eval('(100,200)')
result = getattr(my_inst, method_name)(*args)
In my case the arguments are all strings or integers, so it looks as if this
approach should be safe. Do you see any problem with it?
Frank
More information about the Python-list
mailing list