-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction_tracer.py
More file actions
2807 lines (2134 loc) · 107 KB
/
Copy pathfunction_tracer.py
File metadata and controls
2807 lines (2134 loc) · 107 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
#!/bin/env python
"""
A Windows x64 function call tracer using WinAppDbg, Keystone, and a helper DLL (calltracer.dll).
This script can start or attach to a target process, inject a DLL, and hook functions listed
in the PE's .pdata (runtime function table). It also patches CALL instructions to trace
inter-function calls, printing a readable call/return log similar to:
enter: draw_cubedx11_19
call: nr_1 draw_cubedx11_31 from draw_cubedx11_19
enter: draw_cubedx11_31
exit: draw_cubedx11_31
called: nr_1 from draw_cubedx11_19
...
Functionality is intentionally preserved from the original version; this revision adds:
- Typing annotations
- Docstrings
- Clearer comments
- Spelling fixes in identifiers, strings, and comments
Requirements:
pip install pefile
pip install keystone-engine
pip install capstone==6.0.0a4
pip install pdbparse
Note: Run on Windows.
"""
# function_tracer.py notepad++.exe | "C:\Program Files\Git\usr\bin\tee.exe" test.txt
import sys
import ctypes
import ctypes.wintypes as wintypes
import pefile
import os
import json
import time
import struct
from functools import partial
from keystone import Ks, KS_ARCH_X86, KS_MODE_64, KsError
from typing import Dict, List, Tuple, Optional, Callable, Any
import traceback
import hook_lib
import locale
import bisect
import hashlib
import argparse
import re
_strip_semicolon_comments = re.compile(r'[ \t]*;[^\r\n]*')
import cProfile, pstats, io
pr = cProfile.Profile()
pr.enable()
# -----------------------------
# Globals / State
# -----------------------------
# External breakpoints mapped by address to callback
external_breakpoints: Dict[int, Callable[[Any], None]] = {}
# Loaded module base addresses by basename (e.g., "kernel32")
loaded_modules: Dict[str, int] = {}
# Exported functions from calltracer.dll resolved to absolute addresses
call_tracer_dll_func: Dict[str, int] = {}
call_tracer_thunk_func = {}
call_tracer_thunk_func_ptr = {}
# Per-thread replacement return addresses for MinHook trampolines
# Structure: ret_replacements[tid][jump_table_addr] = [return_addr_stack]
ret_replacements: Dict[int, Dict[int, List[int]]] = {}
# Queue of (assembly_str, callback) to inject and execute
asm_code_to_run: List[Tuple[str, Optional[Callable[[Any], None]]]] = []
# Control flags / addresses
in_loading_phase: bool = True
is_in_injected_code: bool = False
code_injection_address: Optional[int] = None
register_save_address: Optional[int] = None
shell_code_address: Optional[int] = None
shell_code_address_offset: int = 20 # Start at 20 arbitrarily to keep some space free.
# PE / function metadata (.pdata)
pdata: Optional[bytes] = None
pdata_functions: List[Tuple[int, int, int, int]] = []
pdata_index = None
pdata_function_ids: Dict[int, str] = {}
exe_entry_address: int = 0
disassembled_functions = {}
asembly_cache = {}
function_data = {}
# Simple call stack for pretty printing
call_stack: List[str] = []
# Functions (addresses) we plan to hook via MinHook (in calltracer.dll)
# Each entry: (target_fn_addr, enter_callback, exit_callback)
functions_to_hook: List[Tuple[int, Callable[[Any], None], Callable[[Any], None]]] = []
moved_instructions = {}
ref_instructions = {}
suspended = False
# Initialize Keystone for x64.
ks = Ks(KS_ARCH_X86, KS_MODE_64)
jump_breakpoints = []
jump_writes = []
#Thread Storage
thread_storage_list_address = None
thread_storage_list_addresses = {}
single_tracing_address = None
threads_to_setup = []
area_for_function_table = None
area_for_return_addr_linked_list = 3*8* 100000#this is how deap the recursion can be traced
area_for_tracing_results = 8*10000000
area_for_xsave64 = 12228 #we give xsave 8192 12228 to save its data
nr_of_prepared_alocations = 10
spawned = False
call_trace_dll_ready = False
load_dll_tid = -1
jumps = {}
calls = {}
jumps_index = []
calls_index = []
classfied_extra_functions = []
max_thread_ids = 30000
os.makedirs('output', exist_ok=True)
os.makedirs('cache', exist_ok=True)
out_file = None
call_map = []
functions_end = {}
exe_basic_name = None
exe_name = None
forbid_break_point_jumps = False # if set to try break point jumps are not used (meaning some functions that need them wont be traced)
use_calls_for_patching = False #Replaces jumps with calls. Slower than jumps as the return address needs to be captured, saved then restored. Using a jump techic uses 2 instructions using calls uses about 150 instructions and multiple memmory writes and reads
redirect_return = True
respect_prolog_size = False #If we wont replace any instructions after the said prolog size
forbid_entry_tracing = False #does not add any tracing code just injects. For use in testing when program craches
trace_calls = True
only_trace_unknown_calls = True #Only trace dynamic calls, calles which target is not hard coded in memory
use_single_tracing = True #Disables the tracepoint after it is hit the first time, usefull to redece the amount of tracing data together with only_trace_unknown_calls when maping dynamic calls.
use_single_tracing_entry = False #same as use_single_tracing but for entry and exit
only_replace_single_instruction_init = False # Only replace the first instruciton in the function init
only_allow_single_instruction_replacements = False # When tracing calls only allow one instruction replacement, leads to many uses of break point jumps whereever a 5 byte jump wont fit (breakpoint jumps are SLOW) ONLY applies to call replacements not INIT replacements.
exclude_call_tracing_in_force_truncated_functions = True # if a function has been truncated (cause it contains data) dont trace calls
force_all_detours = False #if you want to force detorring when if there was no need (for debuging)
if forbid_entry_tracing and redirect_return:
raise ValueError("cant forbid forbid_entry_tracing when also redirecting return")
call_exclusions = [
#(2666, 0),
]
enter_exclusions = [
]
rsp_ofset = 128
function_exclusions = []
# -----------------------------
# Helpers
# -----------------------------
def start_or_attach(argv: List[str]) -> None:
"""Start or attach to the given executable.
"""
global spawned, exe_basic_name, out_file, exe_name, asembly_cache, suspended
pid = None
p = argparse.ArgumentParser(description="Run a for-loop over each line of a file.")
p.add_argument("executable", help="pid or executable")
p.add_argument("--pause_on_load", action="store_true", help="Wait for the proces to start and load kernel32.dll then pauses it")
p.add_argument("--find_upacking_region", action="store_true", help="Use together with --pause_on_load to find what regions are unpacked")
p.add_argument("--wait_for_unpack", help="Wait until executable is unpacked using data from find_upacking_region, format intaddress:hexbyte use together with --pause_on_load")
p.add_argument("--only_analyse", action="store_true", help="Only does executable analysis")
p.add_argument("--exclude_functions", default="utf-8", help="json file with function ordinals to exclude")
p.add_argument("--memory_scan", type=int, default=None, nargs="?", const=-1, help="scans the executable periodicly for changes in executable code. Changes like hooks and unpacking.")
args = p.parse_args()
arg1 = args.executable
if arg1.isdigit():
pid = int(arg1)
else:
exe = arg1
# Try to expand to absolute path if provided
exe_path = exe
if os.path.isabs(exe):
exe_path = exe
else:
# leave as name (we will match by basename)
exe_path = exe
if args.pause_on_load:
print("searching for launch of:", exe)
while True:
pids = hook_lib.get_pids_by_name(exe)
if len(pids) >= 1:
pid = pids[0]
break
else:
# 1) find running PIDs
pids = hook_lib.get_pids_by_name(exe_path)
if pids:
if len(pids) > 1:
print(f"Found {len(pids)} running process(es) named '{os.path.basename(exe_path)}': {pids} selecting first pid")
pid = pids[0]
else:
print(f"No running process named '{os.path.basename(exe_path)}' found. Attempting to start it...")
pid = hook_lib.try_start_executable(exe_path)
spawned = True
handle = hook_lib.get_handle(pid)
executable_path = hook_lib.get_process_image_path(handle)
has_loaded_dll = False
print("waiting for kernel32")
mods = wait_for_kernel32(handle)
# if we just spawned the process we suspend it now that kernel32 is loaded to try to catch as much of the activity as posible
# some activity might still get lost as the way we probe for kernel32 is async but doing it syncronysly would be much more complicated
if spawned or args.pause_on_load:
print("suspending process as it has just loaded")
suspended = True
res = hook_lib.NtSuspendProcess(handle)
exe_basic_name = get_base_name(executable_path)
exe_name = executable_path.split("\\")[-1].lower()
out_file = os.path.abspath('output'+os.sep+exe_basic_name+'.trace')
if os.path.exists(out_file):
os.remove(out_file)
base_addr = mods[exe_name]['base']
assembled_cache_file = "cache\\" + exe_basic_name + "_asembly_cache.json"
if os.path.exists(assembled_cache_file) and time.time() - os.path.getmtime(assembled_cache_file) < 12 * 3600:
with open(assembled_cache_file, "r") as f:
asembly_cache = json.load(f)
for key in asembly_cache:
asembly_cache[key] = bytes.fromhex(asembly_cache[key])
print("get pdata")
get_pdata(executable_path, base_addr, exe_basic_name)
start_addr = 9999999999999999999
end_addr = 0
for function_start_addr, function_end_addr, flags, pdata_ordinal, prolog_size in pdata_functions:
start_addr = min(function_start_addr, start_addr)
end_addr = max(function_end_addr, end_addr)
func_len = function_end_addr - function_start_addr
data_len = end_addr - start_addr
lookup_calltrace_exports()
if args.wait_for_unpack:
num_str, byte_str = args.wait_for_unpack.split(":")
address_of_byte = start_addr + int(num_str)
packed_byte = bytes([int(byte_str, 16)])
mem_dat = hook_lib.read(handle, address_of_byte, 1)
if packed_byte != mem_dat:
raise Exception("TO slow")
if suspended:
print("resuming process while it unpacks")
hook_lib.NtResumeProcess(handle)
suspended = False
while True:
mem_dat = hook_lib.read(handle, address_of_byte, 1)
if packed_byte != mem_dat:
hook_lib.NtSuspendProcess(handle)
print("suspended process as it has now unpacked")
suspended = True
break
#the executable should be suspended and unpacked now
if args.find_upacking_region:
#read packed data
packed_data = hook_lib.read(handle, start_addr, data_len)
if suspended:
print("resuming process")
hook_lib.NtResumeProcess(handle)
suspended = False
#save packed data to cache for later consumtion
#packed_data_file = "cache\\" + exe_basic_name + "_packed_data.bin"
#with open(packed_data_file, "wb") as f:
# f.write(packed_data)
input("press enter when executable has unpacked and loaded completly")
unpacked_data = hook_lib.read(handle, start_addr, data_len)
#save packed data to cache for later consumtion
#unpacked_data_file = "cache\\" + exe_basic_name + "_unpacked_data.bin"
#with open(unpacked_data_file, "wb") as f:
# f.write(unpacked_data)
last_non_matching_byte = None
for i in range(data_len-1, -1, -1):
if packed_data[i] != unpacked_data[i]:
last_non_matching_byte = i
break
if last_non_matching_byte is not None:
org_dat = bytes([packed_data[last_non_matching_byte]]).hex()
desc = str(last_non_matching_byte)+":"+org_dat
print("last_non_matching_byte:", desc)
else:
print("no differance after unpack")
exit()
if args.exclude_functions:
if os.path.exists(args.exclude_functions):
with open(args.exclude_functions, "r") as f:
loaded_json = json.load(f)
for index in loaded_json:
func_ordinal = int(index)
function_exclusions.append(func_ordinal)
#func = get_function_containing(func_addr)
#if func is None:
# print("no function at address:", func_addr)
#else:
# function_exclusions.append(func[3])
if args.memory_scan is not None:
map_file = "output\\"+exe_basic_name+'_map.json'
if not os.path.exists(map_file):
raise Exception("no function map found, run with --only_analyse first (wait for unpacking first if executable does unpacking)")
with open(map_file, "r") as f:
call_map = json.load(f)
function_data_cache_file = "cache\\" + exe_basic_name + "_function_data_cache.json"
if not os.path.exists(function_data_cache_file):
raise Exception("no original function data found, run with --only_analyse first (wait for unpacking first if executable does unpacking)")
with open(function_data_cache_file, "r") as f:
loaded_json = json.load(f)
for index in loaded_json:
function_data[int(index)] = bytes.fromhex(loaded_json[index])
if suspended:
print("resuming process")
hook_lib.NtResumeProcess(handle)
suspended = False
last_func_data = []
for function in call_map:
if function['unlisted']:
continue
last_func_data.append(function_data[function['function_start_addr']])
chnages_file = "output\\"+exe_basic_name+'_changed_functions.json'
changes = {}
if os.path.exists(chnages_file):
with open(chnages_file, "r") as f:
loaded_json = json.load(f)
for index in loaded_json:
changes[int(index)] = loaded_json[index]
process_is_still_running = True
nr_of_checks = 0
while process_is_still_running:
#hook_lib.NtSuspendProcess(handle)
i = 0
for function in call_map:
if function['unlisted']:
continue
#print(function)
func_len = function['function_end_addr'] - function['function_start_addr']
data = hook_lib.read(handle, function['function_start_addr'], func_len)
if (args.memory_scan == -1 and data != last_func_data[i]) or (args.memory_scan != -1 and data[args.memory_scan] != last_func_data[i][args.memory_scan]):
if function['ordinal'] not in changes:
changes[function['ordinal']] = 0
changes[function['ordinal']] += 1
print("function: " + function['function_id'] + " has changed:", changes[function['ordinal']])
last_func_data[i] = data
i += 1
#hook_lib.NtResumeProcess(handle)
print("all functions checked", nr_of_checks)
nr_of_checks += 1
with open(chnages_file, "w") as f:
json.dump(changes, f, indent=2)
time.sleep(30.0)
else:
print("analyse_executable_code")
analyse_executable_code(handle)
if not args.only_analyse and not args.memory_scan is not None:
allocate_mem(handle, exe_entry_address)
inject_trace_injection_functions(handle)
##if we are using breakpoint jumps we need to inject the dll earlier ro make sure that the vectorised exception handler is registerd
if not forbid_break_point_jumps:
print("inject dll")
inject_dll(handle)
print("hooking executable")
hook_calls(handle)
#the last thing we do is inject the calltrace dll as the process needs to be resumed for that to work
#code that needs the calltrace dll will spin untill the dll is ready
if forbid_break_point_jumps:
print("inject dll")
inject_dll(handle)
if suspended:
print("resuming process")
hook_lib.NtResumeProcess(handle)
suspended = False
if not args.only_analyse and not args.memory_scan is not None:
with open(assembled_cache_file, "w") as f:
for key in asembly_cache:
asembly_cache[key] = asembly_cache[key].hex()
json.dump(asembly_cache, f, indent=2)
s = io.StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats('cumulative')
ps.print_stats(30)
print(s.getvalue())
def memory_scan(handle):
pass
def wait_for_kernel32(handle):
mods = None
while True:
try:
mods = hook_lib.enumerate_modules(handle, do_until_sucess = True, base_name = True)
if "kernel32.dll" in mods:
return mods
except OSError as e:
pass #print("enumerate_modules faield trying again")
def get_base_name(filename: str) -> str:
"""Return lowercase filename without extension from a Windows path."""
dname = filename.split("\\")[-1]
basic_name = dname.split(".")[0].lower()
return basic_name
def make_asm_key(code: str, address: int) -> str:
"""asembling is slow so we cache the results"""
h = hashlib.blake2b(digest_size=8)
h.update(code.encode('utf-8'))
h.update(address.to_bytes(8, 'little'))
return str(h.hexdigest())
def asm(CODE: str, address: int = 0) -> bytes:
"""Assemble x64 code at the given address using Keystone."""
##due to the fact that we alocate allot of code dynamicly allot of asm gets lots of cache miseses
asm_hash = make_asm_key(CODE, address)
if asm_hash in asembly_cache:
return asembly_cache[asm_hash]
try:
encoding, count = ks.asm(CODE, address)
except KsError as e:
# e.errno is a keystone error enum, e.count is # of statements assembled
print(CODE, address)
print(f"Keystone error: {e} (errno={getattr(e, 'errno', None)}, " f"count={getattr(e, 'count', None)})")
traceback.print_stack()
exit()
byts = bytes(encoding)
asembly_cache[asm_hash] = byts
return byts
def read_ptr(handle, address: int) -> int:
"""Read an 8-byte pointer from the target process memory at address."""
data = hook_lib.read(handle, address, 8)
return struct.unpack("<Q", data)[0]
def allocate_close(process, address_close_to_code):
process_handle = process.get_handle()
size = 40
adddress_close_by = None
while adddress_close_by == None:
adddress_close_by = ctypes.windll.kernel32.VirtualAllocEx(
process_handle, ctypes.c_void_p(address_close_to_code), size, 0x3000, 0x40
)
address_close_to_code -= 4500
if adddress_close_by == None:
raise Exception("Could not allocate jump table; this can be somewhat random. Please try again.")
process.close_handle()
return adddress_close_by
def allocate_mem(process_handle, address_close_to_code: int) -> None:
"""Allocate remote memory regions."""
global register_save_address, code_injection_address, shell_code_address, thread_storage_list_address, alocated_thread_storages, single_tracing_address
print("allocating memmory")
# VirtualAllocEx signature configuration
ctypes.windll.kernel32.VirtualAllocEx.argtypes = [
wintypes.HANDLE, # hProcess
ctypes.c_void_p, # lpAddress
ctypes.c_size_t, # dwSize
wintypes.DWORD, # flAllocationType
wintypes.DWORD, # flProtect
]
nr_of_max_trace_points = 0
for call_info in call_map:
nr_of_max_trace_points += 2 #one byte for entry one for exit
for call in call_info['calls']:
nr_of_max_trace_points += 2 #one byte for call one for called
# Allocate small utility region (writable)
ctypes.windll.kernel32.VirtualAllocEx.restype = ctypes.c_ulonglong
remote_memory = ctypes.windll.kernel32.VirtualAllocEx(process_handle, None, 1000, 0x3000, 0x04)
if not remote_memory:
raise Exception(f"Failed to allocate memory in target process: {ctypes.WinError()}")
print("remote_memory:", remote_memory)
#we cant to keep the size as small as posible as relative addressing can only handle ofsets of +-2147483647
size = nr_of_max_trace_points*300 + 100000 #we do 300 bytes per tracepoint and 100000 bytes for other stuff
shell_code_address = 0
atempt = 1
while shell_code_address == 0:
# Allocate large RX region for shellcode near code
preferred_address = (address_close_to_code - size* atempt)
shell_code_address = ctypes.windll.kernel32.VirtualAllocEx(
process_handle, ctypes.c_void_p(preferred_address), size, 0x3000, 0x40
)
if shell_code_address == 0:
print("Could not allocate jump table; this can be somewhat random. Trying again.")
#if atempt > 3:
# size //=4
# size *= 3
atempt += 1
print("shell_code_address:", shell_code_address)
last_seize = size
# Allocate register-save area (writable)
register_save_address = ctypes.windll.kernel32.VirtualAllocEx(process_handle, None, 4096, 0x3000, 0x04)
if register_save_address == 0:
print(f"Failed to allocate register_save_address in target process: {ctypes.WinError()}")
sys.exit(0)
print("register_save_address:", register_save_address)
thread_storage_list_address = ctypes.windll.kernel32.VirtualAllocEx(process_handle, None, 8*max_thread_ids, 0x3000, 0x04)
if thread_storage_list_address == 0:
raise Exception(f"Failed to allocate memory in target process: {ctypes.WinError()}")
print("thread_storage_list_address:", thread_storage_list_address)
alocated_thread_storages = ctypes.windll.kernel32.VirtualAllocEx(process_handle, None, nr_of_prepared_alocations*8, 0x3000, 0x04)
if alocated_thread_storages == 0:
raise Exception(f"Failed to allocate memory in target process: {ctypes.WinError()}")
print("alocated_thread_storages:", alocated_thread_storages)
print("setting up thread storage")
#here we prealoacte memory for threads
for stor_id in range(nr_of_prepared_alocations):
thread_storage_address = ctypes.windll.kernel32.VirtualAllocEx(process_handle, None, area_for_xsave64 + area_for_function_table + area_for_return_addr_linked_list + area_for_tracing_results, 0x3000, 0x04)
if thread_storage_address == 0:
raise Exception(f"Failed to allocate memory in target process: {ctypes.WinError()}")
hook_lib.write(process_handle, alocated_thread_storages + stor_id*8, struct.pack("<Q", thread_storage_address))
#OLD code to do allocations using dll: hook_lib.inject_asm(process_handle, "sub rsp, 40\nmov rcx, "+str(alocated_thread_storages + stor_id*8)+"\nmovabs rax, "+str(call_tracer_dll_func['alloc_thread_storage'])+"\n\ncall rax\nadd rsp, 40\nret")
if use_single_tracing or use_single_tracing_entry:
single_tracing_address = ctypes.windll.kernel32.VirtualAllocEx(process_handle, None, nr_of_max_trace_points, 0x3000, 0x04)
def inject_dll(process_handle):
# Inject helper DLL with MinHook-based hooks
run_loadlibrary_in_process(process_handle, "calltracer.dll") #FIXMEEE process
fixup_calltrace_exports(process_handle)
setup_dll_values(process_handle)
fixup_calltrace_exports_thunks(process_handle)
def inject_trace_injection_functions(process_handle):
global call_tracer_thunk_ready_addr, register_save_address, code_injection_address, shell_code_address, thread_storage_list_address, restore_state_address, save_state_address, alocated_thread_storages, debug_func_address, add_entry_trace_address, add_called_trace_address, add_call_trace_address, add_exit_trace_address, push_value_from_linkedlist_address, pop_value_from_linkedlist_address, pop_value_with_sameRSP_from_linkedlist_address
call_tracer_thunk_ready_addr = shell_code_address
shell_code_address += 1
#Setup thunk functions for dll
for name in call_tracer_dll_func:
#this will be zero untill we fill it in
call_tracer_thunk_func_ptr[name] = shell_code_address
shell_code_address += 8
thunk_address = shell_code_address
call_tracer_thunk_func[name] = thunk_address
#This code spins untill the calltracer dll has been loaded
thunk_func_code = asm(strip_semicolon_comments(f"""
.check_if_call_trace_ready:
cmp byte ptr [{call_tracer_thunk_ready_addr}], 0
je .check_if_call_trace_ready
jmp [{call_tracer_thunk_func_ptr[name]}]
"""), call_tracer_thunk_func[name])
shell_code_address += len(thunk_func_code)
hook_lib.write(process_handle, call_tracer_thunk_func[name], thunk_func_code, do_checks = False)
#save state requires you to push 128 bytes to rsp before calling lea rsp, [rsp-128]
#Setup save sate and restore state functions
VirtualAlloc_addr = hook_lib.get_remote_function(process_handle, "kernel32", "VirtualAlloc")
#save state function
save_state_asm = strip_semicolon_comments(f"""
; ===== prologue: preserve flags & callee-saved registers =====
pushfq
sub rsp, 8
; save callee-saved GPRs that we will use or clobber
push r15
mov r15, rsp
add r15, {rsp_ofset+24+8}; save original return_address stack location in r15 fix ofset 24 caused by earlier pushes and 128 from before call and 8 from the call
push rbp
push rsi
push rdi
push rax
push rcx
push rdx
push r8
push r9
push r10
push r11
push r12
push r13
push r14
push rbx
; Find thread storage from list
.find_current_thread_location:
xor rdi,rdi
xor r11,r11
; load current thread id (low 32 bits of GS:[0x48])
xor rax,rax
mov eax, dword ptr gs:[0x48] ; EAX = current TID
xor r12,r12
lea r12, [rax*8] ; fix offset
; base pointer to the array
movabs rsi, """+str(thread_storage_list_address)+""" ; RSI = array base
add r12, rsi
mov rax, [r12]
test rax, rax
jnz .thread_memmory_is_alocated ; jump if not zero (ZF = 0)
; not alocated - get allocation
movabs rsi, """+str(alocated_thread_storages)+"""
mov rcx, """+str(nr_of_prepared_alocations)+"""
; rsi = base, rcx = count
; clobbers: rdi, rax
; returns: rdi = addres of value, rax = popped value (0 if none), ZF=1 if none
mov rdi, rsi ; cursor = base
.scan:
test rcx, rcx
jz .not_found
xor eax, eax ; rax := 0 to swap into the slot
xchg rax, [rdi] ; atomically: rax <- slot, slot <- 0
test rax, rax
jnz .found ; got a non-zero, done
add rdi, 8 ; next qword
dec rcx
jmp .scan
.not_found:
int3 ; can never be allowed to happen
xor eax, eax
jmp .not_found
.found:
mov [r12], rax ; save new vale
mov r11, 1 ;set R11 so we store the extended registers we only do it if we need to as it is slow
;RDI is already set so alloc_thread_storage(uint64_t out_address) will be called further down
.thread_memmory_is_alocated:
mov r12, [r12]
mov r10, r12
add r10, """+str(area_for_xsave64 + area_for_function_table + area_for_return_addr_linked_list)+"""; get memory area for tracing
mov r8, [r10] ;Retrive end on list that is saved in the first 64 bits
test r8, r8
jnz .skip_mem_setup
mov r9, r12
add r9, """+str(area_for_xsave64 + area_for_function_table)+"""
mov [r9], r9 ;setup linked list mem
mov r8, r10
add r8, 8
mov [r10], r8 ;setup trace mem
.skip_mem_setup:
;Check if trace memmory starts be become to big
xor r9, r9
add r10 , """+str(area_for_tracing_results-1000)+"""
cmp r10, r8
ja .size_ok
mov r9, r12 ; We set r9 indicating that we need to empty the memory
mov r11, 1 ;set R11 so we store the extended registers we only do it if we need to as it is slow
.size_ok:
;IF r11 is not zero we need to save the extended state so we can call calling alloc_thread_storage
test r11, r11
jz .skip_saving_extended_state
; set mask: XCR0 -> EDX:EAX, ECX must be 0
xor ecx, ecx
xgetbv
; save extended state; DO NOT use rdx as the memory base (EDX is mask upper)
xsave64 [r12] ; (use xsaveopt if you detect support)
xor ecx, ecx
.skip_saving_extended_state:
; ===== prepare for making the actual code =====
; We must ensure RSP is 16-byte aligned at the CALL instruction and have 32 bytes shadow.
; Compute the adjustment needed to align RSP to 16 bytes:
; r10 currently saved on stack; we'll use r10 as temp for alignment value
mov rax, rsp
and rax, 15 ; rax = rsp % 16
xor r10, r10 ; r10 = 0 (will store correction amount if any)
test rax, rax
je .no_align_needed
mov r10, 16
sub r10, rax ; r10 = (16 - (rsp & 15))
sub rsp, r10 ; adjust stack to align to 16
.no_align_needed:
push r10
push r15
push r11
push r12
; Now allocate the 32-byte shadow space required by Windows x64 ABI
sub rsp, 32
test RDI, RDI
jz .skip_alloc_thread_storage
;Alocate new thread storage rcx is alrady filled from
mov r13, rdi ;save the reg used for storage
;sub rsp, 40
; call VirtualAlloc
xor rcx, rcx ; lpAddress = NULL
movabs rdx, """+str(area_for_xsave64 + area_for_function_table + area_for_return_addr_linked_list + area_for_tracing_results)+""" ; dwSize = thread_storage_size
mov r8, 0x3000 ; MEM_COMMIT | MEM_RESERVE
mov r9, 0x04 ; PAGE_READWRITE
movabs rax, """+str(VirtualAlloc_addr)+"""
call rax
;add rsp, 40
.allocation_error:
test rax, rax
jz .allocation_error
;Save the return adress
mov [r13], rax
;Restore r15
mov r15, [rsp+48]
jmp .skip_dump_trace
.skip_alloc_thread_storage:
;DUMP thread can run at the same time as alloc_thread_storage as registers will be cloberd but it never will so it does not matter
test R9, R9
jz .skip_dump_trace
;dump saved traces
mov rcx, r9 ;set first arg
movabs rax, """+str(call_tracer_thunk_func['dump_trace'])+f"""
call rax
;Restore r15
mov r15, [rsp+48]
.skip_dump_trace:
jmp [r15 - {rsp_ofset+8}] ;Jump back to return address of save call
""")
save_state_address = shell_code_address
save_state_code = asm(save_state_asm, save_state_address)
shell_code_address += len(save_state_code)
hook_lib.write(process_handle, save_state_address, save_state_code, do_checks = False)
debug_save_state_asm = strip_semicolon_comments(f"""
""")
debug_func_address = shell_code_address
debug_save_state_code = asm(debug_save_state_asm, debug_func_address)
shell_code_address += len(debug_save_state_code)
hook_lib.write(process_handle, debug_func_address, debug_save_state_code, do_checks = False)
#restore state function
restore_state_asm = strip_semicolon_comments(f"""
; ===== after call: pop shadow and undo alignment correction =====
add rsp, 40 ; Add 32 plus 8 cause we just did this call
pop r12
pop r11
pop r15
;Save the return address for this restore call
mov r10, [rsp-64]
mov [r15-{rsp_ofset+8}], r10
pop r10
test r10, r10
je .no_align_restore
add rsp, r10
.no_align_restore:
test r11, r11
jz .skip_restoring_extended_state
; ===== restore extended state =====
xor ecx, ecx
xgetbv
xrstor64 [r12] ; restore extended state from stack buffer
.skip_restoring_extended_state:
; ===== restore saved registers in reverse order =====
pop rbx
pop r14
pop r13
pop r12
pop r11
pop r10
pop r9
pop r8
pop rdx
pop rcx
pop rax
pop rdi
pop rsi
pop rbp
pop r15
add rsp, 8
popfq
lea rsp, [rsp+{rsp_ofset+8}] ;restore rsp 128 cause we added that before call + 8 cause of this call
jmp [rsp - {rsp_ofset+8}] ;jump to restore return address
""")
restore_state_address = shell_code_address
restore_state_code = asm(restore_state_asm, restore_state_address)
shell_code_address += len(restore_state_code)
hook_lib.write(process_handle, restore_state_address, restore_state_code, do_checks = False)
add_entry_trace_address = shell_code_address
add_entry_trace_code = asm(strip_semicolon_comments("""
add r12, """+str(area_for_xsave64)+"""
;Save tracing
mov r10, r12
add r10, """+str(area_for_function_table + area_for_return_addr_linked_list)+""" ; get memory area for tracing
mov r8, [r10] ;Retrive end on list that is saved in the first 64 bits
mov byte ptr [r8], 1 ;type 1 is function entry (1 byte)
mov eax, dword ptr gs:[0x48]
mov dword ptr [r8 + 1], eax ;save thread id (4 bytes)
mov dword ptr [r8 + 5], edx;Save function ordinal(4 bytes) edx is a function argument
rdtsc ; EDX:EAX = TSC
shl rdx, 32 ; move high half up
or rax, rdx ; RAX = (EDX<<32) | EAX
mov qword ptr [r8 + 9], rax ;save timestamp (8 bytes)
mov qword ptr [r8 + 17], r15 ;save return address pointer/function entry rsp(8 bytes)
mov rcx, [r15] ;
mov qword ptr [r8 + 25], rcx ;save return address (8 bytes)
lea r8, [r8+33]
mov [r10], r8
ret"""), add_entry_trace_address)
shell_code_address += len(add_entry_trace_code)
hook_lib.write(process_handle, add_entry_trace_address, add_entry_trace_code, do_checks = False)
add_exit_trace_address = shell_code_address
add_exit_trace_code = asm(strip_semicolon_comments("""add r12, """+str(area_for_xsave64)+"""
;Save tracing
mov r10, r12
add r10, """+str(area_for_function_table + area_for_return_addr_linked_list)+""" ; get memory area for tracing
mov r8, [r10] ;Retrive end on list that is saved in the first 64 bits
mov byte ptr [r8], 2 ;type 2 is function exit (1 byte)