This repository has been archived by the owner on May 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathkasan.c
1546 lines (1317 loc) · 40.4 KB
/
kasan.c
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
/*
* Copyright (c) 2016 Apple Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include <vm/vm_map.h>
#include <kern/assert.h>
#include <kern/cpu_data.h>
#include <kern/backtrace.h>
#include <machine/machine_routines.h>
#include <kern/locks.h>
#include <kern/simple_lock.h>
#include <kern/debug.h>
#include <mach/mach_vm.h>
#include <mach/mach_types.h>
#include <mach/vm_param.h>
#include <mach/machine/vm_param.h>
#include <mach/sdt.h>
#include <libkern/libkern.h>
#include <libkern/OSAtomic.h>
#include <libkern/kernel_mach_header.h>
#include <sys/queue.h>
#include <sys/sysctl.h>
#include <kern/thread.h>
#include <machine/atomic.h>
#include <kasan.h>
#include <kasan_internal.h>
#include <memintrinsics.h>
const uintptr_t __asan_shadow_memory_dynamic_address = KASAN_OFFSET;
static unsigned kexts_loaded;
unsigned shadow_pages_total;
unsigned shadow_pages_used;
vm_offset_t kernel_vbase;
vm_offset_t kernel_vtop;
static unsigned kasan_enabled;
static unsigned quarantine_enabled;
static unsigned enabled_checks = TYPE_ALL & ~TYPE_LEAK; /* bitmask of enabled checks */
static unsigned report_ignored; /* issue non-fatal report for disabled/blacklisted checks */
static unsigned free_yield = 0; /* ms yield after each free */
static unsigned leak_threshold = 3; /* threshold for uninitialized memory leak detection */
static unsigned leak_fatal_threshold = 0; /* threshold for treating leaks as fatal errors (0 means never) */
/* forward decls */
static void kasan_crash_report(uptr p, uptr width, access_t access, violation_t reason);
static void kasan_log_report(uptr p, uptr width, access_t access, violation_t reason);
/* imported osfmk functions */
extern vm_offset_t ml_stack_base(void);
extern vm_size_t ml_stack_size(void);
/*
* unused: expected to be called, but (currently) does nothing
*/
#define UNUSED_ABI(func, ...) \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wunused-parameter\"") \
void func(__VA_ARGS__); \
void func(__VA_ARGS__) {}; \
_Pragma("clang diagnostic pop") \
static const size_t BACKTRACE_BITS = 4;
static const size_t BACKTRACE_MAXFRAMES = (1UL << BACKTRACE_BITS) - 1;
static vm_size_t kasan_alloc_retrieve_bt(vm_address_t addr, uintptr_t frames[static BACKTRACE_MAXFRAMES]);
decl_simple_lock_data(, kasan_vm_lock);
static thread_t kasan_lock_holder;
/*
* kasan is called from the interrupt path, so we need to disable interrupts to
* ensure atomicity manipulating the global objects
*/
void
kasan_lock(boolean_t *b)
{
*b = ml_set_interrupts_enabled(false);
simple_lock(&kasan_vm_lock, LCK_GRP_NULL);
kasan_lock_holder = current_thread();
}
void
kasan_unlock(boolean_t b)
{
kasan_lock_holder = THREAD_NULL;
simple_unlock(&kasan_vm_lock);
ml_set_interrupts_enabled(b);
}
/* Return true if 'thread' holds the kasan lock. Only safe if 'thread' == current
* thread */
bool
kasan_lock_held(thread_t thread)
{
return thread && thread == kasan_lock_holder;
}
static inline bool
kasan_check_enabled(access_t access)
{
return kasan_enabled && (enabled_checks & access) && !kasan_is_blacklisted(access);
}
static inline bool
kasan_poison_active(uint8_t flags)
{
switch (flags) {
case ASAN_GLOBAL_RZ:
return kasan_check_enabled(TYPE_POISON_GLOBAL);
case ASAN_HEAP_RZ:
case ASAN_HEAP_LEFT_RZ:
case ASAN_HEAP_RIGHT_RZ:
case ASAN_HEAP_FREED:
return kasan_check_enabled(TYPE_POISON_HEAP);
default:
return true;
}
}
/*
* poison redzones in the shadow map
*/
void NOINLINE
kasan_poison(vm_offset_t base, vm_size_t size, vm_size_t leftrz, vm_size_t rightrz, uint8_t flags)
{
uint8_t *shadow = SHADOW_FOR_ADDRESS(base);
uint8_t partial = (uint8_t)kasan_granule_partial(size);
vm_size_t total = leftrz + size + rightrz;
vm_size_t i = 0;
/* ensure base, leftrz and total allocation size are granule-aligned */
assert(kasan_granule_partial(base) == 0);
assert(kasan_granule_partial(leftrz) == 0);
assert(kasan_granule_partial(total) == 0);
if (!kasan_enabled || !kasan_poison_active(flags)) {
return;
}
leftrz >>= KASAN_SCALE;
size >>= KASAN_SCALE;
total >>= KASAN_SCALE;
uint8_t l_flags = flags;
uint8_t r_flags = flags;
if (flags == ASAN_STACK_RZ) {
l_flags = ASAN_STACK_LEFT_RZ;
r_flags = ASAN_STACK_RIGHT_RZ;
} else if (flags == ASAN_HEAP_RZ) {
l_flags = ASAN_HEAP_LEFT_RZ;
r_flags = ASAN_HEAP_RIGHT_RZ;
}
/*
* poison the redzones and unpoison the valid bytes
*/
for (; i < leftrz; i++) {
shadow[i] = l_flags;
}
for (; i < leftrz + size; i++) {
shadow[i] = ASAN_VALID; /* XXX: should not be necessary */
}
if (partial && (i < total)) {
shadow[i] = partial;
i++;
}
for (; i < total; i++) {
shadow[i] = r_flags;
}
}
void
kasan_poison_range(vm_offset_t base, vm_size_t size, uint8_t flags)
{
assert(kasan_granule_partial(base) == 0);
assert(kasan_granule_partial(size) == 0);
kasan_poison(base, 0, 0, size, flags);
}
void NOINLINE
kasan_unpoison(void *base, vm_size_t size)
{
kasan_poison((vm_offset_t)base, size, 0, 0, 0);
}
void NOINLINE
kasan_unpoison_stack(uintptr_t base, size_t size)
{
assert(base > 0);
assert(size > 0);
size_t partial = kasan_granule_partial(base);
base = kasan_granule_trunc(base);
size = kasan_granule_round(size + partial);
kasan_unpoison((void *)base, size);
}
/*
* write junk into the redzones
*/
static void NOINLINE
kasan_rz_clobber(vm_offset_t base, vm_size_t size, vm_size_t leftrz, vm_size_t rightrz)
{
#if KASAN_DEBUG
vm_size_t i;
const uint8_t deadbeef[] = { 0xde, 0xad, 0xbe, 0xef };
const uint8_t c0ffee[] = { 0xc0, 0xff, 0xee, 0xc0 };
uint8_t *buf = (uint8_t *)base;
assert(kasan_granule_partial(base) == 0);
assert(kasan_granule_partial(leftrz) == 0);
assert(kasan_granule_partial(size + leftrz + rightrz) == 0);
for (i = 0; i < leftrz; i++) {
buf[i] = deadbeef[i % 4];
}
for (i = 0; i < rightrz; i++) {
buf[i + size + leftrz] = c0ffee[i % 4];
}
#else
(void)base;
(void)size;
(void)leftrz;
(void)rightrz;
#endif
}
/*
* Report a violation that may be disabled and/or blacklisted. This can only be
* called for dynamic checks (i.e. where the fault is recoverable). Use
* kasan_crash_report() for static (unrecoverable) violations.
*
* access: what we were trying to do when the violation occured
* reason: what failed about the access
*/
static void
kasan_violation(uintptr_t addr, size_t size, access_t access, violation_t reason)
{
assert(__builtin_popcount(access) == 1);
if (!kasan_check_enabled(access)) {
if (report_ignored) {
kasan_log_report(addr, size, access, reason);
}
return;
}
kasan_crash_report(addr, size, access, reason);
}
void NOINLINE
kasan_check_range(const void *x, size_t sz, access_t access)
{
uintptr_t invalid;
uintptr_t ptr = (uintptr_t)x;
if (kasan_range_poisoned(ptr, sz, &invalid)) {
size_t remaining = sz - (invalid - ptr);
kasan_violation(invalid, remaining, access, 0);
}
}
/*
* Return true if [base, base+sz) is unpoisoned or has given shadow value.
*/
bool
kasan_check_shadow(vm_address_t addr, vm_size_t sz, uint8_t shadow)
{
/* round 'base' up to skip any partial, which won't match 'shadow' */
uintptr_t base = kasan_granule_round(addr);
sz -= base - addr;
uintptr_t end = base + sz;
while (base < end) {
uint8_t *sh = SHADOW_FOR_ADDRESS(base);
if (*sh && *sh != shadow) {
return false;
}
base += KASAN_GRANULE;
}
return true;
}
static void
kasan_report_leak(vm_address_t base, vm_size_t sz, vm_offset_t offset, vm_size_t leak_sz)
{
if (leak_fatal_threshold > leak_threshold && leak_sz >= leak_fatal_threshold) {
kasan_violation(base + offset, leak_sz, TYPE_LEAK, REASON_UNINITIALIZED);
}
char string_rep[BACKTRACE_MAXFRAMES * 20] = {};
vm_offset_t stack_base = dtrace_get_kernel_stack(current_thread());
bool is_stack = (base >= stack_base && base < (stack_base + kernel_stack_size));
if (!is_stack) {
uintptr_t alloc_bt[BACKTRACE_MAXFRAMES] = {};
vm_size_t num_frames = 0;
size_t l = 0;
num_frames = kasan_alloc_retrieve_bt(base, alloc_bt);
for (vm_size_t i = 0; i < num_frames; i++) {
l += scnprintf(string_rep + l, sizeof(string_rep) - l, " %lx", alloc_bt[i]);
}
}
DTRACE_KASAN5(leak_detected,
vm_address_t, base,
vm_size_t, sz,
vm_offset_t, offset,
vm_size_t, leak_sz,
char *, string_rep);
}
/*
* Initialize buffer by writing unique pattern that can be looked for
* in copyout path to detect uninitialized memory leaks.
*/
void
kasan_leak_init(vm_address_t addr, vm_size_t sz)
{
if (enabled_checks & TYPE_LEAK) {
__nosan_memset((void *)addr, KASAN_UNINITIALIZED_HEAP, sz);
}
}
/*
* Check for possible uninitialized memory contained in [base, base+sz).
*/
void
kasan_check_uninitialized(vm_address_t base, vm_size_t sz)
{
if (!(enabled_checks & TYPE_LEAK) || sz < leak_threshold) {
return;
}
vm_address_t cur = base;
vm_address_t end = base + sz;
vm_size_t count = 0;
vm_size_t max_count = 0;
vm_address_t leak_offset = 0;
uint8_t byte = 0;
while (cur < end) {
byte = *(uint8_t *)cur;
count = (byte == KASAN_UNINITIALIZED_HEAP) ? (count + 1) : 0;
if (count > max_count) {
max_count = count;
leak_offset = cur - (count - 1) - base;
}
cur += 1;
}
if (max_count >= leak_threshold) {
kasan_report_leak(base, sz, leak_offset, max_count);
}
}
/*
*
* KASAN violation reporting
*
*/
static const char *
access_str(access_t type)
{
if (type & TYPE_READ) {
return "load from";
} else if (type & TYPE_WRITE) {
return "store to";
} else if (type & TYPE_FREE) {
return "free of";
} else if (type & TYPE_LEAK) {
return "leak from";
} else {
return "access of";
}
}
static const char *shadow_strings[] = {
[ASAN_VALID] = "VALID",
[ASAN_PARTIAL1] = "PARTIAL1",
[ASAN_PARTIAL2] = "PARTIAL2",
[ASAN_PARTIAL3] = "PARTIAL3",
[ASAN_PARTIAL4] = "PARTIAL4",
[ASAN_PARTIAL5] = "PARTIAL5",
[ASAN_PARTIAL6] = "PARTIAL6",
[ASAN_PARTIAL7] = "PARTIAL7",
[ASAN_STACK_LEFT_RZ] = "STACK_LEFT_RZ",
[ASAN_STACK_MID_RZ] = "STACK_MID_RZ",
[ASAN_STACK_RIGHT_RZ] = "STACK_RIGHT_RZ",
[ASAN_STACK_FREED] = "STACK_FREED",
[ASAN_STACK_OOSCOPE] = "STACK_OOSCOPE",
[ASAN_GLOBAL_RZ] = "GLOBAL_RZ",
[ASAN_HEAP_LEFT_RZ] = "HEAP_LEFT_RZ",
[ASAN_HEAP_RIGHT_RZ] = "HEAP_RIGHT_RZ",
[ASAN_HEAP_FREED] = "HEAP_FREED",
[0xff] = NULL
};
#define CRASH_CONTEXT_BEFORE 5
#define CRASH_CONTEXT_AFTER 5
static size_t
kasan_shadow_crashlog(uptr p, char *buf, size_t len)
{
int i, j;
size_t n = 0;
int before = CRASH_CONTEXT_BEFORE;
int after = CRASH_CONTEXT_AFTER;
uptr shadow = (uptr)SHADOW_FOR_ADDRESS(p);
uptr shadow_p = shadow;
uptr shadow_page = vm_map_round_page(shadow_p, HW_PAGE_MASK);
/* rewind to start of context block */
shadow &= ~((uptr)0xf);
shadow -= 16 * before;
n += scnprintf(buf + n, len - n,
" Shadow 0 1 2 3 4 5 6 7 8 9 a b c d e f\n");
for (i = 0; i < 1 + before + after; i++, shadow += 16) {
if ((vm_map_round_page(shadow, HW_PAGE_MASK) != shadow_page) && !kasan_is_shadow_mapped(shadow)) {
/* avoid unmapped shadow when crossing page boundaries */
continue;
}
n += scnprintf(buf + n, len - n, " %16lx:", shadow);
char *left = " ";
char *right;
for (j = 0; j < 16; j++) {
uint8_t *x = (uint8_t *)(shadow + j);
right = " ";
if ((uptr)x == shadow_p) {
left = "[";
right = "]";
} else if ((uptr)(x + 1) == shadow_p) {
right = "";
}
n += scnprintf(buf + n, len - n, "%s%02x%s", left, (unsigned)*x, right);
left = "";
}
n += scnprintf(buf + n, len - n, "\n");
}
n += scnprintf(buf + n, len - n, "\n");
return n;
}
static void
kasan_report_internal(uptr p, uptr width, access_t access, violation_t reason, bool dopanic)
{
const size_t len = 4096;
static char buf[len];
size_t n = 0;
uint8_t *shadow_ptr = SHADOW_FOR_ADDRESS(p);
uint8_t shadow_type = *shadow_ptr;
const char *shadow_str = shadow_strings[shadow_type];
if (!shadow_str) {
shadow_str = "<invalid>";
}
buf[0] = '\0';
if (reason == REASON_MOD_OOB || reason == REASON_BAD_METADATA) {
n += scnprintf(buf + n, len - n, "KASan: free of corrupted/invalid object %#lx\n", p);
} else if (reason == REASON_MOD_AFTER_FREE) {
n += scnprintf(buf + n, len - n, "KASan: UaF of quarantined object %#lx\n", p);
} else {
n += scnprintf(buf + n, len - n, "KASan: invalid %lu-byte %s %#lx [%s]\n",
width, access_str(access), p, shadow_str);
}
n += kasan_shadow_crashlog(p, buf + n, len - n);
if (dopanic) {
panic("%s", buf);
} else {
printf("%s", buf);
}
}
static void NOINLINE OS_NORETURN
kasan_crash_report(uptr p, uptr width, access_t access, violation_t reason)
{
kasan_handle_test();
kasan_report_internal(p, width, access, reason, true);
__builtin_unreachable(); /* we cant handle this returning anyway */
}
static void
kasan_log_report(uptr p, uptr width, access_t access, violation_t reason)
{
const size_t len = 256;
char buf[len];
size_t l = 0;
uint32_t nframes = 14;
uintptr_t frames[nframes];
uintptr_t *bt = frames;
kasan_report_internal(p, width, access, reason, false);
/*
* print a backtrace
*/
nframes = backtrace_frame(bt, nframes, __builtin_frame_address(0),
NULL); /* ignore current frame */
buf[0] = '\0';
l += scnprintf(buf + l, len - l, "Backtrace: ");
for (uint32_t i = 0; i < nframes; i++) {
l += scnprintf(buf + l, len - l, "%lx,", VM_KERNEL_UNSLIDE(bt[i]));
}
l += scnprintf(buf + l, len - l, "\n");
printf("%s", buf);
}
#define REPORT_DECLARE(n) \
void OS_NORETURN __asan_report_load##n(uptr p) { kasan_crash_report(p, n, TYPE_LOAD, 0); } \
void OS_NORETURN __asan_report_store##n(uptr p) { kasan_crash_report(p, n, TYPE_STORE, 0); } \
void OS_NORETURN UNSUPPORTED_API(__asan_report_exp_load##n, uptr a, int32_t b); \
void OS_NORETURN UNSUPPORTED_API(__asan_report_exp_store##n, uptr a, int32_t b);
REPORT_DECLARE(1)
REPORT_DECLARE(2)
REPORT_DECLARE(4)
REPORT_DECLARE(8)
REPORT_DECLARE(16)
void OS_NORETURN
__asan_report_load_n(uptr p, unsigned long sz)
{
kasan_crash_report(p, sz, TYPE_LOAD, 0);
}
void OS_NORETURN
__asan_report_store_n(uptr p, unsigned long sz)
{
kasan_crash_report(p, sz, TYPE_STORE, 0);
}
/* unpoison the current stack */
void NOINLINE
kasan_unpoison_curstack(bool whole_stack)
{
uintptr_t base = ml_stack_base();
size_t sz = ml_stack_size();
uintptr_t cur = (uintptr_t)&base;
if (whole_stack) {
cur = base;
}
if (cur >= base && cur < base + sz) {
/* unpoison from current stack depth to the top */
size_t unused = cur - base;
kasan_unpoison_stack(cur, sz - unused);
}
}
void NOINLINE
__asan_handle_no_return(void)
{
kasan_unpoison_curstack(false);
/*
* No need to free any fakestack objects because they must stay alive until
* we drop the real stack, at which point we can drop the entire fakestack
* anyway.
*/
}
bool NOINLINE
kasan_range_poisoned(vm_offset_t base, vm_size_t size, vm_offset_t *first_invalid)
{
uint8_t *shadow;
vm_size_t i;
if (!kasan_enabled) {
return false;
}
size += kasan_granule_partial(base);
base = kasan_granule_trunc(base);
shadow = SHADOW_FOR_ADDRESS(base);
size_t limit = (size + KASAN_GRANULE - 1) / KASAN_GRANULE;
/* XXX: to make debugging easier, catch unmapped shadow here */
for (i = 0; i < limit; i++, size -= KASAN_GRANULE) {
assert(size > 0);
uint8_t s = shadow[i];
if (s == 0 || (size < KASAN_GRANULE && s >= size && s < KASAN_GRANULE)) {
/* valid */
} else {
goto fail;
}
}
return false;
fail:
if (first_invalid) {
/* XXX: calculate the exact first byte that failed */
*first_invalid = base + i * 8;
}
return true;
}
static void NOINLINE
kasan_init_globals(vm_offset_t base, vm_size_t size)
{
struct asan_global *glob = (struct asan_global *)base;
struct asan_global *glob_end = (struct asan_global *)(base + size);
for (; glob < glob_end; glob++) {
/* handle one global */
kasan_poison(glob->addr, glob->size, 0, glob->size_with_redzone - glob->size, ASAN_GLOBAL_RZ);
}
}
void NOINLINE
kasan_load_kext(vm_offset_t base, vm_size_t __unused size, const void *bundleid)
{
unsigned long sectsz;
void *sect;
#if KASAN_DYNAMIC_BLACKLIST
kasan_dybl_load_kext(base, bundleid);
#endif
/* find the kasan globals segment/section */
sect = getsectdatafromheader((void *)base, KASAN_GLOBAL_SEGNAME, KASAN_GLOBAL_SECTNAME, §sz);
if (sect) {
kasan_init_globals((vm_address_t)sect, (vm_size_t)sectsz);
kexts_loaded++;
}
}
void NOINLINE
kasan_unload_kext(vm_offset_t base, vm_size_t size)
{
unsigned long sectsz;
void *sect;
/* find the kasan globals segment/section */
sect = getsectdatafromheader((void *)base, KASAN_GLOBAL_SEGNAME, KASAN_GLOBAL_SECTNAME, §sz);
if (sect) {
kasan_unpoison((void *)base, size);
kexts_loaded--;
}
#if KASAN_DYNAMIC_BLACKLIST
kasan_dybl_unload_kext(base);
#endif
}
/*
* Turn off as much as possible for panic path etc. There's no way to turn it back
* on.
*/
void NOINLINE
kasan_disable(void)
{
__asan_option_detect_stack_use_after_return = 0;
fakestack_enabled = 0;
kasan_enabled = 0;
quarantine_enabled = 0;
enabled_checks = 0;
}
static void NOINLINE
kasan_init_xnu_globals(void)
{
const char *seg = KASAN_GLOBAL_SEGNAME;
const char *sect = KASAN_GLOBAL_SECTNAME;
unsigned long _size;
vm_offset_t globals;
vm_size_t size;
kernel_mach_header_t *header = (kernel_mach_header_t *)&_mh_execute_header;
if (!header) {
printf("KASan: failed to find kernel mach header\n");
printf("KASan: redzones for globals not poisoned\n");
return;
}
globals = (vm_offset_t)getsectdatafromheader(header, seg, sect, &_size);
if (!globals) {
printf("KASan: failed to find segment %s section %s\n", seg, sect);
printf("KASan: redzones for globals not poisoned\n");
return;
}
size = (vm_size_t)_size;
printf("KASan: found (%s,%s) at %#lx + %lu\n", seg, sect, globals, size);
printf("KASan: poisoning redzone for %lu globals\n", size / sizeof(struct asan_global));
kasan_init_globals(globals, size);
}
void NOINLINE
kasan_late_init(void)
{
#if KASAN_DYNAMIC_BLACKLIST
kasan_init_dybl();
#endif
kasan_init_fakestack();
kasan_init_xnu_globals();
}
void NOINLINE
kasan_notify_stolen(vm_offset_t top)
{
kasan_map_shadow(kernel_vtop, top - kernel_vtop, false);
}
static void NOINLINE
kasan_debug_touch_mappings(vm_offset_t base, vm_size_t sz)
{
#if KASAN_DEBUG
vm_size_t i;
uint8_t tmp1, tmp2;
/* Hit every byte in the shadow map. Don't write due to the zero mappings. */
for (i = 0; i < sz; i += sizeof(uint64_t)) {
vm_offset_t addr = base + i;
uint8_t *x = SHADOW_FOR_ADDRESS(addr);
tmp1 = *x;
asm volatile ("" ::: "memory");
tmp2 = *x;
asm volatile ("" ::: "memory");
assert(tmp1 == tmp2);
}
#else
(void)base;
(void)sz;
#endif
}
void NOINLINE
kasan_init(void)
{
unsigned arg;
simple_lock_init(&kasan_vm_lock, 0);
/* Map all of the kernel text and data */
kasan_map_shadow(kernel_vbase, kernel_vtop - kernel_vbase, false);
kasan_arch_init();
/*
* handle KASan boot-args
*/
if (PE_parse_boot_argn("kasan.checks", &arg, sizeof(arg))) {
enabled_checks = arg;
}
if (PE_parse_boot_argn("kasan", &arg, sizeof(arg))) {
if (arg & KASAN_ARGS_FAKESTACK) {
fakestack_enabled = 1;
}
if (arg & KASAN_ARGS_REPORTIGNORED) {
report_ignored = 1;
}
if (arg & KASAN_ARGS_NODYCHECKS) {
enabled_checks &= ~TYPE_DYNAMIC;
}
if (arg & KASAN_ARGS_NOPOISON_HEAP) {
enabled_checks &= ~TYPE_POISON_HEAP;
}
if (arg & KASAN_ARGS_NOPOISON_GLOBAL) {
enabled_checks &= ~TYPE_POISON_GLOBAL;
}
if (arg & KASAN_ARGS_CHECK_LEAKS) {
enabled_checks |= TYPE_LEAK;
}
}
if (PE_parse_boot_argn("kasan.free_yield_ms", &arg, sizeof(arg))) {
free_yield = arg;
}
if (PE_parse_boot_argn("kasan.leak_threshold", &arg, sizeof(arg))) {
leak_threshold = arg;
}
if (PE_parse_boot_argn("kasan.leak_fatal_threshold", &arg, sizeof(arg))) {
leak_fatal_threshold = arg;
}
/* kasan.bl boot-arg handled in kasan_init_dybl() */
quarantine_enabled = 1;
kasan_enabled = 1;
}
static void NOINLINE
kasan_notify_address_internal(vm_offset_t address, vm_size_t size, bool is_zero)
{
assert(address < VM_MAX_KERNEL_ADDRESS);
if (!kasan_enabled) {
return;
}
if (address < VM_MIN_KERNEL_AND_KEXT_ADDRESS) {
/* only map kernel addresses */
return;
}
if (!size) {
/* nothing to map */
return;
}
boolean_t flags;
kasan_lock(&flags);
kasan_map_shadow(address, size, is_zero);
kasan_unlock(flags);
kasan_debug_touch_mappings(address, size);
}
void
kasan_notify_address(vm_offset_t address, vm_size_t size)
{
kasan_notify_address_internal(address, size, false);
}
/*
* Allocate read-only, all-zeros shadow for memory that can never be poisoned
*/
void
kasan_notify_address_nopoison(vm_offset_t address, vm_size_t size)
{
kasan_notify_address_internal(address, size, true);
}
/*
*
* allocator hooks
*
*/
struct kasan_alloc_header {
uint16_t magic;
uint16_t crc;
uint32_t alloc_size;
uint32_t user_size;
struct {
uint32_t left_rz : 32 - BACKTRACE_BITS;
uint32_t frames : BACKTRACE_BITS;
};
};
_Static_assert(sizeof(struct kasan_alloc_header) <= KASAN_GUARD_SIZE, "kasan alloc header exceeds guard size");
struct kasan_alloc_footer {
uint32_t backtrace[0];
};
_Static_assert(sizeof(struct kasan_alloc_footer) <= KASAN_GUARD_SIZE, "kasan alloc footer exceeds guard size");
#define LIVE_XOR ((uint16_t)0x3a65)
#define FREE_XOR ((uint16_t)0xf233)
static uint16_t
magic_for_addr(vm_offset_t addr, uint16_t magic_xor)
{
uint16_t magic = addr & 0xFFFF;
magic ^= (addr >> 16) & 0xFFFF;
magic ^= (addr >> 32) & 0xFFFF;
magic ^= (addr >> 48) & 0xFFFF;
magic ^= magic_xor;
return magic;
}
static struct kasan_alloc_header *
header_for_user_addr(vm_offset_t addr)
{
return (void *)(addr - sizeof(struct kasan_alloc_header));
}
static struct kasan_alloc_footer *
footer_for_user_addr(vm_offset_t addr, vm_size_t *size)
{
struct kasan_alloc_header *h = header_for_user_addr(addr);
vm_size_t rightrz = h->alloc_size - h->user_size - h->left_rz;
*size = rightrz;
return (void *)(addr + h->user_size);
}
/*
* size: user-requested allocation size
* ret: minimum size for the real allocation
*/
vm_size_t
kasan_alloc_resize(vm_size_t size)
{
vm_size_t tmp;
if (os_add_overflow(size, 4 * PAGE_SIZE, &tmp)) {
panic("allocation size overflow (%lu)", size);
}
if (size >= 128) {
/* Add a little extra right redzone to larger objects. Gives us extra
* overflow protection, and more space for the backtrace. */
size += 16;
}
/* add left and right redzones */
size += KASAN_GUARD_PAD;
/* ensure the final allocation is a multiple of the granule */
size = kasan_granule_round(size);
return size;
}
extern vm_offset_t vm_kernel_slid_base;
static vm_size_t
kasan_alloc_bt(uint32_t *ptr, vm_size_t sz, vm_size_t skip)
{
uintptr_t buf[BACKTRACE_MAXFRAMES];
uintptr_t *bt = buf;
sz /= sizeof(uint32_t);
vm_size_t frames = sz;
if (frames > 0) {
frames = min((uint32_t)(frames + skip), BACKTRACE_MAXFRAMES);
frames = backtrace(bt, (uint32_t)frames, NULL);
while (frames > sz && skip > 0) {
bt++;
frames--;
skip--;
}
/* only store the offset from kernel base, and cram that into 32
* bits */
for (vm_size_t i = 0; i < frames; i++) {
ptr[i] = (uint32_t)(bt[i] - vm_kernel_slid_base);
}
}
return frames;
}
/* addr: user address of allocation */
static uint16_t
kasan_alloc_crc(vm_offset_t addr)
{
struct kasan_alloc_header *h = header_for_user_addr(addr);
vm_size_t rightrz = h->alloc_size - h->user_size - h->left_rz;
uint16_t crc_orig = h->crc;
h->crc = 0;
uint16_t crc = 0;
crc = __nosan_crc16(crc, (void *)(addr - h->left_rz), h->left_rz);
crc = __nosan_crc16(crc, (void *)(addr + h->user_size), rightrz);
h->crc = crc_orig;