/
HookCase.cpp
16615 lines (15209 loc) · 556 KB
/
HookCase.cpp
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
// The MIT License (MIT)
//
// Copyright (c) 2023 Steven Michaud
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// HookCase.kext is a macOS/OS X kernel extension that reimplements and extends
// Apple's DYLD_INSERT_LIBRARIES functionality (as described here:
// https://books.google.com/books?id=K8vUkpOXhN4C&pg=PA73&lpg=PA73&dq="dyld+interposing"+Singh.)
// It also removes all the restrictions that Apple has placed upon it. So
// HookCase.kext can be used with an app that has entitlements, is setuid or
// setgid, or has a __restrict section in a __RESTRICT segment. But to load
// HookCase.kext you need to turn off Apple's System Integrity Protection at
// least partially
// (https://developer.apple.com/library/content/documentation/Security/Conceptual/System_Integrity_Protection_Guide/KernelExtensions/KernelExtensions.html).
// So it's not easy to use for nefarious purposes.
//
// Apple's DYLD_INSERT_LIBRARIES environment variable allows you to hook calls
// made from one module to methods exported from other, dynamically
// loaded modules (by changing pointers in the first module's symbol table).
// HookCase.kext supports this kind of hook, which we call an "interpose hook".
// But it also supports an even more powerful technique, which can be used to
// hook any method in any module (even non-exported ones, and even those that
// don't have an entry in their own module's symbol table). This we call a
// "patch hook", since it requires that we "patch" the beginning of the
// original method with an assembly language "int 0x30" instruction. This is
// analogous to what a debugger does when it sets a breakpoint (though it uses
// "int 3" instead of "int 0x30").
//
// Patch hooks can sometimes be substantially less performant than interpose
// hooks, because sometimes we need to "unset" the breakpoint on every call to
// the hook, then "reset" it afterwards (and to protect these operations from
// race conditions). But this isn't needed for methods that start with a
// standard C/C++ prologue in machine code (which is most of them). So most
// patch hooks run with only a very small performance penalty (that of a
// single software interrupt), aside from the cost of whatever additional code
// runs inside the hook. (Interpose hooks run with no performance penalty at
// all.)
//
// As with Apple's DYLD_INSERT_LIBRARIES functionality, to use HookCase.kext
// on a process you need to write a "hook library" (aka "interpose library")
// and set an environment variable (HC_INSERT_LIBRARY) to its full path.
// There is a hook library template under "HookLibraryTemplate", and further
// examples under "Examples". Since environment variables are (generally)
// passed to child processes, HookCase.kext by default works on a process and
// all its children. Though this can be turned off (by setting the HC_NOKIDS
// environment variable), it can be quite useful now that many apps use
// multiple processes. Child processes lauched via XPC don't inherit their
// parent's environment. But (on OS X 10.11 and up) HookCase.kext knows which
// XPC children have been launched from a given parent process, so it can use
// the values of HC_INSERT_LIBRARY and HC_NOKIDS in the parent to determine
// what (if anything) gets hooked in the XPC children.
//
// Software interrupts are mostly not used on BSD-style operating systems like
// macOS and OS X. This can be seen from the contents of the xnu kernel's
// osfmk/x86_64/idt_table.h. The unused interrupts are marked there as
// "INTERRUPT(0xNN)". (But note that the ranges 0xD0-0xFF, 0x50-0x5F and
// 0x40-0x4F are reserved for APIC interrupts (see the xnu kernel's
// osfmk/i386/lapic.h). And VMWare uses at least one interrupt in the range
// 0x20-0x2F.) So we're reasonably safe reserving the range 0x30-0x37 for our
// own use, though we currently only use 0x30-0x35. And aside from plenty of
// them being available, there are other advantages to using interrupts as
// breakpoints: They're short (they take up just two bytes of machine code),
// but provide more information than other instructions of equal length (like
// syscall, which doesn't have different "interrupt numbers"). Software
// interrupts work equally well from user mode and kernel mode (again unlike
// syscall). Interrupts also (like syscall) have very good support for making
// the transition between different privilege levels (for example between user
// mode and kernel mode).
// HookCase.kext is compatible with DYLD_INSERT_LIBRARIES, and doesn't stomp on
// any of the changes it may have been used to make. So a
// DYLD_INSERT_LIBRARIES hook will always override the "same" HookCase.kext
// interpose hook. This is because Apple often uses DYLD_INSERT_LIBRARIES
// internally, in ways it doesn't document. HookCase.kext would likely break
// Apple functionality if it could override Apple's hooks. But this doesn't
// apply to patch hooks, which are an entirely different kind of beast. If an
// interpose hook doesn't seem to work, try a patch hook instead.
// HookCase.kext is compatible with lldb and gdb: Any process with
// HookCase.kext's interpose or patch hooks can run inside these debuggers.
// But you may encounter trouble if you set a breakpoint and a patch hook on
// the same method, or try to step through code that contains a patch hook.
// Apple only supports a subset of C/C++ for kernel extensions. Apple
// documents some of the features which are disallowed[1], but not all of
// them. Apple's list of disallowed features includes exceptions, multiple
// inheritance, templates and RTTI. But complex initialization of local
// variables is also disallowed -- for example structure initialization and
// variable initialization in a "for" statement (e.g. "for (int i = 1; ; )").
// You won't always get a compiler warning if you use one of these disallowed
// features. And you may not always see problems using the resulting binary.
// But in at least some cases you will see mysterious kernel panics.
//
// [1]https://developer.apple.com/library/mac/documentation/DeviceDrivers/Conceptual/IOKitFundamentals/Features/Features.html#//apple_ref/doc/uid/TP0000012-TPXREF105
#include <libkern/libkern.h>
#include <AvailabilityMacros.h>
#include <sys/types.h>
#include <sys/kernel_types.h>
#include <mach/mach_types.h>
#include <sys/fcntl.h>
#include <sys/lock.h>
#include <sys/proc.h>
#include <sys/queue.h>
#include <sys/spawn.h>
#include <sys/sysctl.h>
#include <sys/vnode.h>
#include <kern/host.h>
#include <mach-o/loader.h>
// This definition is missing from loader.h on some macOS versions
#define S_INIT_FUNC_OFFSETS 0x16
#include <mach-o/nlist.h>
#include <libkern/OSAtomic.h>
#include <i386/cpuid.h>
#include <i386/proc_reg.h>
#include <libkern/c++/OSNumber.h>
#include <libkern/c++/OSString.h>
#include <libkern/c++/OSArray.h>
#include <libkern/c++/OSDictionary.h>
#include <libkern/c++/OSSerialize.h>
#include <IOKit/IOLib.h>
#define MH_FILESET 0xc /* set of mach-o's */
#include "HookCase.h"
extern "C" int atoi(const char *str);
typedef struct pmap *pmap_t;
extern pmap_t kernel_pmap;
extern vm_map_t kernel_map;
extern "C" void vm_kernel_unslide_or_perm_external(vm_offset_t addr,
vm_offset_t *up_addr);
extern "C" ppnum_t pmap_find_phys(pmap_t map, addr64_t va);
extern "C" lck_rw_type_t lck_rw_done(lck_rw_t *lck);
extern "C" void *get_bsdtask_info(task_t);
/*------------------------------*/
// "kern.osrelease" is what's returned by 'uname -r', which uses a different
// numbering system than the "standard" one. These defines translate from
// that (kernel) system to the "standard" one.
#define MAC_OS_X_VERSION_10_9_HEX 0x00000D00
#define MAC_OS_X_VERSION_10_10_HEX 0x00000E00
#define MAC_OS_X_VERSION_10_11_HEX 0x00000F00
#define MAC_OS_X_VERSION_10_12_HEX 0x00001000
#define MAC_OS_X_VERSION_10_13_HEX 0x00001100
#define MAC_OS_X_VERSION_10_14_HEX 0x00001200
#define MAC_OS_X_VERSION_10_15_HEX 0x00001300
#define MAC_OS_X_VERSION_11_HEX 0x00001400
#define MAC_OS_X_VERSION_12_HEX 0x00001500
#define MAC_OS_X_VERSION_13_HEX 0x00001600
#define MAC_OS_X_VERSION_14_HEX 0x00001700
char *gOSVersionString = NULL;
size_t gOSVersionStringLength = 0;
int32_t OSX_Version()
{
static int32_t version = -1;
if (version != -1) {
return version;
}
version = 0;
sysctlbyname("kern.osrelease", NULL, &gOSVersionStringLength, NULL, 0);
gOSVersionString = (char *) IOMalloc(gOSVersionStringLength);
char *version_string = (char *) IOMalloc(gOSVersionStringLength);
if (!gOSVersionString || !version_string) {
return version;
}
if (sysctlbyname("kern.osrelease", gOSVersionString,
&gOSVersionStringLength, NULL, 0) < 0)
{
IOFree(version_string, gOSVersionStringLength);
return version;
}
strncpy(version_string, gOSVersionString, gOSVersionStringLength);
char *version_string_iterator = version_string;
const char *part; int i;
for (i = 0; i < 3; ++i) {
part = strsep(&version_string_iterator, ".");
if (!part) {
break;
}
version += (atoi(part) << ((2 - i) * 4));
}
IOFree(version_string, gOSVersionStringLength);
return version;
}
long macOS_build_num()
{
static long retval = -1;
if (retval == -1) {
size_t build_id_string_length;
sysctlbyname("kern.osversion", NULL, &build_id_string_length, NULL, 0);
char *build_id_string = (char *) IOMalloc(build_id_string_length);
if (!build_id_string) {
return -1;
}
// Build ids for macOS all start with a three-character alphanumeric value
// which corresponds to part or all of the version number -- for example
// "13A" for "10.9", "13B" for "10.9.1" and "22G" for "13.5.X" and
// "13.6.X". Remove this and use the rest as a build number. Note that the
// build numbers restart from zero for each three-character value.
if (sysctlbyname("kern.osversion", build_id_string,
&build_id_string_length, NULL, 0) == 0)
{
const char *build_num_string = build_id_string + 3;
retval = strtol(build_num_string, NULL, 10);
}
IOFree(build_id_string, build_id_string_length);
}
return retval;
}
bool OSX_Mavericks()
{
return ((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_10_9_HEX);
}
bool OSX_Yosemite()
{
return ((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_10_10_HEX);
}
bool OSX_ElCapitan()
{
return ((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_10_11_HEX);
}
bool macOS_Sierra()
{
return ((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_10_12_HEX);
}
bool macOS_HighSierra()
{
return ((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_10_13_HEX);
}
bool macOS_HighSierra_less_than_4()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_10_13_HEX)) {
return false;
}
// The output of "uname -r" for macOS 10.13.4 is actually "17.5.0"
return ((OSX_Version() & 0xFF) < 0x50);
}
// Build 17G7020 is a post-10.13.6 security fix.
bool macOS_HighSierra_less_than_17G7020()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_10_13_HEX)) {
return false;
}
// The output of "uname -r" for macOS 10.13.6 is actually "17.7.0"
if ((OSX_Version() & 0xFF) < 0x70) {
return false;
}
static long build_num = -1;
if (build_num == -1) {
size_t build_id_string_length;
sysctlbyname("kern.osversion", NULL, &build_id_string_length, NULL, 0);
char *build_id_string = (char *) IOMalloc(build_id_string_length);
if (!build_id_string) {
return false;
}
// Build ids for macOS 10.13.6 all start with "17G". Remove that and
// use the rest as a build number.
if (sysctlbyname("kern.osversion", build_id_string,
&build_id_string_length, NULL, 0) == 0)
{
const char *build_num_string = build_id_string + 3;
build_num = strtol(build_num_string, NULL, 10);
}
IOFree(build_id_string, build_id_string_length);
if (build_num == -1) {
return false;
}
}
return (build_num < 7020);
}
bool macOS_Mojave()
{
return ((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_10_14_HEX);
}
bool macOS_Mojave_less_than_2()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_10_14_HEX)) {
return false;
}
return ((OSX_Version() & 0xFF) < 0x20);
}
bool macOS_Mojave_less_than_5()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_10_14_HEX)) {
return false;
}
// The output of "uname -r" for macOS 10.14.5 is actually "18.6.0"
return ((OSX_Version() & 0xFF) < 0x60);
}
bool macOS_Catalina()
{
return ((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_10_15_HEX);
}
bool macOS_Catalina_less_than_5()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_10_15_HEX)) {
return false;
}
return ((OSX_Version() & 0xFF) < 0x50);
}
bool macOS_BigSur()
{
return ((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_11_HEX);
}
bool macOS_BigSur_less_than_3()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_11_HEX)) {
return false;
}
// The output of "uname -r" for macOS 11.3 is actually "20.4.0", and
// for 11.2.3 is "20.3.0".
return ((OSX_Version() & 0xFF) < 0x40);
}
bool macOS_BigSur_4_or_greater()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_11_HEX)) {
return false;
}
// The output of "uname -r" for macOS 11.4 is actually "20.5.0", and
// for 11.3 is "20.4.0".
return ((OSX_Version() & 0xFF) >= 0x50);
}
bool macOS_Monterey()
{
return ((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_12_HEX);
}
bool macOS_Monterey_less_than_1()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_12_HEX)) {
return false;
}
// The output of "uname -r" for macOS 12.1 is actually "21.2.0".
return ((OSX_Version() & 0xFF) < 0x20);
}
bool macOS_Monterey_1_or_greater()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_12_HEX)) {
return false;
}
// The output of "uname -r" for macOS 12.1 is actually "21.2.0".
return ((OSX_Version() & 0xFF) >= 0x20);
}
bool macOS_Monterey_less_than_3()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_12_HEX)) {
return false;
}
// The output of "uname -r" for macOS 12.3 is actually "21.4.0".
return ((OSX_Version() & 0xFF) < 0x40);
}
bool macOS_Monterey_3_or_greater()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_12_HEX)) {
return false;
}
// The output of "uname -r" for macOS 12.3 is actually "21.4.0".
return ((OSX_Version() & 0xFF) >= 0x40);
}
bool macOS_Monterey_less_than_4()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_12_HEX)) {
return false;
}
// The output of "uname -r" for macOS 12.4 is actually "21.5.0".
return ((OSX_Version() & 0xFF) < 0x50);
}
bool macOS_Monterey_4_or_greater()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_12_HEX)) {
return false;
}
// The output of "uname -r" for macOS 12.4 is actually "21.5.0".
return ((OSX_Version() & 0xFF) >= 0x50);
}
bool macOS_Monterey_less_than_5()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_12_HEX)) {
return false;
}
// The output of "uname -r" for macOS 12.5 is actually "21.6.0".
return ((OSX_Version() & 0xFF) < 0x60);
}
bool macOS_Monterey_5_or_greater()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_12_HEX)) {
return false;
}
// The output of "uname -r" for macOS 12.5 is actually "21.6.0".
return ((OSX_Version() & 0xFF) >= 0x60);
}
// The build number for macOS 12.7.1 is 21G920.
bool macOS_Monterey_less_than_7_1()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_12_HEX)) {
return false;
}
// The output of "uname -r" for macOS 12.7.X is "21.6.0"
if ((OSX_Version() & 0xFF) > 0x60) {
return false;
}
long build_num = macOS_build_num();
return ((build_num != -1) && (build_num < 920));
}
// The build number for macOS 12.7.1 is 21G920.
bool macOS_Monterey_7_1_or_greater()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_12_HEX)) {
return false;
}
// The output of "uname -r" for macOS 12.7.X is "21.6.0"
if ((OSX_Version() & 0xFF) < 0x60) {
return false;
}
long build_num = macOS_build_num();
return ((build_num != -1) && (build_num >= 920));
}
bool macOS_Ventura()
{
return ((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_13_HEX);
}
bool macOS_Ventura_less_than_3()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_13_HEX)) {
return false;
}
// The output of "uname -r" for macOS 13.3 is actually "22.4.0".
return ((OSX_Version() & 0xFF) < 0x40);
}
bool macOS_Ventura_3_or_greater()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_13_HEX)) {
return false;
}
// The output of "uname -r" for macOS 13.3 is actually "22.4.0".
return ((OSX_Version() & 0xFF) >= 0x40);
}
// The build number for macOS 13.6.1 is 22G313.
bool macOS_Ventura_less_than_6_1()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_13_HEX)) {
return false;
}
// The output of "uname -r" for macOS 13.6.X is "22.6.0"
if ((OSX_Version() & 0xFF) > 0x60) {
return false;
}
long build_num = macOS_build_num();
return ((build_num != -1) && (build_num < 313));
}
// The build number for macOS 13.6.1 is 22G313.
bool macOS_Ventura_6_1_or_greater()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_13_HEX)) {
return false;
}
// The output of "uname -r" for macOS 13.6.X is "22.6.0"
if ((OSX_Version() & 0xFF) < 0x60) {
return false;
}
long build_num = macOS_build_num();
return ((build_num != -1) && (build_num >= 313));
}
bool macOS_Sonoma()
{
return ((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_14_HEX);
}
bool macOS_Sonoma_less_than_1()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_14_HEX)) {
return false;
}
return ((OSX_Version() & 0xFF) < 0x10);
}
bool macOS_Sonoma_1_or_greater()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_14_HEX)) {
return false;
}
return ((OSX_Version() & 0xFF) >= 0x10);
}
bool macOS_Sonoma_less_than_4()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_14_HEX)) {
return false;
}
return ((OSX_Version() & 0xFF) < 0x40);
}
bool macOS_Sonoma_4_or_greater()
{
if (!((OSX_Version() & 0xFF00) == MAC_OS_X_VERSION_14_HEX)) {
return false;
}
return ((OSX_Version() & 0xFF) >= 0x40);
}
bool OSX_Version_Unsupported()
{
return (((OSX_Version() & 0xFF00) < MAC_OS_X_VERSION_10_9_HEX) ||
((OSX_Version() & 0xFF00) > MAC_OS_X_VERSION_14_HEX));
}
// When using the debug kernel, set "kernel_stack_pages=6" in the boot args
// (1.5 times its default value). Otherwise we can run out of stack space, at
// least on ElCapitan. A sign of this is a double-fault with CR2 set to an
// address on the stack.
// It is *not* safe to use the value of the kcsuffix boot-arg to determine
// what kind of kernel is running. There are other ways of choosing which
// kernel to run, and sometimes the value of kcsuffix is ignored.
char *g_kernel_version = NULL;
typedef char *(*strnstr_t)(char *s, const char *find, size_t slen);
static strnstr_t strnstr_ptr = NULL;
typedef enum {
kernel_type_unknown = 0,
kernel_type_release = 1,
kernel_type_development = 2,
kernel_type_debug = 3,
kernel_type_unset = -1,
} kernel_type;
void *kernel_dlsym(const char *symbol);
kernel_type get_kernel_type()
{
static kernel_type type = kernel_type_unset;
if (type != kernel_type_unset) {
return type;
}
if (!g_kernel_version) {
g_kernel_version = (char *)
kernel_dlsym("_version");
if (!g_kernel_version) {
return kernel_type_unknown;
}
}
if (!strnstr_ptr) {
strnstr_ptr = (strnstr_t)
kernel_dlsym("_strnstr");
if (!strnstr_ptr) {
return kernel_type_unknown;
}
}
if (strnstr_ptr(g_kernel_version, "RELEASE", strlen(g_kernel_version))) {
type = kernel_type_release;
} else if (strnstr_ptr(g_kernel_version, "DEVELOPMENT", strlen(g_kernel_version))) {
type = kernel_type_development;
} else if (strnstr_ptr(g_kernel_version, "DEBUG", strlen(g_kernel_version))) {
type = kernel_type_debug;
} else {
type = kernel_type_unknown;
}
// The DEBUG kernel is currently very flaky on macOS 10.14, to the extent
// that we need to disable support for it. There are lots of panics, with
// and without HookCase. In fact all that's needed to trigger a panic is to
// start Safari, visit apple.com, then quit it. These panics all have the
// error "Assertion failed: object->vo_purgeable_volatilizer == NULL".
//
// The macOS 10.14 DEBUG kernel is still a bit flaky (as of 10.14.5), but
// it's not nearly so bad as before.
#if (0)
if (macOS_Mojave()) {
if (type == kernel_type_debug) {
type = kernel_type_unknown;
}
}
#endif
return type;
}
bool kernel_type_is_release()
{
return (get_kernel_type() == kernel_type_release);
}
bool kernel_type_is_development()
{
return (get_kernel_type() == kernel_type_development);
}
bool kernel_type_is_debug()
{
return (get_kernel_type() == kernel_type_debug);
}
bool kernel_type_is_unknown()
{
return (get_kernel_type() == kernel_type_unknown);
}
#define VM_MIN_KERNEL_ADDRESS ((vm_offset_t) 0xFFFFFF8000000000UL)
#define VM_MIN_KERNEL_AND_KEXT_ADDRESS (VM_MIN_KERNEL_ADDRESS - 0x80000000ULL)
#define VM_MAX_USER_PAGE_ADDRESS ((user_addr_t)0x00007FFFFFFFF000ULL)
// The system kernel (stored in /System/Library/Kernels on OS X 10.10 and up)
// is (in some senses) an ordinary Mach-O binary. You can use 'otool -hv' to
// show its Mach header, and 'otool -lv' to display its "load commands" (all
// of its segments and sections). From the output of 'otool -lv' it's
// apparent that the kernel (starting with its Mach header) is meant to be
// loaded at 0xFFFFFF8000200000. But recent versions of OS X implement ASLR
// (Address Space Layout Randomization) for the kernel -- they "slide" all
// kernel addresses by a random value (determined at startup). So in order
// to find the address of the kernel (and of its Mach header), we also need to
// know the value of this "kernel slide".
#define KERNEL_HEADER_ADDR 0xFFFFFF8000200000
vm_offset_t g_kernel_slide = 0;
struct mach_header_64 *g_kernel_header = NULL;
// Find the address of the kernel's Mach header.
bool find_kernel_header()
{
if (g_kernel_header) {
return true;
}
#if (defined(MAC_OS_X_VERSION_10_11)) && \
(MAC_OS_X_VERSION_MAX_ALLOWED / 100) >= (MAC_OS_X_VERSION_10_11 / 100)
// vm_kernel_unslide_or_perm_external() is only available on OS X 10.11 and up.
if (OSX_ElCapitan() || macOS_Sierra() || macOS_HighSierra() ||
macOS_Mojave() || macOS_Catalina() || macOS_BigSur() ||
macOS_Monterey() || macOS_Ventura() || macOS_Sonoma())
{
vm_offset_t func_address = (vm_offset_t) vm_kernel_unslide_or_perm_external;
vm_offset_t func_address_unslid = 0;
vm_kernel_unslide_or_perm_external(func_address, &func_address_unslid);
vm_offset_t slide = func_address - func_address_unslid;
// On macOS Big Sur and up, 'slide' is set to the the "kernel cache
// slide" -- an offset to the location of the "kernel cache", which
// contains the kernel and a bunch of kernel extensions. The kernel
// itself is inside this "cache". Find it to determine the "kernel slide".
if (macOS_Sonoma() || macOS_Ventura() || macOS_Monterey() ||
macOS_BigSur())
{
bool kernel_header_found = false;
vm_offset_t slide_increment;
// The 0x100000 limit and 0x1000 increment were determined by trial
// and error.
for (slide_increment = 0; slide_increment < 0x100000;
slide_increment += 0x1000)
{
addr64_t addr = KERNEL_HEADER_ADDR + slide + slide_increment;
// pmap_find_phys() returns 0 if 'addr' isn't a valid address.
if (!pmap_find_phys(kernel_pmap, addr)) {
continue;
}
struct mach_header_64 *header = (struct mach_header_64 *) addr;
if ((header->magic != MH_MAGIC_64) ||
(header->cputype != CPU_TYPE_X86_64) ||
(header->cpusubtype != CPU_SUBTYPE_I386_ALL) ||
(header->filetype != MH_EXECUTE) ||
!(header->flags & (MH_NOUNDEFS | MH_PIE)))
{
continue;
}
g_kernel_slide = slide + slide_increment;
kernel_header_found = true;
break;
}
if (!kernel_header_found) {
return false;
}
} else {
g_kernel_slide = slide;
}
} else {
#endif
bool kernel_header_found = false;
vm_offset_t slide;
// The 0x10000 increment was determined by trial and error.
for (slide = 0; slide < 0x100000000; slide += 0x10000) {
addr64_t addr = KERNEL_HEADER_ADDR + slide;
// pmap_find_phys() returns 0 if 'addr' isn't a valid address.
if (!pmap_find_phys(kernel_pmap, addr)) {
continue;
}
struct mach_header_64 *header = (struct mach_header_64 *) addr;
if ((header->magic != MH_MAGIC_64) ||
(header->cputype != CPU_TYPE_X86_64) ||
(header->cpusubtype != CPU_SUBTYPE_I386_ALL) ||
(header->filetype != MH_EXECUTE) ||
!(header->flags & (MH_NOUNDEFS | MH_PIE)))
{
continue;
}
g_kernel_slide = slide;
kernel_header_found = true;
break;
}
if (!kernel_header_found) {
return false;
}
#if (defined(MAC_OS_X_VERSION_10_11)) && \
(MAC_OS_X_VERSION_MAX_ALLOWED / 100) >= (MAC_OS_X_VERSION_10_11 / 100)
}
#endif
g_kernel_header = (struct mach_header_64 *)
(KERNEL_HEADER_ADDR + g_kernel_slide);
return true;
}
// Fill the whole structure with 0xFF to indicate that it hasn't yet been
// initialized.
typedef struct _symbol_table_info {
vm_offset_t symbolTableOffset;
vm_offset_t stringTableOffset;
uint32_t symbols_index;
uint32_t symbols_count;
} symbol_table_info_t;
void *kernel_module_dlsym(struct mach_header_64 *header, const char *symbol,
symbol_table_info_t *info)
{
if (!header || !symbol) {
return NULL;
}
// Sanity check
if (!pmap_find_phys(kernel_pmap, (addr64_t) header)) {
return NULL;
}
if ((header->magic != MH_MAGIC_64) ||
(header->cputype != CPU_TYPE_X86_64) ||
(header->cpusubtype != CPU_SUBTYPE_I386_ALL) ||
((header->filetype != MH_EXECUTE) &&
(header->filetype != MH_KEXT_BUNDLE)) ||
((header->flags & MH_NOUNDEFS) == 0))
{
return NULL;
}
vm_offset_t symbolTableOffset = 0;
vm_offset_t stringTableOffset = 0;
uint32_t symbols_index = 0;
uint32_t symbols_count = 0;
uint32_t all_symbols_count = 0;
// Find the symbol table, if need be
if (info && info->symbolTableOffset != -1L) {
symbolTableOffset = info->symbolTableOffset;
stringTableOffset = info->stringTableOffset;
symbols_index = info->symbols_index;
symbols_count = info->symbols_count;
} else {
vm_offset_t linkedit_fileoff_increment = 0;
bool found_symbol_table = false;
bool found_linkedit_segment = false;
bool found_symtab_segment = false;
bool found_dysymtab_segment = false;
uint32_t num_commands = header->ncmds;
const struct load_command *load_command = (struct load_command *)
((vm_offset_t)header + sizeof(struct mach_header_64));
uint32_t i;
for (i = 1; i <= num_commands; ++i) {
uint32_t cmd = load_command->cmd;
switch (cmd) {
case LC_SEGMENT_64: {
if (found_linkedit_segment) {
return NULL;
}
struct segment_command_64 *command =
(struct segment_command_64 *) load_command;
const char *linkedit_segname = "__LINKEDIT";
if (!strncmp(command->segname, linkedit_segname,
strlen(linkedit_segname) + 1))
{
linkedit_fileoff_increment = command->vmaddr - command->fileoff;
found_linkedit_segment = true;
}
break;
}
case LC_SYMTAB: {
if (!found_linkedit_segment) {
return NULL;
}
struct symtab_command *command =
(struct symtab_command *) load_command;
symbolTableOffset = command->symoff + linkedit_fileoff_increment;
stringTableOffset = command->stroff + linkedit_fileoff_increment;
all_symbols_count = command->nsyms;
found_symtab_segment = true;
// It seems that either LC_SYMTAB's nsyms will be set or LC_DSYMTAB's
// iextdefsym and nextdefsym, but not both. Loaded kexts use nsyms,
// but the kernel itself uses iextdefsym and nextdefsym. If nsyms is
// set, LC_DYSYMTAB is no longer needed. And as of the macOS 10.15.5
// supplemental update it's absent altogether in kexts.
if (all_symbols_count) {
symbols_index = 0;
symbols_count = all_symbols_count;
found_dysymtab_segment = true;
}
break;
}
case LC_DYSYMTAB: {
if (!found_linkedit_segment) {
return NULL;
}
if (!all_symbols_count) {
struct dysymtab_command *command =
(struct dysymtab_command *) load_command;
symbols_index = command->iextdefsym;
symbols_count = symbols_index + command->nextdefsym;
}
found_dysymtab_segment = true;
break;
}
default: {
if (found_linkedit_segment) {
return NULL;
}
break;
}
}
if (found_linkedit_segment && found_symtab_segment && found_dysymtab_segment) {
found_symbol_table = true;
break;
}
load_command = (struct load_command *)
((vm_offset_t)load_command + load_command->cmdsize);
}
if (!found_symbol_table) {
return NULL;
}
if (info) {
info->symbolTableOffset = symbolTableOffset;
info->stringTableOffset = stringTableOffset;
info->symbols_index = symbols_index;
info->symbols_count = symbols_count;
}
}
// If we're in a kernel extension, the symbol and string tables won't be
// accessible unless the "keepsyms=1" kernel boot arg has been specified.
// Use this check to fail gracefully in this situation.
if (!pmap_find_phys(kernel_pmap, (addr64_t) symbolTableOffset) ||
!pmap_find_phys(kernel_pmap, (addr64_t) stringTableOffset))
{
return NULL;
}
// Search the symbol table
uint32_t i;
for (i = symbols_index; i < symbols_count; ++i) {
struct nlist_64 *symbolTableItem = (struct nlist_64 *)
(symbolTableOffset + i * sizeof(struct nlist_64));
uint8_t type = symbolTableItem->n_type;
if ((type & N_STAB) || ((type & N_TYPE) != N_SECT)) {
continue;
}
uint8_t sect = symbolTableItem->n_sect;
if (!sect) {
continue;
}
const char *stringTableItem = (char *)
(stringTableOffset + symbolTableItem->n_un.n_strx);
if (stringTableItem &&
!strncmp(stringTableItem, symbol, strlen(symbol) + 1))
{
return (void *) symbolTableItem->n_value;
}
}
return NULL;
}
// The running kernel contains a valid symbol table. We can use this to find
// the address of any "external" kernel symbol, including those considered
// "private". 'symbol' should be exactly what's listed in the symbol table,
// including the "extra" leading underscore.
void *kernel_dlsym(const char *symbol)
{
if (!find_kernel_header()) {
return NULL;
}
static symbol_table_info_t kernel_symbol_info;
static bool found_symbol_table = false;
if (!found_symbol_table) {
memset((void *) &kernel_symbol_info, 0xFF, sizeof(kernel_symbol_info));
}
void *retval =
kernel_module_dlsym(g_kernel_header, symbol, &kernel_symbol_info);
if (kernel_symbol_info.symbolTableOffset != -1L) {
found_symbol_table = true;
}
return retval;
}
typedef OSDictionary *(*OSKext_copyLoadedKextInfo_t)(OSArray *kextIdentifiers,
OSArray *infoKeys);
static OSKext_copyLoadedKextInfo_t OSKext_copyLoadedKextInfo = NULL;
#define kOSBundleLoadAddressKey "OSBundleLoadAddress"
// Loaded kernel extensions also contain valid symbol tables. But unless the
// "keepsyms=1" kernel boot arg has been specified, they have been made
// inaccessible in OSKext::jettisonLinkeditSegment().
void *kext_dlsym(const char *bundle_id, const char *symbol)
{
if (!OSKext_copyLoadedKextInfo) {
OSKext_copyLoadedKextInfo = (OSKext_copyLoadedKextInfo_t)
kernel_dlsym("__ZN6OSKext18copyLoadedKextInfoEP7OSArrayS1_");
if (!OSKext_copyLoadedKextInfo) {
return NULL;
}
}