-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWin32Hooking.py
More file actions
1900 lines (1560 loc) · 55.8 KB
/
Win32Hooking.py
File metadata and controls
1900 lines (1560 loc) · 55.8 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
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
###################
# This module hooks IAT and EAT to monitor all external functions calls,
# very useful for [malware] reverse and debugging.
# Copyright (C) 2025 Win32Hooking
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
###################
"""
This module hooks IAT and EAT to monitor all external functions calls,
very useful for [malware] reverse and debugging.
"""
__version__ = "1.2.0"
__author__ = "Maurice Lambert"
__author_email__ = "mauricelambert434@gmail.com"
__maintainer__ = "Maurice Lambert"
__maintainer_email__ = "mauricelambert434@gmail.com"
__description__ = """
This module hooks IAT and EAT to monitor all external functions calls,
very useful for [malware] reverse and debugging.
"""
__url__ = "https://github.com/mauricelambert/Win32Hooking"
# __all__ = []
__license__ = "GPL-3.0 License"
__copyright__ = """
Win32Hooking Copyright (C) 2025 Maurice Lambert
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions.
"""
copyright = __copyright__
license = __license__
print(copyright)
from ctypes import (
windll,
WinError,
Structure,
CFUNCTYPE,
POINTER,
memmove,
cast,
byref,
addressof,
sizeof,
get_last_error,
string_at,
c_size_t,
c_void_p,
c_byte,
c_char,
c_int,
c_uint8,
c_uint16,
c_ushort,
c_uint32,
c_ulong,
c_uint64,
c_ulonglong,
c_char_p,
c_wchar_p,
c_bool,
)
from PyPeLoader import (
IMAGE_DOS_HEADER,
IMAGE_NT_HEADERS,
IMAGE_FILE_HEADER,
IMAGE_OPTIONAL_HEADER64,
IMAGE_OPTIONAL_HEADER32,
ImportFunction,
PeHeaders,
load_headers,
load_in_memory,
get_imports,
load_relocations,
)
from ctypes.wintypes import (
DWORD,
HMODULE,
MAX_PATH,
HANDLE,
BOOL,
LPCWSTR,
LPVOID,
)
from typing import Iterator, Callable, Dict, Union, List, Tuple, Set, Iterable
from logging import StreamHandler, DEBUG, FileHandler, Logger
from PythonToolsKit.Logs import get_custom_logger
from sys import argv, executable, exit, stderr
from threading import get_native_id, Lock
from dataclasses import dataclass, field
from os.path import basename, splitext
from json import load as json_load
from _io import _BufferedIOBase
from re import fullmatch
from os import getpid
PAGE_EXECUTE_READWRITE = 0x40
PAGE_EXECUTE_READ = 0x20
PAGE_READONLY = 0x02
PAGE_READWRITE = 0x04
MEM_COMMIT = 0x1000
MEM_RESERVE = 0x2000
MEM_FREE = 0x10000
IMAGE_DIRECTORY_ENTRY_EXPORT = 0
TH32CS_SNAPMODULE = 0x00000008
class CallbackManager:
lock: Lock = Lock()
thread_id: int = 0
indent: int = 0
config: dict = {}
run: bool = -1
class UNICODE_STRING(Structure):
"""
This class implements the Unicode String for
LdrLoadDll argument value.
"""
_fields_ = [
("Length", c_ushort),
("MaximumLength", c_ushort),
("Buffer", c_wchar_p),
]
class MODULEENTRY32(Structure):
"""
This class implements the Module Entry for
CreateToolhelp32Snapshot return value.
"""
_fields_ = [
("dwSize", DWORD),
("th32ModuleID", DWORD),
("th32ProcessID", DWORD),
("GlblcntUsage", DWORD),
("ProccntUsage", DWORD),
("modBaseAddr", POINTER(c_byte)),
("modBaseSize", DWORD),
("hModule", HMODULE),
("szModule", c_char * 256),
("szExePath", c_char * MAX_PATH),
]
class IMAGE_EXPORT_DIRECTORY(Structure):
"""
This class implements the image export directory
to access export functions.
"""
_fields_ = [
("Characteristics", c_uint32),
("TimeDateStamp", c_uint32),
("MajorVersion", c_uint16),
("MinorVersion", c_uint16),
("Name", c_uint32),
("Base", c_uint32),
("NumberOfFunctions", c_uint32),
("NumberOfNames", c_uint32),
("AddressOfFunctions", c_uint32), # RVA to DWORD array
("AddressOfNames", c_uint32), # RVA to RVA array (function names)
("AddressOfNameOrdinals", c_uint32), # RVA to WORD array
]
class MEMORY_BASIC_INFORMATION(Structure):
"""
This class implements the structure to get memory information.
"""
_fields_ = [
("BaseAddress", c_void_p),
("AllocationBase", c_void_p),
("AllocationProtect", DWORD),
("RegionSize", c_size_t),
("State", DWORD),
("Protect", DWORD),
("Type", DWORD),
]
X86_CONTEXT_i386 = 0x00010000
X86_CONTEXT_CONTROL = 0x00000001
X86_CONTEXT_INTEGER = 0x00000002
X86_CONTEXT_FULL = X86_CONTEXT_CONTROL | X86_CONTEXT_INTEGER | X86_CONTEXT_i386
class FLOATING_SAVE_AREA(Structure):
_fields_ = [
("ControlWord", c_uint32),
("StatusWord", c_uint32),
("TagWord", c_uint32),
("ErrorOffset", c_uint32),
("ErrorSelector", c_uint32),
("DataOffset", c_uint32),
("DataSelector", c_uint32),
("RegisterArea", c_byte * 80),
("Cr0NpxState", c_uint32),
]
class CONTEXT32(Structure):
_fields_ = [
("ContextFlags", c_uint32),
("Dr0", c_uint32),
("Dr1", c_uint32),
("Dr2", c_uint32),
("Dr3", c_uint32),
("Dr6", c_uint32),
("Dr7", c_uint32),
("FloatSave", FLOATING_SAVE_AREA),
("SegGs", c_uint32),
("SegFs", c_uint32),
("SegEs", c_uint32),
("SegDs", c_uint32),
("Edi", c_uint32),
("Esi", c_uint32),
("Ebx", c_uint32),
("Edx", c_uint32),
("Ecx", c_uint32),
("Eax", c_uint32),
("Ebp", c_uint32),
("Eip", c_uint32),
("SegCs", c_uint32),
("EFlags", c_uint32),
("Esp", c_uint32),
("SegSs", c_uint32),
("ExtendedRegisters", c_byte * 512),
]
X64_CONTEXT_CONTROL = 0x00100001
X64_CONTEXT_INTEGER = 0x00010000
X64_CONTEXT_FULL = X64_CONTEXT_CONTROL | X64_CONTEXT_INTEGER
is_x64: bool = sizeof(c_void_p) == 8
class CONTEXT64(Structure):
"""
This class is the ThreadContext structure for NtCreateThread.
"""
_fields_ = [
("P1Home", c_ulonglong),
("P2Home", c_ulonglong),
("P3Home", c_ulonglong),
("P4Home", c_ulonglong),
("P5Home", c_ulonglong),
("P6Home", c_ulonglong),
("ContextFlags", c_ulong),
("MxCsr", c_ulong),
("SegCs", c_ushort),
("SegDs", c_ushort),
("SegEs", c_ushort),
("SegFs", c_ushort),
("SegGs", c_ushort),
("SegSs", c_ushort),
("EFlags", c_ulong),
("Dr0", c_ulonglong),
("Dr1", c_ulonglong),
("Dr2", c_ulonglong),
("Dr3", c_ulonglong),
("Dr6", c_ulonglong),
("Dr7", c_ulonglong),
("Rax", c_ulonglong),
("Rcx", c_ulonglong),
("Rdx", c_ulonglong),
("Rbx", c_ulonglong),
("Rsp", c_ulonglong),
("Rbp", c_ulonglong),
("Rsi", c_ulonglong),
("Rdi", c_ulonglong),
("R8", c_ulonglong),
("R9", c_ulonglong),
("R10", c_ulonglong),
("R11", c_ulonglong),
("R12", c_ulonglong),
("R13", c_ulonglong),
("R14", c_ulonglong),
("R15", c_ulonglong),
("Rip", c_ulonglong),
]
@dataclass
class Function:
module: MODULEENTRY32
module_name: str
name: str
address: int
rva: int
export_address: int
index: int
ordinal: int
pointer: type = None
hook: Callable = None
hook_rva: int = None
arguments: List[str] = None
hide: bool = False
count_call: int = 0
calls: List[Dict[str, Union[int, Callable]]] = field(default_factory=list)
class Callbacks:
"""
This class contains all callbacks define in configuration.
"""
thread_ids_to_unhook_NtAllocateVirtualMemory: Set[int] = set()
def kernelbase_VirtualAlloc_pre(
type_: str,
function: Union[Function, ImportFunction],
arguments: Tuple,
) -> Tuple:
"""
This function is a callback executed before the VirtualAlloc
execution to unhook NtAllocateVirtualMemory on a new thread creation.
"""
if get_native_id() not in Callbacks.thread_ids_to_unhook_NtAllocateVirtualMemory:
return arguments
unhook_IAT("ntdll.dll", "NtAllocateVirtualMemory", "KERNELBASE.dll")
unhook_EAT("ntdll.dll", "NtAllocateVirtualMemory")
return arguments
def kernelbase_VirtualAlloc_post(
type_: str,
function: Union[Function, ImportFunction],
arguments: Tuple,
return_value: c_void_p,
) -> c_void_p:
"""
This function is a callback executed after the VirtualAlloc
execution to rehook NtAllocateVirtualMemory on a new thread creation.
"""
thread_id = get_native_id()
if thread_id not in Callbacks.thread_ids_to_unhook_NtAllocateVirtualMemory:
return return_value
rehook_IAT("ntdll.dll", "NtAllocateVirtualMemory", "KERNELBASE.dll")
rehook_EAT("ntdll.dll", "NtAllocateVirtualMemory")
Callbacks.thread_ids_to_unhook_NtAllocateVirtualMemory.remove(
thread_id
)
return return_value
def ntdll_NtCreateThreadEx_pre(
type_: str,
function: Union[Function, ImportFunction],
arguments: Tuple,
) -> Tuple:
"""
This function is a callback executed before the NtCreateThreadEx
execution to change the start address to initialize the new stack.
"""
callback_print(
" " * (4 * CallbackManager.indent - 1),
"original call ",
function.module_name,
function.name + ":",
*(
[
(
f"{x} = {arguments[i]} ({arguments[i]:x})"
if isinstance(arguments[i], int)
else f"{x} = {arguments[i]}"
)
for i, x in enumerate(function.arguments)
]
if function.arguments
else []
),
)
arguments = (
arguments[0],
arguments[1],
arguments[2],
arguments[3],
get_thread_hook(arguments[4]),
arguments[5],
arguments[6],
arguments[7],
arguments[8],
arguments[9],
arguments[10],
)
callback_print(
" " * (4 * CallbackManager.indent - 1),
"modified call ",
function.module_name,
function.name + ":",
*(
[
(
f"{x} = {arguments[i]} ({arguments[i]:x})"
if isinstance(arguments[i], int)
else f"{x} = {arguments[i]}"
)
for i, x in enumerate(function.arguments)
]
if function.arguments
else []
),
)
unhook_IAT("ntdll.dll", "NtAllocateVirtualMemory", "KERNELBASE.dll")
unhook_IAT("ntdll.dll", "NtQueryVirtualMemory", "KERNELBASE.dll")
unhook_IAT("KERNELBASE.DLL", "VirtualAlloc", "KERNEL32.DLL")
return arguments
def ntdll_NtCreateThread_post(
type_: str,
function: Union[Function, ImportFunction],
arguments: Tuple,
return_value: c_void_p,
) -> c_void_p:
"""
This function rebuild the hook for ntdll.dll NtAllocateVirtualMemory
in KERNELBASE.dll IAT and ntdll.dll EAT.
"""
rehook_IAT("ntdll.dll", "NtAllocateVirtualMemory", "KERNELBASE.dll")
rehook_IAT("ntdll.dll", "NtQueryVirtualMemory", "KERNELBASE.dll")
rehook_IAT("KERNELBASE.DLL", "VirtualAlloc", "KERNEL32.DLL")
thread_handle = cast(POINTER(HANDLE), arguments[0]).contents.value
thread_id = GetThreadId(thread_handle)
Callbacks.thread_ids_to_unhook_NtAllocateVirtualMemory.add(thread_id)
return return_value
def shell32_ShellExecuteA_pre(
type_: str,
function: Union[Function, ImportFunction],
arguments: Tuple,
) -> Tuple:
"""
This function is a callback executed before the NtCreateThreadEx
execution to change the start address to initialize the new stack.
"""
unhook_IAT("ntdll.dll", "LdrLoadDll", "KERNELBASE.dll")
unhook_IAT("ntdll.dll", "LdrLoadDll", "KERNEL32.DLL")
unhook_EAT("ntdll.dll", "LdrLoadDll")
return arguments
def shell32_ShellExecuteA_post(
type_: str,
function: Union[Function, ImportFunction],
arguments: Tuple,
return_value: c_void_p,
) -> c_void_p:
"""
This function rebuild the hook for ntdll.dll NtAllocateVirtualMemory
in KERNELBASE.dll IAT and ntdll.dll EAT.
"""
rehook_IAT("ntdll.dll", "LdrLoadDll", "KERNELBASE.dll")
rehook_IAT("ntdll.dll", "LdrLoadDll", "KERNEL32.DLL")
rehook_EAT("ntdll.dll", "LdrLoadDll")
return return_value
def ntdll_NtCreateThread_pre(
type_: str,
function: Union[Function, ImportFunction],
arguments: Tuple,
) -> Tuple:
"""
This function is a callback executed before the NtCreateThread
execution to change the start address to initialize the new stack.
"""
if is_x64:
context = CONTEXT64()
size = sizeof(CONTEXT64)
else:
context = CONTEXT32()
size = sizeof(CONTEXT32)
memmove(addressof(context), arguments[5], size)
if is_x64:
context.Rip = get_thread_hook(context.Rip)
else:
context.Eip = new_ip
memmove(arguments[5], addressof(context), size)
return arguments
def breakpoint(
type_: str,
function: Union[Function, ImportFunction],
arguments: Tuple,
return_value: c_void_p,
) -> c_void_p:
"""
This function is a simple breakpoint to block the execution and analyze
arguments and returns values.
"""
breakpoint()
return return_value
def kernelbase_GetWindowsDirectoryW(
type_: str,
function: Union[Function, ImportFunction],
arguments: Tuple,
return_value: c_void_p,
) -> c_void_p:
"""
This function defines the GetWindowsDirectoryW hooking behavior.
"""
if return_value:
print(
" " * (4 * (CallbackManager.indent + 1)),
"GetWindowsDirectoryW: [OUT] Path =",
c_wchar_p(arguments[0]).value + ",",
"[IN] Size =",
arguments[1],
"[OUT] Number of bytes written =",
return_value,
)
return return_value
def kernelbase_GetModuleHandleExW(
type_: str,
function: Union[Function, ImportFunction],
arguments: Tuple,
return_value: c_void_p,
) -> c_void_p:
"""
This function defines the GetModuleHandleExW hooking behavior.
"""
if arguments[0] != 4:
print(
" " * (4 * (CallbackManager.indent + 1)),
"GetModuleHandleExW:",
"[IN] Flags =",
hex(arguments[0]) + ",",
"[IN] Module Name =",
c_wchar_p(arguments[1]).value,
"[OUT] Module Handle =",
hex(arguments[2] if arguments[2] else 0) + ",",
"[OUT] Success =",
bool(return_value),
)
return return_value
def kernelbase_GetModuleFileNameW(
type_: str,
function: Union[Function, ImportFunction],
arguments: Tuple,
return_value: c_void_p,
) -> c_void_p:
"""
This function defines the GetModuleFileNameW hooking behavior.
"""
if return_value:
print(
" " * (4 * (CallbackManager.indent + 1)),
"GetModuleFileNameW:",
"[IN] Module Handle =",
hex(arguments[0] if arguments[0] else 0) + ",",
"[OUT] Filename =",
c_wchar_p(arguments[1]).value,
"[IN] Size =",
str(arguments[2]) + ",",
"[OUT] Number of bytes written =",
return_value,
)
return return_value
def ntdll_ApiSetQueryApiSetPresence(
type_: str,
function: Union[Function, ImportFunction],
arguments: Tuple,
return_value: c_void_p,
) -> c_void_p:
"""
This function defines the ApiSetQueryApiSetPresence hooking behavior.
"""
namespace = cast(arguments[0], POINTER(UNICODE_STRING)).contents
present = cast(arguments[1], POINTER(c_bool)).contents.value
print(
" " * (4 * (CallbackManager.indent + 1)),
"ApiSetQueryApiSetPresence: [IN] Namespace =",
repr(namespace.Buffer) + ",",
"[OUT] Present =",
str(present) + ',',
'[OUT] Return =',
str(return_value)
)
return return_value
def ntdll_LdrLoadDll(
type_: str,
function: Union[Function, ImportFunction],
arguments: Tuple,
return_value: c_void_p,
) -> c_void_p:
"""
This function defines the LdrLoadDll hooking behavior.
"""
unicode_string = cast(arguments[2], POINTER(UNICODE_STRING)).contents
module_handle = cast(arguments[3], POINTER(c_uint64)).contents.value
dos_headers = cast(module_handle, POINTER(IMAGE_DOS_HEADER)).contents
nt_position = module_handle + dos_headers.e_lfanew
nt_headers = cast(nt_position, POINTER(IMAGE_NT_HEADERS)).contents
file_header = nt_headers.FileHeader
if file_header.Machine == 0x014C: # IMAGE_FILE_MACHINE_I386
optional_header = nt_headers.OptionalHeader
arch = 32
elif file_header.Machine == 0x8664: # IMAGE_FILE_MACHINE_AMD64
optional_header_position = (
nt_position
+ sizeof(IMAGE_NT_HEADERS)
- sizeof(IMAGE_OPTIONAL_HEADER32)
)
optional_header = cast(
optional_header_position, POINTER(IMAGE_OPTIONAL_HEADER64)
).contents
arch = 64
module = MODULEENTRY32(
sizeof(MODULEENTRY32),
1,
getpid(),
0,
1,
cast(module_handle, POINTER(c_byte)),
optional_header.SizeOfImage,
module_handle,
unicode_string.Buffer.encode("latin-1").ljust(256, b"\0"),
b"\0" * MAX_PATH,
)
if module_handle not in modules:
imports = []
exports, forwarded = hooks_DLL(module, Hooks.export_hooks, imports)
for function in imports:
hooks = Hooks.ordinal_hooks if isinstance(function.name, int) else Hooks.name_hooks
export_function = hooks.get(function.module_name + "|" + str(function.name))
if export_function:
function.address = export_function.address
hooks_IAT(imports, False)
write_EAT_hooks(exports)
hooks_forwarded(forwarded)
print(
" " * (4 * (CallbackManager.indent + 1)),
"LdrLoadDll: [IN] Path =",
str(c_wchar_p(arguments[0])) + ",",
"[IN] Flags =",
hex(cast(arguments[1], POINTER(c_ulong)).contents.value) + ",",
"[IN] Module =",
repr(unicode_string.Buffer) + ",",
"[OUT] Handle =",
module_handle,
"(" + hex(module_handle) + ")",
)
return return_value
def kernel32_GetProcAddress(
type_: str,
function: Union[Function, ImportFunction],
arguments: Tuple,
return_value: c_void_p,
) -> c_void_p:
"""
This function defines the GetProcAddress hooking behavior.
"""
module = arguments[0]
function_name = arguments[1].decode()
identifier = str(module) + "|" + function_name
if (proc := Hooks.get_proc_address_hooks.get(identifier)) is None:
func = Hooks.export_hooks[identifier]
proc = Function(
func.module,
func.module_name,
func.name,
func.address,
func.rva,
func.export_address,
func.index,
func.ordinal,
)
build_generic_callback("GetProcAddress", proc)
Hooks.get_proc_address_hooks[identifier] = proc
proc_pointer = cast(proc.hook, c_void_p).value
callback_print(
(" " * (4 * (CallbackManager.indent + 1)))
+ f"GetProcAddress: Module = {hex(module)} ({proc.module_name})"
f", Function = {function_name}, HookAddress = {hex(proc_pointer)}"
)
logger.info("Hook " + proc.module_name + " " + proc.name)
return proc_pointer
def interactive(
type_: str,
function: Union[Function, ImportFunction],
arguments: Tuple,
return_value: c_void_p,
) -> c_void_p:
"""
This function defines interactive actions on callback.
"""
answer = None
while answer not in ("b", "c", "e"):
answer = input(
"Enter [b] for breakpoint, [c] to continue and [e] to exit: "
)
if answer == "b":
breakpoint()
elif answer == "e":
exit(1)
return return_value
def exit(
type_: str,
function: Union[Function, ImportFunction],
arguments: Tuple,
return_value: c_void_p,
) -> c_void_p:
"""
This function terminates/exits the program.
"""
function_type = CFUNCTYPE(c_void_p, c_int)
function = function_type(
Hooks.name_hooks["KERNEL32.DLL|ExitProcess"].address
)
return function(0)
def print(
type_: str,
function: Union[Function, ImportFunction],
arguments: Tuple,
return_value: c_void_p,
) -> c_void_p:
"""
This function prints function, return value and arguments,
it's a simple demo.
"""
print(type_, function.module, function.name, arguments, return_value)
return return_value
class Hooks:
"""
This class contains all data about hooks.
"""
get_proc_address_hooks: Dict[str, Function] = {}
reserved_hooks_space: Dict[str, int] = {}
export_hooks: Dict[str, Function] = {}
import_hooks: Dict[str, ImportFunction] = {}
name_hooks: Dict[str, Function] = {}
ordinal_hooks: Dict[str, Function] = {}
types: Dict[str, CFUNCTYPE] = {}
threads_stack_alloc: Dict[int, int] = {}
start_hooking: bool = False
def rehook_IAT(module_name: str, function_name: str, imported_by: str) -> None:
'''
This function re-hooks a specific IAT function (hook after unhooking).
'''
function = Hooks.import_hooks[
str(addressof(
modules[module_name.upper().encode()].modBaseAddr.contents
)) + f"|{function_name}|{imported_by.upper()}"
]
write_in_memory(
function.import_address,
cast(function.hook, c_void_p).value.to_bytes(sizeof(c_void_p), byteorder="little"),
)
def rehook_EAT(module_name: str, function_name: str) -> None:
'''
This function re-hooks a specific EAT function (hook after unhooking).
'''
function = Hooks.name_hooks[
module_name.upper() + "|" + function_name
]
write_in_memory(
function.export_address,
function.hook_rva.to_bytes(4, byteorder="little"),
)
def unhook_IAT(module_name: str, function_name: str, imported_by: str) -> None:
'''
This function unhooks a specific IAT function.
'''
function = Hooks.import_hooks[
str(addressof(
modules[module_name.upper().encode()].modBaseAddr.contents
)) +
f"|{function_name}|{imported_by.upper()}"
]
write_in_memory(
function.import_address,
function.address.to_bytes(sizeof(c_void_p), byteorder="little"),
)
def unhook_EAT(module_name: str, function_name: str) -> None:
'''
This function unhooks a specific EAT function.
'''
function = Hooks.name_hooks[
module_name.upper() + "|" + function_name
]
write_in_memory(
function.export_address,
function.rva.to_bytes(4, byteorder="little"),
)
def resolve_type(module_type: str) -> type:
"""
This function returns a type from python module.
"""
modules, type_ = module_type.rsplit(".", 1)
module = __import__(modules)
for element in modules.split(".")[1:]:
module = getattr(module, element)
return getattr(module, type_)
def get_callback_type(
arguments: Union[None, List[Dict[str, str]]],
return_value: Union[str, None],
) -> CFUNCTYPE:
"""
This function builds and returns the callback CFUNCTYPE.
"""
if arguments is None and return_value is None:
return generic_callback
if return_value is None:
return_value = c_void_p
else:
return_value = resolve_type(return_value)
if arguments is None:
arguments_ = [c_void_p] * 67
else:
arguments_ = []
for argument in arguments:
arguments_.append(resolve_type(argument["type"]))
return CFUNCTYPE(return_value, *arguments_)
generic_callback = CFUNCTYPE(c_void_p, *([c_void_p] * 67))
kernel32 = windll.kernel32
CreateToolhelp32Snapshot = kernel32.CreateToolhelp32Snapshot
CreateToolhelp32Snapshot.argtypes = [DWORD, DWORD]
CreateToolhelp32Snapshot.restype = HANDLE
Module32First = kernel32.Module32First
Module32First.argtypes = [HANDLE, POINTER(MODULEENTRY32)]
Module32First.restype = BOOL
Module32Next = kernel32.Module32Next
Module32Next.argtypes = [HANDLE, POINTER(MODULEENTRY32)]
Module32Next.restype = BOOL
CloseHandle = kernel32.CloseHandle
VirtualProtect = kernel32.VirtualProtect
VirtualProtect.argtypes = [c_void_p, c_size_t, DWORD, POINTER(DWORD)]
VirtualProtect.restype = BOOL
VirtualAlloc = kernel32.VirtualAlloc
VirtualAlloc.argtypes = [c_void_p, c_size_t, DWORD, DWORD]
VirtualAlloc.restype = LPVOID
GetModuleHandleW = kernel32.GetModuleHandleW
GetModuleHandleW.argtypes = [LPCWSTR]
GetModuleHandleW.restype = HMODULE
LoadLibraryW = kernel32.LoadLibraryW
LoadLibraryW.argtypes = [LPCWSTR]
LoadLibraryW.restype = HMODULE
GetProcAddress = kernel32.GetProcAddress
GetProcAddress.argtypes = [HMODULE, c_char_p]
GetProcAddress.restype = c_void_p
GetThreadId = kernel32.GetThreadId
GetModuleHandleW.argtypes = [HANDLE]
GetModuleHandleW.restype = DWORD
modules: Dict[Union[int, str], MODULEENTRY32] = {}
def get_logger(name: str) -> Logger:
"""
This function gets a specific logger and modify
the handler but keep the formatter.
"""
logger = get_custom_logger(name)
file_handler = FileHandler(name + ".log")
logger.addHandler(file_handler)
logger.setLevel(DEBUG)
for handler in logger.handlers:
if isinstance(handler, StreamHandler):
file_handler.setFormatter(handler.formatter)
logger.removeHandler(handler)
return logger
logger = get_logger(splitext(basename(__file__))[0])
callback_logger = get_logger("callback")
def init_lock() -> bool:
"""
This function manages concurrency for callbacks.
"""
thread_id = get_native_id()
acquire = thread_id != CallbackManager.thread_id
if acquire:
CallbackManager.lock.acquire()
CallbackManager.thread_id = thread_id
return acquire
def reset_lock(acquire: bool) -> None:
"""
This function releases locker and resets elements for concurrency.
"""
if acquire:
CallbackManager.indent = 0
CallbackManager.thread_id = None
CallbackManager.lock.release()