Is this a safe use of eval?
Peter Otten
__peter__ at web.de
Thu Feb 24 04:01:45 EST 2011
Frank Millman wrote:
> Hi all
>
> I know that the use of 'eval' is discouraged because of the dangers of
> executing untrusted code.
>
> Here is a variation that seems safe to me, but I could be missing
> something.
>
> I have a class, and the class has one or more methods which accept various
> arguments and return a result.
>
> I want to accept a method name and arguments in string form, and 'eval' it
> to get the result.
>
> Assume I have an instance called my_inst, and a method called 'calc_area',
> with arguments w and h.
>
> I then receive my_string = 'calc_area(100, 200)'.
>
>>>> result = eval('my_inst.{0}'.format(my_string))
>
> This will only work if the string contains a valid method name with valid
> arguments.
>
> Can anyone see anything wrong with this?
How do you prevent that a malicious source sends you
my_string = 'calc_area(__import__("os").system("rm important_file") or 100,
200)'
instead?
More information about the Python-list
mailing list