You are not logged in.

#1 2005-07-16 12:30:24

cmp
Member
Registered: 2005-01-03
Posts: 350

Python: A Sandbox Enviroment

Hi, everybody.
I tried to create a simple sandbox enviroment for my game console. I know there is rexec, but I didn't know about it, when I started my own secure execution enviroment, and for some strange reason it complains about my python version (It says it would be unsecure to use it in python 2.2 and 2.3, but my version 2.4.1).
It's not a full featured python enviroment, there is no module support and no import support, you can just use include(name) to use seperate source files and there is only one global scope (sandbox), but that functionality is enough for my needs.
But I'm not that experienced with python, so I would be happy, If you would try to break out of my sandbox and test it for security.

The usage is quite easy:
import sandbox
sandbox.init()
sandbox.execute("any valid python statement, except import wink")

The source:
sandbox.py

# set up the sandbox
def init():
    global init, sandtools
    import sandtools
    
    sandtools.makeSecure(globals())    
    
    # import sandtools
    for i in sandtools.__all__:
        sandtools.imp(i, sandtools, globals())
    
    del init
    del sandtools

def execute(str):
    setOut()
    try:
        exec str in globals()
    except Exception, inst:
        print inst
    except:
        pass
    unsetOut()

sandtools.py

import types
import sys 
import __builtin__
import sandbox

__all__ = [ "include", "setOut", "unsetOut"]
stdout     = None
sysout    = sys.stdout

def setOut():
    global stdout
    
    if stdout:
        sys.stdout = stdout

def unsetOut():
    global sysout

    sys.stdout = sysout

def imp(name, src, dst):
    fun = getattr(src, name)
    dst[name] = fun

def makeSecure(dict):
    
    to_import = [ "abs", "basestring", "bool", "callable",
    "chr", "classmethod", "cmp", "complex", "delattr", 
    "dict", "dir", "divmod", "enumerate", "filter", "float",
    "frozenset", "getattr", "globals", "hasattr", "hash",
    "help", "hex", "id", "input", "int", "isinstance", 
    "issubclass", "iter", "len", "list", "locals", "long",
    "map", "max", "min", "object", "oct", "ord", "pow",
    "property", "range", "reduce", "repr", "reversed",
    "round", "set", "setattr", "slice", "sorted", 
    "staticmethod", "str", "sum", "super", "tuple", "type",
    "unichr", "unicode", "vars", "xrange", "zip",
    # non essitial builtin methods
    "apply", "buffer", "coerce", "intern",
    # some other stuff
    "Exception"]
    
    # import all harmless methods
    for i in to_import:
        imp(i, __builtin__, dict)
    
    
    del dict["__builtins__"]
    
    return dict
    

def include(mod, globals = None, locals = None, fromlist = []):
    # just a test
    name = mod + ".py"
    file = open(name, "r")
    sandbox.execute(file)

Offline

Board footer

Powered by FluxBB