Skip to content

Instantly share code, notes, and snippets.

@h4sh5
Created July 3, 2023 14:01
Show Gist options
  • Save h4sh5/eb81ef8bb0aacf4d5e144f2a1eb88f08 to your computer and use it in GitHub Desktop.
Save h4sh5/eb81ef8bb0aacf4d5e144f2a1eb88f08 to your computer and use it in GitHub Desktop.
patch hex patterns in file
#!/usr/bin/env python3
import re
import binascii
import sys
import time
if len(sys.argv) < 3:
print("usage: %s <file> <hex pattern> [replace pattern (default all NOPs)]" %sys.argv[0])
exit(1)
file = sys.argv[1]
data = open(file,'rb').read()
pattern = binascii.unhexlify(sys.argv[2].replace(' ','')) # get rid of spaces
# default replacement, all NOPs
replacement = b"\x90" * len(pattern)
if len(sys.argv) > 3:
replacement = binascii.unhexlify(sys.argv[3])
print('pattern:',pattern)
print('replacement:', replacement)
found_index = data.find(pattern)
occurrences = 0
while found_index != -1:
if found_index != -1:
occurrences += 1
print('found at', hex(found_index))
found_index = data.find(pattern, found_index+1)
print("found",occurrences,"occurrences")
outfilename = file + "." + str(int(time.time())) + ".patched"
with open(outfilename, 'wb+') as f:
f.write(data.replace(pattern, replacement))
print("done, written to", outfilename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment