Skip to content
Advertisement

Compiling and executing simple user defined code in Python

I want to allow my users a way to run very simple Python functions for a project. Of course, eval() comes to mind, but it is a huge risk. After thinking about it for a time, I realized that most of the functions that a user might need are very rudimentary, similar to the most common excel functions. So I was thinking something along the lines of maintaining a dictionary where the keys are the functions names, and the user can only pick functions which are defined (by me) within that dictionary. So for example:

JavaScript

Now, if a user defines a line as add(4, 5), the result is the expected 9, however, if they define something like foo(4), since the key does not exist in my dictionary, an error would be raised. My question is this: how safe is this? Are there any potential vulnerabilities that I am overlooking here?

Advertisement

Answer

You can de-fang eval somewhat by using appropriate globals and locals arguments. For example, this is wat I used in a kind of calculator.

JavaScript

But you schould probably screen expressions beforehand as well. Reject those that contain import or eval or exec:

JavaScript

The module linked above also contains the use of ast to convert Python calculations into LaTeX math expressions. You could also use ast to build a custom expression evaluator.

Otherwise, here is a small stack-based postfix expression evaluator that I made.

One difference is that I added the number of arguments that each operator needs to the _ops values, so that I know how many operands to take from the stack.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement