python 脚本处理IDA的Dif文件

时间:2021-09-12 10:09:25

dif文件例子:

This difference file has been created by IDA

armhook
This difference file has been created by IDA

armhook
000001CC: 04 53
000001CD: B0 A8
000001CE: 2D 01
000001CF: E5 EB

0006A320: 02 F0
0006A321: 02 47
0006A322: 02 2D
0006A323: 02 E9
0006A324: 02 30
0006A325: 02 00
0006A326: 02 9F
0006A327: 02 E5
0006A328: 02 DA
0006A329: 02 62
0006A32A: 02 FE
0006A32B: 02 EB
0006A32C: 02 04
0006A32D: 02 B0
0006A32E: 02 2D
0006A32F: 02 E5
0006A330: 02 F0
0006A331: 02 87
0006A332: 02 BD
0006A333: 02 E8

0006A350: 02 68
0006A351: 02 69
0006A352: 02 20
0006A353: 02 61
0006A354: 02 72
0006A355: 02 6D
0006A356: 0C 20
0006A357: 02 68
0006A358: 02 6F
0006A359: 02 6F
0006A35A: 02 6B
0006A35B: 03 00
0006A35C: 02 50
0006A35D: 02 23
0006A35E: 02 07
0006A35F: 02 00

对应的idadiff.py脚本代码

#!/usr/bin/env python
# coding=cp936

# 将ida导出的.dif 补丁到程序中
import re
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), orig.decode('hex'), new.decode('hex')
if revert:
if code[o]==new:
code = code[:o]+orig+code[o+1:]
else:
raise Exception("patched byte at %s is not %02X" % (offset, ord(new)))
else:
if code[o]==orig:
code = code[:o]+new+code[o+1:]
else:
raise Exception("original byte at %s is not %02X" % (offset, ord(orig)))
open(file,'wb').write(code)

def main():
if len(argv)<3:
print "Usage: %s <binary> <IDA.dif file> [revert]" % (argv[0])
print "For example: idadif executable.exe executable.dif"
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, e:
print "Error: %s" % str(e)
exit(1)

if __name__ == "__main__":
main()