Python: make eval safe

Question:

I want an easy way to do a “calculator API” in Python.

Right now I don’t care much about the exact set of features the calculator is going to support.

I want it to receive a string, say "1+1" and return a string with the result, in our case "2".

Is there a way to make eval safe for such a thing?

For a start I would do

env = {}
env["locals"]   = None
env["globals"]  = None
env["__name__"] = None
env["__file__"] = None
env["__builtins__"] = None

eval(users_str, env)

so that the caller cannot mess with my local variables (or see them).

But I am sure I am overseeing a lot here.

Are eval‘s security issues fixable or are there just too many tiny details to get it working right?

Asked By: flybywire

||

Answers:

The security issues are not (even close to) fixable.

I would use pyparsing to parse the expression into a list of tokens (this should not be too difficult, because the grammar is straightforward) and then handle the tokens individually.

You could also use the ast module to build a Python AST (since you are using valid Python syntax), but this may be open to subtle security holes.

Answered By: Katriel

are eval’s security issues fixable or
are there just too many tiny details
to get it working right?

Definitely the latter — a clever hacker will always manage to find a way around your precautions.

If you’re satisfied with plain expressions using elementary-type literals only, use ast.literal_eval — that’s what it’s for! For anything fancier, I recommend a parsing package, such as ply if you’re familiar and comfortable with the classic lexx/yacc approach, or pyparsing for a possibly more Pythonic approach.

Answered By: Alex Martelli

It is possible to get access to any class that has been defined in the process, and then you can instantiate it and invoke methods on it. It is possible to segfault the CPython interpreter, or make it quit. See this: Eval really is dangerous

Answered By: Ned Batchelder

Perl has a Safe eval module http://perldoc.perl.org/Safe.html

Googling “Python equivalent of Perl Safe” finds
http://docs.python.org/2/library/rexec.html

but this Python “restricted exec” is deprecated.

overall, “eval” security, in any language, is a big issue. SQL injection attacks are just an example of such a security hole. Perl Safe has had security bugs over the years – most recent one I remember, it was safe, except for destructors on objects returned from the safe eval.

It’s the sort of thing that i might use for my own tools, but not web exposed.

However, I hope that someday fully secure evals will be available in many / any languages.

Answered By: Krazy Glew
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.