How can I give users the ability to write scripts (in a safe way)?

I am currently having a problem when I need to write a function that receives a dictionary where all values ​​are strings or dictionaries and prints a string. The problem is the logic behind creating this output string. I would like to allow the user to write logic.

Now, of course, I can just ask the user to create a valid Python script with a function

def generate_string(input_dict): # your logic return "some_string" 

The problem is that I do not want users to be able to execute arbitrary code. Especially working with the file system (reading / writing / deleting files) should not be possible. There should also be a limitation in computation / memory time.

Is it possible?

I am currently letting them enter a format string. But this seems too limited, as it skips if .

Example

This is just a minimal abstract example:

 def generate_string(input_dict): if input_dict['type'] == 1: return "I want my date in {d:%Y%m%d}".format(d=input_dict['date']) elif input_dict['type'] == 2: return "type is {}".format(input_dict['type']) return "some_string" d = {'type': 1, 'date': datetime.date(2017, 1, 14)} generate_string(d) 
+5
source share
1 answer

Python is not a simple language to block. Since it has a powerful api introspection, it is difficult, if not impossible, to block all system calls.

The only safe approach I can come up with is to run scripts in a separate environment, such as a docker container or vm, designed to run scripts.

There is also pypy that can be run in isolated mode, but it is still a prototype, and it may need a little more work before it can be fully used.

The python wiki directory has a page about the python sandbox https://wiki.python.org/moin/Asking%20for%20Help/How%20can%20I%20run%20an%20untrusted%20Python%20script%20safely%20%28i. e.% 20Sandbox% 29

PyPy sandbox: http://pypy.org/features.html#sandboxing

Also, see How can I write Python in pure Python? which has an amazing answer to the same question.

+2
source

Source: https://habr.com/ru/post/1270680/


All Articles