Last active
January 19, 2023 17:48
-
-
Save olivierlemoal/410a6d4a3b5247c9515b to your computer and use it in GitHub Desktop.
Python 3 port of idadif.py
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
#!/usr/bin/env python3 | |
# Small IDA .dif patcher | |
import re | |
import struct | |
from binascii import unhexlify | |
from sys import argv, exit | |
def patch(file, dif, revert=False): | |
code = open(file, 'rb').read() | |
dif = open(dif, 'r').read() | |
m = re.findall('([0-9a-fA-F]+): ([0-9a-fA-F]+) ([0-9a-fA-F]+)', dif) | |
for offset, orig, new in m: | |
o, orig, new = int(offset, 16), unhexlify(orig), unhexlify(new) | |
codeByte = struct.pack("B", code[o]) | |
if revert: | |
if codeByte == new: | |
code = code[:o] + orig + code[o + 1:] | |
else: | |
raise Exception( | |
"patched byte at %s is not %s" % (offset, new)) | |
else: | |
if codeByte == orig: | |
code = code[:o] + new + code[o + 1:] | |
else: | |
raise Exception( | |
"original byte at %s is not %s" % (offset, orig)) | |
open(file, 'wb').write(code) | |
def main(): | |
if len(argv) < 3: | |
print("Usage: %s <binary> <IDA.dif file> [revert]" % (argv[0])) | |
print("Applies given IDA .dif file to patch binary; use revert to revert patch.") | |
exit(0) | |
file, dif, revert = argv[1], argv[2], False | |
if len(argv) > 3: | |
revert = True | |
print("Reverting patch %r on file %r" % (dif, file)) | |
else: | |
print("Patching file %r with %r" % (file, dif)) | |
try: | |
patch(file, dif, revert) | |
print("Done") | |
except Exception as e: | |
print("Error: %s" % str(e)) | |
exit(1) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment