healeycodes / untrusted-python

📦 Run untrusted python code on the server.
https://untrusted-python.vercel.app
35 stars 2 forks source link

Couldn't import some standard Python libs because of the permission issue #1

Open mozedz opened 8 months ago

mozedz commented 8 months ago

Hi @healeycodes , firstly I'd like to say thanks for the great idea and making it work. But it there seems to be an issue what we can't import several standard libraries. For example:

└─> curl -X POST https://untrusted-python.fly.dev/api/exec \
-H "Content-Type: application/json" \
-d '{"code":"import datetime"}'

Traceback (most recent call last):
  File "/app/./sandbox.py", line 41, in <module>
  File "<string>", line 1, in <module>
ModuleNotFoundError: No module named 'datetime'

After checking around I can see the issue is because some permissions are missing. After disabled the drop_perms() function, it works well. Like this:

if __name__ == "__main__":
    code = sys.argv[1]
    set_mem_limit()
    # drop_perms()
    exec(code)

Then it works:

└─> curl -X POST http://localhost:3000/api/exec \
-H "Content-Type: application/json" \
-d '{"code":"import datetime\nprint(1)"}'
1

So ideally we should improve this function to let all default Python's functionality work well.

briandoesdev commented 8 months ago

From a cursory look over his blog, this seems to be done on purpose: https://healeycodes.com/running-untrusted-python-code

healeycodes commented 8 months ago

@briandoesdev is right! The sandbox is very strict on purpose. Allowing more functionality without regressing on security is non-trivial (as I understand it).

guangrei commented 3 months ago

@briandoesdev is right! The sandbox is very strict on purpose. Allowing more functionality without regressing on security is non-trivial (as I understand it).

Is datetime module harmful?

healeycodes commented 3 months ago

@briandoesdev is right! The sandbox is very strict on purpose. Allowing more functionality without regressing on security is non-trivial (as I understand it).

Is datetime module harmful?

It depends! Per https://python-security.readthedocs.io/security.html you're not supposed to build a sandbox inside CPython. So it's all harmful really.

Ultimately, importing/using datetime requires system calls. This demo shows how to restrict all system calls.