6

Implementing a 'sandbox' environment in Python used to be done with the rexec module (http://docs.python.org/library/rexec.html). Unfortunately, it has been deprecated/removed due to some security vulnerabilities. Is there an alternative?

My goal is to have Python code execute semi-trusted Python scripts. In a perfect world, calls to any functions outside of a pre-defined set would raise exceptions. From what I've read about rexec's deprecation, this may not be possible. So I'll settle for as much as I can get. I can spawn a separate process to run the scripts, which helps a lot. But they could still abuse I/O or processor/memory resources.

DNS
  • 37,249
  • 18
  • 95
  • 132

3 Answers3

4

You might want to provide your own __import__ to prevent inclusion of any modules you deem "abuse I/O or processor/memory resources."

You might want to start with pypy and create your own interpreter with limitations and constraints on resource use.

S.Lott
  • 384,516
  • 81
  • 508
  • 779
  • Providing your own __import__ is a great idea, and is far better than any other solution ever done for sandboxing! – kylebrooks Feb 09 '09 at 00:51
  • @kylebrooks: "far better than any other solution" is a bit string. It lets you whitelist (and blacklist) modules, but it doesn't prevent or even detect a process that attempts to "abuse I/O or processor/memory resources." – S.Lott Feb 10 '09 at 02:59
  • You can only whitelist or blacklist those modules if you don't have access to objects that hold references to them (or a c-extension that bypasses the python-level modules entirely). The lack of encapsulation in python seems to be the biggest security challenge. – DylanYoung Dec 08 '17 at 18:26
2

in cpython "sandboxing" for security reasons is a: "don't do that at your company kids"-thing.

try :

  • jython with java "sandboxing"
  • pypy -> see Answer S.Lott
  • maybe ironpython has a solution ?

see Warning:

Warning

In Python 2.3 these modules have been disabled due to various known and not readily fixable security holes. The modules are still documented here to help in reading old code that uses the rexec and Bastion modules.

Blauohr
  • 5,985
  • 2
  • 25
  • 31
  • It seems all those security holes requires creating thread or process. So rexec is safe if pid creation is ulimit. – user2284570 Sep 16 '16 at 17:03
1

Your best bet for security in cPython is using OS-level sandboxing mechanisms and running untrusted code in a separate process constrained by the OS.

This is equivalent to using 'jython with java "sandboxing"', as per the answer above, but probably a little more difficult to configure.

DylanYoung
  • 2,423
  • 27
  • 30