-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathread_write_heap.py
More file actions
executable file
·79 lines (63 loc) · 2.48 KB
/
read_write_heap.py
File metadata and controls
executable file
·79 lines (63 loc) · 2.48 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/python3
"""Find and replace a string in the heap of a running process.
Usage: `read_write_heap.py pid search_string replace_string`
Where:
- pid is the PID of the running process
- strings are represented in ASCII.
"""
import sys
if len(sys.argv) != 4:
print("Usage: read_write_heap.py pid search_string replace_string")
sys.exit(1)
pid = sys.argv[1]
search_string = sys.argv[2]
replace_string = sys.argv[3] + "\0"
print("Hacking a VM, eh? So you like to live dangerously... ")
print(" <> Searching for PID heap {}... ".format(pid), end="")
address = ""
maps_path = "/proc/" + pid + "/maps"
try:
with open(maps_path, "r") as maps_file:
for line in maps_file:
if "[heap]" in line:
print("the heap has been located.")
if "r" not in line or "w" not in line:
print(" [ERROR] PID heap lacks read/write permissions")
sys.exit(0)
line = line.split()
print(" >< pathname: {}".format(maps_path))
print(" >< address: {}".format(line[0]))
print(" >< permissions: {}".format(line[1]))
print(" >< offset: {}".format(line[2]))
print(" >< device: {}".format(line[3]))
print(" >< inode: {}".format(line[4]))
address = line[0].split('-')
except IOError as e:
print(" [ERROR] cannot open file {}".format(maps_path))
print(e)
sys.exit(1)
start = int(address[0], 16)
end = int(address[1], 16)
print(" <> Searching for string {}... ".format(search_string), end="")
mem_path = "/proc/" + pid + "/mem"
try:
with open(mem_path, "rb+") as mem_file:
mem_file.seek(start)
heap = mem_file.read(end - start)
try:
index = heap.index(search_string.encode("ASCII"))
print("the string has been located.")
print(" >< index: {}".format(index))
except Exception as e:
print(" [ERROR] cannot locate string {}".format(search_string))
print(e)
sys.exit(0)
print(" <> Replacing string {} ".format(search_string), end="")
print("with {}... ".format(replace_string[:-1]), end="")
mem_file.seek(start + index)
mem_file.write(replace_string.encode("ASCII"))
print("the string has been replaced.")
except IOError:
print(" [ERROR] cannot write to file {}".format(mem_path))
sys.exit(1)
print("Happy hacking, hacker!")