Python Restricted Execution Mode

In prior chapters, I’ve been careful to point out the dangers of running arbitrary Python code that was shipped across the Internet. There is nothing stopping a malicious user, for instance, from sending a string such as os.system('rm *') in a form field where we expect a simple number; running such a code string with the built-in eval function or exec statement may, by default, really work -- it might just delete all the files in the server or client directory where the calling Python script runs!

Moreover, a truly malicious user can use such hooks to view or download password files, and otherwise access, corrupt, or overload resources on your machine. Alas, where there is a hole, there is probably a hacker. As I’ve cautioned, if you are expecting a number in a form, you should use simpler string conversion tools such as int or string.atoi instead of interpreting field contents as Python program syntax with eval.

But what if you really want to run Python code transmitted over the Net? For instance, you may wish to put together a web-based training system that allows users to run code from a browser. It is possible to do this safely, but you need to use Python’s restricted execution mode tools when you ask Python to run the code. Python’s restricted execution mode support is provided in two standard library modules, rexec and bastion. rexec is the primary interface to restricted execution, while bastion can be used to restrict and monitor access ...

Get Programming Python, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.