#!/usr/bin/python
"""
simple script to patch a binary file
"""
import sys,os
from binascii import *
import re
def read_bytes(filename,start_address,number_of_bytes):
fh = open(filename,'rb')
fh.seek(start_address)
data = fh.read(number_of_bytes)
fh.close()
return hexlify(data)
def replace_bytes(filename,search,replace):
output = filename + ".patched"
o = open(output,wb)
data = open(filename).read()
o.write(re.sub(a2b_hex(search),a2b_hex(replace),data) )
o.close()
def write_bytes(filename,start_address,newbytes):
output = filename + ".patched"
fh = open(output,'wb')
newbytes_hex = a2b_hex(newbytes)
bytesize = len(newbytes_hex)/2 #read data up to the start address
end_address = start_address + bytesize
for i in open(filename,'rb').read():
t = fh.tell()
if t < start_address or t > end_address:
fh.write(i)
#print fh.tell()
else:
fh.write(newbytes_hex)
#print "patched " + output +" with " + newbytes + " starting at " + hex(t)
fh.flush()
fh.close()
def main(name,address,bytes):
size = len(bytes)/2
print "before " + read_bytes(name,address,size)
write_bytes(name,address,bytes)
print "after " + read_bytes(name+".patched",address,size)
if __name__ == "__main__":
f = "test.exe"
a = 0x0003113
w = "DEADBEEF"
main(f,a,w)
-
No comments:
Post a Comment