Skip to content

Instantly share code, notes, and snippets.

@zachriggle
Created Jun 25, 2014
Embed
What would you like to do?
Applies IDA Patches to Binaries
import argparse
import fileinput
import re
import binascii
import struct
unhex = binascii.unhexlify
u32 = lambda x: struct.unpack('>L', x)[0]
hexa = r'[0-9A-F]'
pattern = r'(%s{8}): (%s{2}) (%s{2})' % (hexa, hexa, hexa)
regex = re.compile(pattern)
def apply_patch(data, patch):
"""Applies a patch to data
Args:
data: List of bytes to patch
patch: File to read the patch data from, in the format generated
by IDA Pro.
Returns:
Patched list of bytes
"""
for line in patch.readlines():
match = regex.match(line)
if not match:
continue
offset, old, new = match.groups(line)
offset = u32(unhex(offset))
old = unhex(old)
new = unhex(new)
print "%08x: %r %r" % (offset, old, new)
cur = data[offset]
if cur != old:
print "ERROR! Offset %x doesn't match (expected %r, got %r)" % (offset, old, cur)
return None
data[offset] = new
return data
if __name__ == '__main__':
p = argparse.ArgumentParser()
p.add_argument('--input', type=argparse.FileType('rb'))
p.add_argument('--output', type=argparse.FileType('wb'))
p.add_argument('patches', type=argparse.FileType('rb'), nargs='+')
args = p.parse_args()
data = list(args.input.read())
for patchfile in args.patches:
data = apply_patch(data, patchfile)
args.output.write(''.join(data))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment