Skip to content

Instantly share code, notes, and snippets.

@thomasfinch
Last active June 4, 2018 06:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasfinch/4f6a78fcd8f999cfa0df to your computer and use it in GitHub Desktop.
Save thomasfinch/4f6a78fcd8f999cfa0df to your computer and use it in GitHub Desktop.
Simple ROP gadget finder in python
import sys
from capstone import *
if len(sys.argv) < 2:
print 'Error: need file name argument'
exit()
# Read binary input file into an array
fileName = sys.argv[1]
file = open(fileName, "rb")
byteArr = []
try:
byte = file.read(1)
while byte != '':
byte = file.read(1)
byteArr.append(byte)
finally:
file.close()
# Find all potential gadgets (bytes before a c3 byte (return instruction)) and put them in an array
potentialGadgets = []
for gadgetSize in range(1, 12): # Try multiple gadget sizes (in bytes)
for index, byte in enumerate(byteArr):
if byte == '\xc3':
potentialGadgets.append((byteArr[index - gadgetSize : index + 1], index - gadgetSize))
# Disassemble the gadgets with Capstone and output to a text file
outFile = open('potentialGadgets.txt', 'w')
md = Cs(CS_ARCH_X86, CS_MODE_32)
count = 0
for gadget in potentialGadgets:
bytes = ''.join(gadget[0])
offset = gadget[1]
instructions = []
for i in md.disasm(bytes, 0x0):
instructions.append(i)
# Only use gadgets that actually end with a ret
if len(instructions) > 1 and instructions[len(instructions) - 1].mnemonic == 'ret':
outFile.write('Offset 0x%s:\n' % format(offset+1, 'x'))
for i in instructions:
outFile.write('{} {}\t{}\n'.format(i.mnemonic, i.op_str, '('+''.join([format(c, 'x') for c in i.bytes])+')'))
count += 1
outFile.write('\n')
outFile.close()
print 'Found', count, 'gadgets.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment