Repository navigation
Expand file tree
/
Copy path_lldbinit.py
More file actions
5289 lines (4854 loc) · 201 KB
/
Copy path_lldbinit.py
File metadata and controls
5289 lines (4854 loc) · 201 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
import lldb
import sys
import re
import os
import struct
import argparse
import subprocess
import tempfile
import json
import hashlib
import datetime
# just a silly shortcut - requires the command to have the help option
def cmd_man(debugger, command, ctx, result, dict):
cmd = command.split()
if len(cmd) == 0:
err_msg("The man command requires an argument.")
return
res = lldb.SBCommandReturnObject()
# just call the target command with the help option
debugger.GetCommandInterpreter().HandleCommand(command + " " + "help", res)
if res.GetErrorSize() > 0:
err_msg("Requested man page for unknown command '{}'.".format(command))
def cmd_banner(debugger, command, ctx, result, dict):
global LLDB_VARIANT, LLDB_MAJOR, LLDB_MINOR
print("{}[+] Loaded lldbinit version {}.{} @ lldb-{}.{} ({} version){}".format(GREEN, VERSION, BUILD, LLDB_MAJOR, LLDB_MINOR, LLDB_VARIANT, RESET))
def cmd_lldbinitcmds(debugger, command, ctx, result, dict):
"""Display all available lldbinit commands."""
help_table = [
["", ""],
["lldbinitcmds", "this command"],
["", ""],
["----[ Settings ]----", ""],
["enable", "configure lldb and lldbinit options"],
["disable", "configure lldb and lldbinit options"],
["contextcodesize", "set number of instruction lines in code window"],
["enablesolib/disablesolib", "enable/disable the stop on library load events"],
["enableaslr/disableaslr", "enable/disable process ASLR"],
["datawin", "set start address to display on data window"],
["", ""],
["----[ Sessions ]----", ""],
["ls", "display available sessions"],
["ss", "save current session"],
["rs", "restore session"],
["", ""],
["----[ Breakpoints ]----", ""],
["b", "breakpoint address"],
["bpt", "set a temporary software breakpoint"],
["bh", "set an hardware breakpoint"],
["bht", "set a temporary hardware breakpoint"],
["bpc", "clear breakpoint"],
["bpca", "clear all breakpoints"],
["bpd", "disable breakpoint"],
["bpda", "disable all breakpoints"],
["bpe", "enable a breakpoint"],
["bpea", "enable all breakpoints"],
["bcmd", "alias to breakpoint command add"],
["bpl", "list all breakpoints"],
["bpn", "temporarly breakpoint next instruction"],
["bm", "breakpoint on module load"],
["bmc", "clear all module load breakpoints"],
["bml", "list all on module load breakpoints"],
["break_entrypoint", "launch target and stop at entrypoint"],
["skip", "skip current instruction"],
["int3", "patch memory address with INT3"],
["rint3", "restore original byte at address patched with INT3"],
["listint3", "list all INT3 patched addresses"],
["lb", "load breakpoints from file and apply them (currently only func names are applied)"],
["lbrva", "load breakpoints from file and apply to main executable, only RVA in this case"],
["print_images", "print all images available at gdb_image_notifier() breakpoint"],
["", ""],
["----[ Memory ]----", ""],
["nop", "patch memory address with NOP"],
["null", "patch memory address with NULL"],
["db/dw/dd/dq", "memory hex dump in different formats"],
["findmem", "search memory"],
["showregions", "display process memory regions"],
["", ""],
["----[ Disassembly ]----", ""],
["u", "dump instructions"],
["ctx/context", "show current instruction pointer CPU context"],
["stepo", "step over calls and loop instructions"],
["acm", "add disassembly comment"],
["dcm", "remove disassembly comment"],
["lcm", "list disassembly comments"],
["", ""],
["----[ Registers and CPU Flags ]----", ""],
["rip/rax/rbx/etc", "shortcuts to modify x64 registers"],
["eip/eax/ebx/etc", "shortcuts to modify x86 registers"],
["x{0..28}", "shortcuts to modify ARM64 registers"],
["cfa/cfc/cfd/cfi/cfo/cfp/cfs/cft/cfz", "change x86/x64 CPU flags"],
["cfn/cfz/cfc/cfv", "change AArch64 CPU flags (NZCV register)"],
["", ""],
["----[ File headers ]----", ""],
["show_loadcmds", "show otool output of Mach-O load commands"],
["show_header", "show otool output of Mach-O header"],
["", ""],
["----[ Cracking ]----", ""],
["crack", "return from current function"],
["crackcmd", "set a breakpoint and return from that function"],
["crackcmd_noret", "set a breakpoint and set a register value. doesn't return from function"],
["", ""],
["----[ Misc ]----", ""],
["", ""],
["----[ Assembler ]----", ""],
["asm32/asm64", "x86/x64 assembler using keystone"],
["arm32/arm64/armthumb", "ARM assembler using keystone"],
]
print(" ---------------------------")
print(" lldbinit available commands")
print(" ---------------------------")
for row in help_table:
if not row[1]:
print(" {: <20} {: <30}".format(*row))
else:
print(" {: <20} - {: <30}".format(*row))
print("\nUse 'cmdname help' for extended command help.")
# placeholder to make tests
def cmd_tester(debugger, command, ctx, result, dict):
print("test")
help = {
"cmd": "tester",
"short": "test command",
"desc": """Testing the help command.\nThis is a multiline test.""",
"args": "<settings> [<size>]",
"options": [
{
"name": "settings",
"desc": "The available settings are:",
"values": [
{
"n": "solib",
"d": "Enable stop on library events trick."
},
{
"n": "aslr",
"d": "Enable process ASLR."
}
],
},
{
"name": "size",
"desc": "The number of bytes to patch. Default is 1."
}
],
"example": "tester",
"notes": [
"This is note1.",
"This is note2."
]
}
help_msg(help)
return
# -------------------------
# Settings related commands
# -------------------------
def cmd_enable(debugger, command, ctx, result, dict):
"""Enable certain lldb and lldbinit options. Use \'enable help\' for more information."""
help = {
"cmd": "enable",
"short": "enable configuration options",
"desc": "Enable certain lldb and lldbinit configuration options.",
"args": "<setting>",
"options": [
{
"name": "settings",
"desc": "The available settings are:",
"values": [
{"n": "solib", "d": "Enable stop on library events trick."},
{"n": "aslr", "d": "Enable process ASLR."},
{"n": "stack", "d": "Enable stack window in context display."},
{"n": "data", "d": "Enable data window in context display, configure address with datawin."},
{"n": "flow", "d": "Enable call targets and objective-c class/methods window in context display."},
],
},
],
}
global CONFIG_DISPLAY_STACK_WINDOW
global CONFIG_DISPLAY_FLOW_WINDOW
global CONFIG_DISPLAY_DATA_WINDOW
cmd = command.split()
if len(cmd) == 0:
err_msg("The command requires an argument.")
help_msg(help)
return
if cmd[0] == "solib":
debugger.HandleCommand("settings set target.process.stop-on-sharedlibrary-events true")
print("[+] Enabled stop on library events trick.")
elif cmd[0] == "aslr":
debugger.HandleCommand("settings set target.disable-aslr false")
print("[+] Enabled ASLR.")
elif cmd[0] == "stack":
CONFIG_DISPLAY_STACK_WINDOW = 1
print("[+] Enabled stack window in context display.")
elif cmd[0] == "flow":
CONFIG_DISPLAY_FLOW_WINDOW = 1
print("[+] Enabled indirect control flow window in context display.")
elif cmd[0] == "data":
CONFIG_DISPLAY_DATA_WINDOW = 1
print("[+] Enabled data window in context display. Configure address with 'datawin' cmd.")
elif cmd[0] == "help":
help_msg(help)
else:
err_msg("Unrecognized command.")
help_msg(help)
return
def cmd_disable(debugger, command, ctx, result, dict):
"""Disable certain lldb and lldbinit options. Use \'disable help\' for more information."""
help = {
"cmd": "disable",
"short": "disable configuration options",
"desc": "Disable certain lldb and lldbinit configuration options.",
"args": "<setting>",
"options": [
{
"name": "settings",
"desc": "The available settings are:",
"values": [
{"n": "solib", "d": "Disable stop on library events trick."},
{"n": "aslr", "d": "Disable process ASLR."},
{"n": "stack", "d": "Disable stack window in context display."},
{"n": "data", "d": "Disable data window in context display, configure address with datawin."},
{"n": "flow", "d": "Disable call targets and objective-c class/methods window in context display."},
],
},
],
}
global CONFIG_DISPLAY_STACK_WINDOW
global CONFIG_DISPLAY_FLOW_WINDOW
global CONFIG_DISPLAY_DATA_WINDOW
cmd = command.split()
if len(cmd) == 0:
err_msg("The command requires an argument.")
help_msg(help)
return
if cmd[0] == "solib":
debugger.HandleCommand("settings set target.process.stop-on-sharedlibrary-events false")
print("[+] Disabled stop on library events trick.")
elif cmd[0] == "aslr":
debugger.HandleCommand("settings set target.disable-aslr true")
print("[+] Disabled ASLR.")
elif cmd[0] == "stack":
CONFIG_DISPLAY_STACK_WINDOW = 0
print("[+] Disabled stack window in context display.")
elif cmd[0] == "flow":
CONFIG_DISPLAY_FLOW_WINDOW = 0
print("[+] Disabled indirect control flow window in context display.")
elif cmd[0] == "data":
CONFIG_DISPLAY_DATA_WINDOW = 0
print("[+] Disabled data window in context display.")
elif cmd[0] == "help":
help_msg(help)
else:
err_msg("Unrecognized command.")
help_msg(help)
return
def cmd_contextcodesize(debugger, command, ctx, result, dict):
"""Set the number of disassembly lines in code window. Use \'contextcodesize help\' for more information."""
help = {
"cmd": "contextcodesize",
"short": "set disassembly lines",
"desc": "Configures the number of disassembly lines displayed in code window.",
"args": "<line count>",
"options": [{"name": "line count", "desc": "Number of disassembly lines to display. Default is 8."}],
"notes": ["Expressions are supported, do not use spaces between operators."],
}
global CONFIG_DISASSEMBLY_LINE_COUNT
cmd = command.split()
if len(cmd) != 1:
err_msg("Please insert the number of disassembly lines to display.")
help_msg(help)
return
if cmd[0] == "help":
help_msg(help)
print("Current configuration value is: {:d}".format(CONFIG_DISASSEMBLY_LINE_COUNT))
return
value = evaluate(ctx, cmd[0])
if value is None:
err_msg("Invalid input value.")
help_msg(help)
return
CONFIG_DISASSEMBLY_LINE_COUNT = value
return
# ---------------------------------
# Color and output related commands
# ---------------------------------
# this was used to append data to a global string and then output at the end of hook-stop
# replace it with direct print since I don't see any more usage to it
def output(x):
print(x, end='')
# ---------------------------------
# Threads related commands
# ---------------------------------
def cmd_listthreads(debugger, command, ctx, result, dict):
"""List current threads. Use \'tl help\' for more information."""
help = {
"cmd": "tl",
"short": "list threads",
"desc": "List current running threads.",
"args": "",
}
cmd = command.split()
if len(cmd) > 0 and cmd[0] == "help":
help_msg(help)
return
proc = ctx.GetProcess()
if proc.num_threads == 0:
err_msg("No threads available. Is the target started?")
return
print("Available threads")
for thread in proc:
ID = thread.GetThreadID()
index = thread.GetIndexID()
print("ID: {} Number: {}".format(ID, index))
def cmd_suspendthread(debugger, command, ctx, result, dict):
"""Suspend a thread. Use \'ts help\' for more information."""
help = {
"cmd": "ts",
"short": "suspend thread",
"desc": "Suspend a thread.",
"args": "<thread number>",
"options": [{"name": "thread number", "desc": "The thread number to suspend. List available threads with 'thread list' or 'tl' command."}],
}
cmd = command.split()
if len(cmd) != 1:
err_msg("Please insert a thread index.")
help_msg(help)
return
if cmd[0] == "help":
help_msg(help)
return
# breakpoint disable only accepts breakpoint numbers not addresses
value = evaluate(ctx, cmd[0])
if value is None:
err_msg("Invalid input value - only a thread index is valid.")
help_msg(help)
return
proc = ctx.GetProcess()
thread = proc.GetThreadByIndexID(value)
result = thread.Suspend()
if result is False:
err_msg("Failed to suspend thread.")
return
# ---------------------------
# Breakpoint related commands
# ---------------------------
ANTIDEBUG_SYSCTL_OBJS = []
# the second step breakpoint callback of the sysctl antidebug bypass
# we are at the return address of sysctl symbol
# and we simply remove the P_TRACED flag if it exists
def antidebug_callback_step2(frame, bp_loc, dict):
P_TRACED = 0x800
global ANTIDEBUG_SYSCTL_OBJS
# print("[+] Hit antidebug_callback_step2")
for i in ANTIDEBUG_SYSCTL_OBJS:
ANTIDEBUG_SYSCTL_OBJS.remove(i)
# offset to kp_proc.p_flag - this should be stable
offset = 0x20
target = frame.GetThread().GetProcess().GetTarget()
error = lldb.SBError()
# read the current value so we can modify and write again
value = frame.GetThread().GetProcess().ReadUnsignedFromMemory(i + offset, 4, error)
# remove P_TRACED flag if it exists
if value & P_TRACED:
print("[+] Hit sysctl antidebug request")
value = value ^ P_TRACED
# WriteMemory accepts a string so we need to pack this
patch = struct.pack("I", value)
result = target.GetProcess().WriteMemory(i + offset, patch, error)
if not error.Success():
err_msg("Failed to write memory at 0x{:x}.".format(i + offset))
return
frame.GetThread().GetProcess().Continue()
# the first step breakpoint callback of the sysctl antidebug bypass
# this deals with the breakpoint at sysctl symbol
# the purpose is to verify the request and set a second stage on return address
# where the debug flag is removed
def antidebug_callback_step1(frame, bp_loc, dict):
global ANTIDEBUG_SYSCTL_OBJS
error = lldb.SBError()
if frame is None:
return 0
target = frame.GetThread().GetProcess().GetTarget()
if is_x64(target):
src_reg = "rdi"
dst_reg = "rdx"
elif is_arm(target):
src_reg = "x0"
dst_reg = "x2"
else:
err_msg("Unsupported architecture.")
return 0
mib_addr = int(frame.FindRegister(src_reg).GetValue(), 16)
mib0 = frame.GetThread().GetProcess().ReadUnsignedFromMemory(mib_addr, 4, error)
if not error.Success():
err_msg("Failed to read mib0.")
return
mib1 = frame.GetThread().GetProcess().ReadUnsignedFromMemory(mib_addr + 4, 4, error)
if not error.Success():
err_msg("Failed to read mib1.")
return
mib2 = frame.GetThread().GetProcess().ReadUnsignedFromMemory(mib_addr + 8, 4, error)
if not error.Success():
err_msg("Failed to read mib2.")
return
# check if it's a potential AmIBeingDebugged request
# it's a common request from some apps
# so we need to verify on the return and remove the flag
# CTL_KERN (1) - KERN_PROC (14) - KERN_PROC_PID (1)
if mib0 == 1 and mib1 == 14 and mib2 == 1:
# print("[+] Hit sysctl antidebug request")
# the pointer to the sysctl output oldp
oldp = int(frame.FindRegister(dst_reg).GetValue(), 16)
if oldp == 0:
print("[!] Warning: oldp == 0")
frame.GetThread().GetProcess().Continue()
ANTIDEBUG_SYSCTL_OBJS.append(oldp)
# set a temporary breakpoint on the ret
# temporary because we can't sync this with other sysctl calls
# and we don't want to tamper with the rest of the results - just with the P_TRACED flag
mem_sbaddr = lldb.SBAddress(int(frame.FindRegister("pc").GetValue(), 16), target)
# flavor only relevant for x86, ignored when aarch64
inst = target.ReadInstructions(mem_sbaddr, 64)
for i in inst:
# print(hex(i.GetAddress().GetLoadAddress(target)), i.GetMnemonic(target))
# the properties seem broken in newer lldb versions because this will fail
# if we use i.mnemonic - the SBTarget will be NULL
# what's going on with lldb regressions?
# x64 - ret ; aarch64 - retab
if i.GetMnemonic(target).startswith("ret"):
# print(hex(i.addr.GetLoadAddress(target)), i.GetMnemonic(target))
nextbp = target.BreakpointCreateByAddress(i.GetAddress().GetLoadAddress(target))
nextbp.SetOneShot(True)
nextbp.SetThreadID(frame.GetThread().GetThreadID())
# this will generate a traceback on newer lldb versions
# it seems we can't set another callback while inside a callback
# lldb regressions ftw...
nextbp.SetScriptCallbackFunction("lldbinit.antidebug_callback_step2")
# everything automatic here so continue in any case
frame.GetThread().GetProcess().Continue()
# bypass PT_DENY_ATTACH via ptrace() call
def antidebug_ptrace_callback(frame, bp_loc, dict):
PT_DENY_ATTACH = 31
error = lldb.SBError()
proc = frame.GetThread().GetProcess()
target = proc.GetTarget()
if is_x64(target):
src_reg = "rdi"
elif is_arm(target):
src_reg = "x0"
request = int(frame.FindRegister(src_reg).GetValue(), 16)
if request == PT_DENY_ATTACH:
print("[+] Hit ptrace anti-debug request")
if is_x64(target):
src_reg = "rax"
elif is_arm(target):
src_reg = "x0"
# we are essentially bypassing the whole call to return a value of 0
result = frame.registers[0].GetChildMemberWithName(src_reg).SetValueFromCString("0x0", error)
if not result:
err_msg("Failed to write to {} register.".format(src_reg))
return 0
# and return immediately to the caller without executing any ptrace() code
frame.GetThread().ReturnFromFrame(frame, frame.registers[0].GetChildMemberWithName(src_reg))
proc.Continue()
# debugger detection via the mach exception ports
def antidebug_task_exception_ports_callback(frame, bp_loc, dict):
if frame is None:
return 0
proc = frame.GetThread().GetProcess()
target = proc.GetTarget()
if is_x64(target):
src_reg = "rsi"
elif is_arm(target):
src_reg = "x1"
exception_mask = int(frame.FindRegister(src_reg).GetValue(), 16)
if exception_mask != 0x0:
print("[+] Hit {} antidebug request".format(frame.symbol.name))
error = lldb.SBError()
result = frame.registers[0].GetChildMemberWithName(src_reg).SetValueFromCString("0x0", error)
if not result:
err_msg("Failed to write to {} register.".format(src_reg))
return 0
proc.Continue()
def cmd_antidebug(debugger, command, ctx, result, dict):
"""Enable anti-anti-debugging. Use \'antidebug help\' for more information."""
help = {
"cmd": "antidebug",
"short": "enable anti-anti-debugging",
"desc": "Enable anti-anti-debugging measures.\nBypasses debugger detection via sysctl, ptrace PT_DENY_ATTACH, and task exception ports.",
"args": "",
}
cmd = command.split()
if len(cmd) > 0 and cmd[0] == "help":
help_msg(help)
return
target = ctx.GetTarget()
for m in target.module_iter():
if m.file.fullpath == "/usr/lib/dyld":
# sysctl
bp = target.BreakpointCreateByName("sysctl", "/usr/lib/system/libsystem_c.dylib")
bp.SetScriptCallbackFunction("lldbinit.antidebug_callback_step1")
# PT_DENY_ATTACH
bp2 = target.BreakpointCreateByName("ptrace", "/usr/lib/system/libsystem_kernel.dylib")
bp2.SetScriptCallbackFunction("lldbinit.antidebug_ptrace_callback")
# mach exception ports
bp3 = target.BreakpointCreateByName("task_get_exception_ports", "/usr/lib/system/libsystem_kernel.dylib")
bp3.SetScriptCallbackFunction("lldbinit.antidebug_task_exception_ports_callback")
bp4 = target.BreakpointCreateByName("task_set_exception_ports", "/usr/lib/system/libsystem_kernel.dylib")
bp4.SetScriptCallbackFunction("lldbinit.antidebug_task_exception_ports_callback")
print("[+] Enabled anti-anti-debugging measures")
break
# the callback for the specific module loaded breakpoint
# supports x64, i386, arm64
def module_breakpoint_callback(frame, bp_loc, dict):
global modules_list
# rdx contains the module address
# rdx+8 contains pointer to the module name string
if frame is None:
return 0
error = lldb.SBError()
proc = frame.GetThread().GetProcess()
target = proc.GetTarget()
i386 = is_i386(target)
x64 = is_x64(target)
arm = is_arm(target)
if not i386 and not x64 and not arm:
err_msg("Unsupported architecture.")
# for i386 we need the stack pointer to retrieve arguments
if i386:
sp = frame.FindRegister("esp")
sp = int(sp.GetValue(), 16)
# static void gdb_image_notifier(enum dyld_image_mode mode, uint32_t infoCount, const dyld_image_info info[])
# static void lldb_image_notifier(enum dyld_image_mode mode, uint32_t infoCount, const dyld_image_info info[])
if x64:
pc = frame.FindRegister("rdi")
mode = int(pc.GetValue(), 16)
elif arm:
# argument registers from x0 to x7
pc = frame.FindRegister("x0")
mode = int(pc.GetValue(), 16)
elif i386:
mode = proc.ReadUnsignedFromMemory(sp + 4, 4, error)
if not error.Success():
err_msg("Failed to read mode from stack.")
return
# only interested in new images
# enum dyld_image_mode { dyld_image_adding=0, dyld_image_removing=1, dyld_image_info_change=2, dyld_image_dyld_moved=3 };
if mode != 0:
proc.Continue()
return
# infoCount argument
if x64:
pc = frame.FindRegister("rsi")
infoCount = int(pc.GetValue(), 16)
elif arm:
pc = frame.FindRegister("x1")
infoCount = int(pc.GetValue(), 16)
elif i386:
infoCount = proc.ReadUnsignedFromMemory(sp + 8, 4, error)
if not error.Success():
err_msg("Failed to read infoCount from stack.")
return
# info argument
if x64:
pc = frame.FindRegister("rdx")
info = int(pc.GetValue(), 16)
elif arm:
pc = frame.FindRegister("x2")
info = int(pc.GetValue(), 16)
elif i386:
info = proc.ReadUnsignedFromMemory(sp + 12, 4, error)
if not error.Success():
err_msg("Failed to read address from rdx.")
return
# set values according to target platform
if i386:
readSize = 4
# sizeof(struct dyld_image_info) - this should be constant?
dyld_image_info_size = 4 * 3
else:
readSize = 8
dyld_image_info_size = 8 * 3
hit = 0
# go over all the images being added and try to found the ones we are interested in
for x in range(infoCount):
address = proc.ReadUnsignedFromMemory(info, readSize, error)
if not error.Success():
err_msg("Failed to read address from info structure:" + error)
return
string_ptr = proc.ReadUnsignedFromMemory(info + readSize, readSize, error)
if not error.Success():
err_msg("Failed to read string pointer from info structure.")
return
string = proc.ReadCStringFromMemory(string_ptr, 1024, error)
if not error.Success():
err_msg("Failed to read module name string.")
return
# XXX: convert this to dictionary? we expect this to be always quite small (one or just a few entries)
for i in modules_list:
if i == string:
hit = 1
print("[+] Hit module loading: {0} @ {1}".format(string, hex(address)))
break
# we found the module so no point continuing
# lldb stays at the gdb_image_notifier() breakpoint
# so that user can do something
if hit == 1:
return
# advance to next one
info += dyld_image_info_size
# nothing found so we resume execution
if hit == 0:
proc.Continue()
# breakpoint on specific module
def cmd_bm(debugger, command, ctx, result, dict):
"""Set breakpoint on specific module load. Use \'bm help\' for more information."""
help = {
"cmd": "bm",
"short": "set breakpoint on module load",
"desc": """Set gdb_image_notifier() or lldb_image_notifier() breakpoint on module load.
Similar to stop on shared library events feature but stops only on configured modules.
Issue the command multiple times to add different modules.
If no module path specified it will just be a shortcut to set breakpoint
at beginning of image notifier. Use \'print_images\' to show all images there.""",
"args": "[<full path to module>]",
"notes": ["The gdb_image_notifier() was removed in Monterey."],
"example": "bm /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation",
}
global modules_list
cmd = command.split()
if len(cmd) > 0 and cmd[0] == "help":
help_msg(help)
return
# convert everything to a single string
# spaces should be fine on the path without escaping since we expect them like that in memory
# when matching the modules at the callback
modpath = " ".join([str(item) for item in cmd[0:]])
found = 0
target = ctx.GetTarget()
for m in target.module_iter():
# print(m.file.fullpath)
if m.file.fullpath == "/usr/lib/dyld":
for symbol in m:
# mangled is easier because the other symbol commands will retrieve with prototype info in the name
name = symbol.GetMangledName()
# XXX: improve this because we are doubling the amount of work?
# the lldb symbol isn't mangled
name2 = symbol.GetName()
if name == "_ZL18gdb_image_notifier15dyld_image_modejPK15dyld_image_info" or name2 == "lldb_image_notifier":
saddr = symbol.GetStartAddress()
# process needs to be loaded before we can execute this command...
if saddr.GetLoadAddress(target) == 0xFFFFFFFFFFFFFFFF:
err_msg("Failed to retrieve address of gdb_image_notifier. use 'break_entrypoint' or 'process launch -s' command first and then this one.")
return
bpt_addr = saddr.GetLoadAddress(target)
# check if it's a duplicate breakpoint
# just add to the module list if the callback is already set
for bpt in target.breakpoint_iter():
# we need to iterate all locations of each breakpoint... geezzzzzz
for bl in bpt:
if bl.GetLoadAddress() == bpt_addr:
print("[+] Added '{}' to breakpoint on module load.".format(modpath))
modules_list.append(modpath)
return
print("[+] Setting breakpoint on gdb_image_notifier located at address {0}".format(hex(saddr.GetLoadAddress(target))))
breakpoint = target.BreakpointCreateByAddress(bpt_addr)
# append the module name to the list if set
if len(cmd) > 0:
breakpoint.SetScriptCallbackFunction("lldbinit.module_breakpoint_callback")
print("[+] Added '{}' to breakpoint on module load.".format(modpath))
modules_list.append(modpath)
found = 1
break
if found:
break
def cmd_bmc(debugger, command, ctx, result, dict):
"""Clear all breakpoints on specific module load. Use \'bmc help\' for more information."""
help = {
"cmd": "bmc",
"short": "clear breakpoints",
"desc": "Clear all breakpoints set on module load. Check the 'bm' command for further information.",
"args": "",
}
global modules_list
cmd = command.split()
if len(cmd) > 0 and cmd[0] == "help":
help_msg(help)
return
modules_list = []
def cmd_bml(debugger, command, ctx, result, dict):
"""List all breakpoints on module load."""
help = {
"cmd": "bml",
"short": "list breakpoints",
"desc": "List all breakpoints set on module load. Check the 'bm' command for further information.",
"args": "",
}
cmd = command.split()
if len(cmd) > 0 and cmd[0] == "help":
help_msg(help)
return
if len(modules_list) == 0:
print("No breakpoints on modules currently set.")
return
print("Breakpoints on modules:")
for i in modules_list:
print("- " + i)
def cmd_print_notifier_images(debugger, command, ctx, result, dict):
"""Print all images available at gdb_image_notifier/lldb_image_notifier breakpoint."""
help = {
"cmd": "print_images",
"short": "print target modules",
"desc": """Print all modules available at gdb_image_notifier() or lldb_image_notifier() breakpoint.\nOnly valid when breakpoint set at beginning of the image notifier.""",
"args": "",
"notes": ["The gdb_image_notifier() was removed in Monterey."],
}
cmd = command.split()
if len(cmd) > 0 and cmd[0] == "help":
help_msg(help)
return
frame = ctx.GetFrame()
if frame is None:
return 0
error = lldb.SBError()
# XXX: check that we are effectively at gdb_image_notifier address
target = ctx.GetTarget()
i386 = is_i386(target)
x64 = is_x64(target)
arm = is_arm(target)
if not i386 and not x64 and not arm:
err_msg("Unsupported architecture.")
# for i386 we need the stack pointer to retrieve arguments
if i386:
sp = frame.FindRegister("esp")
sp = int(sp.GetValue(), 16)
# static void gdb_image_notifier(enum dyld_image_mode mode, uint32_t infoCount, const dyld_image_info info[])
# static void lldb_image_notifier(enum dyld_image_mode mode, uint32_t infoCount, const dyld_image_info info[])
# mode argument
if x64:
pc = frame.FindRegister("rdi")
mode = int(pc.GetValue(), 16)
elif arm:
# argument registers from x0 to x7
pc = frame.FindRegister("x0")
mode = int(pc.GetValue(), 16)
elif i386:
mode = ctx.GetProcess().ReadUnsignedFromMemory(sp + 4, 4, error)
if not error.Success():
err_msg("Failed to read mode from stack.")
return
# infoCount argument
if x64:
pc = frame.FindRegister("rsi")
infoCount = int(pc.GetValue(), 16)
elif arm:
pc = frame.FindRegister("x1")
infoCount = int(pc.GetValue(), 16)
elif i386:
infoCount = ctx.GetProcess().ReadUnsignedFromMemory(sp + 8, 4, error)
if not error.Success():
err_msg("Failed to read infoCount from stack.")
return
# info argument
if x64:
pc = frame.FindRegister("rdx")
info = int(pc.GetValue(), 16)
elif arm:
pc = frame.FindRegister("x2")
info = int(pc.GetValue(), 16)
elif i386:
info = ctx.GetProcess().ReadUnsignedFromMemory(sp + 12, 4, error)
if not error.Success():
err_msg("Failed to read address from rdx.")
return
# set values according to target platform
if i386:
readSize = 4
dyld_image_info_size = 4 * 3
else:
readSize = 8
dyld_image_info_size = 8 * 3
print("gdb_image_notifier available dyld_image_info images: {0}".format(infoCount))
if infoCount == 0:
return
print("Mode: {0} ({1})".format(mode, dyld_mode_dict[mode]))
print("Loaded modules:")
print("----------------------------------------------------------")
for x in range(infoCount):
address = ctx.GetProcess().ReadUnsignedFromMemory(info, readSize, error)
if not error.Success():
err_msg("Failed to read address from info structure.")
return
string_ptr = ctx.GetProcess().ReadUnsignedFromMemory(info + readSize, readSize, error)
if not error.Success():
err_msg("Failed to read string pointer from info structure.")
return
string = ctx.GetProcess().ReadCStringFromMemory(string_ptr, 1024, error)
if not error.Success():
err_msg("Failed to read module name string.")
return
print("0x{:>014x} | {:s}".format(address, string))
# advance to next one sizeof(struct dyld_image_info)
info += dyld_image_info_size
# software breakpoint
# overwrites the default alias
# XXX: should we verify duplicate breakpoints?
# they should exist, for example one with condition another without
# and user can enable/disable the one he wants to work with
#
# NOTE: this is straighforward breakpoint without conditions etc
# user can always set conditions via regular commands
def cmd_bp(debugger, command, ctx, result, dict):
"""Set a software breakpoint."""
help = {
"cmd": "bp",
"short": "set software breakpoint",
"desc": """Set a software breakpoint.""",
"args": "<address> [<breakpoint name>]",
"options": [
{"name": "address", "desc": "The breakpoint address."},
{"name": "breakpoint name", "desc": "The breakpoint name."},
],
"notes": ["Expressions are supported, do not use spaces between operators."],
}
cmd = command.split()
if len(cmd) < 1:
err_msg("Please insert a breakpoint address.")
help_msg(help)
return
if cmd[0] == "help":
help_msg(help)
return
value = evaluate(ctx, cmd[0])
if value is None:
err_msg("Invalid input value.")
help_msg(help)
return
# accept spaces and replace them with underscores
# the breakpoint names don't allow spaces?
name = ""
if len(cmd) > 1:
name = "_".join([str(item) for item in cmd[1:]])
target = ctx.GetTarget()
breakpoint = target.BreakpointCreateByAddress(value)
if name != "":
breakpoint.AddName(name)
print("[+] Software #{:d} breakpoint set at 0x{:x}".format(breakpoint.id, value))
return
# temporary software breakpoint
def cmd_bpt(debugger, command, ctx, result, dict):
"""Set a temporary software breakpoint. Use \'bpt help\' for more information."""
help = {
"cmd": "bpt",
"short": "set temporary software breakpoint",
"desc": "Set a temporary software breakpoint. Breakpoint is deleted on first hit.",
"args": "<address>",
"options": [{"name": "address", "desc": "The breakpoint address."}],
"notes": ["Expressions are supported, do not use spaces between operators."],
}
cmd = command.split()
if len(cmd) != 1:
err_msg("Please insert a breakpoint address.")
help_msg(help)
return
if cmd[0] == "help":
help_msg(help)
return
value = evaluate(ctx, cmd[0])
if value is None:
err_msg("Invalid input value.")
help_msg(help)
return
target = ctx.GetTarget()
breakpoint = target.BreakpointCreateByAddress(value)
breakpoint.SetOneShot(True)
breakpoint.SetThreadID(ctx.GetThread().GetThreadID())
print("[+] Temporary software breakpoint #{:d} set at 0x{:x}".format(target.num_breakpoints, value))
# hardware breakpoint
def cmd_bh(debugger, command, ctx, result, dict):
"""Set an hardware breakpoint."""
help = {
"cmd": "bh",
"short": "set hardware breakpoint",
"desc": """Set an hardware breakpoint.""",
"args": "<address> [<breakpoint name>]",
"options": [
{"name": "address", "desc": "The breakpoint address."},
{"name": "breakpoint name", "desc": "The breakpoint name."}
],
"notes": [
"Expressions are supported, do not use spaces between operators.",
"Breakpoint name must *not* use spaces."
],
}
cmd = command.split()
if len(cmd) < 1:
err_msg("Please insert a breakpoint address.")
help_msg(help)
return
if cmd[0] == "help":
help_msg(help)
return
value = evaluate(ctx, cmd[0])
if value is None:
err_msg("Invalid input value.")
help_msg(help)
return
# accept spaces and replace them with underscores
# the breakpoint names don't allow spaces?
name = ""
if len(cmd) > 1:
name = "_".join([str(item) for item in cmd[1:]])
res = lldb.SBCommandReturnObject()
# the python API doesn't seem to support hardware breakpoints
# so we set it via command line interpreter
if name != "":
debugger.GetCommandInterpreter().HandleCommand("breakpoint set -H -a {} -N {}".format(hex(value), name), res)
else: