Secure Python

Stephan Kuhagen nospam at domain.tld
Thu Nov 16 10:54:36 CET 2006

Fredrik Tolf wrote:

> If this doesn't work, might there be some other way to run untrusted
> code that I haven't thought of (apart from using O/S-specific stuff like
> SECCOMD, of course).

There was a module called rexec which tries to give you a restricted
environment for executing code. But it seems, that it is not maintained
anymore, because there were too much problems with it. It seems, that it is
very complicated to get a restricted execution environment without losing
too much of Pythons functionality. 

One question is, what you want to achieve. As another posting in this thread
mentioned, you can't get around of denial of service attacks, even in
restricted or trusted environments. So I assume, that what you want is
something like a sandbox, where specific file actions (deleting files,
access to specific part of the FS at all) and some other things can be
restricted or forbidden. I think, this should be possible, even for some
DOS-Attacks (e.g. restricting the amount of memory that can be used by the
script, or the max stack size, depth of recursion limits etc.), but it is a
hard job to find all places, where code can break out of your sandbox. For
a full load of bad examples, simply have a look at JavaScript... 

For a IMHO really good implementation of the sandbox idea, have a look at
the "safe interp" in Tcl. A short description (and by no mean complete) of
the safe interp is to run a second and completely independent interpreter
with all possibly dangerous commands completely removed and a
one-way-channel to inject commands and scripts into its evaluation loop
from the trusted interpreter. Depending on how much faith you have into the
untrusted script, you can selectively allow additional commands in the safe
interp or map common commands to other restricted or monitored versions of
them, which you implemented yourself inside your trusted environment. I do
not know, how complex it would be to do this in Python (since Tcl may look
a little old fashioned to some people but has some unique features that
helps especially with this kind of problem, such as having no keywords,
which makes it possible to change the semantics of even the most basic
constructs in the language from the scripting level), but I think it would
be a really useful feature for Python to have a sandbox mechanism to run
untrusted code.


More information about the Python-list mailing list