Python: make eval safe [duplicate] Python: make eval safe [duplicate] python python

Python: make eval safe [duplicate]


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.


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


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.