Repository navigation
Expand file tree
/
Copy pathPYAS_Process.py
More file actions
342 lines (256 loc) · 10.7 KB
/
Copy pathPYAS_Process.py
File metadata and controls
342 lines (256 loc) · 10.7 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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
from PYAS_Diagnostics import log_exception
import os
import re
import io
import time
import ctypes
import ctypes.wintypes
from PYAS_WinAPI import (
IO_COUNTERS,
MIB_TCPROW_OWNER_PID,
PROCESSENTRY32W,
PROCESS_BASIC_INFORMATION,
PYAS_PROCESS_TERMINATE_ACCESS,
UNICODE_STRING,
)
class ProcessMixin:
def device_path_to_drive(self, path):
if not path:
return ""
for d in range(65, 91):
drive = f"{chr(d)}:"
buf = ctypes.create_unicode_buffer(1024)
if self.kernel32.QueryDosDeviceW(drive, buf, 1024) and path.startswith(buf.value):
return path.replace(buf.value, drive, 1)
return path
def get_exe_info(self, pid):
name, file_path = None, None
h = self.kernel32.OpenProcess(0x1000, False, pid)
if h:
try:
buf = ctypes.create_unicode_buffer(1024)
size = ctypes.wintypes.DWORD(1024)
if self.kernel32.QueryFullProcessImageNameW(h, 0, buf, ctypes.byref(size)):
file_path = self.norm_path(buf.value)
if file_path:
name = os.path.basename(file_path)
elif self.psapi.GetProcessImageFileNameW(h, buf, 1024):
file_path = self.norm_path(self.device_path_to_drive(buf.value))
if file_path:
name = os.path.basename(file_path)
finally:
self.kernel32.CloseHandle(h)
return name, file_path
def get_process_file(self, h_process):
buf = ctypes.create_unicode_buffer(1024)
if self.psapi.GetProcessImageFileNameW(h_process, buf, 1024):
return self.norm_path(self.device_path_to_drive(buf.value))
return ""
def get_process_cmdline(self, h):
try:
pbi = PROCESS_BASIC_INFORMATION()
returned = ctypes.wintypes.ULONG()
if (
self.ntdll.NtQueryInformationProcess(
h, 0, ctypes.byref(pbi), ctypes.sizeof(pbi), ctypes.byref(returned)
)
!= 0
):
return ""
if returned.value != ctypes.sizeof(pbi) or not pbi.PebBaseAddress:
return ""
def read_exact(address, destination):
transferred = ctypes.c_size_t()
capacity = ctypes.sizeof(destination)
return (
bool(
self.kernel32.ReadProcessMemory(
h,
ctypes.c_void_p(address),
ctypes.byref(destination),
capacity,
ctypes.byref(transferred),
)
)
and transferred.value == capacity
)
pointer_size = ctypes.sizeof(ctypes.c_void_p)
parameters = ctypes.c_void_p()
if (
not read_exact(
int(pbi.PebBaseAddress) + (0x20 if pointer_size == 8 else 0x10), parameters
)
or not parameters.value
):
return ""
descriptor = UNICODE_STRING()
if not read_exact(parameters.value + (0x70 if pointer_size == 8 else 0x40), descriptor):
return ""
length = int(descriptor.Length)
if not descriptor.Buffer or not length:
return ""
if length % 2 or length > descriptor.MaximumLength:
raise ValueError("Invalid remote UTF-16 command-line length")
buffer = (ctypes.c_ubyte * length)()
if not read_exact(int(descriptor.Buffer), buffer):
return ""
return bytes(buffer).decode("utf-16-le", errors="surrogatepass")
except Exception:
log_exception("ProcessMixin.get_process_cmdline")
return ""
def extract_paths_from_cmdline(self, cmdline):
if not cmdline:
return []
found = []
for m in re.finditer(r'"([^"]+)"|\'([^\']+)\'', cmdline):
path = m.group(1) or m.group(2)
if re.match(r"^[A-Za-z]:\\|^\\\\", path):
found.append(path)
if not found:
m = re.search(
r'([A-Za-z]:\\[^\*?"<>\|]+\.(?:exe|dll|bat|cmd|vbs|sys|com|pif))',
cmdline,
re.IGNORECASE,
)
if m:
found.append(m.group(1))
if not found:
argc = ctypes.c_int(0)
argv = self.shell32.CommandLineToArgvW(cmdline, ctypes.byref(argc))
if argv:
args = [argv[i] for i in range(argc.value)]
self.kernel32.LocalFree(ctypes.cast(argv, ctypes.c_void_p))
patterns = [
r'([A-Za-z]:\\[^"\']+)',
r'(\\\\[^"\']+)',
r'(\.\\[^"\']+)',
r'(\./[^"\']+)',
r'([A-Za-z]:/[^"\']+)',
r"([^\s]*\\[^\s]+)",
]
for arg in args:
for p in patterns:
for match in re.finditer(p, arg):
found.append(match.group(1).strip('"').strip("'"))
return list(dict.fromkeys([p.strip('"').strip("'") for p in found]))
def _enum_processes(self):
pe = PROCESSENTRY32W()
pe.dwSize = ctypes.sizeof(PROCESSENTRY32W)
snapshot = self.kernel32.CreateToolhelp32Snapshot(0x00000002, 0)
if snapshot in (-1, 0xFFFFFFFF, 0xFFFFFFFFFFFFFFFF):
return
try:
if self.kernel32.Process32FirstW(snapshot, ctypes.byref(pe)):
while True:
yield pe.th32ProcessID, pe.szExeFile
if not self.kernel32.Process32NextW(snapshot, ctypes.byref(pe)):
break
finally:
self.kernel32.CloseHandle(snapshot)
def get_process_list(self):
result = []
for pid, exe_name in self._enum_processes():
name, file_path = None, None
if pid > 4:
name, file_path = self.get_exe_info(pid)
if not name:
try:
name = exe_name
except Exception:
log_exception("PYAS_Process.ProcessMixin.get_process_list:140")
name = "Unknown"
result.append({"pid": pid, "name": name, "path": file_path or "None"})
return result
def get_process_list_pids(self):
return {pid for pid, _ in self._enum_processes()}
def kill_process(self, pid, expected_path=None):
try:
h = self.kernel32.OpenProcess(PYAS_PROCESS_TERMINATE_ACCESS, False, pid)
if h:
try:
return self._terminate_process_handle(h, pid=pid, expected_path=expected_path)
finally:
self.kernel32.CloseHandle(h)
except Exception as e:
log_exception("PYAS_Process.ProcessMixin.kill_process:159")
self.write_log(
"WARN", "kill_process", pid=pid, detail=str(e), operate=True, success=False
)
return False
def get_connections_list(self):
connections = set()
try:
size = ctypes.wintypes.DWORD()
if self.iphlpapi.GetExtendedTcpTable(None, ctypes.byref(size), True, 2, 5, 0) != 122:
return connections
buf = ctypes.create_string_buffer(size.value)
if self.iphlpapi.GetExtendedTcpTable(buf, ctypes.byref(size), True, 2, 5, 0) != 0:
return connections
num_entries = ctypes.cast(buf, ctypes.POINTER(ctypes.wintypes.DWORD)).contents.value
for i in range(num_entries):
row = MIB_TCPROW_OWNER_PID.from_address(
ctypes.addressof(buf)
+ ctypes.sizeof(ctypes.wintypes.DWORD)
+ i * ctypes.sizeof(MIB_TCPROW_OWNER_PID)
)
connections.add((row.dwOwningPid, row.dwRemoteAddr, row.dwRemotePort))
except Exception:
log_exception("PYAS_Process.ProcessMixin.get_connections_list:179")
pass
return connections
def get_traffic_list(self):
conns = self.get_connections_list()
conn_map = {}
for pid, _, _ in conns:
conn_map[pid] = conn_map.get(pid, 0) + 1
current_io = {}
current_time = time.time()
with self.lock_io:
time_diff = current_time - self.last_io_time
if time_diff <= 0:
time_diff = 1
self.last_io_time = current_time
old_counters = self.last_io_counters.copy()
result = []
exist_process = self.get_process_list_pids()
for pid in exist_process:
name, file_path = "Unknown", ""
if pid > 4:
name, file_path = self.get_exe_info(pid)
else:
name = "System"
down_speed, up_speed = 0, 0
h = self.kernel32.OpenProcess(0x1000, False, pid)
if h:
try:
io = IO_COUNTERS()
if self.kernel32.GetProcessIoCounters(h, ctypes.byref(io)):
current_io[pid] = (io.ReadTransferCount, io.WriteTransferCount)
if pid in old_counters:
old_read, old_write = old_counters[pid]
down_speed = max(0, (io.ReadTransferCount - old_read) / time_diff)
up_speed = max(0, (io.WriteTransferCount - old_write) / time_diff)
finally:
self.kernel32.CloseHandle(h)
count = conn_map.get(pid, 0)
if count > 0 or down_speed > 0 or up_speed > 0:
result.append(
{
"pid": pid,
"name": name,
"path": file_path or "None",
"down": int(down_speed),
"up": int(up_speed),
"conn": count,
}
)
with self.lock_io:
self.last_io_counters = current_io
return result
def _terminate_process_handle(self, handle, pid=None, expected_path=None):
file_path = self.norm_path(self.get_process_file(handle))
if self.path_equal(file_path, self.file_pyas):
return False
if expected_path and not self.path_equal(file_path, expected_path):
return False
return bool(self.kernel32.TerminateProcess(handle, 0))