Paste number 43630: safe.py

Paste number 43630: safe.py
Pasted by: tav
When:4 years, 10 months ago
Share:Tweet this! | http://paste.lisp.org/+XNY
Channel:#esp
Paste contents:
Raw Source | XML | Display As
# do from safe import *
# then try to break it...

import __builtin__ 

from types import FunctionType

__all__ = ['FileReader']

# capability.py functions

def Namespace(*args, **kwargs):

    for arg in args:
        kwargs[arg.__name__] = arg

    def get(key):
        return kwargs.get(key)

    return get

class Getter(object):

    def __init__(self, getter):
        self.getter = getter

    def __repr__(self):
        return self.getter('__repr__') or object.__repr__(self)

    def __getattr__(self, attr):
        return self.getter(attr)

# io.py module

real_open = __builtin__.open

def FileReader(name):

    file = real_open(name, 'r')

    def __repr__():
        return '<FileReader: %r>' % name

    def read(bufsize=-1):
        return file.read(bufsize)

    def close():
        return file.close()

    return Getter(Namespace(__repr__, read, close))

# process A -- which has full access to all objects -- can do:

# motd = FileReader('/etc/motd')

# and pass it to "process B" operating in a limited scope.
# process B can now run:

# motd.read()
# motd.close()

# print motd # <FileReader: /etc/motd>

# but process B cannot do anything else... since it doesn't
# have a reference to other functionality.

from ctypes import pythonapi, POINTER, py_object

getdict = pythonapi._PyObject_GetDictPtr
getdict.restype = POINTER(py_object)
getdict.argtypes = [py_object]

def dictionary_of(ob):
    dptr = getdict(ob)
    if dptr and dptr.contents:
        return dptr.contents.value

del dictionary_of(type)['__subclasses__']

del dictionary_of(FunctionType)['func_closure']
del dictionary_of(FunctionType)['func_code']
del dictionary_of(FunctionType)['func_globals']

for item in ['open', 'file', 'execfile']:
    del __builtin__.__dict__[item]

def null(*args, **kwargs):
    pass

__builtin__.__import__ = null

This paste has no annotations.

Colorize as:
Show Line Numbers

Lisppaste pastes can be made by anyone at any time. Imagine a fearsomely comprehensive disclaimer of liability. Now fear, comprehensively.