Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: make eval safe [duplicate]

Tags:

python

eval

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?

like image 817
flybywire Avatar asked Aug 18 '10 14:08

flybywire


People also ask

How do I make Python eval safe?

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.

Why is eval not safe Python?

eval() will allow malicious data to compromise your entire system, kill your cat, eat your dog and make love to your wife.

Is it bad to use eval?

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.

Is eval bad practice Python?

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.


2 Answers

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.

like image 171
Alex Martelli Avatar answered Oct 03 '22 06:10

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

like image 24
Ned Batchelder Avatar answered Oct 03 '22 08:10

Ned Batchelder