6

Possible Duplicate:
Python, safe, sandbox

I'm building a corporate web system in Python which allows scripts to be uploaded and run serverside. Given I'm already developing in Python and its such a nice simple language, it seems like a good language to write the scripts in. However, there is a security hazard there, I want to block all function calls except a limited subset. Is there a mechanism I can use to do this, or some other technique? Do I need to use something else, Lua perhaps? I'm developing in Pyramid/Pylons.

Community
  • 1
  • 1
Liam M
  • 5,306
  • 4
  • 39
  • 55
  • 2
    also: http://stackoverflow.com/questions/3068139/how-can-i-sandbox-python-in-pure-python – FogleBird Jul 06 '12 at 02:34
  • 2
    also: http://stackoverflow.com/questions/3910223/sandbox-to-execute-possibly-unfriendly-python-code – FogleBird Jul 06 '12 at 02:34
  • 2
    also: http://stackoverflow.com/questions/1019707/sandboxing-in-linux – FogleBird Jul 06 '12 at 02:35
  • 3
    I feel your pain. Proper sandboxing that isn't a pain to setup is a gap that needs to be filled. – FogleBird Jul 06 '12 at 02:36
  • @FogleBird Thanks for all the suggestions, I'll have a look at those and post back with my thoughts. It seems like the sort of niche Python should fill, I agree with you. – Liam M Jul 06 '12 at 03:02
  • @FogleBird the answer is in there: I'd like to leave this question unanswered, experiment with python ast and then come back with an answer of my own. [link](http://stackoverflow.com/questions/3068139/how-can-i-sandbox-python-in-pure-python) is close, but I think a much more complete answer can be given. – Liam M Jul 06 '12 at 03:18
  • I'm not sure why nobody mentions this, but Zope 2 has a thing called Python Script, which is exactly that - restricted Python executed in a sandbox, without any access to filesystem, with access to other Zope objects controlled by Zope security machinery, with imports limited to a safe subset. Zope in general is pretty safe, so I would imagine there are no known or obvious ways to break out of the sandbox. I'm not sure how exactly Python Scripts are implemented, but the feature was around since like year 2000. – Sergey Jul 06 '12 at 09:06
  • 1
    And here's the magic behind PythonScripts, with detailed documentation: http://pypi.python.org/pypi/RestrictedPython/ - it even looks like it doesn't have any dependencies on Zope, so can be used standalone. – Sergey Jul 06 '12 at 09:19

1 Answers1

0

This is a terrible idea, but just to let you know about the option:

You could sanitize a string that contains the Python code (and by sanitize I mean you need to do like a few hundred malicious unit tests and heavily test that the sanitation is adequate) with RegEx to only match the function calls you want and then call eval() on the string.

Alex W
  • 37,233
  • 13
  • 109
  • 109