Is this the "right" way to do rexec?

Paul Miller pwmiller1 at adelphia.net
Tue Jun 29 22:33:08 EDT 2004


I came across this recipe on the Python Cookbook site:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286134

As written, it allows evaluation of either constants or more general
expressions involving constants and operators (but not function
calls).

I haven't thoroughly tested it for security, but it at least passes
the smoke test.  Assuming that this can either be demonstrated to be
as secure as the python interpreter itself (i.e. we can't blame the
recipe for some hypothetical exploit that targets the Python
interpreter), or that testing can demonstrate a reasonable probability
that it's secure, would this be a good basis for implementing a
restricted execution environment?

Pros: It analyzes the Python bytecode itself looking for fishy stuff. 
This means it should be harder to trick using, for example:

del __builtins__;import os

... which would compromise the old rexec.

Cons: It's a bytecode hack.  Python bytecodes are not guaranteed to be
portable across versions of CPython, and it certainly wouldn't work on
Jython (although a similar module that analyzes the Java bytecodes
might work).

The recipe's author gives a hint on how to allow certain types of
imports by restricting what can be referenced via the LOAD_NAME
opcode.  For example, by scanning LOAD_NAME, you could allow importing
say, the math and cmath modules, but not os or sys.  Or, by going a
step further and analyzing LOAD_ATTR opcodes, you could allow
selective usage of certain symbols within a module or attributes of a
class.  You could allow say, read access but not write access to an
object's __class__ and __dict__.  And, of course, you'd have to do
similar things with assignments.

Could something like this go into the standard CPython library if it
were proved secure enough?



More information about the Python-list mailing list