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?
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.
eval() will allow malicious data to compromise your entire system, kill your cat, eat your dog and make love to your wife.
eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension.
eval() is considered insecure because it allows you (or your users) to dynamically execute arbitrary Python code. This is considered bad programming practice because the code that you're reading (or writing) is not the code that you'll execute.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With