2

This is a rather weird use-case, however, a project we are developing needs a way for it to store user-defined functions and run them within views. The function code will be stored in a TextField in a model.

The functions themselves would be ideally very simple, mostly involving arithmetic operations, if-else blocks, and loops. The functions can also be in any language, as long as Python is able to run them somehow.

The obvious problem is the possible security issues, since it is always best to assume the code will come from untrusted sources. Anyway, we have thought about these possible solutions:

  1. Storing Python functions as strings, and running them using eval().
  2. Storing Javascript functions as strings, and running them using Js2Py.
  3. Creating a simple programming language, a subset of Python, which removes all the methods and operators which could possible cause security issues. The function would therefore be written in this new language.

What is my best option? Obviously, the first two options are very insecure, while the third one is hard to implement. Is there a better way to do this?

7
  • I can only comment on (1); awful idea. I don't think you can properly make this safe. Are you trying to host a sandpit or something? Commented Nov 22, 2018 at 9:03
  • 1
    Is it really a requirement that the whole function is defined by the user? Commented Nov 22, 2018 at 9:05
  • Yeah, the first "solution" was always out of the question. Also what do you mean by sandpit? Commented Nov 22, 2018 at 9:05
  • A sandpit in terms of allowing users to execute arbitrary code in the browser. Similar to what you get in tutorials or coding challenges Commented Nov 22, 2018 at 9:06
  • Yeah kinda like that. The function will take in data they have defined earlier and run itself with the data as the parameters basically. As for the whole function thing, well I mean does it really make a difference if the user defines the whole function or just a small code block? Commented Nov 22, 2018 at 9:08

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.