Skip to content

Instantly share code, notes, and snippets.

@chewxy
Created August 7, 2014 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chewxy/17e6920b608208647a74 to your computer and use it in GitHub Desktop.
Save chewxy/17e6920b608208647a74 to your computer and use it in GitHub Desktop.
Running arbitrary code in Python
# Sorry for using Python 2.7
from ctypes import *
import os, sys
argv = int(sys.argv[1])
argv2 = int(sys.argv[2])
PROT_NONE = 0x0
PROT_READ = 0x1
PROT_WRITE = 0x2
PROT_EXEC = 0x4
buf = ''.join(map(chr, [
0x55, # pushq %rbp
0x48, 0x89, 0xe5, # movq %rsp, %rbp
0x89, 0x7d, 0xfc, # movl %edi, -4(%rbp)
0x89, 0x75, 0xf8, # movl %esi, -8(%rbp)
0x8b, 0x45, 0xf8, # movl -8(%rbp), %eax
0x8b, 0x55, 0xfc, # movl -4(%rbp), %edx
0x01, 0xd0, # addl %edx, %eax
0x5d, # popq %rbp
0xc3, # ret
]))
stringBuffer = create_string_buffer(buf)
print "String Buffer: ",
print(repr(stringBuffer.raw))
codeAddress = addressof(stringBuffer)
print "Code sits in",
print hex(codeAddress)
pageSize = pythonapi.getpagesize()
print "Page Size", pageSize
sizeOfCode = sizeof(stringBuffer)
mask = pageSize - 1
returnedValue = pythonapi.mprotect(~mask&codeAddress, mask&codeAddress + sizeOfCode, PROT_READ|PROT_WRITE|PROT_EXEC)
if returnedValue == -1:
raise StandardError("Something Bad Happened")
function = cast(stringBuffer, CFUNCTYPE(c_long, c_long))
print "Answer is: ", repr(function(argv,argv2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment