Safe Python Execution

Steven Bethard steven.bethard at gmail.com
Wed Feb 15 23:14:56 EST 2006


Graham wrote:
> The way i'm controlling functionality is with some games and exec, so
> if 'code' was the text code you wanted to execute i run:
> 
> exec code in {'__builtins__':None"}
> 
> obviously this doesn't give you much to play with, but it does remove
> file access and importing as far as i can tell. Can anyone think of a
> hack around this? I assume if it was this easy it would be a module
> already but i figured i would ask.

Search the newsgroups, but one of the major problems is that all 
subclasses of object are available through object.__subclasses__():

 >>> (1).__class__.__bases__[0].__subclasses__()
[<type 'type'>, <type 'weakref'>, <type 'int'>, <type 'basestring'>,
...
<type 'dictproxy'>, <type 'code'>, <type 'frame'>]

Note that this also includes any classes you define that are subclasses 
of object:

 >>> class C(object):
...     dont_change_this = 42
...
 >>> exec '''\
... subclasses = (1).__class__.__bases__[0].__subclasses__()
... C, = [cls for cls in subclasses if cls.__name__ == 'C']
... C.dont_change_this = 'bwahahaha'
... ''' in {'__builtins__':None}
 >>> C.dont_change_this
'bwahahaha'

So if you're really concerned about your objects being manipulated with 
users, the ``exec code in {'__builtins__':None}`` technique is not going 
to help you out.  However, the code will be executed in restricted mode, 
so things like the file constructor won't work.  Not sure if that's 
enough for you...

STeVe



More information about the Python-list mailing list