-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefbase_process.py
More file actions
461 lines (343 loc) · 14.5 KB
/
Copy pathdefbase_process.py
File metadata and controls
461 lines (343 loc) · 14.5 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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
from .processthreadsapi import *
from .defbase_errordef import *
from .wow64apiset import *
from .handleapi import *
from .memoryapi import *
from .winuser import *
from .psapi import *
from .winnt import *
from typing import TypeVar, Self, ClassVar, TYPE_CHECKING
from ctypes import _SimpleCData as SimpleCData
from . import defbase as defb
from .defbase import *
class CSimpleDataInterProcess(SimpleCData):
remote_address: WT_ADDRLIKE
process: 'CProcess'
@classmethod
def initialize(cls, process: 'CProcess', remote_address: WT_ADDRLIKE) -> Self:
csdip = cls()
csdip.remote_address = remote_address
csdip.process = process
return csdip
_type_ = 'i' # bypass the check
@property
def c_value(self):
self.process.read(self.remote_address, byref(self), sizeof(self))
return self.value
@c_value.setter
def c_value(self, value):
self.value = value
self.process.write(self.remote_address, byref(self), sizeof(self))
class InterProcessType:
remote_address: WT_ADDRLIKE
process: 'CProcess'
@classmethod
def initialize(cls, process: 'CProcess', remote_address: WT_ADDRLIKE) -> Self:
ipt = cls()
ipt.remote_address = remote_address
ipt.process = process
return ipt
value: Any
class CCharPointerInterProcess(InterProcessType):
@property
def value(self) -> bytes:
buffer = create_string_buffer(1024)
self.process.read(self.remote_address, byref(buffer), 1024)
return buffer.value
@value.setter
def value(self, value: bytes):
buffer = create_string_buffer(value)
self.process.write(self.remote_address, byref(buffer), len(buffer))
class CWideCharPointerInterProcess(InterProcessType):
@property
def value(self) -> bytes:
buffer = create_unicode_buffer(1024)
self.process.read(self.remote_address, byref(buffer), 1024)
return buffer.value
@value.setter
def value(self, value: bytes):
buffer = create_unicode_buffer(value)
self.process.write(self.remote_address, byref(buffer), len(buffer))
from struct import calcsize
class InterProcessTypes:
class py_object(CSimpleDataInterProcess):
_type_ = "O"
def __repr__(self):
try:
return super().__repr__()
except ValueError:
return "%s(<NULL>)" % type(self).__name__
class c_short(CSimpleDataInterProcess):
_type_ = "h"
class c_ushort(CSimpleDataInterProcess):
_type_ = "H"
class c_long(CSimpleDataInterProcess):
_type_ = "l"
class c_ulong(CSimpleDataInterProcess):
_type_ = "L"
if calcsize("i") == calcsize("l"):
c_int = c_long
c_uint = c_ulong
else:
class c_int(CSimpleDataInterProcess):
_type_ = "i"
class c_uint(CSimpleDataInterProcess):
_type_ = "I"
class c_float(CSimpleDataInterProcess):
_type_ = "f"
class c_double(CSimpleDataInterProcess):
_type_ = "d"
class c_longdouble(CSimpleDataInterProcess):
_type_ = "g"
if sizeof(c_longdouble) == sizeof(c_double):
c_longdouble = c_double
if calcsize("l") == calcsize("q"):
c_longlong = c_long
c_ulonglong = c_ulong
else:
class c_longlong(CSimpleDataInterProcess):
_type_ = "q"
class c_ulonglong(CSimpleDataInterProcess):
_type_ = "Q"
class c_ubyte(CSimpleDataInterProcess):
_type_ = "B"
c_ubyte.__ctype_le__ = c_ubyte.__ctype_be__ = c_ubyte
class c_byte(CSimpleDataInterProcess):
_type_ = "b"
c_byte.__ctype_le__ = c_byte.__ctype_be__ = c_byte
class c_char(CSimpleDataInterProcess):
_type_ = "c"
c_char.__ctype_le__ = c_char.__ctype_be__ = c_char
c_char_p = CCharPointerInterProcess
class c_void_p(CSimpleDataInterProcess):
_type_ = "P"
class c_bool(CSimpleDataInterProcess):
_type_ = "?"
c_wchar_p = CWideCharPointerInterProcess
class c_wchar(CSimpleDataInterProcess):
_type_ = "u"
def _contents_from_addr(T: type, process: 'CProcess', address: int):
if issubclass(T, CStructure):
return T.inter_process(process, address)
elif issubclass(T, (CSimpleDataInterProcess, InterProcessType)):
return T.initialize(process, address)
elif issubclass(T, CPointer32):
remote_address = InterProcessTypes.c_void_p.initialize(process, address).c_value
return T(process, remote_address)
raise ValueError('Incorrect type of pointer.')
def _make_offset(T: type, value: int, index: int) -> int:
return value + (index * sizeof(T))
class IPointer32(IPointer[WT], IAliasableGenericWithPayload[WT]):
remote_address: WT_ADDRLIKE
process: 'CProcess'
@interface_abstract_method
def __init__(self, process: 'CProcess', remote_address: WT_ADDRLIKE = NULL): ...
@classmethod
def _get_alias_(cls, **kwargs):
generic_alias = cls.get_genericalias()
typ = genericalias_single_type(generic_alias)
return PTR32(typ)
# pure implementation
class CPointer32(c_int32):
process: 'CProcess'
_T: ClassVar[type]
@property
def contents(self):
return _contents_from_addr(self._T, self.process, self.value)
def __getitem__(self, index: int):
return _contents_from_addr(self._T, self.process, _make_offset(self._T, self.value, index))
def __setitem__(self, index: int, value):
if issubclass(self._T, CSimpleDataInterProcess):
csdip: CSimpleDataInterProcess = self[index]
csdip.c_value = value
elif issubclass(self._T, InterProcessType):
ipt: InterProcessType = self[index]
ipt.value = value
else:
self.process.write(_make_offset(self._T, self.value, index), byref(value), sizeof(value))
def PTR32(typ: type[WT]) -> type[IPointer32[WT]]:
return type(f'LP_{typ.__name__}', (CPointer32,), {'_T': typ})
POINTER32 = PTR32
def DOUBLE_PTR32(typ: type[WT]) -> type[IPointer32[IPointer32[WT]]]:
return PTR32(PTR32(typ))
class CStructureInterProcess(CStructure):
remote_address: WT_ADDRLIKE
process: 'CProcess'
@classmethod
def initialize(cls, process: 'CProcess', remote_address: WT_ADDRLIKE) -> Self:
cip = cls()
super(cls, cip).__setattr__('remote_address', remote_address)
super(cls, cip).__setattr__('process', process)
return cip
def __getattribute__(self, name: str) -> Any:
if super().__getattribute__('has_field')(name):
self.process.read(self.remote_address, byref(self), sizeof(self))
value = super().__getattribute__(name)
if isinstance(value, CStructure):
value = value.inter_process(super().__getattribute__('process'),
super().__getattribute__('remote_address')+super().__getattribute__('offset')(name))
elif isinstance(value, CPointer32):
value.process = self.process
return value
return super().__getattribute__(name)
def __setattr__(self, name: str, value: Any) -> Any:
field_type = super().__getattribute__('field_type')(name)
if field_type is not None:
remote_address = PtrUtil.get_address(super().__getattribute__('remote_address'))
local_address = PtrUtil.get_address(byref(self))
offset = super().__getattribute__('offset')(name)
super().__setattr__(name, value)
self.process.write(remote_address+offset, local_address+offset, sizeof(field_type))
return
super().__setattr__(name, value)
WT_CIP = TypeVar('WT_CIP', bound=CStructureInterProcess)
if TYPE_CHECKING:
from .defbase_module import CModule
class CProcess:
current: 'CProcess' = None
is_current: bool
handle: int
pid: int
def __init__(self, pid: int = None, flags: int = PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION):
if pid == -1:
self.is_current = False
self.handle = None
self.pid = -1
return
if pid is None:
self.handle = GetCurrentProcess()
handle = HANDLE()
if not DuplicateHandle(self.handle, self.handle, self.handle,
byref(handle), 0, FALSE, DUPLICATE_SAME_ACCESS):
raise WinException()
self.handle = handle.value
self.pid = GetCurrentProcessId()
self.is_current = True
return
self.handle = OpenProcess(flags, False, pid)
self.is_current = False
self.pid = pid
if not self.handle:
raise WinException()
@classmethod
def new(self, app_name: str, command_line: str = NULL, process_attributes: SECURITY_ATTRIBUTES = NULL,
thread_attributes: SECURITY_ATTRIBUTES = NULL, inherit_handles: bool=False, flags: int=0,
environment: WT_ADDRLIKE = NULL, current_directory: str = NULL, si: STARTUPINFOW=NULL) -> 'CProcess':
if process_attributes is not None:
process_attributes = process_attributes.ref()
if thread_attributes is not None:
thread_attributes = thread_attributes.ref()
if si is not None:
si = si.ref()
pi = PROCESS_INFORMATION()
environment = PtrUtil.get_address(environment)
process = CProcess(-1)
if not CreateProcessW(
app_name, command_line, process_attributes,
thread_attributes, inherit_handles, flags,
environment, current_directory, si, pi.ref()):
raise WinException()
process.handle = pi.hProcess
process.pid = pi.dwProcessId
CloseHandle(pi.hThread)
return process
def open(self, flags: int = PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION):
self.handle = OpenProcess(flags, False, self.pid)
if not self.handle:
raise WinException()
@classmethod
def enum_processes(cls) -> list['CProcess']:
processes: list[CProcess] = []
nPids = 2048
cbPids = PtrArithmetic.size(DWORD, nPids)
pids: IArray[int] = (DWORD * nPids)()
cbNeeded = DWORD()
if not EnumProcesses(pids, cbPids, byref(cbNeeded)):
raise WinException()
currentProcessId = GetCurrentProcessId()
for i in range(cbNeeded.value // sizeof(DWORD)):
pid = pids[i]
if pid == 0: continue
process = CProcess(-1)
process.pid = pid
if pid == currentProcessId:
process.is_current = True
processes.append(process)
return processes
@classmethod
def from_hwnd(cls, hwnd: int) -> 'CProcess':
if not IsWindow(hwnd):
raise OSError('Invalid HWND.')
dwProcessID = DWORD()
GetWindowThreadProcessId(hwnd, byref(dwProcessID))
return cls(dwProcessID.value)
def __str__(self) -> str:
return f'Process PID {self.pid}'
def __repr__(self) -> str:
return f'<CProcess pid={self.pid} handle={self.handle}>'
def structure(self, cip_cls: type[WT_CIP],
remote_address: WT_ADDRLIKE) -> WT_CIP:
cip = cip_cls()
self.read(remote_address, cip.ref(), cip.size())
return cip
def write(self, remote_address: WT_ADDRLIKE,
local_buffer: WT_ADDRLIKE, size: int) -> int:
if not self.handle:
raise OSError(f'Cannot write to memory of {self}.')
written = SIZE_T()
if not WriteProcessMemory(self.handle, remote_address,
local_buffer, size, byref(written)):
raise WinException()
return written.value
def read(self, remote_address: WT_ADDRLIKE,
local_buffer: WT_ADDRLIKE, size: int) -> int:
if not self.handle:
raise OSError(f'Cannot read memory of {self}.')
read = SIZE_T()
if not ReadProcessMemory(self.handle, remote_address,
local_buffer, size, byref(read)):
raise WinException()
return read.value
def terminate(self, exit_code: int = 0):
if not self.handle:
raise OSError(f'Cannot terminate {self}.')
if not TerminateProcess(self.handle, exit_code):
raise WinException()
def enum_modules(self) -> list['CModule']:
if not self.handle:
raise OSError(f'Cannot enumerate modules for {self}.')
defbase_module = getattr(defb._defb_state, '_defbase_module', None)
if defbase_module is None:
from . import defbase_module
defb._defb_state._defbase_module = defbase_module
modules: list['CModule'] = []
hModules = (HMODULE * 1024)()
cbNeeded = DWORD()
if EnumProcessModules(self.handle, hModules, 1024, byref(cbNeeded)):
for i in range(cbNeeded.value // sizeof(HMODULE)):
module = defbase_module.CModule.from_handle(hModules[i])
if not self.is_current:
module.process = self
modules.append(module)
return modules
def close(self):
if self.handle:
CloseHandle(self.handle)
self.handle = None
@property
def is_wow64(self) -> bool:
is_wow64 = BOOL()
if IsWow64Process(self.handle, byref(is_wow64)):
return bool(is_wow64.value)
return False
def __del__(self):
self.close()
def format_address(self, address: WT_ADDRLIKE) -> str:
if not isinstance(address, int):
address = PtrUtil.get_address(address)
for module in self.enum_modules():
module_address = module.format_address(address)
if module_address is None: continue
return module_address
return format_hex(address, sizeof(PVOID))
CProcess.current = CProcess()