Repository navigation
Expand file tree
/
Copy pathopcode-scanner.py
More file actions
190 lines (165 loc) · 6.71 KB
/
Copy pathopcode-scanner.py
File metadata and controls
190 lines (165 loc) · 6.71 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import ctypes
import sys
import argparse
from ctypes import wintypes
import psutil
# winapi constants for process/memory access
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
MEM_COMMIT = 0x1000
PAGE_READONLY = 0x02
PAGE_READWRITE = 0x04
PAGE_EXECUTE_READ = 0x20
PAGE_EXECUTE_READWRITE = 0x40
class MEMORY_BASIC_INFORMATION(ctypes.Structure):
_fields_ = [
("BaseAddress", wintypes.LPVOID),
("AllocationBase", wintypes.LPVOID),
("AllocationProtect", wintypes.DWORD),
("RegionSize", ctypes.c_size_t),
("State", wintypes.DWORD),
("Protect", wintypes.DWORD),
("Type", wintypes.DWORD),
]
ctypes.windll.kernel32.VirtualQueryEx.argtypes = [
wintypes.HANDLE,
wintypes.LPCVOID,
ctypes.POINTER(MEMORY_BASIC_INFORMATION),
ctypes.c_size_t
]
ctypes.windll.kernel32.VirtualQueryEx.restype = ctypes.c_size_t
ctypes.windll.kernel32.ReadProcessMemory.argtypes = [
wintypes.HANDLE,
wintypes.LPCVOID,
wintypes.LPVOID,
ctypes.c_size_t,
ctypes.POINTER(ctypes.c_size_t)
]
ctypes.windll.kernel32.ReadProcessMemory.restype = wintypes.BOOL
def get_process_id(process_name):
for proc in psutil.process_iter(['pid', 'name']):
if proc.info['name'] == process_name:
return proc.info['pid']
return None
def is_readable(protect):
return protect in (PAGE_READONLY, PAGE_READWRITE, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE)
def get_module_info(process_handle, pid):
try:
process = psutil.Process(pid)
modules = {}
for module in process.memory_maps(grouped=False):
path = module.path
base_address = int(module.addr.split('-')[0], 16)
modules[path] = {
'base': base_address,
'name': path.split('\\')[-1] if '\\' in path else path
}
return modules
except Exception as e:
print(f"Error getting module info: {e}")
return {}
# scan memory for opcode pattern, optionally check for preceding pattern
def scan_process_memory(pid, opcode_pattern, preceding_pattern=None):
process_handle = ctypes.windll.kernel32.OpenProcess(
PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
False,
pid
)
if process_handle == 0:
print(f"Failed to open process. Error: {ctypes.GetLastError()}")
return [], {}
modules = get_module_info(process_handle, pid)
address = 0
mbi = MEMORY_BASIC_INFORMATION()
found_addresses = []
module_addresses = {}
while ctypes.windll.kernel32.VirtualQueryEx(
process_handle,
address,
ctypes.byref(mbi),
ctypes.sizeof(mbi)
) == ctypes.sizeof(mbi):
if mbi.State == MEM_COMMIT and is_readable(mbi.Protect):
buffer = (ctypes.c_byte * mbi.RegionSize)()
bytes_read = ctypes.c_size_t()
if ctypes.windll.kernel32.ReadProcessMemory(
process_handle,
address,
ctypes.byref(buffer),
mbi.RegionSize,
ctypes.byref(bytes_read)
):
data = bytes(buffer)
index = 0
while index <= len(data) - len(opcode_pattern):
found = data.find(opcode_pattern, index)
if found == -1:
break
absolute_address = address + found
found_addresses.append(absolute_address)
# figure out which module this address is in
for module_path, module_info in modules.items():
if absolute_address >= module_info['base']:
module_offset = absolute_address - module_info['base']
module_name = module_info['name']
module_addresses[absolute_address] = {
'module': module_name,
'offset': module_offset,
'full_path': module_path
}
break
# check for preceding pattern if requested
if preceding_pattern and found >= len(preceding_pattern):
preceding_bytes = data[found - len(preceding_pattern):found]
if preceding_bytes == preceding_pattern:
if absolute_address in module_addresses:
module_addresses[absolute_address]['has_preceding'] = True
index = found + 1
address += mbi.RegionSize
ctypes.windll.kernel32.CloseHandle(process_handle)
return found_addresses, module_addresses
def main():
parser = argparse.ArgumentParser(description="Universal opcode pattern scanner for Windows processes")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-p", "--pid", type=int, help="Target process PID")
group.add_argument("-n", "--name", type=str, help="Target process name")
parser.add_argument("-o", "--opcode", type=str, required=True, help="Opcode pattern to search for (hex, e.g. 'F3 0F 11 0C 98')")
parser.add_argument("-b", "--before", type=str, default=None, help="Optional preceding pattern to check (hex, e.g. 'F3 0F 58 C8')")
args = parser.parse_args()
if args.pid:
pid = args.pid
else:
pid = get_process_id(args.name)
if pid is None:
print(f"Process '{args.name}' not found.")
sys.exit(1)
try:
opcode_pattern = bytes.fromhex(args.opcode)
except Exception:
print("Invalid opcode pattern hex string.")
sys.exit(1)
preceding_pattern = None
if args.before:
try:
preceding_pattern = bytes.fromhex(args.before)
except Exception:
print("Invalid preceding pattern hex string.")
sys.exit(1)
print(f"Scanning PID {pid} for pattern {args.opcode}...")
addresses, module_addresses = scan_process_memory(pid, opcode_pattern, preceding_pattern)
if addresses:
print(f"Found {len(addresses)} matches:")
for addr in addresses:
module_info = module_addresses.get(addr, {})
module_name = module_info.get('module', 'Unknown')
offset = module_info.get('offset', 0)
location = f"{module_name}+{offset:X}" if module_name != 'Unknown' else f"0x{addr:016X}"
has_preceding = module_info.get('has_preceding', False)
if has_preceding:
print(f"{location} [PRECEDING MATCH]")
else:
print(f"{location}")
else:
print("Pattern not found.")
if __name__ == "__main__":
main()