/
read_write_heap.py
executable file
·65 lines (50 loc) · 1.46 KB
/
read_write_heap.py
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
#!/usr/bin/python3
"""contains the main method"""
import sys
def print_usage_and_exit():
"""module for printing usage
"""
print('Usage: {} pid search write'.format(sys.argv[0]))
sys.exit(1)
if len(sys.argv) != 4:
print_usage_and_exit()
pid = int(sys.argv[1])
search_string = sys.argv[2]
write_string = str(sys.argv[3])
if write_string == "":
write_string = " "
try:
file_maps = open("/proc/{}/maps".format(pid), 'r')
except Exception as e:
print(e)
exit(1)
try:
memory_file = open("/proc/{}/mem".format(pid), 'r+b', 0)
except Exception as e:
print(e)
exit(1)
heap_found = False
for line in file_maps:
s_line = line.split(' ')
if "heap" in line:
heap_found = True
print("found HEAP")
memory_range = s_line[0].split('-')
memory_start = int(memory_range[0], 16)
memory_end = int(memory_range[1], 16)
memory_file.seek(memory_start)
memory_search = memory_file.read(memory_end - memory_start)
index_search = memory_search.find(bytes(search_string, 'ASCII'))
if index_search == -1:
print("break one")
break
memory_file.seek(memory_start + index_search)
memory_file.write(bytes(write_string, "ASCII"))
print("write memory break")
break
file_maps.close()
memory_file.close()
if not heap_found:
print("heap not found")
exit(1)
print("now replacing string in memory: /proc/{}/mem".format(pid))