Simple Python Sandbox

Roland Koebler r.koebler at
Sun Aug 15 01:24:00 CEST 2010


> I know all this -- but its not relevant really, I think. I'm not trying
> to create a safe yet relatively complete or functional Python. All those
> efforts to sandbox Python fail because of the incredible dynamic nature
> of the language has lots of enticing little holes in it. But I'm not
> interested in a full or even vaguely full subset of Python, and I'm not
> requiring that this security be done on the code-level.
I had the same problem, and so I created a "pseudo-sandbox" for embedding
Python in templates. This "pseudo-sandbox" creates a restricted Python
environment, where only whitelisted functions/classes are allowed.
Additionally, it prevents things like '0 .__class__'.

You can find some documentation at,
and the pseudo-sandbox itself in my template-engine, class
"EvalPseudoSandbox" on the website above.
(Please write me if you have any comments.)

But note that this is not a real sandbox! As soon as you allow *any*
unsafe function (e.g. open, import, eval, getattr etc.), you can easily
break out.
Also, don't directly pass complete modules to the pseudo-sandbox, since
they may contain unsafe functions/classes/etc.

And be warned: There *may* also be ways to break out of the pseudo-sandbox
even without passing unsafe functions to it -- although I don't know any.
If you know or find such a way: Please tell me!

You could also take a look at Jinja (which is also a template-engine),
and which claims to include a sandbox. But the Jinja-sandbox seems to
be much more complicated than my pseudo-sandbox, and I haven't analyzed
it and don't know how it works.

> For example, when you go to save your bit of code, it will go in and if
> it finds __ anywhere in the text it just replaces it with xx. And, since
> getattr is not available, '_' + '_' won't get you anywhere.
I don't think that searching the text is the right way; in my
pseudo-sandbox, I compile the code and search co_names for such
names instead.

> I just need a certain limited context where someone can be handed
> certain Python objects and manipulate them. I'd like people to be able
> to use some fundamental Python power -- the rich, beautiful data types
> for example (notably in this case, strings), list comprehensions and
> stuff, to do what they need to do. Python's very easy, I'd like them to
> be able to use that easy.
I was in the exact same position ;).
(Although I don't have fully untrusted/bad users, and so my pseudo-sandbox
is sufficient for my cases, even though I haven't proved that it really is


More information about the Python-list mailing list