-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathhexreplace.py
More file actions
79 lines (69 loc) · 3.19 KB
/
hexreplace.py
File metadata and controls
79 lines (69 loc) · 3.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env python3
import os
class Module:
def __init__(self, incoming=False, verbose=False, options=None):
# extract the file name from __file__. __file__ is proxymodules/name.py
self.name = os.path.splitext(os.path.basename(__file__))[0]
self.description = 'Replace hex data on the fly defining search and replace-pairs in a file or as module parameters'
self.verbose = verbose
self.filename = None
self.separator = ':'
self.len = 16
search = None
if options is not None:
if 'search' in options.keys():
search = bytes.fromhex(options['search'])
if 'replace' in options.keys():
replace = bytes.fromhex(options['replace'])
if 'file' in options.keys():
self.filename = options['file']
try:
open(self.filename)
except IOError as ioe:
print("Error opening %s: %s" % (self.filename, ioe.strerror))
self.filename = None
if 'separator' in options.keys():
self.separator = options['separator']
self.pairs = [] # list of (search, replace) tuples
if search is not None and replace is not None:
self.pairs.append((search, replace))
if self.filename is not None:
for line in open(self.filename).readlines():
try:
search, replace = line.split(self.separator, 1)
self.pairs.append((bytes.fromhex(search.strip()), bytes.fromhex(replace.strip())))
except ValueError:
# line does not contain separator and will be ignored
pass
def hexdump(self, data):
result = []
digits = 2
for i in range(0, len(data), self.len):
s = data[i:i + self.len]
hexa = ' '.join(['%0*X' % (digits, x) for x in s])
text = ''.join([chr(x) if 0x20 <= x < 0x7F else '.' for x in s])
result.append("%04X %-*s %s" % (i, self.len * (digits + 1), hexa, text))
print("\n".join(result))
def execute(self, data):
if self.verbose:
print(f"Incoming packet with size {len(data)}:")
for search, replace in self.pairs:
if search in data:
if self.verbose:
print("########## data found ###########")
print("[Before:]")
self.hexdump(data)
data = data.replace(search, replace)
if self.verbose:
print("[After:]")
self.hexdump(data)
return data
def help(self):
h = '\tsearch: hex string (i.e. "deadbeef") to search for\n'
h += ('\treplace: hex string the search string should be replaced with\n')
h += ('\tfile: file containing search:replace pairs, one per line\n')
h += ('\tseparator: define a custom search:replace separator in the file, e.g. search#replace\n')
h += ('\n\tUse at least file or search and replace (or both).\n')
return h
if __name__ == '__main__':
print('This module is not supposed to be executed alone!')