Python: make eval safe [duplicate]
Solution 1:
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.
Solution 2:
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
Solution 3:
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.