AK_is_curious
AK_is_curious

Reputation: 239

python eval() to only accept conditions

I have text input in this form from a textbox:

gzip == True

gzip == False and count >= 100

gzip == True or msg == "Hello!"

I use eval() to get the result of the condition. However there are the obvious "security concerns" with eval like code injection.

Is there any way I can limit it to conditions? I dont need it for anything else.

Upvotes: 0

Views: 766

Answers (3)

jaywhy13
jaywhy13

Reputation: 1116

pyparsing is a great option. If you don't want to define a grammar and all that jazz though, another option you could try is this:

safe_variables = {} # use this to define safe functions and variables
code = "...."
eval(code, {"__builtins__": None}, safe_variables)

By passing a dictionary with the builtins explicitly set None, you are ensuring that the code has NO access to the builtin functions of Python e.g. (abs, open, filter, etc...). If it's not explicitly set to None then the current globals will be copied.

That locks down the code alot. Next, explicitly list the variables and functions that you want the code to have access to in the safe_variables dictionary.

Upvotes: 1

Nurjan
Nurjan

Reputation: 6073

As @scotty3785 mentioned you need to create a separate function for checking the input for certain operations you need. Then you pass the input to ast.literal_eval(node_or_string). I would avoid using eval() at all.

Upvotes: 2

MishaVacic
MishaVacic

Reputation: 1887

Yes,with eval there are security issues.I think that you should use pyparsing to parse the expression into tokens list and after that deal with tokens.You can find more http://pyparsing.wikispaces.com/

Upvotes: 1

Related Questions