Created
June 25, 2014 18:10
-
-
Save zachriggle/2f80a49c96009d56eddd to your computer and use it in GitHub Desktop.
Applies IDA Patches to Binaries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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