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?

darkhorse
  • 8,192
  • 21
  • 72
  • 148
  • 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? – roganjosh Nov 22 '18 at 09:03
  • 1
    Is it really a requirement that the _whole_ function is defined by the user? – roganjosh Nov 22 '18 at 09:05
  • Yeah, the first "solution" was always out of the question. Also what do you mean by sandpit? – darkhorse Nov 22 '18 at 09: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 – roganjosh Nov 22 '18 at 09: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? – darkhorse Nov 22 '18 at 09:08
  • Yes, because if they are only inserting values to a pre-made function, it's much easier to control that – roganjosh Nov 22 '18 at 09:09
  • Huh, "sandbox" not "sandpit". Too early in the morning for me apparently. But that's the kind of thing you want to be searching. – roganjosh Nov 22 '18 at 09:10

0 Answers0