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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access