[Tutor] Evaluating a string expression

Modulok modulok at gmail.com
Fri Nov 6 21:35:17 CET 2009


[snip]
>>>> I would like to know how would I evaluate a string expression in python.
>>>> For example, if i say:
>>>>>>>
>>>>>>> a = "3*2"
>>>>
>>>> I want to do something to evaluate the variable 'a' to give me 6. How
>>>> can I do this?
>>>
>>> The eval() function can do this:
>>>
>>>  eval("3*2")
>>>
>>> WARNING: Long winded security rant below...
...

>> And these are valid warnings which begs the question what are the
>> alternatives?
>
> Python 2.6 includes the ast.literal_eval() function which will
> evaluate literal expressions:
> http://docs.python.org/library/ast.html#ast.literal_eval
>
> This is a bit too limited for the OP however.
>
> The Python Cookbook has several examples of safe eval functions that
> work by parsing an expression and evaluating the parse tree, only
> allowing specific types of nodes. For example this one which does
> allow arithmetic expressions:
> http://code.activestate.com/recipes/286134/
>
> Kent
[/snip]

>From the article: http://code.activestate.com/recipes/286134/

"Also, it should be noted that a malicious user can still for example
cause the expression to take vast amounts of memory by inputting
something like '100100100100100**100...'. There is no way to really
prevent this from within Python, without making the expression
limitations too restrictive."

Just thinking aloud here for a moment: I wonder if it would be
reasonably possible to put the eval() step into a sub-process, with
the dispatcher process timing execution and killing the subprocess if
it consumes too much time/memory. ...of course the problem there, is
the sub-process runs at the same permission level, so if it is
hijacked it could potentially kill its parent first :S I think the
root-owned dispatcher, spawning lesser privileged processes, is the
only 'secure' way in regards to protecting the system from a denial of
service attack through an infinite variety of simply expressed, but
computationally intractable, expressions. The war between security and
ease of use (implementation in this case) wages onward.

-Modulok-


More information about the Tutor mailing list