Merge tag 'for-6.7-rc1-tag' of git://git.kernel.org/pub/scm/linux/kernel/git/kdave...
[linux-2.6-microblaze.git] / mm / kasan / kasan_test.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *
4  * Copyright (c) 2014 Samsung Electronics Co., Ltd.
5  * Author: Andrey Ryabinin <a.ryabinin@samsung.com>
6  */
7
8 #define pr_fmt(fmt) "kasan: test: " fmt
9
10 #include <kunit/test.h>
11 #include <linux/bitops.h>
12 #include <linux/delay.h>
13 #include <linux/io.h>
14 #include <linux/kasan.h>
15 #include <linux/kernel.h>
16 #include <linux/mm.h>
17 #include <linux/mman.h>
18 #include <linux/module.h>
19 #include <linux/printk.h>
20 #include <linux/random.h>
21 #include <linux/set_memory.h>
22 #include <linux/slab.h>
23 #include <linux/string.h>
24 #include <linux/tracepoint.h>
25 #include <linux/uaccess.h>
26 #include <linux/vmalloc.h>
27 #include <trace/events/printk.h>
28
29 #include <asm/page.h>
30
31 #include "kasan.h"
32
33 #define OOB_TAG_OFF (IS_ENABLED(CONFIG_KASAN_GENERIC) ? 0 : KASAN_GRANULE_SIZE)
34
35 static bool multishot;
36
37 /* Fields set based on lines observed in the console. */
38 static struct {
39         bool report_found;
40         bool async_fault;
41 } test_status;
42
43 /*
44  * Some tests use these global variables to store return values from function
45  * calls that could otherwise be eliminated by the compiler as dead code.
46  */
47 void *kasan_ptr_result;
48 int kasan_int_result;
49
50 /* Probe for console output: obtains test_status lines of interest. */
51 static void probe_console(void *ignore, const char *buf, size_t len)
52 {
53         if (strnstr(buf, "BUG: KASAN: ", len))
54                 WRITE_ONCE(test_status.report_found, true);
55         else if (strnstr(buf, "Asynchronous fault: ", len))
56                 WRITE_ONCE(test_status.async_fault, true);
57 }
58
59 static int kasan_suite_init(struct kunit_suite *suite)
60 {
61         if (!kasan_enabled()) {
62                 pr_err("Can't run KASAN tests with KASAN disabled");
63                 return -1;
64         }
65
66         /* Stop failing KUnit tests on KASAN reports. */
67         kasan_kunit_test_suite_start();
68
69         /*
70          * Temporarily enable multi-shot mode. Otherwise, KASAN would only
71          * report the first detected bug and panic the kernel if panic_on_warn
72          * is enabled.
73          */
74         multishot = kasan_save_enable_multi_shot();
75
76         register_trace_console(probe_console, NULL);
77         return 0;
78 }
79
80 static void kasan_suite_exit(struct kunit_suite *suite)
81 {
82         kasan_kunit_test_suite_end();
83         kasan_restore_multi_shot(multishot);
84         unregister_trace_console(probe_console, NULL);
85         tracepoint_synchronize_unregister();
86 }
87
88 static void kasan_test_exit(struct kunit *test)
89 {
90         KUNIT_EXPECT_FALSE(test, READ_ONCE(test_status.report_found));
91 }
92
93 /**
94  * KUNIT_EXPECT_KASAN_FAIL - check that the executed expression produces a
95  * KASAN report; causes a KUnit test failure otherwise.
96  *
97  * @test: Currently executing KUnit test.
98  * @expression: Expression that must produce a KASAN report.
99  *
100  * For hardware tag-based KASAN, when a synchronous tag fault happens, tag
101  * checking is auto-disabled. When this happens, this test handler reenables
102  * tag checking. As tag checking can be only disabled or enabled per CPU,
103  * this handler disables migration (preemption).
104  *
105  * Since the compiler doesn't see that the expression can change the test_status
106  * fields, it can reorder or optimize away the accesses to those fields.
107  * Use READ/WRITE_ONCE() for the accesses and compiler barriers around the
108  * expression to prevent that.
109  *
110  * In between KUNIT_EXPECT_KASAN_FAIL checks, test_status.report_found is kept
111  * as false. This allows detecting KASAN reports that happen outside of the
112  * checks by asserting !test_status.report_found at the start of
113  * KUNIT_EXPECT_KASAN_FAIL and in kasan_test_exit.
114  */
115 #define KUNIT_EXPECT_KASAN_FAIL(test, expression) do {                  \
116         if (IS_ENABLED(CONFIG_KASAN_HW_TAGS) &&                         \
117             kasan_sync_fault_possible())                                \
118                 migrate_disable();                                      \
119         KUNIT_EXPECT_FALSE(test, READ_ONCE(test_status.report_found));  \
120         barrier();                                                      \
121         expression;                                                     \
122         barrier();                                                      \
123         if (kasan_async_fault_possible())                               \
124                 kasan_force_async_fault();                              \
125         if (!READ_ONCE(test_status.report_found)) {                     \
126                 KUNIT_FAIL(test, KUNIT_SUBTEST_INDENT "KASAN failure "  \
127                                 "expected in \"" #expression            \
128                                  "\", but none occurred");              \
129         }                                                               \
130         if (IS_ENABLED(CONFIG_KASAN_HW_TAGS) &&                         \
131             kasan_sync_fault_possible()) {                              \
132                 if (READ_ONCE(test_status.report_found) &&              \
133                     !READ_ONCE(test_status.async_fault))                \
134                         kasan_enable_hw_tags();                         \
135                 migrate_enable();                                       \
136         }                                                               \
137         WRITE_ONCE(test_status.report_found, false);                    \
138         WRITE_ONCE(test_status.async_fault, false);                     \
139 } while (0)
140
141 #define KASAN_TEST_NEEDS_CONFIG_ON(test, config) do {                   \
142         if (!IS_ENABLED(config))                                        \
143                 kunit_skip((test), "Test requires " #config "=y");      \
144 } while (0)
145
146 #define KASAN_TEST_NEEDS_CONFIG_OFF(test, config) do {                  \
147         if (IS_ENABLED(config))                                         \
148                 kunit_skip((test), "Test requires " #config "=n");      \
149 } while (0)
150
151 #define KASAN_TEST_NEEDS_CHECKED_MEMINTRINSICS(test) do {               \
152         if (IS_ENABLED(CONFIG_KASAN_HW_TAGS))                           \
153                 break;  /* No compiler instrumentation. */              \
154         if (IS_ENABLED(CONFIG_CC_HAS_KASAN_MEMINTRINSIC_PREFIX))        \
155                 break;  /* Should always be instrumented! */            \
156         if (IS_ENABLED(CONFIG_GENERIC_ENTRY))                           \
157                 kunit_skip((test), "Test requires checked mem*()");     \
158 } while (0)
159
160 static void kmalloc_oob_right(struct kunit *test)
161 {
162         char *ptr;
163         size_t size = 128 - KASAN_GRANULE_SIZE - 5;
164
165         ptr = kmalloc(size, GFP_KERNEL);
166         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
167
168         OPTIMIZER_HIDE_VAR(ptr);
169         /*
170          * An unaligned access past the requested kmalloc size.
171          * Only generic KASAN can precisely detect these.
172          */
173         if (IS_ENABLED(CONFIG_KASAN_GENERIC))
174                 KUNIT_EXPECT_KASAN_FAIL(test, ptr[size] = 'x');
175
176         /*
177          * An aligned access into the first out-of-bounds granule that falls
178          * within the aligned kmalloc object.
179          */
180         KUNIT_EXPECT_KASAN_FAIL(test, ptr[size + 5] = 'y');
181
182         /* Out-of-bounds access past the aligned kmalloc object. */
183         KUNIT_EXPECT_KASAN_FAIL(test, ptr[0] =
184                                         ptr[size + KASAN_GRANULE_SIZE + 5]);
185
186         kfree(ptr);
187 }
188
189 static void kmalloc_oob_left(struct kunit *test)
190 {
191         char *ptr;
192         size_t size = 15;
193
194         ptr = kmalloc(size, GFP_KERNEL);
195         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
196
197         OPTIMIZER_HIDE_VAR(ptr);
198         KUNIT_EXPECT_KASAN_FAIL(test, *ptr = *(ptr - 1));
199         kfree(ptr);
200 }
201
202 static void kmalloc_node_oob_right(struct kunit *test)
203 {
204         char *ptr;
205         size_t size = 4096;
206
207         ptr = kmalloc_node(size, GFP_KERNEL, 0);
208         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
209
210         OPTIMIZER_HIDE_VAR(ptr);
211         KUNIT_EXPECT_KASAN_FAIL(test, ptr[0] = ptr[size]);
212         kfree(ptr);
213 }
214
215 /*
216  * These kmalloc_pagealloc_* tests try allocating a memory chunk that doesn't
217  * fit into a slab cache and therefore is allocated via the page allocator
218  * fallback. Since this kind of fallback is only implemented for SLUB, these
219  * tests are limited to that allocator.
220  */
221 static void kmalloc_pagealloc_oob_right(struct kunit *test)
222 {
223         char *ptr;
224         size_t size = KMALLOC_MAX_CACHE_SIZE + 10;
225
226         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_SLUB);
227
228         ptr = kmalloc(size, GFP_KERNEL);
229         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
230
231         OPTIMIZER_HIDE_VAR(ptr);
232         KUNIT_EXPECT_KASAN_FAIL(test, ptr[size + OOB_TAG_OFF] = 0);
233
234         kfree(ptr);
235 }
236
237 static void kmalloc_pagealloc_uaf(struct kunit *test)
238 {
239         char *ptr;
240         size_t size = KMALLOC_MAX_CACHE_SIZE + 10;
241
242         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_SLUB);
243
244         ptr = kmalloc(size, GFP_KERNEL);
245         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
246         kfree(ptr);
247
248         KUNIT_EXPECT_KASAN_FAIL(test, ((volatile char *)ptr)[0]);
249 }
250
251 static void kmalloc_pagealloc_invalid_free(struct kunit *test)
252 {
253         char *ptr;
254         size_t size = KMALLOC_MAX_CACHE_SIZE + 10;
255
256         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_SLUB);
257
258         ptr = kmalloc(size, GFP_KERNEL);
259         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
260
261         KUNIT_EXPECT_KASAN_FAIL(test, kfree(ptr + 1));
262 }
263
264 static void pagealloc_oob_right(struct kunit *test)
265 {
266         char *ptr;
267         struct page *pages;
268         size_t order = 4;
269         size_t size = (1UL << (PAGE_SHIFT + order));
270
271         /*
272          * With generic KASAN page allocations have no redzones, thus
273          * out-of-bounds detection is not guaranteed.
274          * See https://bugzilla.kernel.org/show_bug.cgi?id=210503.
275          */
276         KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_KASAN_GENERIC);
277
278         pages = alloc_pages(GFP_KERNEL, order);
279         ptr = page_address(pages);
280         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
281
282         KUNIT_EXPECT_KASAN_FAIL(test, ptr[0] = ptr[size]);
283         free_pages((unsigned long)ptr, order);
284 }
285
286 static void pagealloc_uaf(struct kunit *test)
287 {
288         char *ptr;
289         struct page *pages;
290         size_t order = 4;
291
292         pages = alloc_pages(GFP_KERNEL, order);
293         ptr = page_address(pages);
294         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
295         free_pages((unsigned long)ptr, order);
296
297         KUNIT_EXPECT_KASAN_FAIL(test, ((volatile char *)ptr)[0]);
298 }
299
300 static void kmalloc_large_oob_right(struct kunit *test)
301 {
302         char *ptr;
303         size_t size = KMALLOC_MAX_CACHE_SIZE - 256;
304
305         /*
306          * Allocate a chunk that is large enough, but still fits into a slab
307          * and does not trigger the page allocator fallback in SLUB.
308          */
309         ptr = kmalloc(size, GFP_KERNEL);
310         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
311
312         OPTIMIZER_HIDE_VAR(ptr);
313         KUNIT_EXPECT_KASAN_FAIL(test, ptr[size] = 0);
314         kfree(ptr);
315 }
316
317 static void krealloc_more_oob_helper(struct kunit *test,
318                                         size_t size1, size_t size2)
319 {
320         char *ptr1, *ptr2;
321         size_t middle;
322
323         KUNIT_ASSERT_LT(test, size1, size2);
324         middle = size1 + (size2 - size1) / 2;
325
326         ptr1 = kmalloc(size1, GFP_KERNEL);
327         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr1);
328
329         ptr2 = krealloc(ptr1, size2, GFP_KERNEL);
330         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr2);
331
332         /* Suppress -Warray-bounds warnings. */
333         OPTIMIZER_HIDE_VAR(ptr2);
334
335         /* All offsets up to size2 must be accessible. */
336         ptr2[size1 - 1] = 'x';
337         ptr2[size1] = 'x';
338         ptr2[middle] = 'x';
339         ptr2[size2 - 1] = 'x';
340
341         /* Generic mode is precise, so unaligned size2 must be inaccessible. */
342         if (IS_ENABLED(CONFIG_KASAN_GENERIC))
343                 KUNIT_EXPECT_KASAN_FAIL(test, ptr2[size2] = 'x');
344
345         /* For all modes first aligned offset after size2 must be inaccessible. */
346         KUNIT_EXPECT_KASAN_FAIL(test,
347                 ptr2[round_up(size2, KASAN_GRANULE_SIZE)] = 'x');
348
349         kfree(ptr2);
350 }
351
352 static void krealloc_less_oob_helper(struct kunit *test,
353                                         size_t size1, size_t size2)
354 {
355         char *ptr1, *ptr2;
356         size_t middle;
357
358         KUNIT_ASSERT_LT(test, size2, size1);
359         middle = size2 + (size1 - size2) / 2;
360
361         ptr1 = kmalloc(size1, GFP_KERNEL);
362         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr1);
363
364         ptr2 = krealloc(ptr1, size2, GFP_KERNEL);
365         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr2);
366
367         /* Suppress -Warray-bounds warnings. */
368         OPTIMIZER_HIDE_VAR(ptr2);
369
370         /* Must be accessible for all modes. */
371         ptr2[size2 - 1] = 'x';
372
373         /* Generic mode is precise, so unaligned size2 must be inaccessible. */
374         if (IS_ENABLED(CONFIG_KASAN_GENERIC))
375                 KUNIT_EXPECT_KASAN_FAIL(test, ptr2[size2] = 'x');
376
377         /* For all modes first aligned offset after size2 must be inaccessible. */
378         KUNIT_EXPECT_KASAN_FAIL(test,
379                 ptr2[round_up(size2, KASAN_GRANULE_SIZE)] = 'x');
380
381         /*
382          * For all modes all size2, middle, and size1 should land in separate
383          * granules and thus the latter two offsets should be inaccessible.
384          */
385         KUNIT_EXPECT_LE(test, round_up(size2, KASAN_GRANULE_SIZE),
386                                 round_down(middle, KASAN_GRANULE_SIZE));
387         KUNIT_EXPECT_LE(test, round_up(middle, KASAN_GRANULE_SIZE),
388                                 round_down(size1, KASAN_GRANULE_SIZE));
389         KUNIT_EXPECT_KASAN_FAIL(test, ptr2[middle] = 'x');
390         KUNIT_EXPECT_KASAN_FAIL(test, ptr2[size1 - 1] = 'x');
391         KUNIT_EXPECT_KASAN_FAIL(test, ptr2[size1] = 'x');
392
393         kfree(ptr2);
394 }
395
396 static void krealloc_more_oob(struct kunit *test)
397 {
398         krealloc_more_oob_helper(test, 201, 235);
399 }
400
401 static void krealloc_less_oob(struct kunit *test)
402 {
403         krealloc_less_oob_helper(test, 235, 201);
404 }
405
406 static void krealloc_pagealloc_more_oob(struct kunit *test)
407 {
408         /* page_alloc fallback in only implemented for SLUB. */
409         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_SLUB);
410
411         krealloc_more_oob_helper(test, KMALLOC_MAX_CACHE_SIZE + 201,
412                                         KMALLOC_MAX_CACHE_SIZE + 235);
413 }
414
415 static void krealloc_pagealloc_less_oob(struct kunit *test)
416 {
417         /* page_alloc fallback in only implemented for SLUB. */
418         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_SLUB);
419
420         krealloc_less_oob_helper(test, KMALLOC_MAX_CACHE_SIZE + 235,
421                                         KMALLOC_MAX_CACHE_SIZE + 201);
422 }
423
424 /*
425  * Check that krealloc() detects a use-after-free, returns NULL,
426  * and doesn't unpoison the freed object.
427  */
428 static void krealloc_uaf(struct kunit *test)
429 {
430         char *ptr1, *ptr2;
431         int size1 = 201;
432         int size2 = 235;
433
434         ptr1 = kmalloc(size1, GFP_KERNEL);
435         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr1);
436         kfree(ptr1);
437
438         KUNIT_EXPECT_KASAN_FAIL(test, ptr2 = krealloc(ptr1, size2, GFP_KERNEL));
439         KUNIT_ASSERT_NULL(test, ptr2);
440         KUNIT_EXPECT_KASAN_FAIL(test, *(volatile char *)ptr1);
441 }
442
443 static void kmalloc_oob_16(struct kunit *test)
444 {
445         struct {
446                 u64 words[2];
447         } *ptr1, *ptr2;
448
449         KASAN_TEST_NEEDS_CHECKED_MEMINTRINSICS(test);
450
451         /* This test is specifically crafted for the generic mode. */
452         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_GENERIC);
453
454         ptr1 = kmalloc(sizeof(*ptr1) - 3, GFP_KERNEL);
455         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr1);
456
457         ptr2 = kmalloc(sizeof(*ptr2), GFP_KERNEL);
458         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr2);
459
460         OPTIMIZER_HIDE_VAR(ptr1);
461         OPTIMIZER_HIDE_VAR(ptr2);
462         KUNIT_EXPECT_KASAN_FAIL(test, *ptr1 = *ptr2);
463         kfree(ptr1);
464         kfree(ptr2);
465 }
466
467 static void kmalloc_uaf_16(struct kunit *test)
468 {
469         struct {
470                 u64 words[2];
471         } *ptr1, *ptr2;
472
473         KASAN_TEST_NEEDS_CHECKED_MEMINTRINSICS(test);
474
475         ptr1 = kmalloc(sizeof(*ptr1), GFP_KERNEL);
476         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr1);
477
478         ptr2 = kmalloc(sizeof(*ptr2), GFP_KERNEL);
479         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr2);
480         kfree(ptr2);
481
482         KUNIT_EXPECT_KASAN_FAIL(test, *ptr1 = *ptr2);
483         kfree(ptr1);
484 }
485
486 /*
487  * Note: in the memset tests below, the written range touches both valid and
488  * invalid memory. This makes sure that the instrumentation does not only check
489  * the starting address but the whole range.
490  */
491
492 static void kmalloc_oob_memset_2(struct kunit *test)
493 {
494         char *ptr;
495         size_t size = 128 - KASAN_GRANULE_SIZE;
496
497         KASAN_TEST_NEEDS_CHECKED_MEMINTRINSICS(test);
498
499         ptr = kmalloc(size, GFP_KERNEL);
500         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
501
502         OPTIMIZER_HIDE_VAR(size);
503         KUNIT_EXPECT_KASAN_FAIL(test, memset(ptr + size - 1, 0, 2));
504         kfree(ptr);
505 }
506
507 static void kmalloc_oob_memset_4(struct kunit *test)
508 {
509         char *ptr;
510         size_t size = 128 - KASAN_GRANULE_SIZE;
511
512         KASAN_TEST_NEEDS_CHECKED_MEMINTRINSICS(test);
513
514         ptr = kmalloc(size, GFP_KERNEL);
515         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
516
517         OPTIMIZER_HIDE_VAR(size);
518         KUNIT_EXPECT_KASAN_FAIL(test, memset(ptr + size - 3, 0, 4));
519         kfree(ptr);
520 }
521
522 static void kmalloc_oob_memset_8(struct kunit *test)
523 {
524         char *ptr;
525         size_t size = 128 - KASAN_GRANULE_SIZE;
526
527         KASAN_TEST_NEEDS_CHECKED_MEMINTRINSICS(test);
528
529         ptr = kmalloc(size, GFP_KERNEL);
530         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
531
532         OPTIMIZER_HIDE_VAR(size);
533         KUNIT_EXPECT_KASAN_FAIL(test, memset(ptr + size - 7, 0, 8));
534         kfree(ptr);
535 }
536
537 static void kmalloc_oob_memset_16(struct kunit *test)
538 {
539         char *ptr;
540         size_t size = 128 - KASAN_GRANULE_SIZE;
541
542         KASAN_TEST_NEEDS_CHECKED_MEMINTRINSICS(test);
543
544         ptr = kmalloc(size, GFP_KERNEL);
545         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
546
547         OPTIMIZER_HIDE_VAR(size);
548         KUNIT_EXPECT_KASAN_FAIL(test, memset(ptr + size - 15, 0, 16));
549         kfree(ptr);
550 }
551
552 static void kmalloc_oob_in_memset(struct kunit *test)
553 {
554         char *ptr;
555         size_t size = 128 - KASAN_GRANULE_SIZE;
556
557         KASAN_TEST_NEEDS_CHECKED_MEMINTRINSICS(test);
558
559         ptr = kmalloc(size, GFP_KERNEL);
560         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
561
562         OPTIMIZER_HIDE_VAR(ptr);
563         OPTIMIZER_HIDE_VAR(size);
564         KUNIT_EXPECT_KASAN_FAIL(test,
565                                 memset(ptr, 0, size + KASAN_GRANULE_SIZE));
566         kfree(ptr);
567 }
568
569 static void kmalloc_memmove_negative_size(struct kunit *test)
570 {
571         char *ptr;
572         size_t size = 64;
573         size_t invalid_size = -2;
574
575         KASAN_TEST_NEEDS_CHECKED_MEMINTRINSICS(test);
576
577         /*
578          * Hardware tag-based mode doesn't check memmove for negative size.
579          * As a result, this test introduces a side-effect memory corruption,
580          * which can result in a crash.
581          */
582         KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_KASAN_HW_TAGS);
583
584         ptr = kmalloc(size, GFP_KERNEL);
585         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
586
587         memset((char *)ptr, 0, 64);
588         OPTIMIZER_HIDE_VAR(ptr);
589         OPTIMIZER_HIDE_VAR(invalid_size);
590         KUNIT_EXPECT_KASAN_FAIL(test,
591                 memmove((char *)ptr, (char *)ptr + 4, invalid_size));
592         kfree(ptr);
593 }
594
595 static void kmalloc_memmove_invalid_size(struct kunit *test)
596 {
597         char *ptr;
598         size_t size = 64;
599         size_t invalid_size = size;
600
601         KASAN_TEST_NEEDS_CHECKED_MEMINTRINSICS(test);
602
603         ptr = kmalloc(size, GFP_KERNEL);
604         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
605
606         memset((char *)ptr, 0, 64);
607         OPTIMIZER_HIDE_VAR(ptr);
608         OPTIMIZER_HIDE_VAR(invalid_size);
609         KUNIT_EXPECT_KASAN_FAIL(test,
610                 memmove((char *)ptr, (char *)ptr + 4, invalid_size));
611         kfree(ptr);
612 }
613
614 static void kmalloc_uaf(struct kunit *test)
615 {
616         char *ptr;
617         size_t size = 10;
618
619         ptr = kmalloc(size, GFP_KERNEL);
620         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
621
622         kfree(ptr);
623         KUNIT_EXPECT_KASAN_FAIL(test, ((volatile char *)ptr)[8]);
624 }
625
626 static void kmalloc_uaf_memset(struct kunit *test)
627 {
628         char *ptr;
629         size_t size = 33;
630
631         KASAN_TEST_NEEDS_CHECKED_MEMINTRINSICS(test);
632
633         /*
634          * Only generic KASAN uses quarantine, which is required to avoid a
635          * kernel memory corruption this test causes.
636          */
637         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_GENERIC);
638
639         ptr = kmalloc(size, GFP_KERNEL);
640         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
641
642         kfree(ptr);
643         KUNIT_EXPECT_KASAN_FAIL(test, memset(ptr, 0, size));
644 }
645
646 static void kmalloc_uaf2(struct kunit *test)
647 {
648         char *ptr1, *ptr2;
649         size_t size = 43;
650         int counter = 0;
651
652 again:
653         ptr1 = kmalloc(size, GFP_KERNEL);
654         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr1);
655
656         kfree(ptr1);
657
658         ptr2 = kmalloc(size, GFP_KERNEL);
659         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr2);
660
661         /*
662          * For tag-based KASAN ptr1 and ptr2 tags might happen to be the same.
663          * Allow up to 16 attempts at generating different tags.
664          */
665         if (!IS_ENABLED(CONFIG_KASAN_GENERIC) && ptr1 == ptr2 && counter++ < 16) {
666                 kfree(ptr2);
667                 goto again;
668         }
669
670         KUNIT_EXPECT_KASAN_FAIL(test, ((volatile char *)ptr1)[40]);
671         KUNIT_EXPECT_PTR_NE(test, ptr1, ptr2);
672
673         kfree(ptr2);
674 }
675
676 /*
677  * Check that KASAN detects use-after-free when another object was allocated in
678  * the same slot. Relevant for the tag-based modes, which do not use quarantine.
679  */
680 static void kmalloc_uaf3(struct kunit *test)
681 {
682         char *ptr1, *ptr2;
683         size_t size = 100;
684
685         /* This test is specifically crafted for tag-based modes. */
686         KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_KASAN_GENERIC);
687
688         ptr1 = kmalloc(size, GFP_KERNEL);
689         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr1);
690         kfree(ptr1);
691
692         ptr2 = kmalloc(size, GFP_KERNEL);
693         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr2);
694         kfree(ptr2);
695
696         KUNIT_EXPECT_KASAN_FAIL(test, ((volatile char *)ptr1)[8]);
697 }
698
699 static void kfree_via_page(struct kunit *test)
700 {
701         char *ptr;
702         size_t size = 8;
703         struct page *page;
704         unsigned long offset;
705
706         ptr = kmalloc(size, GFP_KERNEL);
707         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
708
709         page = virt_to_page(ptr);
710         offset = offset_in_page(ptr);
711         kfree(page_address(page) + offset);
712 }
713
714 static void kfree_via_phys(struct kunit *test)
715 {
716         char *ptr;
717         size_t size = 8;
718         phys_addr_t phys;
719
720         ptr = kmalloc(size, GFP_KERNEL);
721         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
722
723         phys = virt_to_phys(ptr);
724         kfree(phys_to_virt(phys));
725 }
726
727 static void kmem_cache_oob(struct kunit *test)
728 {
729         char *p;
730         size_t size = 200;
731         struct kmem_cache *cache;
732
733         cache = kmem_cache_create("test_cache", size, 0, 0, NULL);
734         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, cache);
735
736         p = kmem_cache_alloc(cache, GFP_KERNEL);
737         if (!p) {
738                 kunit_err(test, "Allocation failed: %s\n", __func__);
739                 kmem_cache_destroy(cache);
740                 return;
741         }
742
743         KUNIT_EXPECT_KASAN_FAIL(test, *p = p[size + OOB_TAG_OFF]);
744
745         kmem_cache_free(cache, p);
746         kmem_cache_destroy(cache);
747 }
748
749 static void kmem_cache_accounted(struct kunit *test)
750 {
751         int i;
752         char *p;
753         size_t size = 200;
754         struct kmem_cache *cache;
755
756         cache = kmem_cache_create("test_cache", size, 0, SLAB_ACCOUNT, NULL);
757         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, cache);
758
759         /*
760          * Several allocations with a delay to allow for lazy per memcg kmem
761          * cache creation.
762          */
763         for (i = 0; i < 5; i++) {
764                 p = kmem_cache_alloc(cache, GFP_KERNEL);
765                 if (!p)
766                         goto free_cache;
767
768                 kmem_cache_free(cache, p);
769                 msleep(100);
770         }
771
772 free_cache:
773         kmem_cache_destroy(cache);
774 }
775
776 static void kmem_cache_bulk(struct kunit *test)
777 {
778         struct kmem_cache *cache;
779         size_t size = 200;
780         char *p[10];
781         bool ret;
782         int i;
783
784         cache = kmem_cache_create("test_cache", size, 0, 0, NULL);
785         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, cache);
786
787         ret = kmem_cache_alloc_bulk(cache, GFP_KERNEL, ARRAY_SIZE(p), (void **)&p);
788         if (!ret) {
789                 kunit_err(test, "Allocation failed: %s\n", __func__);
790                 kmem_cache_destroy(cache);
791                 return;
792         }
793
794         for (i = 0; i < ARRAY_SIZE(p); i++)
795                 p[i][0] = p[i][size - 1] = 42;
796
797         kmem_cache_free_bulk(cache, ARRAY_SIZE(p), (void **)&p);
798         kmem_cache_destroy(cache);
799 }
800
801 static char global_array[10];
802
803 static void kasan_global_oob_right(struct kunit *test)
804 {
805         /*
806          * Deliberate out-of-bounds access. To prevent CONFIG_UBSAN_LOCAL_BOUNDS
807          * from failing here and panicking the kernel, access the array via a
808          * volatile pointer, which will prevent the compiler from being able to
809          * determine the array bounds.
810          *
811          * This access uses a volatile pointer to char (char *volatile) rather
812          * than the more conventional pointer to volatile char (volatile char *)
813          * because we want to prevent the compiler from making inferences about
814          * the pointer itself (i.e. its array bounds), not the data that it
815          * refers to.
816          */
817         char *volatile array = global_array;
818         char *p = &array[ARRAY_SIZE(global_array) + 3];
819
820         /* Only generic mode instruments globals. */
821         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_GENERIC);
822
823         KUNIT_EXPECT_KASAN_FAIL(test, *(volatile char *)p);
824 }
825
826 static void kasan_global_oob_left(struct kunit *test)
827 {
828         char *volatile array = global_array;
829         char *p = array - 3;
830
831         /*
832          * GCC is known to fail this test, skip it.
833          * See https://bugzilla.kernel.org/show_bug.cgi?id=215051.
834          */
835         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_CC_IS_CLANG);
836         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_GENERIC);
837         KUNIT_EXPECT_KASAN_FAIL(test, *(volatile char *)p);
838 }
839
840 /* Check that ksize() does NOT unpoison whole object. */
841 static void ksize_unpoisons_memory(struct kunit *test)
842 {
843         char *ptr;
844         size_t size = 128 - KASAN_GRANULE_SIZE - 5;
845         size_t real_size;
846
847         ptr = kmalloc(size, GFP_KERNEL);
848         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
849
850         real_size = ksize(ptr);
851         KUNIT_EXPECT_GT(test, real_size, size);
852
853         OPTIMIZER_HIDE_VAR(ptr);
854
855         /* These accesses shouldn't trigger a KASAN report. */
856         ptr[0] = 'x';
857         ptr[size - 1] = 'x';
858
859         /* These must trigger a KASAN report. */
860         if (IS_ENABLED(CONFIG_KASAN_GENERIC))
861                 KUNIT_EXPECT_KASAN_FAIL(test, ((volatile char *)ptr)[size]);
862         KUNIT_EXPECT_KASAN_FAIL(test, ((volatile char *)ptr)[size + 5]);
863         KUNIT_EXPECT_KASAN_FAIL(test, ((volatile char *)ptr)[real_size - 1]);
864
865         kfree(ptr);
866 }
867
868 /*
869  * Check that a use-after-free is detected by ksize() and via normal accesses
870  * after it.
871  */
872 static void ksize_uaf(struct kunit *test)
873 {
874         char *ptr;
875         int size = 128 - KASAN_GRANULE_SIZE;
876
877         ptr = kmalloc(size, GFP_KERNEL);
878         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
879         kfree(ptr);
880
881         OPTIMIZER_HIDE_VAR(ptr);
882         KUNIT_EXPECT_KASAN_FAIL(test, ksize(ptr));
883         KUNIT_EXPECT_KASAN_FAIL(test, ((volatile char *)ptr)[0]);
884         KUNIT_EXPECT_KASAN_FAIL(test, ((volatile char *)ptr)[size]);
885 }
886
887 static void kasan_stack_oob(struct kunit *test)
888 {
889         char stack_array[10];
890         /* See comment in kasan_global_oob_right. */
891         char *volatile array = stack_array;
892         char *p = &array[ARRAY_SIZE(stack_array) + OOB_TAG_OFF];
893
894         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_STACK);
895
896         KUNIT_EXPECT_KASAN_FAIL(test, *(volatile char *)p);
897 }
898
899 static void kasan_alloca_oob_left(struct kunit *test)
900 {
901         volatile int i = 10;
902         char alloca_array[i];
903         /* See comment in kasan_global_oob_right. */
904         char *volatile array = alloca_array;
905         char *p = array - 1;
906
907         /* Only generic mode instruments dynamic allocas. */
908         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_GENERIC);
909         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_STACK);
910
911         KUNIT_EXPECT_KASAN_FAIL(test, *(volatile char *)p);
912 }
913
914 static void kasan_alloca_oob_right(struct kunit *test)
915 {
916         volatile int i = 10;
917         char alloca_array[i];
918         /* See comment in kasan_global_oob_right. */
919         char *volatile array = alloca_array;
920         char *p = array + i;
921
922         /* Only generic mode instruments dynamic allocas. */
923         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_GENERIC);
924         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_STACK);
925
926         KUNIT_EXPECT_KASAN_FAIL(test, *(volatile char *)p);
927 }
928
929 static void kmem_cache_double_free(struct kunit *test)
930 {
931         char *p;
932         size_t size = 200;
933         struct kmem_cache *cache;
934
935         cache = kmem_cache_create("test_cache", size, 0, 0, NULL);
936         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, cache);
937
938         p = kmem_cache_alloc(cache, GFP_KERNEL);
939         if (!p) {
940                 kunit_err(test, "Allocation failed: %s\n", __func__);
941                 kmem_cache_destroy(cache);
942                 return;
943         }
944
945         kmem_cache_free(cache, p);
946         KUNIT_EXPECT_KASAN_FAIL(test, kmem_cache_free(cache, p));
947         kmem_cache_destroy(cache);
948 }
949
950 static void kmem_cache_invalid_free(struct kunit *test)
951 {
952         char *p;
953         size_t size = 200;
954         struct kmem_cache *cache;
955
956         cache = kmem_cache_create("test_cache", size, 0, SLAB_TYPESAFE_BY_RCU,
957                                   NULL);
958         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, cache);
959
960         p = kmem_cache_alloc(cache, GFP_KERNEL);
961         if (!p) {
962                 kunit_err(test, "Allocation failed: %s\n", __func__);
963                 kmem_cache_destroy(cache);
964                 return;
965         }
966
967         /* Trigger invalid free, the object doesn't get freed. */
968         KUNIT_EXPECT_KASAN_FAIL(test, kmem_cache_free(cache, p + 1));
969
970         /*
971          * Properly free the object to prevent the "Objects remaining in
972          * test_cache on __kmem_cache_shutdown" BUG failure.
973          */
974         kmem_cache_free(cache, p);
975
976         kmem_cache_destroy(cache);
977 }
978
979 static void empty_cache_ctor(void *object) { }
980
981 static void kmem_cache_double_destroy(struct kunit *test)
982 {
983         struct kmem_cache *cache;
984
985         /* Provide a constructor to prevent cache merging. */
986         cache = kmem_cache_create("test_cache", 200, 0, 0, empty_cache_ctor);
987         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, cache);
988         kmem_cache_destroy(cache);
989         KUNIT_EXPECT_KASAN_FAIL(test, kmem_cache_destroy(cache));
990 }
991
992 static void kasan_memchr(struct kunit *test)
993 {
994         char *ptr;
995         size_t size = 24;
996
997         /*
998          * str* functions are not instrumented with CONFIG_AMD_MEM_ENCRYPT.
999          * See https://bugzilla.kernel.org/show_bug.cgi?id=206337 for details.
1000          */
1001         KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_AMD_MEM_ENCRYPT);
1002
1003         if (OOB_TAG_OFF)
1004                 size = round_up(size, OOB_TAG_OFF);
1005
1006         ptr = kmalloc(size, GFP_KERNEL | __GFP_ZERO);
1007         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
1008
1009         OPTIMIZER_HIDE_VAR(ptr);
1010         OPTIMIZER_HIDE_VAR(size);
1011         KUNIT_EXPECT_KASAN_FAIL(test,
1012                 kasan_ptr_result = memchr(ptr, '1', size + 1));
1013
1014         kfree(ptr);
1015 }
1016
1017 static void kasan_memcmp(struct kunit *test)
1018 {
1019         char *ptr;
1020         size_t size = 24;
1021         int arr[9];
1022
1023         /*
1024          * str* functions are not instrumented with CONFIG_AMD_MEM_ENCRYPT.
1025          * See https://bugzilla.kernel.org/show_bug.cgi?id=206337 for details.
1026          */
1027         KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_AMD_MEM_ENCRYPT);
1028
1029         if (OOB_TAG_OFF)
1030                 size = round_up(size, OOB_TAG_OFF);
1031
1032         ptr = kmalloc(size, GFP_KERNEL | __GFP_ZERO);
1033         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
1034         memset(arr, 0, sizeof(arr));
1035
1036         OPTIMIZER_HIDE_VAR(ptr);
1037         OPTIMIZER_HIDE_VAR(size);
1038         KUNIT_EXPECT_KASAN_FAIL(test,
1039                 kasan_int_result = memcmp(ptr, arr, size+1));
1040         kfree(ptr);
1041 }
1042
1043 static void kasan_strings(struct kunit *test)
1044 {
1045         char *ptr;
1046         size_t size = 24;
1047
1048         /*
1049          * str* functions are not instrumented with CONFIG_AMD_MEM_ENCRYPT.
1050          * See https://bugzilla.kernel.org/show_bug.cgi?id=206337 for details.
1051          */
1052         KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_AMD_MEM_ENCRYPT);
1053
1054         ptr = kmalloc(size, GFP_KERNEL | __GFP_ZERO);
1055         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
1056
1057         kfree(ptr);
1058
1059         /*
1060          * Try to cause only 1 invalid access (less spam in dmesg).
1061          * For that we need ptr to point to zeroed byte.
1062          * Skip metadata that could be stored in freed object so ptr
1063          * will likely point to zeroed byte.
1064          */
1065         ptr += 16;
1066         KUNIT_EXPECT_KASAN_FAIL(test, kasan_ptr_result = strchr(ptr, '1'));
1067
1068         KUNIT_EXPECT_KASAN_FAIL(test, kasan_ptr_result = strrchr(ptr, '1'));
1069
1070         KUNIT_EXPECT_KASAN_FAIL(test, kasan_int_result = strcmp(ptr, "2"));
1071
1072         KUNIT_EXPECT_KASAN_FAIL(test, kasan_int_result = strncmp(ptr, "2", 1));
1073
1074         KUNIT_EXPECT_KASAN_FAIL(test, kasan_int_result = strlen(ptr));
1075
1076         KUNIT_EXPECT_KASAN_FAIL(test, kasan_int_result = strnlen(ptr, 1));
1077 }
1078
1079 static void kasan_bitops_modify(struct kunit *test, int nr, void *addr)
1080 {
1081         KUNIT_EXPECT_KASAN_FAIL(test, set_bit(nr, addr));
1082         KUNIT_EXPECT_KASAN_FAIL(test, __set_bit(nr, addr));
1083         KUNIT_EXPECT_KASAN_FAIL(test, clear_bit(nr, addr));
1084         KUNIT_EXPECT_KASAN_FAIL(test, __clear_bit(nr, addr));
1085         KUNIT_EXPECT_KASAN_FAIL(test, clear_bit_unlock(nr, addr));
1086         KUNIT_EXPECT_KASAN_FAIL(test, __clear_bit_unlock(nr, addr));
1087         KUNIT_EXPECT_KASAN_FAIL(test, change_bit(nr, addr));
1088         KUNIT_EXPECT_KASAN_FAIL(test, __change_bit(nr, addr));
1089 }
1090
1091 static void kasan_bitops_test_and_modify(struct kunit *test, int nr, void *addr)
1092 {
1093         KUNIT_EXPECT_KASAN_FAIL(test, test_and_set_bit(nr, addr));
1094         KUNIT_EXPECT_KASAN_FAIL(test, __test_and_set_bit(nr, addr));
1095         KUNIT_EXPECT_KASAN_FAIL(test, test_and_set_bit_lock(nr, addr));
1096         KUNIT_EXPECT_KASAN_FAIL(test, test_and_clear_bit(nr, addr));
1097         KUNIT_EXPECT_KASAN_FAIL(test, __test_and_clear_bit(nr, addr));
1098         KUNIT_EXPECT_KASAN_FAIL(test, test_and_change_bit(nr, addr));
1099         KUNIT_EXPECT_KASAN_FAIL(test, __test_and_change_bit(nr, addr));
1100         KUNIT_EXPECT_KASAN_FAIL(test, kasan_int_result = test_bit(nr, addr));
1101         if (nr < 7)
1102                 KUNIT_EXPECT_KASAN_FAIL(test, kasan_int_result =
1103                                 xor_unlock_is_negative_byte(1 << nr, addr));
1104 }
1105
1106 static void kasan_bitops_generic(struct kunit *test)
1107 {
1108         long *bits;
1109
1110         /* This test is specifically crafted for the generic mode. */
1111         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_GENERIC);
1112
1113         /*
1114          * Allocate 1 more byte, which causes kzalloc to round up to 16 bytes;
1115          * this way we do not actually corrupt other memory.
1116          */
1117         bits = kzalloc(sizeof(*bits) + 1, GFP_KERNEL);
1118         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bits);
1119
1120         /*
1121          * Below calls try to access bit within allocated memory; however, the
1122          * below accesses are still out-of-bounds, since bitops are defined to
1123          * operate on the whole long the bit is in.
1124          */
1125         kasan_bitops_modify(test, BITS_PER_LONG, bits);
1126
1127         /*
1128          * Below calls try to access bit beyond allocated memory.
1129          */
1130         kasan_bitops_test_and_modify(test, BITS_PER_LONG + BITS_PER_BYTE, bits);
1131
1132         kfree(bits);
1133 }
1134
1135 static void kasan_bitops_tags(struct kunit *test)
1136 {
1137         long *bits;
1138
1139         /* This test is specifically crafted for tag-based modes. */
1140         KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_KASAN_GENERIC);
1141
1142         /* kmalloc-64 cache will be used and the last 16 bytes will be the redzone. */
1143         bits = kzalloc(48, GFP_KERNEL);
1144         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bits);
1145
1146         /* Do the accesses past the 48 allocated bytes, but within the redone. */
1147         kasan_bitops_modify(test, BITS_PER_LONG, (void *)bits + 48);
1148         kasan_bitops_test_and_modify(test, BITS_PER_LONG + BITS_PER_BYTE, (void *)bits + 48);
1149
1150         kfree(bits);
1151 }
1152
1153 static void kmalloc_double_kzfree(struct kunit *test)
1154 {
1155         char *ptr;
1156         size_t size = 16;
1157
1158         ptr = kmalloc(size, GFP_KERNEL);
1159         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
1160
1161         kfree_sensitive(ptr);
1162         KUNIT_EXPECT_KASAN_FAIL(test, kfree_sensitive(ptr));
1163 }
1164
1165 /*
1166  * The two tests below check that Generic KASAN prints auxiliary stack traces
1167  * for RCU callbacks and workqueues. The reports need to be inspected manually.
1168  *
1169  * These tests are still enabled for other KASAN modes to make sure that all
1170  * modes report bad accesses in tested scenarios.
1171  */
1172
1173 static struct kasan_rcu_info {
1174         int i;
1175         struct rcu_head rcu;
1176 } *global_rcu_ptr;
1177
1178 static void rcu_uaf_reclaim(struct rcu_head *rp)
1179 {
1180         struct kasan_rcu_info *fp =
1181                 container_of(rp, struct kasan_rcu_info, rcu);
1182
1183         kfree(fp);
1184         ((volatile struct kasan_rcu_info *)fp)->i;
1185 }
1186
1187 static void rcu_uaf(struct kunit *test)
1188 {
1189         struct kasan_rcu_info *ptr;
1190
1191         ptr = kmalloc(sizeof(struct kasan_rcu_info), GFP_KERNEL);
1192         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
1193
1194         global_rcu_ptr = rcu_dereference_protected(
1195                                 (struct kasan_rcu_info __rcu *)ptr, NULL);
1196
1197         KUNIT_EXPECT_KASAN_FAIL(test,
1198                 call_rcu(&global_rcu_ptr->rcu, rcu_uaf_reclaim);
1199                 rcu_barrier());
1200 }
1201
1202 static void workqueue_uaf_work(struct work_struct *work)
1203 {
1204         kfree(work);
1205 }
1206
1207 static void workqueue_uaf(struct kunit *test)
1208 {
1209         struct workqueue_struct *workqueue;
1210         struct work_struct *work;
1211
1212         workqueue = create_workqueue("kasan_workqueue_test");
1213         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, workqueue);
1214
1215         work = kmalloc(sizeof(struct work_struct), GFP_KERNEL);
1216         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, work);
1217
1218         INIT_WORK(work, workqueue_uaf_work);
1219         queue_work(workqueue, work);
1220         destroy_workqueue(workqueue);
1221
1222         KUNIT_EXPECT_KASAN_FAIL(test,
1223                 ((volatile struct work_struct *)work)->data);
1224 }
1225
1226 static void vmalloc_helpers_tags(struct kunit *test)
1227 {
1228         void *ptr;
1229
1230         /* This test is intended for tag-based modes. */
1231         KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_KASAN_GENERIC);
1232
1233         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_VMALLOC);
1234
1235         ptr = vmalloc(PAGE_SIZE);
1236         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
1237
1238         /* Check that the returned pointer is tagged. */
1239         KUNIT_EXPECT_GE(test, (u8)get_tag(ptr), (u8)KASAN_TAG_MIN);
1240         KUNIT_EXPECT_LT(test, (u8)get_tag(ptr), (u8)KASAN_TAG_KERNEL);
1241
1242         /* Make sure exported vmalloc helpers handle tagged pointers. */
1243         KUNIT_ASSERT_TRUE(test, is_vmalloc_addr(ptr));
1244         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, vmalloc_to_page(ptr));
1245
1246 #if !IS_MODULE(CONFIG_KASAN_KUNIT_TEST)
1247         {
1248                 int rv;
1249
1250                 /* Make sure vmalloc'ed memory permissions can be changed. */
1251                 rv = set_memory_ro((unsigned long)ptr, 1);
1252                 KUNIT_ASSERT_GE(test, rv, 0);
1253                 rv = set_memory_rw((unsigned long)ptr, 1);
1254                 KUNIT_ASSERT_GE(test, rv, 0);
1255         }
1256 #endif
1257
1258         vfree(ptr);
1259 }
1260
1261 static void vmalloc_oob(struct kunit *test)
1262 {
1263         char *v_ptr, *p_ptr;
1264         struct page *page;
1265         size_t size = PAGE_SIZE / 2 - KASAN_GRANULE_SIZE - 5;
1266
1267         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_VMALLOC);
1268
1269         v_ptr = vmalloc(size);
1270         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, v_ptr);
1271
1272         OPTIMIZER_HIDE_VAR(v_ptr);
1273
1274         /*
1275          * We have to be careful not to hit the guard page in vmalloc tests.
1276          * The MMU will catch that and crash us.
1277          */
1278
1279         /* Make sure in-bounds accesses are valid. */
1280         v_ptr[0] = 0;
1281         v_ptr[size - 1] = 0;
1282
1283         /*
1284          * An unaligned access past the requested vmalloc size.
1285          * Only generic KASAN can precisely detect these.
1286          */
1287         if (IS_ENABLED(CONFIG_KASAN_GENERIC))
1288                 KUNIT_EXPECT_KASAN_FAIL(test, ((volatile char *)v_ptr)[size]);
1289
1290         /* An aligned access into the first out-of-bounds granule. */
1291         KUNIT_EXPECT_KASAN_FAIL(test, ((volatile char *)v_ptr)[size + 5]);
1292
1293         /* Check that in-bounds accesses to the physical page are valid. */
1294         page = vmalloc_to_page(v_ptr);
1295         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, page);
1296         p_ptr = page_address(page);
1297         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, p_ptr);
1298         p_ptr[0] = 0;
1299
1300         vfree(v_ptr);
1301
1302         /*
1303          * We can't check for use-after-unmap bugs in this nor in the following
1304          * vmalloc tests, as the page might be fully unmapped and accessing it
1305          * will crash the kernel.
1306          */
1307 }
1308
1309 static void vmap_tags(struct kunit *test)
1310 {
1311         char *p_ptr, *v_ptr;
1312         struct page *p_page, *v_page;
1313
1314         /*
1315          * This test is specifically crafted for the software tag-based mode,
1316          * the only tag-based mode that poisons vmap mappings.
1317          */
1318         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_SW_TAGS);
1319
1320         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_VMALLOC);
1321
1322         p_page = alloc_pages(GFP_KERNEL, 1);
1323         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, p_page);
1324         p_ptr = page_address(p_page);
1325         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, p_ptr);
1326
1327         v_ptr = vmap(&p_page, 1, VM_MAP, PAGE_KERNEL);
1328         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, v_ptr);
1329
1330         /*
1331          * We can't check for out-of-bounds bugs in this nor in the following
1332          * vmalloc tests, as allocations have page granularity and accessing
1333          * the guard page will crash the kernel.
1334          */
1335
1336         KUNIT_EXPECT_GE(test, (u8)get_tag(v_ptr), (u8)KASAN_TAG_MIN);
1337         KUNIT_EXPECT_LT(test, (u8)get_tag(v_ptr), (u8)KASAN_TAG_KERNEL);
1338
1339         /* Make sure that in-bounds accesses through both pointers work. */
1340         *p_ptr = 0;
1341         *v_ptr = 0;
1342
1343         /* Make sure vmalloc_to_page() correctly recovers the page pointer. */
1344         v_page = vmalloc_to_page(v_ptr);
1345         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, v_page);
1346         KUNIT_EXPECT_PTR_EQ(test, p_page, v_page);
1347
1348         vunmap(v_ptr);
1349         free_pages((unsigned long)p_ptr, 1);
1350 }
1351
1352 static void vm_map_ram_tags(struct kunit *test)
1353 {
1354         char *p_ptr, *v_ptr;
1355         struct page *page;
1356
1357         /*
1358          * This test is specifically crafted for the software tag-based mode,
1359          * the only tag-based mode that poisons vm_map_ram mappings.
1360          */
1361         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_SW_TAGS);
1362
1363         page = alloc_pages(GFP_KERNEL, 1);
1364         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, page);
1365         p_ptr = page_address(page);
1366         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, p_ptr);
1367
1368         v_ptr = vm_map_ram(&page, 1, -1);
1369         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, v_ptr);
1370
1371         KUNIT_EXPECT_GE(test, (u8)get_tag(v_ptr), (u8)KASAN_TAG_MIN);
1372         KUNIT_EXPECT_LT(test, (u8)get_tag(v_ptr), (u8)KASAN_TAG_KERNEL);
1373
1374         /* Make sure that in-bounds accesses through both pointers work. */
1375         *p_ptr = 0;
1376         *v_ptr = 0;
1377
1378         vm_unmap_ram(v_ptr, 1);
1379         free_pages((unsigned long)p_ptr, 1);
1380 }
1381
1382 static void vmalloc_percpu(struct kunit *test)
1383 {
1384         char __percpu *ptr;
1385         int cpu;
1386
1387         /*
1388          * This test is specifically crafted for the software tag-based mode,
1389          * the only tag-based mode that poisons percpu mappings.
1390          */
1391         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_SW_TAGS);
1392
1393         ptr = __alloc_percpu(PAGE_SIZE, PAGE_SIZE);
1394
1395         for_each_possible_cpu(cpu) {
1396                 char *c_ptr = per_cpu_ptr(ptr, cpu);
1397
1398                 KUNIT_EXPECT_GE(test, (u8)get_tag(c_ptr), (u8)KASAN_TAG_MIN);
1399                 KUNIT_EXPECT_LT(test, (u8)get_tag(c_ptr), (u8)KASAN_TAG_KERNEL);
1400
1401                 /* Make sure that in-bounds accesses don't crash the kernel. */
1402                 *c_ptr = 0;
1403         }
1404
1405         free_percpu(ptr);
1406 }
1407
1408 /*
1409  * Check that the assigned pointer tag falls within the [KASAN_TAG_MIN,
1410  * KASAN_TAG_KERNEL) range (note: excluding the match-all tag) for tag-based
1411  * modes.
1412  */
1413 static void match_all_not_assigned(struct kunit *test)
1414 {
1415         char *ptr;
1416         struct page *pages;
1417         int i, size, order;
1418
1419         KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_KASAN_GENERIC);
1420
1421         for (i = 0; i < 256; i++) {
1422                 size = get_random_u32_inclusive(1, 1024);
1423                 ptr = kmalloc(size, GFP_KERNEL);
1424                 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
1425                 KUNIT_EXPECT_GE(test, (u8)get_tag(ptr), (u8)KASAN_TAG_MIN);
1426                 KUNIT_EXPECT_LT(test, (u8)get_tag(ptr), (u8)KASAN_TAG_KERNEL);
1427                 kfree(ptr);
1428         }
1429
1430         for (i = 0; i < 256; i++) {
1431                 order = get_random_u32_inclusive(1, 4);
1432                 pages = alloc_pages(GFP_KERNEL, order);
1433                 ptr = page_address(pages);
1434                 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
1435                 KUNIT_EXPECT_GE(test, (u8)get_tag(ptr), (u8)KASAN_TAG_MIN);
1436                 KUNIT_EXPECT_LT(test, (u8)get_tag(ptr), (u8)KASAN_TAG_KERNEL);
1437                 free_pages((unsigned long)ptr, order);
1438         }
1439
1440         if (!IS_ENABLED(CONFIG_KASAN_VMALLOC))
1441                 return;
1442
1443         for (i = 0; i < 256; i++) {
1444                 size = get_random_u32_inclusive(1, 1024);
1445                 ptr = vmalloc(size);
1446                 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
1447                 KUNIT_EXPECT_GE(test, (u8)get_tag(ptr), (u8)KASAN_TAG_MIN);
1448                 KUNIT_EXPECT_LT(test, (u8)get_tag(ptr), (u8)KASAN_TAG_KERNEL);
1449                 vfree(ptr);
1450         }
1451 }
1452
1453 /* Check that 0xff works as a match-all pointer tag for tag-based modes. */
1454 static void match_all_ptr_tag(struct kunit *test)
1455 {
1456         char *ptr;
1457         u8 tag;
1458
1459         KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_KASAN_GENERIC);
1460
1461         ptr = kmalloc(128, GFP_KERNEL);
1462         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
1463
1464         /* Backup the assigned tag. */
1465         tag = get_tag(ptr);
1466         KUNIT_EXPECT_NE(test, tag, (u8)KASAN_TAG_KERNEL);
1467
1468         /* Reset the tag to 0xff.*/
1469         ptr = set_tag(ptr, KASAN_TAG_KERNEL);
1470
1471         /* This access shouldn't trigger a KASAN report. */
1472         *ptr = 0;
1473
1474         /* Recover the pointer tag and free. */
1475         ptr = set_tag(ptr, tag);
1476         kfree(ptr);
1477 }
1478
1479 /* Check that there are no match-all memory tags for tag-based modes. */
1480 static void match_all_mem_tag(struct kunit *test)
1481 {
1482         char *ptr;
1483         int tag;
1484
1485         KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_KASAN_GENERIC);
1486
1487         ptr = kmalloc(128, GFP_KERNEL);
1488         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
1489         KUNIT_EXPECT_NE(test, (u8)get_tag(ptr), (u8)KASAN_TAG_KERNEL);
1490
1491         /* For each possible tag value not matching the pointer tag. */
1492         for (tag = KASAN_TAG_MIN; tag <= KASAN_TAG_KERNEL; tag++) {
1493                 if (tag == get_tag(ptr))
1494                         continue;
1495
1496                 /* Mark the first memory granule with the chosen memory tag. */
1497                 kasan_poison(ptr, KASAN_GRANULE_SIZE, (u8)tag, false);
1498
1499                 /* This access must cause a KASAN report. */
1500                 KUNIT_EXPECT_KASAN_FAIL(test, *ptr = 0);
1501         }
1502
1503         /* Recover the memory tag and free. */
1504         kasan_poison(ptr, KASAN_GRANULE_SIZE, get_tag(ptr), false);
1505         kfree(ptr);
1506 }
1507
1508 static struct kunit_case kasan_kunit_test_cases[] = {
1509         KUNIT_CASE(kmalloc_oob_right),
1510         KUNIT_CASE(kmalloc_oob_left),
1511         KUNIT_CASE(kmalloc_node_oob_right),
1512         KUNIT_CASE(kmalloc_pagealloc_oob_right),
1513         KUNIT_CASE(kmalloc_pagealloc_uaf),
1514         KUNIT_CASE(kmalloc_pagealloc_invalid_free),
1515         KUNIT_CASE(pagealloc_oob_right),
1516         KUNIT_CASE(pagealloc_uaf),
1517         KUNIT_CASE(kmalloc_large_oob_right),
1518         KUNIT_CASE(krealloc_more_oob),
1519         KUNIT_CASE(krealloc_less_oob),
1520         KUNIT_CASE(krealloc_pagealloc_more_oob),
1521         KUNIT_CASE(krealloc_pagealloc_less_oob),
1522         KUNIT_CASE(krealloc_uaf),
1523         KUNIT_CASE(kmalloc_oob_16),
1524         KUNIT_CASE(kmalloc_uaf_16),
1525         KUNIT_CASE(kmalloc_oob_in_memset),
1526         KUNIT_CASE(kmalloc_oob_memset_2),
1527         KUNIT_CASE(kmalloc_oob_memset_4),
1528         KUNIT_CASE(kmalloc_oob_memset_8),
1529         KUNIT_CASE(kmalloc_oob_memset_16),
1530         KUNIT_CASE(kmalloc_memmove_negative_size),
1531         KUNIT_CASE(kmalloc_memmove_invalid_size),
1532         KUNIT_CASE(kmalloc_uaf),
1533         KUNIT_CASE(kmalloc_uaf_memset),
1534         KUNIT_CASE(kmalloc_uaf2),
1535         KUNIT_CASE(kmalloc_uaf3),
1536         KUNIT_CASE(kfree_via_page),
1537         KUNIT_CASE(kfree_via_phys),
1538         KUNIT_CASE(kmem_cache_oob),
1539         KUNIT_CASE(kmem_cache_accounted),
1540         KUNIT_CASE(kmem_cache_bulk),
1541         KUNIT_CASE(kasan_global_oob_right),
1542         KUNIT_CASE(kasan_global_oob_left),
1543         KUNIT_CASE(kasan_stack_oob),
1544         KUNIT_CASE(kasan_alloca_oob_left),
1545         KUNIT_CASE(kasan_alloca_oob_right),
1546         KUNIT_CASE(ksize_unpoisons_memory),
1547         KUNIT_CASE(ksize_uaf),
1548         KUNIT_CASE(kmem_cache_double_free),
1549         KUNIT_CASE(kmem_cache_invalid_free),
1550         KUNIT_CASE(kmem_cache_double_destroy),
1551         KUNIT_CASE(kasan_memchr),
1552         KUNIT_CASE(kasan_memcmp),
1553         KUNIT_CASE(kasan_strings),
1554         KUNIT_CASE(kasan_bitops_generic),
1555         KUNIT_CASE(kasan_bitops_tags),
1556         KUNIT_CASE(kmalloc_double_kzfree),
1557         KUNIT_CASE(rcu_uaf),
1558         KUNIT_CASE(workqueue_uaf),
1559         KUNIT_CASE(vmalloc_helpers_tags),
1560         KUNIT_CASE(vmalloc_oob),
1561         KUNIT_CASE(vmap_tags),
1562         KUNIT_CASE(vm_map_ram_tags),
1563         KUNIT_CASE(vmalloc_percpu),
1564         KUNIT_CASE(match_all_not_assigned),
1565         KUNIT_CASE(match_all_ptr_tag),
1566         KUNIT_CASE(match_all_mem_tag),
1567         {}
1568 };
1569
1570 static struct kunit_suite kasan_kunit_test_suite = {
1571         .name = "kasan",
1572         .test_cases = kasan_kunit_test_cases,
1573         .exit = kasan_test_exit,
1574         .suite_init = kasan_suite_init,
1575         .suite_exit = kasan_suite_exit,
1576 };
1577
1578 kunit_test_suite(kasan_kunit_test_suite);
1579
1580 MODULE_LICENSE("GPL");