JesseTG
JesseTG

Reputation: 2123

How to restrict the expressions eval() or exec() can run?

So I'm trying to make a Python app that's sort of like a set theory calculator (i.e. the union of two sets, intersection, complement, etc.). I want to have a text field that, when executed, is evaluated like Python expressions, with braces and all turned into sets. When the new sets are computed, the result will be printed on-screen. However, I want to make sure the user doesn't enter any Python commands that may screw the whole app (or worse; system) up, whether intentionally or not. He should only be able to enter the following;

To give you an idea, this is what input and output should look like (this app will be with a GUI, I just use terminal style for convenience):

>>> {1, 2, a} - {a}
{1, 2}

Any tips? Or should I just implement a mini-language which I turn into Python commands?

Upvotes: 0

Views: 140

Answers (2)

damzam
damzam

Reputation: 1961

I'd go with the mini language that you can translate into python commands.

If you want to represent sets with {} notation, you would just make sure that every non-numeric value contained within the brackets is treated like a string (to avoid security risks). Nested brackets would be instantiated as frozen sets as sets are unhashable and cannot be nested.

Operands between parsed sets should probably be limited to:

s <= t  test whether every element in s is in t
s >= t  test whether every element in t is in s
s | t   new set with elements from both s and t
s & t   new set with elements common to s and t
s - t   new set with elements in s but not in t
s ^ t   new set with elements in either s or t but not both

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799200

Compile the expression first, then walk the resultant AST to verify that it only contains operations you explicitly want to allow. Then evaluate it.

Upvotes: 1

Related Questions