kasan: test: clean up ksize_uaf
[linux-2.6-microblaze.git] / lib / test_kasan.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 #include <linux/bitops.h>
9 #include <linux/delay.h>
10 #include <linux/kasan.h>
11 #include <linux/kernel.h>
12 #include <linux/mm.h>
13 #include <linux/mman.h>
14 #include <linux/module.h>
15 #include <linux/printk.h>
16 #include <linux/random.h>
17 #include <linux/slab.h>
18 #include <linux/string.h>
19 #include <linux/uaccess.h>
20 #include <linux/io.h>
21 #include <linux/vmalloc.h>
22
23 #include <asm/page.h>
24
25 #include <kunit/test.h>
26
27 #include "../mm/kasan/kasan.h"
28
29 #define OOB_TAG_OFF (IS_ENABLED(CONFIG_KASAN_GENERIC) ? 0 : KASAN_GRANULE_SIZE)
30
31 /*
32  * Some tests use these global variables to store return values from function
33  * calls that could otherwise be eliminated by the compiler as dead code.
34  */
35 void *kasan_ptr_result;
36 int kasan_int_result;
37
38 static struct kunit_resource resource;
39 static struct kunit_kasan_expectation fail_data;
40 static bool multishot;
41
42 /*
43  * Temporarily enable multi-shot mode. Otherwise, KASAN would only report the
44  * first detected bug and panic the kernel if panic_on_warn is enabled. For
45  * hardware tag-based KASAN also allow tag checking to be reenabled for each
46  * test, see the comment for KUNIT_EXPECT_KASAN_FAIL().
47  */
48 static int kasan_test_init(struct kunit *test)
49 {
50         if (!kasan_enabled()) {
51                 kunit_err(test, "can't run KASAN tests with KASAN disabled");
52                 return -1;
53         }
54
55         multishot = kasan_save_enable_multi_shot();
56         kasan_set_tagging_report_once(false);
57         fail_data.report_found = false;
58         kunit_add_named_resource(test, NULL, NULL, &resource,
59                                         "kasan_data", &fail_data);
60         return 0;
61 }
62
63 static void kasan_test_exit(struct kunit *test)
64 {
65         kasan_set_tagging_report_once(true);
66         kasan_restore_multi_shot(multishot);
67         KUNIT_EXPECT_FALSE(test, fail_data.report_found);
68 }
69
70 /**
71  * KUNIT_EXPECT_KASAN_FAIL() - check that the executed expression produces a
72  * KASAN report; causes a test failure otherwise. This relies on a KUnit
73  * resource named "kasan_data". Do not use this name for KUnit resources
74  * outside of KASAN tests.
75  *
76  * For hardware tag-based KASAN in sync mode, when a tag fault happens, tag
77  * checking is auto-disabled. When this happens, this test handler reenables
78  * tag checking. As tag checking can be only disabled or enabled per CPU,
79  * this handler disables migration (preemption).
80  *
81  * Since the compiler doesn't see that the expression can change the fail_data
82  * fields, it can reorder or optimize away the accesses to those fields.
83  * Use READ/WRITE_ONCE() for the accesses and compiler barriers around the
84  * expression to prevent that.
85  *
86  * In between KUNIT_EXPECT_KASAN_FAIL checks, fail_data.report_found is kept as
87  * false. This allows detecting KASAN reports that happen outside of the checks
88  * by asserting !fail_data.report_found at the start of KUNIT_EXPECT_KASAN_FAIL
89  * and in kasan_test_exit.
90  */
91 #define KUNIT_EXPECT_KASAN_FAIL(test, expression) do {                  \
92         if (IS_ENABLED(CONFIG_KASAN_HW_TAGS) &&                         \
93             !kasan_async_mode_enabled())                                \
94                 migrate_disable();                                      \
95         KUNIT_EXPECT_FALSE(test, READ_ONCE(fail_data.report_found));    \
96         barrier();                                                      \
97         expression;                                                     \
98         barrier();                                                      \
99         if (!READ_ONCE(fail_data.report_found)) {                       \
100                 KUNIT_FAIL(test, KUNIT_SUBTEST_INDENT "KASAN failure "  \
101                                 "expected in \"" #expression            \
102                                  "\", but none occurred");              \
103         }                                                               \
104         if (IS_ENABLED(CONFIG_KASAN_HW_TAGS)) {                         \
105                 if (READ_ONCE(fail_data.report_found))                  \
106                         kasan_enable_tagging_sync();                    \
107                 migrate_enable();                                       \
108         }                                                               \
109         WRITE_ONCE(fail_data.report_found, false);                      \
110 } while (0)
111
112 #define KASAN_TEST_NEEDS_CONFIG_ON(test, config) do {                   \
113         if (!IS_ENABLED(config))                                        \
114                 kunit_skip((test), "Test requires " #config "=y");      \
115 } while (0)
116
117 #define KASAN_TEST_NEEDS_CONFIG_OFF(test, config) do {                  \
118         if (IS_ENABLED(config))                                         \
119                 kunit_skip((test), "Test requires " #config "=n");      \
120 } while (0)
121
122 static void kmalloc_oob_right(struct kunit *test)
123 {
124         char *ptr;
125         size_t size = 128 - KASAN_GRANULE_SIZE - 5;
126
127         ptr = kmalloc(size, GFP_KERNEL);
128         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
129
130         /*
131          * An unaligned access past the requested kmalloc size.
132          * Only generic KASAN can precisely detect these.
133          */
134         if (IS_ENABLED(CONFIG_KASAN_GENERIC))
135                 KUNIT_EXPECT_KASAN_FAIL(test, ptr[size] = 'x');
136
137         /*
138          * An aligned access into the first out-of-bounds granule that falls
139          * within the aligned kmalloc object.
140          */
141         KUNIT_EXPECT_KASAN_FAIL(test, ptr[size + 5] = 'y');
142
143         /* Out-of-bounds access past the aligned kmalloc object. */
144         KUNIT_EXPECT_KASAN_FAIL(test, ptr[0] =
145                                         ptr[size + KASAN_GRANULE_SIZE + 5]);
146
147         kfree(ptr);
148 }
149
150 static void kmalloc_oob_left(struct kunit *test)
151 {
152         char *ptr;
153         size_t size = 15;
154
155         ptr = kmalloc(size, GFP_KERNEL);
156         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
157
158         KUNIT_EXPECT_KASAN_FAIL(test, *ptr = *(ptr - 1));
159         kfree(ptr);
160 }
161
162 static void kmalloc_node_oob_right(struct kunit *test)
163 {
164         char *ptr;
165         size_t size = 4096;
166
167         ptr = kmalloc_node(size, GFP_KERNEL, 0);
168         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
169
170         KUNIT_EXPECT_KASAN_FAIL(test, ptr[0] = ptr[size]);
171         kfree(ptr);
172 }
173
174 /*
175  * These kmalloc_pagealloc_* tests try allocating a memory chunk that doesn't
176  * fit into a slab cache and therefore is allocated via the page allocator
177  * fallback. Since this kind of fallback is only implemented for SLUB, these
178  * tests are limited to that allocator.
179  */
180 static void kmalloc_pagealloc_oob_right(struct kunit *test)
181 {
182         char *ptr;
183         size_t size = KMALLOC_MAX_CACHE_SIZE + 10;
184
185         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_SLUB);
186
187         ptr = kmalloc(size, GFP_KERNEL);
188         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
189
190         KUNIT_EXPECT_KASAN_FAIL(test, ptr[size + OOB_TAG_OFF] = 0);
191
192         kfree(ptr);
193 }
194
195 static void kmalloc_pagealloc_uaf(struct kunit *test)
196 {
197         char *ptr;
198         size_t size = KMALLOC_MAX_CACHE_SIZE + 10;
199
200         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_SLUB);
201
202         ptr = kmalloc(size, GFP_KERNEL);
203         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
204         kfree(ptr);
205
206         KUNIT_EXPECT_KASAN_FAIL(test, ((volatile char *)ptr)[0]);
207 }
208
209 static void kmalloc_pagealloc_invalid_free(struct kunit *test)
210 {
211         char *ptr;
212         size_t size = KMALLOC_MAX_CACHE_SIZE + 10;
213
214         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_SLUB);
215
216         ptr = kmalloc(size, GFP_KERNEL);
217         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
218
219         KUNIT_EXPECT_KASAN_FAIL(test, kfree(ptr + 1));
220 }
221
222 static void pagealloc_oob_right(struct kunit *test)
223 {
224         char *ptr;
225         struct page *pages;
226         size_t order = 4;
227         size_t size = (1UL << (PAGE_SHIFT + order));
228
229         /*
230          * With generic KASAN page allocations have no redzones, thus
231          * out-of-bounds detection is not guaranteed.
232          * See https://bugzilla.kernel.org/show_bug.cgi?id=210503.
233          */
234         KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_KASAN_GENERIC);
235
236         pages = alloc_pages(GFP_KERNEL, order);
237         ptr = page_address(pages);
238         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
239
240         KUNIT_EXPECT_KASAN_FAIL(test, ptr[0] = ptr[size]);
241         free_pages((unsigned long)ptr, order);
242 }
243
244 static void pagealloc_uaf(struct kunit *test)
245 {
246         char *ptr;
247         struct page *pages;
248         size_t order = 4;
249
250         pages = alloc_pages(GFP_KERNEL, order);
251         ptr = page_address(pages);
252         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
253         free_pages((unsigned long)ptr, order);
254
255         KUNIT_EXPECT_KASAN_FAIL(test, ((volatile char *)ptr)[0]);
256 }
257
258 static void kmalloc_large_oob_right(struct kunit *test)
259 {
260         char *ptr;
261         size_t size = KMALLOC_MAX_CACHE_SIZE - 256;
262
263         /*
264          * Allocate a chunk that is large enough, but still fits into a slab
265          * and does not trigger the page allocator fallback in SLUB.
266          */
267         ptr = kmalloc(size, GFP_KERNEL);
268         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
269
270         KUNIT_EXPECT_KASAN_FAIL(test, ptr[size] = 0);
271         kfree(ptr);
272 }
273
274 static void krealloc_more_oob_helper(struct kunit *test,
275                                         size_t size1, size_t size2)
276 {
277         char *ptr1, *ptr2;
278         size_t middle;
279
280         KUNIT_ASSERT_LT(test, size1, size2);
281         middle = size1 + (size2 - size1) / 2;
282
283         ptr1 = kmalloc(size1, GFP_KERNEL);
284         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr1);
285
286         ptr2 = krealloc(ptr1, size2, GFP_KERNEL);
287         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr2);
288
289         /* All offsets up to size2 must be accessible. */
290         ptr2[size1 - 1] = 'x';
291         ptr2[size1] = 'x';
292         ptr2[middle] = 'x';
293         ptr2[size2 - 1] = 'x';
294
295         /* Generic mode is precise, so unaligned size2 must be inaccessible. */
296         if (IS_ENABLED(CONFIG_KASAN_GENERIC))
297                 KUNIT_EXPECT_KASAN_FAIL(test, ptr2[size2] = 'x');
298
299         /* For all modes first aligned offset after size2 must be inaccessible. */
300         KUNIT_EXPECT_KASAN_FAIL(test,
301                 ptr2[round_up(size2, KASAN_GRANULE_SIZE)] = 'x');
302
303         kfree(ptr2);
304 }
305
306 static void krealloc_less_oob_helper(struct kunit *test,
307                                         size_t size1, size_t size2)
308 {
309         char *ptr1, *ptr2;
310         size_t middle;
311
312         KUNIT_ASSERT_LT(test, size2, size1);
313         middle = size2 + (size1 - size2) / 2;
314
315         ptr1 = kmalloc(size1, GFP_KERNEL);
316         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr1);
317
318         ptr2 = krealloc(ptr1, size2, GFP_KERNEL);
319         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr2);
320
321         /* Must be accessible for all modes. */
322         ptr2[size2 - 1] = 'x';
323
324         /* Generic mode is precise, so unaligned size2 must be inaccessible. */
325         if (IS_ENABLED(CONFIG_KASAN_GENERIC))
326                 KUNIT_EXPECT_KASAN_FAIL(test, ptr2[size2] = 'x');
327
328         /* For all modes first aligned offset after size2 must be inaccessible. */
329         KUNIT_EXPECT_KASAN_FAIL(test,
330                 ptr2[round_up(size2, KASAN_GRANULE_SIZE)] = 'x');
331
332         /*
333          * For all modes all size2, middle, and size1 should land in separate
334          * granules and thus the latter two offsets should be inaccessible.
335          */
336         KUNIT_EXPECT_LE(test, round_up(size2, KASAN_GRANULE_SIZE),
337                                 round_down(middle, KASAN_GRANULE_SIZE));
338         KUNIT_EXPECT_LE(test, round_up(middle, KASAN_GRANULE_SIZE),
339                                 round_down(size1, KASAN_GRANULE_SIZE));
340         KUNIT_EXPECT_KASAN_FAIL(test, ptr2[middle] = 'x');
341         KUNIT_EXPECT_KASAN_FAIL(test, ptr2[size1 - 1] = 'x');
342         KUNIT_EXPECT_KASAN_FAIL(test, ptr2[size1] = 'x');
343
344         kfree(ptr2);
345 }
346
347 static void krealloc_more_oob(struct kunit *test)
348 {
349         krealloc_more_oob_helper(test, 201, 235);
350 }
351
352 static void krealloc_less_oob(struct kunit *test)
353 {
354         krealloc_less_oob_helper(test, 235, 201);
355 }
356
357 static void krealloc_pagealloc_more_oob(struct kunit *test)
358 {
359         /* page_alloc fallback in only implemented for SLUB. */
360         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_SLUB);
361
362         krealloc_more_oob_helper(test, KMALLOC_MAX_CACHE_SIZE + 201,
363                                         KMALLOC_MAX_CACHE_SIZE + 235);
364 }
365
366 static void krealloc_pagealloc_less_oob(struct kunit *test)
367 {
368         /* page_alloc fallback in only implemented for SLUB. */
369         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_SLUB);
370
371         krealloc_less_oob_helper(test, KMALLOC_MAX_CACHE_SIZE + 235,
372                                         KMALLOC_MAX_CACHE_SIZE + 201);
373 }
374
375 /*
376  * Check that krealloc() detects a use-after-free, returns NULL,
377  * and doesn't unpoison the freed object.
378  */
379 static void krealloc_uaf(struct kunit *test)
380 {
381         char *ptr1, *ptr2;
382         int size1 = 201;
383         int size2 = 235;
384
385         ptr1 = kmalloc(size1, GFP_KERNEL);
386         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr1);
387         kfree(ptr1);
388
389         KUNIT_EXPECT_KASAN_FAIL(test, ptr2 = krealloc(ptr1, size2, GFP_KERNEL));
390         KUNIT_ASSERT_PTR_EQ(test, (void *)ptr2, NULL);
391         KUNIT_EXPECT_KASAN_FAIL(test, *(volatile char *)ptr1);
392 }
393
394 static void kmalloc_oob_16(struct kunit *test)
395 {
396         struct {
397                 u64 words[2];
398         } *ptr1, *ptr2;
399
400         /* This test is specifically crafted for the generic mode. */
401         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_GENERIC);
402
403         ptr1 = kmalloc(sizeof(*ptr1) - 3, GFP_KERNEL);
404         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr1);
405
406         ptr2 = kmalloc(sizeof(*ptr2), GFP_KERNEL);
407         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr2);
408
409         KUNIT_EXPECT_KASAN_FAIL(test, *ptr1 = *ptr2);
410         kfree(ptr1);
411         kfree(ptr2);
412 }
413
414 static void kmalloc_uaf_16(struct kunit *test)
415 {
416         struct {
417                 u64 words[2];
418         } *ptr1, *ptr2;
419
420         ptr1 = kmalloc(sizeof(*ptr1), GFP_KERNEL);
421         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr1);
422
423         ptr2 = kmalloc(sizeof(*ptr2), GFP_KERNEL);
424         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr2);
425         kfree(ptr2);
426
427         KUNIT_EXPECT_KASAN_FAIL(test, *ptr1 = *ptr2);
428         kfree(ptr1);
429 }
430
431 /*
432  * Note: in the memset tests below, the written range touches both valid and
433  * invalid memory. This makes sure that the instrumentation does not only check
434  * the starting address but the whole range.
435  */
436
437 static void kmalloc_oob_memset_2(struct kunit *test)
438 {
439         char *ptr;
440         size_t size = 128 - KASAN_GRANULE_SIZE;
441
442         ptr = kmalloc(size, GFP_KERNEL);
443         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
444
445         KUNIT_EXPECT_KASAN_FAIL(test, memset(ptr + size - 1, 0, 2));
446         kfree(ptr);
447 }
448
449 static void kmalloc_oob_memset_4(struct kunit *test)
450 {
451         char *ptr;
452         size_t size = 128 - KASAN_GRANULE_SIZE;
453
454         ptr = kmalloc(size, GFP_KERNEL);
455         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
456
457         KUNIT_EXPECT_KASAN_FAIL(test, memset(ptr + size - 3, 0, 4));
458         kfree(ptr);
459 }
460
461 static void kmalloc_oob_memset_8(struct kunit *test)
462 {
463         char *ptr;
464         size_t size = 128 - KASAN_GRANULE_SIZE;
465
466         ptr = kmalloc(size, GFP_KERNEL);
467         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
468
469         KUNIT_EXPECT_KASAN_FAIL(test, memset(ptr + size - 7, 0, 8));
470         kfree(ptr);
471 }
472
473 static void kmalloc_oob_memset_16(struct kunit *test)
474 {
475         char *ptr;
476         size_t size = 128 - KASAN_GRANULE_SIZE;
477
478         ptr = kmalloc(size, GFP_KERNEL);
479         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
480
481         KUNIT_EXPECT_KASAN_FAIL(test, memset(ptr + size - 15, 0, 16));
482         kfree(ptr);
483 }
484
485 static void kmalloc_oob_in_memset(struct kunit *test)
486 {
487         char *ptr;
488         size_t size = 128 - KASAN_GRANULE_SIZE;
489
490         ptr = kmalloc(size, GFP_KERNEL);
491         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
492
493         KUNIT_EXPECT_KASAN_FAIL(test,
494                                 memset(ptr, 0, size + KASAN_GRANULE_SIZE));
495         kfree(ptr);
496 }
497
498 static void kmalloc_memmove_invalid_size(struct kunit *test)
499 {
500         char *ptr;
501         size_t size = 64;
502         volatile size_t invalid_size = -2;
503
504         /*
505          * Hardware tag-based mode doesn't check memmove for negative size.
506          * As a result, this test introduces a side-effect memory corruption,
507          * which can result in a crash.
508          */
509         KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_KASAN_HW_TAGS);
510
511         ptr = kmalloc(size, GFP_KERNEL);
512         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
513
514         memset((char *)ptr, 0, 64);
515         KUNIT_EXPECT_KASAN_FAIL(test,
516                 memmove((char *)ptr, (char *)ptr + 4, invalid_size));
517         kfree(ptr);
518 }
519
520 static void kmalloc_uaf(struct kunit *test)
521 {
522         char *ptr;
523         size_t size = 10;
524
525         ptr = kmalloc(size, GFP_KERNEL);
526         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
527
528         kfree(ptr);
529         KUNIT_EXPECT_KASAN_FAIL(test, ((volatile char *)ptr)[8]);
530 }
531
532 static void kmalloc_uaf_memset(struct kunit *test)
533 {
534         char *ptr;
535         size_t size = 33;
536
537         /*
538          * Only generic KASAN uses quarantine, which is required to avoid a
539          * kernel memory corruption this test causes.
540          */
541         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_GENERIC);
542
543         ptr = kmalloc(size, GFP_KERNEL);
544         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
545
546         kfree(ptr);
547         KUNIT_EXPECT_KASAN_FAIL(test, memset(ptr, 0, size));
548 }
549
550 static void kmalloc_uaf2(struct kunit *test)
551 {
552         char *ptr1, *ptr2;
553         size_t size = 43;
554         int counter = 0;
555
556 again:
557         ptr1 = kmalloc(size, GFP_KERNEL);
558         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr1);
559
560         kfree(ptr1);
561
562         ptr2 = kmalloc(size, GFP_KERNEL);
563         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr2);
564
565         /*
566          * For tag-based KASAN ptr1 and ptr2 tags might happen to be the same.
567          * Allow up to 16 attempts at generating different tags.
568          */
569         if (!IS_ENABLED(CONFIG_KASAN_GENERIC) && ptr1 == ptr2 && counter++ < 16) {
570                 kfree(ptr2);
571                 goto again;
572         }
573
574         KUNIT_EXPECT_KASAN_FAIL(test, ((volatile char *)ptr1)[40]);
575         KUNIT_EXPECT_PTR_NE(test, ptr1, ptr2);
576
577         kfree(ptr2);
578 }
579
580 static void kfree_via_page(struct kunit *test)
581 {
582         char *ptr;
583         size_t size = 8;
584         struct page *page;
585         unsigned long offset;
586
587         ptr = kmalloc(size, GFP_KERNEL);
588         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
589
590         page = virt_to_page(ptr);
591         offset = offset_in_page(ptr);
592         kfree(page_address(page) + offset);
593 }
594
595 static void kfree_via_phys(struct kunit *test)
596 {
597         char *ptr;
598         size_t size = 8;
599         phys_addr_t phys;
600
601         ptr = kmalloc(size, GFP_KERNEL);
602         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
603
604         phys = virt_to_phys(ptr);
605         kfree(phys_to_virt(phys));
606 }
607
608 static void kmem_cache_oob(struct kunit *test)
609 {
610         char *p;
611         size_t size = 200;
612         struct kmem_cache *cache;
613
614         cache = kmem_cache_create("test_cache", size, 0, 0, NULL);
615         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, cache);
616
617         p = kmem_cache_alloc(cache, GFP_KERNEL);
618         if (!p) {
619                 kunit_err(test, "Allocation failed: %s\n", __func__);
620                 kmem_cache_destroy(cache);
621                 return;
622         }
623
624         KUNIT_EXPECT_KASAN_FAIL(test, *p = p[size + OOB_TAG_OFF]);
625
626         kmem_cache_free(cache, p);
627         kmem_cache_destroy(cache);
628 }
629
630 static void kmem_cache_accounted(struct kunit *test)
631 {
632         int i;
633         char *p;
634         size_t size = 200;
635         struct kmem_cache *cache;
636
637         cache = kmem_cache_create("test_cache", size, 0, SLAB_ACCOUNT, NULL);
638         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, cache);
639
640         /*
641          * Several allocations with a delay to allow for lazy per memcg kmem
642          * cache creation.
643          */
644         for (i = 0; i < 5; i++) {
645                 p = kmem_cache_alloc(cache, GFP_KERNEL);
646                 if (!p)
647                         goto free_cache;
648
649                 kmem_cache_free(cache, p);
650                 msleep(100);
651         }
652
653 free_cache:
654         kmem_cache_destroy(cache);
655 }
656
657 static void kmem_cache_bulk(struct kunit *test)
658 {
659         struct kmem_cache *cache;
660         size_t size = 200;
661         char *p[10];
662         bool ret;
663         int i;
664
665         cache = kmem_cache_create("test_cache", size, 0, 0, NULL);
666         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, cache);
667
668         ret = kmem_cache_alloc_bulk(cache, GFP_KERNEL, ARRAY_SIZE(p), (void **)&p);
669         if (!ret) {
670                 kunit_err(test, "Allocation failed: %s\n", __func__);
671                 kmem_cache_destroy(cache);
672                 return;
673         }
674
675         for (i = 0; i < ARRAY_SIZE(p); i++)
676                 p[i][0] = p[i][size - 1] = 42;
677
678         kmem_cache_free_bulk(cache, ARRAY_SIZE(p), (void **)&p);
679         kmem_cache_destroy(cache);
680 }
681
682 static char global_array[10];
683
684 static void kasan_global_oob(struct kunit *test)
685 {
686         /*
687          * Deliberate out-of-bounds access. To prevent CONFIG_UBSAN_LOCAL_BOUNDS
688          * from failing here and panicking the kernel, access the array via a
689          * volatile pointer, which will prevent the compiler from being able to
690          * determine the array bounds.
691          *
692          * This access uses a volatile pointer to char (char *volatile) rather
693          * than the more conventional pointer to volatile char (volatile char *)
694          * because we want to prevent the compiler from making inferences about
695          * the pointer itself (i.e. its array bounds), not the data that it
696          * refers to.
697          */
698         char *volatile array = global_array;
699         char *p = &array[ARRAY_SIZE(global_array) + 3];
700
701         /* Only generic mode instruments globals. */
702         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_GENERIC);
703
704         KUNIT_EXPECT_KASAN_FAIL(test, *(volatile char *)p);
705 }
706
707 /* Check that ksize() makes the whole object accessible. */
708 static void ksize_unpoisons_memory(struct kunit *test)
709 {
710         char *ptr;
711         size_t size = 123, real_size;
712
713         ptr = kmalloc(size, GFP_KERNEL);
714         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
715         real_size = ksize(ptr);
716
717         /* This access shouldn't trigger a KASAN report. */
718         ptr[size] = 'x';
719
720         /* This one must. */
721         KUNIT_EXPECT_KASAN_FAIL(test, ((volatile char *)ptr)[real_size]);
722
723         kfree(ptr);
724 }
725
726 /*
727  * Check that a use-after-free is detected by ksize() and via normal accesses
728  * after it.
729  */
730 static void ksize_uaf(struct kunit *test)
731 {
732         char *ptr;
733         int size = 128 - KASAN_GRANULE_SIZE;
734
735         ptr = kmalloc(size, GFP_KERNEL);
736         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
737         kfree(ptr);
738
739         KUNIT_EXPECT_KASAN_FAIL(test, ksize(ptr));
740         KUNIT_EXPECT_KASAN_FAIL(test, ((volatile char *)ptr)[0]);
741         KUNIT_EXPECT_KASAN_FAIL(test, ((volatile char *)ptr)[size]);
742 }
743
744 static void kasan_stack_oob(struct kunit *test)
745 {
746         char stack_array[10];
747         /* See comment in kasan_global_oob. */
748         char *volatile array = stack_array;
749         char *p = &array[ARRAY_SIZE(stack_array) + OOB_TAG_OFF];
750
751         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_STACK);
752
753         KUNIT_EXPECT_KASAN_FAIL(test, *(volatile char *)p);
754 }
755
756 static void kasan_alloca_oob_left(struct kunit *test)
757 {
758         volatile int i = 10;
759         char alloca_array[i];
760         /* See comment in kasan_global_oob. */
761         char *volatile array = alloca_array;
762         char *p = array - 1;
763
764         /* Only generic mode instruments dynamic allocas. */
765         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_GENERIC);
766         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_STACK);
767
768         KUNIT_EXPECT_KASAN_FAIL(test, *(volatile char *)p);
769 }
770
771 static void kasan_alloca_oob_right(struct kunit *test)
772 {
773         volatile int i = 10;
774         char alloca_array[i];
775         /* See comment in kasan_global_oob. */
776         char *volatile array = alloca_array;
777         char *p = array + i;
778
779         /* Only generic mode instruments dynamic allocas. */
780         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_GENERIC);
781         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_STACK);
782
783         KUNIT_EXPECT_KASAN_FAIL(test, *(volatile char *)p);
784 }
785
786 static void kmem_cache_double_free(struct kunit *test)
787 {
788         char *p;
789         size_t size = 200;
790         struct kmem_cache *cache;
791
792         cache = kmem_cache_create("test_cache", size, 0, 0, NULL);
793         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, cache);
794
795         p = kmem_cache_alloc(cache, GFP_KERNEL);
796         if (!p) {
797                 kunit_err(test, "Allocation failed: %s\n", __func__);
798                 kmem_cache_destroy(cache);
799                 return;
800         }
801
802         kmem_cache_free(cache, p);
803         KUNIT_EXPECT_KASAN_FAIL(test, kmem_cache_free(cache, p));
804         kmem_cache_destroy(cache);
805 }
806
807 static void kmem_cache_invalid_free(struct kunit *test)
808 {
809         char *p;
810         size_t size = 200;
811         struct kmem_cache *cache;
812
813         cache = kmem_cache_create("test_cache", size, 0, SLAB_TYPESAFE_BY_RCU,
814                                   NULL);
815         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, cache);
816
817         p = kmem_cache_alloc(cache, GFP_KERNEL);
818         if (!p) {
819                 kunit_err(test, "Allocation failed: %s\n", __func__);
820                 kmem_cache_destroy(cache);
821                 return;
822         }
823
824         /* Trigger invalid free, the object doesn't get freed. */
825         KUNIT_EXPECT_KASAN_FAIL(test, kmem_cache_free(cache, p + 1));
826
827         /*
828          * Properly free the object to prevent the "Objects remaining in
829          * test_cache on __kmem_cache_shutdown" BUG failure.
830          */
831         kmem_cache_free(cache, p);
832
833         kmem_cache_destroy(cache);
834 }
835
836 static void kasan_memchr(struct kunit *test)
837 {
838         char *ptr;
839         size_t size = 24;
840
841         /*
842          * str* functions are not instrumented with CONFIG_AMD_MEM_ENCRYPT.
843          * See https://bugzilla.kernel.org/show_bug.cgi?id=206337 for details.
844          */
845         KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_AMD_MEM_ENCRYPT);
846
847         if (OOB_TAG_OFF)
848                 size = round_up(size, OOB_TAG_OFF);
849
850         ptr = kmalloc(size, GFP_KERNEL | __GFP_ZERO);
851         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
852
853         KUNIT_EXPECT_KASAN_FAIL(test,
854                 kasan_ptr_result = memchr(ptr, '1', size + 1));
855
856         kfree(ptr);
857 }
858
859 static void kasan_memcmp(struct kunit *test)
860 {
861         char *ptr;
862         size_t size = 24;
863         int arr[9];
864
865         /*
866          * str* functions are not instrumented with CONFIG_AMD_MEM_ENCRYPT.
867          * See https://bugzilla.kernel.org/show_bug.cgi?id=206337 for details.
868          */
869         KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_AMD_MEM_ENCRYPT);
870
871         if (OOB_TAG_OFF)
872                 size = round_up(size, OOB_TAG_OFF);
873
874         ptr = kmalloc(size, GFP_KERNEL | __GFP_ZERO);
875         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
876         memset(arr, 0, sizeof(arr));
877
878         KUNIT_EXPECT_KASAN_FAIL(test,
879                 kasan_int_result = memcmp(ptr, arr, size+1));
880         kfree(ptr);
881 }
882
883 static void kasan_strings(struct kunit *test)
884 {
885         char *ptr;
886         size_t size = 24;
887
888         /*
889          * str* functions are not instrumented with CONFIG_AMD_MEM_ENCRYPT.
890          * See https://bugzilla.kernel.org/show_bug.cgi?id=206337 for details.
891          */
892         KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_AMD_MEM_ENCRYPT);
893
894         ptr = kmalloc(size, GFP_KERNEL | __GFP_ZERO);
895         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
896
897         kfree(ptr);
898
899         /*
900          * Try to cause only 1 invalid access (less spam in dmesg).
901          * For that we need ptr to point to zeroed byte.
902          * Skip metadata that could be stored in freed object so ptr
903          * will likely point to zeroed byte.
904          */
905         ptr += 16;
906         KUNIT_EXPECT_KASAN_FAIL(test, kasan_ptr_result = strchr(ptr, '1'));
907
908         KUNIT_EXPECT_KASAN_FAIL(test, kasan_ptr_result = strrchr(ptr, '1'));
909
910         KUNIT_EXPECT_KASAN_FAIL(test, kasan_int_result = strcmp(ptr, "2"));
911
912         KUNIT_EXPECT_KASAN_FAIL(test, kasan_int_result = strncmp(ptr, "2", 1));
913
914         KUNIT_EXPECT_KASAN_FAIL(test, kasan_int_result = strlen(ptr));
915
916         KUNIT_EXPECT_KASAN_FAIL(test, kasan_int_result = strnlen(ptr, 1));
917 }
918
919 static void kasan_bitops_modify(struct kunit *test, int nr, void *addr)
920 {
921         KUNIT_EXPECT_KASAN_FAIL(test, set_bit(nr, addr));
922         KUNIT_EXPECT_KASAN_FAIL(test, __set_bit(nr, addr));
923         KUNIT_EXPECT_KASAN_FAIL(test, clear_bit(nr, addr));
924         KUNIT_EXPECT_KASAN_FAIL(test, __clear_bit(nr, addr));
925         KUNIT_EXPECT_KASAN_FAIL(test, clear_bit_unlock(nr, addr));
926         KUNIT_EXPECT_KASAN_FAIL(test, __clear_bit_unlock(nr, addr));
927         KUNIT_EXPECT_KASAN_FAIL(test, change_bit(nr, addr));
928         KUNIT_EXPECT_KASAN_FAIL(test, __change_bit(nr, addr));
929 }
930
931 static void kasan_bitops_test_and_modify(struct kunit *test, int nr, void *addr)
932 {
933         KUNIT_EXPECT_KASAN_FAIL(test, test_and_set_bit(nr, addr));
934         KUNIT_EXPECT_KASAN_FAIL(test, __test_and_set_bit(nr, addr));
935         KUNIT_EXPECT_KASAN_FAIL(test, test_and_set_bit_lock(nr, addr));
936         KUNIT_EXPECT_KASAN_FAIL(test, test_and_clear_bit(nr, addr));
937         KUNIT_EXPECT_KASAN_FAIL(test, __test_and_clear_bit(nr, addr));
938         KUNIT_EXPECT_KASAN_FAIL(test, test_and_change_bit(nr, addr));
939         KUNIT_EXPECT_KASAN_FAIL(test, __test_and_change_bit(nr, addr));
940         KUNIT_EXPECT_KASAN_FAIL(test, kasan_int_result = test_bit(nr, addr));
941
942 #if defined(clear_bit_unlock_is_negative_byte)
943         KUNIT_EXPECT_KASAN_FAIL(test, kasan_int_result =
944                                 clear_bit_unlock_is_negative_byte(nr, addr));
945 #endif
946 }
947
948 static void kasan_bitops_generic(struct kunit *test)
949 {
950         long *bits;
951
952         /* This test is specifically crafted for the generic mode. */
953         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_GENERIC);
954
955         /*
956          * Allocate 1 more byte, which causes kzalloc to round up to 16 bytes;
957          * this way we do not actually corrupt other memory.
958          */
959         bits = kzalloc(sizeof(*bits) + 1, GFP_KERNEL);
960         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bits);
961
962         /*
963          * Below calls try to access bit within allocated memory; however, the
964          * below accesses are still out-of-bounds, since bitops are defined to
965          * operate on the whole long the bit is in.
966          */
967         kasan_bitops_modify(test, BITS_PER_LONG, bits);
968
969         /*
970          * Below calls try to access bit beyond allocated memory.
971          */
972         kasan_bitops_test_and_modify(test, BITS_PER_LONG + BITS_PER_BYTE, bits);
973
974         kfree(bits);
975 }
976
977 static void kasan_bitops_tags(struct kunit *test)
978 {
979         long *bits;
980
981         /* This test is specifically crafted for tag-based modes. */
982         KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_KASAN_GENERIC);
983
984         /* kmalloc-64 cache will be used and the last 16 bytes will be the redzone. */
985         bits = kzalloc(48, GFP_KERNEL);
986         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, bits);
987
988         /* Do the accesses past the 48 allocated bytes, but within the redone. */
989         kasan_bitops_modify(test, BITS_PER_LONG, (void *)bits + 48);
990         kasan_bitops_test_and_modify(test, BITS_PER_LONG + BITS_PER_BYTE, (void *)bits + 48);
991
992         kfree(bits);
993 }
994
995 static void kmalloc_double_kzfree(struct kunit *test)
996 {
997         char *ptr;
998         size_t size = 16;
999
1000         ptr = kmalloc(size, GFP_KERNEL);
1001         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
1002
1003         kfree_sensitive(ptr);
1004         KUNIT_EXPECT_KASAN_FAIL(test, kfree_sensitive(ptr));
1005 }
1006
1007 static void vmalloc_oob(struct kunit *test)
1008 {
1009         void *area;
1010
1011         KASAN_TEST_NEEDS_CONFIG_ON(test, CONFIG_KASAN_VMALLOC);
1012
1013         /*
1014          * We have to be careful not to hit the guard page.
1015          * The MMU will catch that and crash us.
1016          */
1017         area = vmalloc(3000);
1018         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, area);
1019
1020         KUNIT_EXPECT_KASAN_FAIL(test, ((volatile char *)area)[3100]);
1021         vfree(area);
1022 }
1023
1024 /*
1025  * Check that the assigned pointer tag falls within the [KASAN_TAG_MIN,
1026  * KASAN_TAG_KERNEL) range (note: excluding the match-all tag) for tag-based
1027  * modes.
1028  */
1029 static void match_all_not_assigned(struct kunit *test)
1030 {
1031         char *ptr;
1032         struct page *pages;
1033         int i, size, order;
1034
1035         KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_KASAN_GENERIC);
1036
1037         for (i = 0; i < 256; i++) {
1038                 size = (get_random_int() % 1024) + 1;
1039                 ptr = kmalloc(size, GFP_KERNEL);
1040                 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
1041                 KUNIT_EXPECT_GE(test, (u8)get_tag(ptr), (u8)KASAN_TAG_MIN);
1042                 KUNIT_EXPECT_LT(test, (u8)get_tag(ptr), (u8)KASAN_TAG_KERNEL);
1043                 kfree(ptr);
1044         }
1045
1046         for (i = 0; i < 256; i++) {
1047                 order = (get_random_int() % 4) + 1;
1048                 pages = alloc_pages(GFP_KERNEL, order);
1049                 ptr = page_address(pages);
1050                 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
1051                 KUNIT_EXPECT_GE(test, (u8)get_tag(ptr), (u8)KASAN_TAG_MIN);
1052                 KUNIT_EXPECT_LT(test, (u8)get_tag(ptr), (u8)KASAN_TAG_KERNEL);
1053                 free_pages((unsigned long)ptr, order);
1054         }
1055 }
1056
1057 /* Check that 0xff works as a match-all pointer tag for tag-based modes. */
1058 static void match_all_ptr_tag(struct kunit *test)
1059 {
1060         char *ptr;
1061         u8 tag;
1062
1063         KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_KASAN_GENERIC);
1064
1065         ptr = kmalloc(128, GFP_KERNEL);
1066         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
1067
1068         /* Backup the assigned tag. */
1069         tag = get_tag(ptr);
1070         KUNIT_EXPECT_NE(test, tag, (u8)KASAN_TAG_KERNEL);
1071
1072         /* Reset the tag to 0xff.*/
1073         ptr = set_tag(ptr, KASAN_TAG_KERNEL);
1074
1075         /* This access shouldn't trigger a KASAN report. */
1076         *ptr = 0;
1077
1078         /* Recover the pointer tag and free. */
1079         ptr = set_tag(ptr, tag);
1080         kfree(ptr);
1081 }
1082
1083 /* Check that there are no match-all memory tags for tag-based modes. */
1084 static void match_all_mem_tag(struct kunit *test)
1085 {
1086         char *ptr;
1087         int tag;
1088
1089         KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_KASAN_GENERIC);
1090
1091         ptr = kmalloc(128, GFP_KERNEL);
1092         KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
1093         KUNIT_EXPECT_NE(test, (u8)get_tag(ptr), (u8)KASAN_TAG_KERNEL);
1094
1095         /* For each possible tag value not matching the pointer tag. */
1096         for (tag = KASAN_TAG_MIN; tag <= KASAN_TAG_KERNEL; tag++) {
1097                 if (tag == get_tag(ptr))
1098                         continue;
1099
1100                 /* Mark the first memory granule with the chosen memory tag. */
1101                 kasan_poison(ptr, KASAN_GRANULE_SIZE, (u8)tag, false);
1102
1103                 /* This access must cause a KASAN report. */
1104                 KUNIT_EXPECT_KASAN_FAIL(test, *ptr = 0);
1105         }
1106
1107         /* Recover the memory tag and free. */
1108         kasan_poison(ptr, KASAN_GRANULE_SIZE, get_tag(ptr), false);
1109         kfree(ptr);
1110 }
1111
1112 static struct kunit_case kasan_kunit_test_cases[] = {
1113         KUNIT_CASE(kmalloc_oob_right),
1114         KUNIT_CASE(kmalloc_oob_left),
1115         KUNIT_CASE(kmalloc_node_oob_right),
1116         KUNIT_CASE(kmalloc_pagealloc_oob_right),
1117         KUNIT_CASE(kmalloc_pagealloc_uaf),
1118         KUNIT_CASE(kmalloc_pagealloc_invalid_free),
1119         KUNIT_CASE(pagealloc_oob_right),
1120         KUNIT_CASE(pagealloc_uaf),
1121         KUNIT_CASE(kmalloc_large_oob_right),
1122         KUNIT_CASE(krealloc_more_oob),
1123         KUNIT_CASE(krealloc_less_oob),
1124         KUNIT_CASE(krealloc_pagealloc_more_oob),
1125         KUNIT_CASE(krealloc_pagealloc_less_oob),
1126         KUNIT_CASE(krealloc_uaf),
1127         KUNIT_CASE(kmalloc_oob_16),
1128         KUNIT_CASE(kmalloc_uaf_16),
1129         KUNIT_CASE(kmalloc_oob_in_memset),
1130         KUNIT_CASE(kmalloc_oob_memset_2),
1131         KUNIT_CASE(kmalloc_oob_memset_4),
1132         KUNIT_CASE(kmalloc_oob_memset_8),
1133         KUNIT_CASE(kmalloc_oob_memset_16),
1134         KUNIT_CASE(kmalloc_memmove_invalid_size),
1135         KUNIT_CASE(kmalloc_uaf),
1136         KUNIT_CASE(kmalloc_uaf_memset),
1137         KUNIT_CASE(kmalloc_uaf2),
1138         KUNIT_CASE(kfree_via_page),
1139         KUNIT_CASE(kfree_via_phys),
1140         KUNIT_CASE(kmem_cache_oob),
1141         KUNIT_CASE(kmem_cache_accounted),
1142         KUNIT_CASE(kmem_cache_bulk),
1143         KUNIT_CASE(kasan_global_oob),
1144         KUNIT_CASE(kasan_stack_oob),
1145         KUNIT_CASE(kasan_alloca_oob_left),
1146         KUNIT_CASE(kasan_alloca_oob_right),
1147         KUNIT_CASE(ksize_unpoisons_memory),
1148         KUNIT_CASE(ksize_uaf),
1149         KUNIT_CASE(kmem_cache_double_free),
1150         KUNIT_CASE(kmem_cache_invalid_free),
1151         KUNIT_CASE(kasan_memchr),
1152         KUNIT_CASE(kasan_memcmp),
1153         KUNIT_CASE(kasan_strings),
1154         KUNIT_CASE(kasan_bitops_generic),
1155         KUNIT_CASE(kasan_bitops_tags),
1156         KUNIT_CASE(kmalloc_double_kzfree),
1157         KUNIT_CASE(vmalloc_oob),
1158         KUNIT_CASE(match_all_not_assigned),
1159         KUNIT_CASE(match_all_ptr_tag),
1160         KUNIT_CASE(match_all_mem_tag),
1161         {}
1162 };
1163
1164 static struct kunit_suite kasan_kunit_test_suite = {
1165         .name = "kasan",
1166         .init = kasan_test_init,
1167         .test_cases = kasan_kunit_test_cases,
1168         .exit = kasan_test_exit,
1169 };
1170
1171 kunit_test_suite(kasan_kunit_test_suite);
1172
1173 MODULE_LICENSE("GPL");