-
Notifications
You must be signed in to change notification settings - Fork 2
/
pydetours.py
1405 lines (1167 loc) · 47.5 KB
/
pydetours.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
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import binascii
import ctypes
import ctypes.wintypes
import os
import struct
import sys
import traceback
import ctypes.util
from collections import defaultdict
from functools import wraps
from typing import NamedTuple, Union
try:
from functools import cached_property
except ImportError:
from threading import RLock
_NOT_FOUND = object()
class cached_property:
def __init__(self, func):
self.func = func
self.attrname = None
self.lock = RLock()
def __set_name__(self, owner, name):
assert name is not None
self.attrname = name
def __get__(self, instance, owner=None):
cache = instance.__dict__
val = cache.get(self.attrname, _NOT_FOUND)
if val is _NOT_FOUND:
with self.lock:
val = cache.get(self.attrname, _NOT_FOUND)
if val is _NOT_FOUND:
val = self.func(instance)
cache[self.attrname] = val
return val
PYTHON_DLL = f'python{sys.version_info.major}{sys.version_info.minor}.dll'
WORDSIZE = ctypes.sizeof(ctypes.c_void_p)
WORDPACK = 'I' if WORDSIZE == 4 else 'Q'
REX1 = b'' if WORDSIZE == 4 else b'\x48'
# --- ctypes functions, structures, and constants ---
class STARTUPINFO(ctypes.Structure):
_fields_ = [
('cb', ctypes.wintypes.DWORD),
('lpReserved', ctypes.wintypes.LPWSTR),
('lpDesktop', ctypes.wintypes.LPWSTR),
('lpTitle', ctypes.wintypes.LPWSTR),
('dwX', ctypes.wintypes.DWORD),
('dwY', ctypes.wintypes.DWORD),
('dwXSize', ctypes.wintypes.DWORD),
('dwYSize', ctypes.wintypes.DWORD),
('dwXCountChars', ctypes.wintypes.DWORD),
('dwYCountChars', ctypes.wintypes.DWORD),
('dwFillAttribute', ctypes.wintypes.DWORD),
('dwFlags', ctypes.wintypes.DWORD),
('wShowWindow', ctypes.wintypes.WORD),
('cbReserved2', ctypes.wintypes.WORD),
('lpReserved2', ctypes.wintypes.LPBYTE),
('hStdInput', ctypes.wintypes.HANDLE),
('hStdOutput', ctypes.wintypes.HANDLE),
('hStdError', ctypes.wintypes.HANDLE),
]
class PROCESS_INFORMATION(ctypes.Structure):
_fields_ = [
('hProcess', ctypes.wintypes.HANDLE),
('hThread', ctypes.wintypes.HANDLE),
('dwProcessId', ctypes.wintypes.DWORD),
('dwThreadId', ctypes.wintypes.DWORD),
]
CreateProcessW = ctypes.windll.kernel32.CreateProcessW
CreateProcessW.argtypes = (
ctypes.wintypes.LPCWSTR,
ctypes.wintypes.LPWSTR,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.wintypes.BOOL,
ctypes.wintypes.DWORD,
ctypes.wintypes.LPVOID,
ctypes.wintypes.LPCWSTR,
ctypes.POINTER(STARTUPINFO),
ctypes.POINTER(PROCESS_INFORMATION),
)
CreateProcessW.restype = ctypes.wintypes.BOOL
GetCurrentProcess = ctypes.windll.kernel32.GetCurrentProcess
GetCurrentProcess.restype = ctypes.c_void_p
TH32CS_SNAPPROCESS = 0x00000002
class PROCESSENTRY32(ctypes.Structure):
_fields_ = [('dwSize', ctypes.wintypes.DWORD),
('cntUsage', ctypes.wintypes.DWORD),
('th32ProcessID', ctypes.wintypes.DWORD),
('th32DefaultHeapID', ctypes.POINTER(ctypes.wintypes.ULONG)),
('th32ModuleID', ctypes.wintypes.DWORD),
('cntThreads', ctypes.wintypes.DWORD),
('th32ParentProcessID', ctypes.wintypes.DWORD),
('pcPriClassBase', ctypes.wintypes.LONG),
('dwFlags', ctypes.wintypes.DWORD),
('szExeFile', ctypes.c_char * 260)]
CreateToolhelp32Snapshot = ctypes.windll.kernel32.CreateToolhelp32Snapshot
Process32First = ctypes.windll.kernel32.Process32First
Process32Next = ctypes.windll.kernel32.Process32Next
CloseHandle = ctypes.windll.kernel32.CloseHandle
IsWow64Process = ctypes.windll.kernel32.IsWow64Process
IsWow64Process.argtypes = (ctypes.wintypes.HANDLE, ctypes.POINTER(ctypes.wintypes.BOOL))
ResumeThread = ctypes.windll.kernel32.ResumeThread
ResumeThread.argtypes = (ctypes.wintypes.HANDLE, )
try:
EnumProcessModules = ctypes.windll.psapi.EnumProcessModules
except:
EnumProcessModules = ctypes.windll.kernel32.EnumProcessModules
EnumProcessModules.restype = ctypes.c_bool
EnumProcessModules.argtypes = [ctypes.wintypes.HANDLE, ctypes.POINTER(ctypes.wintypes.HMODULE), ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD)]
class MODULEINFO(ctypes.Structure):
_fields_ = [
("lpBaseOfDll", ctypes.c_void_p),
("SizeOfImage", ctypes.wintypes.DWORD),
("EntryPoint", ctypes.c_void_p),
]
try:
GetModuleInformation = ctypes.windll.psapi.GetModuleInformation
except:
GetModuleInformation = ctypes.windll.kernel32.GetModuleInformation
GetModuleInformation.restype = ctypes.c_bool
GetModuleInformation.argtypes = (ctypes.wintypes.HANDLE, ctypes.wintypes.HMODULE, ctypes.POINTER(MODULEINFO), ctypes.wintypes.DWORD)
GetModuleFileNameA = ctypes.windll.kernel32.GetModuleFileNameA
GetModuleFileNameA.argtypes = (ctypes.wintypes.HANDLE, ctypes.wintypes.LPSTR, ctypes.wintypes.DWORD)
GetModuleFileNameExA = ctypes.windll.psapi.GetModuleFileNameExA
GetModuleFileNameExA.argtypes = (ctypes.wintypes.HANDLE, ctypes.wintypes.HANDLE, ctypes.wintypes.LPSTR, ctypes.wintypes.DWORD)
OpenProcess = ctypes.windll.kernel32.OpenProcess
OpenProcess.argtypes = (ctypes.wintypes.DWORD, ctypes.wintypes.BOOL, ctypes.wintypes.DWORD)
OpenProcess.restype = ctypes.wintypes.HANDLE
GetProcAddress = ctypes.windll.kernel32.GetProcAddress
GetProcAddress.argtypes = (ctypes.wintypes.HMODULE, ctypes.wintypes.LPCSTR)
GetProcAddress.restype = ctypes.c_void_p
VirtualAlloc = ctypes.windll.kernel32.VirtualAlloc
VirtualAlloc.argtypes = (ctypes.wintypes.LPVOID, ctypes.c_size_t, ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)
VirtualAlloc.restype = ctypes.wintypes.LPVOID
VirtualAllocEx = ctypes.windll.kernel32.VirtualAllocEx
VirtualAllocEx.argtypes = (ctypes.wintypes.HANDLE, ctypes.wintypes.LPVOID, ctypes.c_size_t, ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)
VirtualAllocEx.restype = ctypes.wintypes.LPVOID
VirtualProtectEx = ctypes.windll.kernel32.VirtualProtectEx
VirtualProtectEx.argtypes = (ctypes.wintypes.HANDLE, ctypes.wintypes.LPVOID, ctypes.c_size_t, ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD))
VirtualProtectEx.restype = ctypes.wintypes.LPVOID
ReadProcessMemory = ctypes.windll.kernel32.ReadProcessMemory
ReadProcessMemory.restype = ctypes.wintypes.BOOL
ReadProcessMemory.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.LPCVOID, ctypes.wintypes.LPVOID, ctypes.c_size_t, ctypes.POINTER(ctypes.c_size_t)]
WriteProcessMemory = ctypes.windll.kernel32.WriteProcessMemory
WriteProcessMemory.restype = ctypes.wintypes.BOOL
WriteProcessMemory.argtypes = (ctypes.wintypes.HANDLE, ctypes.wintypes.LPVOID, ctypes.wintypes.LPVOID, ctypes.c_size_t, ctypes.POINTER(ctypes.c_size_t))
LoadLibraryA = ctypes.windll.kernel32.LoadLibraryA
LoadLibraryA.restype = ctypes.wintypes.HMODULE
LoadLibraryA.argtypes = (ctypes.wintypes.LPSTR, )
CreateRemoteThread = ctypes.windll.kernel32.CreateRemoteThread
CreateRemoteThread.restype = ctypes.wintypes.HANDLE
CreateRemoteThread.argtypes = (ctypes.wintypes.HANDLE, ctypes.c_void_p, ctypes.c_size_t, ctypes.wintypes.LPVOID, ctypes.wintypes.LPVOID, ctypes.wintypes.DWORD, ctypes.wintypes.LPDWORD)
WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject
WaitForSingleObject.restype = ctypes.wintypes.DWORD
WaitForSingleObject.argtypes = (ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)
GetExitCodeThread = ctypes.windll.kernel32.GetExitCodeThread
GetExitCodeThread.restype = ctypes.wintypes.BOOL
GetExitCodeThread.argtypes = (ctypes.wintypes.HANDLE, ctypes.wintypes.LPDWORD)
CREATE_SUSPENDED = 0x00000004
CREATE_NEW_CONSOLE = 0x00000010
DETACHED_PROCESS = 0x00000008
PROCESS_ALL_ACCESS = 0x101ffb
MEM_COMMIT = 0x00001000
MEM_RESERVE = 0x00002000
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa366786%28v=vs.85%29.aspx
PAGE_EXECUTE = 0x10
PAGE_EXECUTE_READ = 0x20
PAGE_EXECUTE_READWRITE = 0x40
PAGE_EXECUTE_WRITECOPY = 0x80
PAGE_NOACCESS = 0x01
PAGE_READONLY = 0x02
PAGE_READWRITE = 0x04
PAGE_WRITECOPY = 0x08
PyMemoryView_FromMemory = ctypes.pythonapi.PyMemoryView_FromMemory
PyMemoryView_FromMemory.restype = ctypes.py_object
PyMemoryView_FromMemory.argtypes = (ctypes.c_void_p, ctypes.c_int, ctypes.c_int)
PyBUF_READ = 0x100
ALLOWED_PADDING = b'\xcc\x90'
ALLOWED_PROLOGUES = [
'55 8b ec', # push ebp; mov ebp, esp - only 3 bytes but can work with padding
'55 89 e5', # alternate encoding
'8b ff 55 8b ec', # windows dlls prepend noop before to allow easy hooking
'55 8b ec 83 ec ??', # push ebp; mov ebp, esp; sub esp, ?? - allocating space for stack variables is a common pattern that results in PIC bytes
'55 8b ec 83 e4 ??', # push ebp; mov ebp, esp; and esp, ?? - or aligning the stack
'55 89 e5 83 ec ??', # push ebp; mov ebp, esp; sub esp, ?? - as above but with alternate encodings for mov
'55 89 e5 83 e4 ??', # push ebp; mov ebp, esp; and esp, ??
'90 90 90 90 90',
]
if WORDSIZE == 8:
ALLOWED_PROLOGUES += [
'55 48 8b ec 48 83 ec ??', # push rbp; mov rbp, rsp; sub rsp, ?? - allocating space for stack variables is a common pattern that results in PIC bytes
'55 48 8b ec 48 83 e4 ??', # push rbp; mov rbp, rsp; and rsp, ?? - or aligning the stack
'55 48 89 e5 48 83 ec ??', # push rbp; mov rbp, rsp; sub rsp, ?? - as above but with alternate encodings for mov
'55 48 89 e5 48 83 e4 ??', # push rbp; mov rbp, rsp; and rsp, ??
]
class Memory:
def __init__(self, handle=None):
self.handle = handle
def read(self, addr, length):
if not self.handle:
buf = (ctypes.c_uint8 * length)()
ctypes.memmove(buf, addr, length)
return bytes(buf)
else:
buf = (ctypes.c_uint8 * length)()
bytes_read = ctypes.c_size_t()
ReadProcessMemory(self.handle, addr, ctypes.byref(buf), length, ctypes.byref(bytes_read))
return bytes(buf[:bytes_read.value])
def __getitem__(self, s):
if isinstance(s, int):
s = slice(s, None, None)
if s.stop is not None:
ln = s.stop - s.start
elif s.step:
ln = s.step
else:
ln = 1
# data = bytes(PyMemoryView_FromMemory(s.start, ln, PyBUF_READ))
data = self.read(s.start, ln)
if s.step is None or s.step == 1:
pass
elif s.step == 8:
data = struct.unpack('<' + 'Q' * (ln // 8), data)
elif s.step == 4:
data = struct.unpack('<' + 'I' * (ln // 4), data)
elif s.step == 2:
data = struct.unpack('<' + 'H' * (ln // 2), data)
else:
raise ValueError('Don\'t know how to support step=%s' % (s.step, ))
if s.stop is None:
return data[0]
else:
return data
def __setitem__(self, s, v):
if self.handle:
raise ValueError('Not implemented for foreign processes')
if isinstance(s, int):
ln = 1
else:
ln = s.stop - s.start
data = ctypes.create_string_buffer(v)
ctypes.memmove(s.start, data, ln)
def cstr(self, addr, maxlen=1024):
if not self.handle:
return ctypes.string_at(addr).decode('ascii')
else:
data = self.read(addr, maxlen)
if 0 in data:
data = data[:data.find(0)]
return data.decode('ascii')
class Module:
def __init__(self, hModule, process_handle=None):
self.hModule = hModule
self.handle = process_handle or handle
self.memory = memory if not process_handle else Memory(process_handle)
cPath = ctypes.create_string_buffer(1024)
if process_handle:
assert GetModuleFileNameExA(process_handle, self.hModule, cPath, ctypes.c_ulong(1024)), f'GetModuleFileNameExA got {ctypes.windll.kernel32.GetLastError():x}'
else:
assert GetModuleFileNameA(self.hModule, cPath, ctypes.c_ulong(1024)), f'GetModuleFileNameA got {ctypes.windll.kernel32.GetLastError():x}'
self.path = cPath.value.decode()
self.name = os.path.basename(self.path.lower())
self.lpBaseOfDll = self.SizeOfImage = self.EntryPoint = None
self.export_directory_data = self.import_directory_data = None
module_info = MODULEINFO()
res = GetModuleInformation(self.handle, self.hModule, ctypes.byref(module_info), ctypes.sizeof(module_info))
if res:
self.lpBaseOfDll = module_info.lpBaseOfDll
self.SizeOfImage = module_info.SizeOfImage
self.EntryPoint = module_info.EntryPoint
if self.lpBaseOfDll:
DosHeader = self.lpBaseOfDll
MZSignature = self.memory[DosHeader:DosHeader + 2]
assert MZSignature == b'\x4d\x5a'
AddressOfNewExeHeader = DosHeader + 60
# https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_nt_headers32
# https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_nt_headers64
NtHeader = DosHeader + self.memory[AddressOfNewExeHeader::4]
Signature = self.memory[NtHeader:NtHeader + 4]
assert Signature == b'\x50\x45\x00\x00'
# https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header32
# https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header64
OptionalHeader = NtHeader + 24
Magic = self.memory[OptionalHeader:OptionalHeader + 2]
if Magic == b'\x0b\x01':
if WORDSIZE != 4:
raise ValueError('OptionalHeader magic specifies module as 32bit, but we are a 64bit process')
DataDirectory = OptionalHeader + 96
elif Magic == b'\x0b\x02':
if WORDSIZE != 8:
raise ValueError('OptionalHeader magic specifies module as 64bit, but we are a 32bit process')
DataDirectory = OptionalHeader + 112
else:
raise ValueError(f'OptionalHeader magic mismatch: got {Magic.hex()}')
self.export_directory_data = tuple(self.memory[DataDirectory:DataDirectory + 8:4])
self.import_directory_data = tuple(self.memory[DataDirectory + 8:DataDirectory + 16:4])
class Exports(list):
@cached_property
def by_name(self):
return {e.name: e for e in self}
@cached_property
def by_ordinal(self):
return {e.ordinal: e for e in self}
@cached_property
def by_name_and_ordinal(self):
r = self.by_name
r.update(self.by_ordinal)
return r
def __getitem__(self, e):
if isinstance(e, str):
return self.by_name[e]
else:
return super().__getitem__(e)
class Export(NamedTuple):
ordinal: int
name: str
address: int
address_ptr: int
@cached_property
def exports(self):
exports = []
# Some modules might fail GetModuleInformation, so have export_directory_data=None, some modules (e.g. exes) might have no exports (export_directory_data.VirtualAddress = 0)
if self.export_directory_data and self.export_directory_data[0] != 0:
ExportDir = self.base + self.export_directory_data[0]
NumberOfFunctions, NumberOfNames, AddressOfFunctions, AddressOfNames, AddressOfNameOrdinals = self.memory[ExportDir + 20:ExportDir + 40:4]
function_addrs = self.memory[self.base + AddressOfFunctions:self.base + AddressOfFunctions + 4 * NumberOfFunctions:4]
name_addrs = self.memory[self.base + AddressOfNames: self.base + AddressOfNames + 4 * NumberOfNames:4]
name_ordinals = self.memory[self.base + AddressOfNameOrdinals: self.base + AddressOfNameOrdinals + 2 * NumberOfNames:2]
functions = []
for i, func_addr in enumerate(function_addrs):
functions.append((i, None, self.base + func_addr))
for i, name_addr in zip(name_ordinals, name_addrs):
# If an export only has an ordinal, ignore it...
# This means we might miss some exports, but some windows DLLs have 100s of junk ordinal-only exports
function_addr = functions[i][2]
exports.append(self.Export(i + 1, self.memory.cstr(self.base + name_addr), function_addr, self.base + AddressOfFunctions + 4 * i))
exports.sort()
return self.Exports(exports)
class FunctionImport(NamedTuple):
name_or_ordinal: Union[str, int]
thunk: int
class Imports(list):
@property
def by_name(self):
return {m.name.lower(): m for m in self}
def __getitem__(self, e):
if isinstance(e, str):
return self.by_name[e.lower()]
else:
return super().__getitem__(e)
class ModuleImport:
class ResolvedFunctionImport(NamedTuple):
ordinal: int
name: str
by_ordinal: bool
thunk: int
original_address: int
resolved_address: int
def __init__(self, name, unresolved, handle=None):
self.name = name
self.unresolved = unresolved
self.memory = memory if not handle else Memory(handle)
@cached_property
def resolved(self):
resolved_imports = []
if self.name.lower() in modules:
exports = modules[self.name.lower()].exports.by_name_and_ordinal
for i, a in self.unresolved:
exp = exports.get(i)
new_resolved_address = self.memory[a::WORDSIZE]
if exp.address != new_resolved_address:
print(f' > {self.name}!{exp.name} (thunk=0x{a:08x}) changed resolved address 0x{exp.address:08x} => 0x{new_resolved_address:08x}')
resolved_imports.append(self.ResolvedFunctionImport(exp.ordinal, exp.name, i is int, a, exp.address, new_resolved_address))
return resolved_imports
@cached_property
def by_name(self):
return {i.name: i for i in self.resolved}
@cached_property
def by_ordinal(self):
return {i.ordinal: i for i in self.resolved}
@cached_property
def by_name_and_ordinal(self):
r = self.by_name
r.update(self.by_ordinal)
return r
def __getitem__(self, e):
if isinstance(e, str):
return self.by_name[e]
else:
return self.resolved[e]
def __str__(self):
return f'ModuleImport({self.name!r}, <{len(self.unresolved)} functions>)'
__repr__ = __str__
@cached_property
def imports(self):
imports = []
ImportDir = self.base + self.import_directory_data[0]
current_import_descriptor = ImportDir
for _ in range(self.import_directory_data[1] // 20):
OriginalFirstThunk, TimeDateStamp, ForwarderChain, Name, FirstThunk = self.memory[current_import_descriptor:current_import_descriptor + 20:4]
if not OriginalFirstThunk:
break
module_name = self.memory.cstr(self.base + Name)
# print(f'{module_name.ljust(42)} OriginalFirstThunk=0x{self.base + OriginalFirstThunk:016x}, FirstThunk=0x{self.base + FirstThunk:016x}')
functions = []
for i in range(4096):
original_thunk_rva = self.memory[self.base + OriginalFirstThunk + i * WORDSIZE::WORDSIZE]
func_ptr_addr = self.base + FirstThunk + i * WORDSIZE
if not original_thunk_rva:
break
if original_thunk_rva & 1 << (WORDSIZE * 8 - 1):
# ordinal
func_name_ord = original_thunk_rva & 0xffff
else:
func_name_ord = self.memory.cstr(self.base + original_thunk_rva + 2)
functions.append(self.FunctionImport(func_name_ord, func_ptr_addr))
imports.append(self.ModuleImport(module_name, functions, handle=self.handle))
current_import_descriptor += 20
return self.Imports(imports)
@property
def base(self):
return self.lpBaseOfDll or self.hModule
def __str__(self):
return f'Module(name={self.name!r}, path={self.path!r}, <{len(self.imports)} imports>, <{len(self.exports)} exports>)'
__repr__ = __str__
class Modules(dict):
def __init__(self, handle):
self.handle = handle
super().__init__(self._load_modules())
def _load_modules(self):
r = {}
hMods = (ctypes.c_void_p * 1024)()
cbNeeded = ctypes.c_ulong()
if not EnumProcessModules(self.handle, hMods, ctypes.sizeof(hMods), ctypes.byref(cbNeeded)):
raise ValueError(f'EnumProcessModules failed. Error=0x{ctypes.windll.kernel32.GetLastError():x}')
for m in hMods[:cbNeeded.value // ctypes.sizeof(ctypes.c_void_p)]:
mod = Module(m, self.handle)
r[mod.name] = mod
return r
def reload(self):
r = self._load_modules()
for k in self:
if k not in r:
del self[k]
for k, v in r.items():
self[k] = v
class Patch:
def __init__(self, address, process_handle=None):
self.address = address
if not process_handle:
process_handle = handle
self.process_handle = process_handle
self.bytecode = b''
def __enter__(self):
return self
def set_args(self, args):
if WORDSIZE == 4:
# push args in reverse order
for a in args[::-1]:
self.bytecode += b'\x68' + struct.pack('<I', a)
else:
assert len(args) <= 4
for a, rcode in zip(args, (b'\x48\xb9', b'\x48\xba', b'\x49\xb8', b'\x49\xb9')):
if isinstance(a, int):
self.bytecode += rcode + struct.pack('<Q', a)
else:
raise ValueError(f"Don't know how to set arg {a!r}")
def call_indirect(self, funcptr, *args, cleanup_in_32bit=True):
self.set_args(args)
if WORDSIZE == 4:
self.bytecode += b'\xff\x15' + struct.pack('<I', funcptr) # call [&funcptr]
if cleanup_in_32bit and len(args):
self.bytecode += b'\x83\xc4' + struct.pack('<B', len(args) * 4) # add esp
else:
self.bytecode += b'\x48\x83\xec\x20' # sub rsp, 32; shadow space
self.bytecode += b'\xff\x15' + struct.pack('<i', funcptr - (self.cursor + 6)) # call [&funptr] (RIP relative)
self.bytecode += b'\x48\x83\xc4\x20' # add rsp, 32 ; shadow space
def call_regrelative(self, register, offset, *args, cleanup_in_32bit=True):
self.set_args(args)
if register[1:] == 'ax':
call_reg = b'\xff\xd0'
add_reg = b'\x05'
else:
raise ValueError(f"Don't know how to call {register!r}")
if WORDSIZE == 4:
if cleanup_in_32bit and len(args):
call_reg += b'\x83\xc4' + struct.pack('<B', len(args) * 4) # add esp
else:
call_reg = (
b'\x48\x83\xec\x20' + # sub rsp, 32; shadow space
call_reg +
b'\x48\x83\xc4\x20' # add rsp, 32 ; shadow space
)
add_reg = REX1 + add_reg
self.bytecode += add_reg + struct.pack('<I', offset)
self.bytecode += call_reg
def call(self, funcaddr, *args, cleanup_in_32bit=True):
self.set_args(args)
if WORDSIZE == 4:
# call funcaddr (relative)
self.bytecode += b'\xe8' + struct.pack('<i', funcaddr - (self.cursor + 5))
# unwind stack
if cleanup_in_32bit and len(args):
self.bytecode += b'\x83\xc4' + struct.pack('<B', len(args) * 4) # add esp
else:
self.bytecode += b'\x48\xb8' + struct.pack('<Q', funcaddr) # mov rax, funcaddr
self.bytecode += b'\x48\x83\xec\x20' # sub rsp, 32; shadow space
self.bytecode += b'\xff\xd0' # call rax
self.bytecode += b'\x48\x83\xc4\x20' # add rsp, 32 ; shadow space
PREFIX = {
'*': REX1,
'r': b'\x48',
'e': b'',
}
def asm(bytecode):
if isinstance(bytecode, bytes):
def func(self):
self.bytecode += bytecode
else:
def func(self, a):
aa = '?' + a[1:]
if aa in bytecode:
a = aa
self.bytecode += bytecode[a]
return func
def jmp(self, rel):
self.bytecode += b'\xeb' + struct.pack('b', rel)
def jne(self, rel):
self.bytecode += b'\x75' + struct.pack('b', rel)
def add(self, a1, a2):
if a1 == 'esp':
self.bytecode += b'\x83\xc4' + struct.pack('b', a2)
else:
raise ValueError(f'Unknown asm "add {a1}, {a2}"')
def sub(self, a1, a2):
if a1[1:] == 'sp':
self.bytecode += self.PREFIX[a1[0]] + b'\x83\xec' + struct.pack('B', a2)
else:
raise ValueError(f'Unknown asm "sub {a1}, {a2}"')
push = asm({
'?ax': b'\x50',
'?sp': b'\x54',
'?bp': b'\x55',
'?cx': b'\x51',
})
pop = asm({
'?bp': b'\x5d',
})
MOV = {
('bx', 'ax'): b'\x8b\xd8',
('cx', 'sp'): b'\x8b\xcc',
('bp', 'sp'): b'\x8b\xec',
('sp', 'bp'): b'\x8b\xe5',
('cx', 'bp'): b'\x8b\xcd',
('r12', 'rax'): b'\x4c\x8b\xe0',
('r13', 'rax'): b'\x4c\x8b\xe8',
('r14', 'rax'): b'\x4c\x8b\xf0',
('rdx', 'r13'): b'\x49\x8B\xD5',
('rdx', 'r14'): b'\x49\x8B\xD6',
('rcx', 'r14'): b'\x49\x8B\xCE',
('rcx', 'r13'): b'\x49\x8B\xCD',
('rcx', 'r12'): b'\x49\x8B\xCC',
}
def mov(self, a1, a2):
if a1[1:] == 'ax':
if a1[0] == '*':
size = WORDPACK
elif a1[0] == 'r':
size = 'Q'
else:
size = 'I'
try:
self.bytecode += self.PREFIX[a1[0]] + b'\xb8' + struct.pack('<' + size, int(a2))
return
except:
pass
sk = a1[1:], a2[1:]
if a1[0] == '[' and a1[2:4] == 'bp' and a2[1:] == 'ax' and a1[1] == a2[0]:
# mov [?bp+?], ?ax
ofs = int(a1[4:-1])
pre = self.PREFIX[a1[1]]
self.bytecode += pre + b'\x89\x45' + struct.pack('b', ofs)
elif a2[0] == '[' and a2[2:4] == 'bp' and a1[1:] in ['ax', 'cx'] and a2[1] == a1[0]:
# mov ?ax, [?bp+?] / mov ?cx, [?bp+?]
ofs = int(a2[4:-1])
pre = self.PREFIX[a2[1]]
dst = b'\x45' if a1[1:] == 'ax' else b'\x4d'
self.bytecode += pre + b'\x8b' + dst + struct.pack('b', ofs)
elif sk in self.MOV and a1[0] == a2[0]:
# support all of {*ax, eax, rax} by determining what prefix we need
self.bytecode += self.PREFIX[a1[0]] + self.MOV[sk]
else:
self.bytecode += self.MOV[(a1, a2)]
def pushad(self):
if WORDSIZE == 4:
self.bytecode += b'\x60'
else:
self.bytecode += b'PQRSTUVWAPAQARASATAUAVAW'
def popad(self):
if WORDSIZE == 4:
self.bytecode += b'\x61'
else:
self.bytecode += b'A_A^A]A\x5cA[AZAYAX_^]\x5c[ZYX'
def test(self, a1, a2):
if a1 == a2 and a1[1:] == 'ax':
self.bytecode += self.PREFIX[a1[0]] + b'\x85\xc0'
else:
raise ValueError(f'Unknown asm "test {a1}, {a2}"')
pushfd = asm(b'\x9c')
popfd = asm(b'\x9d')
ret = asm(b'\xc3')
int8 = asm(b'\xcc')
@property
def cursor(self):
return self.address + len(self.bytecode)
def __exit__(self, exc_type, exc_value, tb):
old_permissions = ctypes.wintypes.DWORD()
if not VirtualProtectEx(self.process_handle, self.address, len(self.bytecode), PAGE_EXECUTE_READWRITE, ctypes.byref(old_permissions)):
raise ValueError('Error: VirtualProtectEx %04x' % ctypes.windll.kernel32.GetLastError())
if self.process_handle == handle:
ctypes.memmove(self.address, self.bytecode, len(self.bytecode))
else:
if not WriteProcessMemory(self.process_handle, self.address, self.bytecode, len(self.bytecode), None):
raise ValueError('Error: WriteProcessMemory %d' % ctypes.windll.kernel32.GetLastError())
if not VirtualProtectEx(self.process_handle, self.address, len(self.bytecode), old_permissions.value, ctypes.byref(old_permissions)):
raise ValueError('Error: VirtualProtectEx %d' % ctypes.windll.kernel32.GetLastError())
class Registers:
REGISTERS = ['eflags']
if WORDSIZE == 8:
REGISTERS += ['r15', 'r14', 'r13', 'r12', 'r11', 'r10', 'r9', 'r8']
REGISTERS += ['edi', 'esi', 'ebp', 'esp', 'ebx', 'edx', 'ecx', 'eax']
def __init__(self, buf, eip):
for rname, rval in zip(self.REGISTERS, struct.unpack(
'<' + WORDPACK * len(self.REGISTERS),
buf,
)):
setattr(self, rname, rval)
self.eip = eip
def pack(self):
vals = [
getattr(self, rname) for rname in self.REGISTERS
]
return struct.pack(
'<' + ''.join(WORDPACK if v >= 0 else WORDPACK.lower() for v in vals),
*vals
)
@classmethod
def getsize(cls):
return WORDSIZE * len(cls.REGISTERS)
def __str__(self):
return 'Registers(' + ', '.join(
f'{rname}=0x{getattr(self, rname):08x}'
for rname
in reversed(self.REGISTERS)
) + ')'
__repr__ = __str__
class Arguments:
def __init__(self, reg, argcount=None):
self.reg = reg
self.argcount = argcount
def argaddr(self, i):
if self.argcount is not None and i >= self.argcount:
raise IndexError(f'Argument {i} is out of bounds for Arguments with argcount={self.argcount}')
if WORDSIZE == 8 and i <= 3:
return ['ecx', 'edx', 'r8', 'r9'][i]
else:
return self.reg.esp + (i + 1) * WORDSIZE
def __getitem__(self, i):
a = self.argaddr(i)
if isinstance(a, str):
return getattr(self.reg, a)
else:
return struct.unpack('<' + WORDPACK, memory[a:a + WORDSIZE])[0]
def __setitem__(self, i, v):
a = self.argaddr(i)
if isinstance(a, str):
setattr(self.reg, a, v)
else:
memory[a:a + WORDSIZE] = struct.pack('<' + WORDPACK, v)
def __str__(self):
if self.argcount is not None:
return 'Arguments[' + ', '.join(hex(self[i]) for i in range(self.argcount)) + ']'
else:
return 'Arguments[...? ' + ', '.join(hex(self[i]) for i in range(4)) + ', ...?]'
__repr__ = __str__
in_hooked_process = getattr(sys, 'in_hooked_process', False)
handle = GetCurrentProcess()
memory = Memory()
modules = Modules(handle)
_dontgc = [] # don't garbage collect otherwise dangling objects - they are needed in the hooks
_already_hooked = set()
def make_patch_to_py(patch, pyfunc):
PyGILState_Ensure = modules[PYTHON_DLL].exports['PyGILState_Ensure'].address
PyGILState_Release = modules[PYTHON_DLL].exports['PyGILState_Release'].address
Py_DecRef = modules[PYTHON_DLL].exports['Py_DecRef'].address
PyTuple_Pack = modules[PYTHON_DLL].exports['PyTuple_Pack'].address
PyLong_FromVoidPtr = modules[PYTHON_DLL].exports['PyLong_FromVoidPtr'].address
PyObject_CallObject = modules[PYTHON_DLL].exports['PyObject_CallObject'].address
if WORDSIZE == 4:
patch.call(PyGILState_Ensure)
patch.push('eax') # ret from PyGILState_Ensure
# use ebp (holds esp's value after pushads) as the argument instead of hardcoded value...
# this means we need to restore the stack after, instead of having patch.call do that since patch.call
# thinks we arent using any args
patch.push('ebp')
patch.call(PyLong_FromVoidPtr)
patch.add('esp', 4)
# again, handle arguments "manually" since we need the result of the last call
# dont clean up stack this time, we will use it later when decref'ing
patch.push('eax') # ret from PyLong_FromVoidPtr
patch.call(PyTuple_Pack, 1)
# as above
patch.push('eax') # ret from PyTuple_Pack
patch.call(PyObject_CallObject, id(pyfunc))
# save return val
patch.mov('ebx', 'eax')
# decref using the non-cleaned-up result from PyTuple_Pack, clean up "manually"
patch.call(Py_DecRef)
patch.add('esp', 4)
# decref using the non-cleaned-up result from PyLong_FromVoidPtr, clean up "manually"
patch.call(Py_DecRef)
patch.add('esp', 4)
# PyGILState_Ensure retval is already on stack, use it then clean it up
patch.call(PyGILState_Release)
patch.add('esp', 4)
else:
# r12 = PyGILState_Ensure()
patch.call(PyGILState_Ensure)
patch.mov('r12', 'rax')
# r13 = PyLong_FromVoidPtr(rbp) - rbp holds esp's value after pushads
patch.mov('rcx', 'rbp')
patch.call(PyLong_FromVoidPtr)
patch.mov('r13', 'rax')
# r14 = PyTuple_Pack(1, r13)
patch.mov('rdx', 'r13') # 2nd arg (rdx) = r13 from created pylong
patch.call(PyTuple_Pack, 1)
patch.mov('r14', 'rax')
# rbx = PyObject_CallObject(pyfunc, r14)
patch.mov('rdx', 'r14') # 2nd arg (rdx) = r14 from created pytuple
patch.call(PyObject_CallObject, id(pyfunc))
patch.mov('rbx', 'rax')
# Py_DecRef(r14)
patch.mov('rcx', 'r14')
patch.call(Py_DecRef)
# Py_DecRef(r13)
patch.mov('rcx', 'r13')
patch.call(Py_DecRef)
# PyGILState_Release(r12)
patch.mov('rcx', 'r12')
patch.call(PyGILState_Release)
def make_landing(func, addr, addr_desc, landing_exit_address, return_pop=0, func_prologue=b''):
if WORDSIZE == 4:
landing_address = VirtualAlloc(None, 1024, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READ)
else:
# in 64bit we need memory nearby to allow reljmping to work
granularity = 0x100000
maxdist = 0x80000000 # max jump is 0x80000000
start = max(addr - maxdist, 0)
start -= start % granularity
end = min(addr + maxdist, 2**64 - 1)
end -= end % granularity
# start from almost maxdist above address, to somewhat minimize retries
for a in range(end - granularity, start + granularity, -granularity):
print(f' ~ Trying to allocate at 0x{a:016x}')
landing_address = VirtualAlloc(a, 1024, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READ)
if landing_address:
break
else:
raise ValueError(f'Failed to allocate memory near 0x{addr:x}')
print(f' - Created landing at 0x{landing_address:08x}')
def func_wrapper(esp):
try:
# load registers object from pushad'd registers
stackdata = memory[esp:esp + Registers.getsize()]
registers = Registers(stackdata[:Registers.getsize()], addr)
pushed_sp = registers.esp
registers.esp = esp + Registers.getsize() # actual esp at time of hook is before push of registers
# ret_from_func = struct.unpack('<' + WORDPACK, stackdata[Registers.getsize() + WORDSIZE:])[0]
force_return = False
rval = func(registers)
if rval is not False and rval is not None:
if not isinstance(rval, int):
raise ValueError(f'Invalid return type/value for c function: {type(rval)} {rval}')
force_return = True
registers.eax = rval
# we can't actually modify esp (yet?) because it would break the popping of the next registers
registers.esp = pushed_sp
memory[esp:esp + Registers.getsize()] = registers.pack()
except Exception as e:
print(f'[!] Got exception running hook {func} for {addr_desc} (0x{addr:08x}): {e}')
traceback.print_exc()
print(f'[!] Hooked code will be run now with no register writeback')
force_return = False
# If the function returns an int, then return immediatly from where we are in asm (hopefully just called a function),
# using this as the return value. See the conditional in the generated landing code
# Let's hope the user set return_pop correctly for the calling convention...
return force_return
_dontgc.append(func_wrapper)
print(f' - Writing function hook landing bytecode to run {func} (0x{id(func):x})')
with Patch(landing_address) as patch:
# save regs
patch.pushad()
patch.pushfd()
# ensure stack is 16byte aligned - store original sp in bp so make_patch_to_py can see pushad'd regs
patch.mov('*bp', '*sp')
if WORDSIZE == 8:
patch.bytecode += b'\x48\x83\xE4\xF0' # and rsp, -16
make_patch_to_py(patch, func_wrapper)
# If func_wrapper returned True (compare to _Py_TrueStruct aka id(True)), restore registers but then ret immediatly
patch.bytecode += REX1 + b'\xb8' + struct.pack('<' + WORDPACK, id(True)) # mov *ax, _Py_TrueStruct
patch.bytecode += REX1 + b'\x3b\xc3' # cmp *ax, *bx
if return_pop and WORDSIZE == 4:
patch.jne(5)
patch.popfd()
patch.popad()
patch.bytecode += b'\xc2' + struct.pack('<H', return_pop)
else:
patch.jne(26 if WORDSIZE == 8 else 3)
patch.popfd()
patch.popad()
patch.ret()
# Otherwise restore registers then run original function
patch.popfd()
patch.popad()
# record where the original (lifted) code starts on the function
func.original_code_start = patch.cursor
# run prologue that got overwritten
patch.bytecode += func_prologue
# jmp landing_exit_address
patch.bytecode += b'\xe9' + struct.pack('<i', landing_exit_address - (patch.cursor + 5))
patch.int8()
return landing_address
def resolve_addr(address_desc):
if isinstance(address_desc, int):
return address_desc
elif '+' in address_desc:
module, offset = address_desc.split('+')
if offset.startswith('0x'):
offset = int(offset[2:], 16)
else:
offset = int(offset)
return modules[module].lpBaseOfDll + offset
else:
raise ValueError('Don\'t know how to support address description %r' % address_desc)
def insert_hook(addr_desc, func, position_independent_bytes=None, return_pop=0):