1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * This file contains common KASAN code.
4 *
5 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
6 * Author: Andrey Ryabinin <ryabinin.a.a@gmail.com>
7 *
8 * Some code borrowed from https://github.com/xairy/kasan-prototype by
9 * Andrey Konovalov <andreyknvl@gmail.com>
10 */
11
12 #include <linux/export.h>
13 #include <linux/init.h>
14 #include <linux/kasan.h>
15 #include <linux/kernel.h>
16 #include <linux/linkage.h>
17 #include <linux/memblock.h>
18 #include <linux/memory.h>
19 #include <linux/mm.h>
20 #include <linux/module.h>
21 #include <linux/printk.h>
22 #include <linux/sched.h>
23 #include <linux/sched/task_stack.h>
24 #include <linux/slab.h>
25 #include <linux/stacktrace.h>
26 #include <linux/string.h>
27 #include <linux/types.h>
28 #include <linux/bug.h>
29
30 #include "kasan.h"
31 #include "../slab.h"
32
kasan_save_stack(gfp_t flags,bool can_alloc)33 depot_stack_handle_t kasan_save_stack(gfp_t flags, bool can_alloc)
34 {
35 unsigned long entries[KASAN_STACK_DEPTH];
36 unsigned int nr_entries;
37
38 nr_entries = stack_trace_save(entries, ARRAY_SIZE(entries), 0);
39 return __stack_depot_save(entries, nr_entries, flags, can_alloc);
40 }
41
kasan_set_track(struct kasan_track * track,gfp_t flags)42 void kasan_set_track(struct kasan_track *track, gfp_t flags)
43 {
44 track->pid = current->pid;
45 track->stack = kasan_save_stack(flags, true);
46 }
47
48 #if defined(CONFIG_KASAN_GENERIC) || defined(CONFIG_KASAN_SW_TAGS)
kasan_enable_current(void)49 void kasan_enable_current(void)
50 {
51 current->kasan_depth++;
52 }
53 EXPORT_SYMBOL(kasan_enable_current);
54
kasan_disable_current(void)55 void kasan_disable_current(void)
56 {
57 current->kasan_depth--;
58 }
59 EXPORT_SYMBOL(kasan_disable_current);
60
61 #endif /* CONFIG_KASAN_GENERIC || CONFIG_KASAN_SW_TAGS */
62
__kasan_unpoison_range(const void * address,size_t size)63 void __kasan_unpoison_range(const void *address, size_t size)
64 {
65 kasan_unpoison(address, size, false);
66 }
67
68 #ifdef CONFIG_KASAN_STACK
69 /* Unpoison the entire stack for a task. */
kasan_unpoison_task_stack(struct task_struct * task)70 void kasan_unpoison_task_stack(struct task_struct *task)
71 {
72 void *base = task_stack_page(task);
73
74 kasan_unpoison(base, THREAD_SIZE, false);
75 }
76
77 /* Unpoison the stack for the current task beyond a watermark sp value. */
kasan_unpoison_task_stack_below(const void * watermark)78 asmlinkage void kasan_unpoison_task_stack_below(const void *watermark)
79 {
80 /*
81 * Calculate the task stack base address. Avoid using 'current'
82 * because this function is called by early resume code which hasn't
83 * yet set up the percpu register (%gs).
84 */
85 void *base = (void *)((unsigned long)watermark & ~(THREAD_SIZE - 1));
86
87 kasan_unpoison(base, watermark - base, false);
88 }
89 #endif /* CONFIG_KASAN_STACK */
90
91 /*
92 * Only allow cache merging when stack collection is disabled and no metadata
93 * is present.
94 */
__kasan_never_merge(void)95 slab_flags_t __kasan_never_merge(void)
96 {
97 if (kasan_stack_collection_enabled())
98 return SLAB_KASAN;
99 return 0;
100 }
101
__kasan_unpoison_pages(struct page * page,unsigned int order,bool init)102 void __kasan_unpoison_pages(struct page *page, unsigned int order, bool init)
103 {
104 u8 tag;
105 unsigned long i;
106
107 if (unlikely(PageHighMem(page)))
108 return;
109
110 tag = kasan_random_tag();
111 for (i = 0; i < (1 << order); i++)
112 page_kasan_tag_set(page + i, tag);
113 kasan_unpoison(page_address(page), PAGE_SIZE << order, init);
114 }
115
__kasan_poison_pages(struct page * page,unsigned int order,bool init)116 void __kasan_poison_pages(struct page *page, unsigned int order, bool init)
117 {
118 if (likely(!PageHighMem(page)))
119 kasan_poison(page_address(page), PAGE_SIZE << order,
120 KASAN_FREE_PAGE, init);
121 }
122
123 /*
124 * Adaptive redzone policy taken from the userspace AddressSanitizer runtime.
125 * For larger allocations larger redzones are used.
126 */
optimal_redzone(unsigned int object_size)127 static inline unsigned int optimal_redzone(unsigned int object_size)
128 {
129 return
130 object_size <= 64 - 16 ? 16 :
131 object_size <= 128 - 32 ? 32 :
132 object_size <= 512 - 64 ? 64 :
133 object_size <= 4096 - 128 ? 128 :
134 object_size <= (1 << 14) - 256 ? 256 :
135 object_size <= (1 << 15) - 512 ? 512 :
136 object_size <= (1 << 16) - 1024 ? 1024 : 2048;
137 }
138
__kasan_cache_create(struct kmem_cache * cache,unsigned int * size,slab_flags_t * flags)139 void __kasan_cache_create(struct kmem_cache *cache, unsigned int *size,
140 slab_flags_t *flags)
141 {
142 unsigned int ok_size;
143 unsigned int optimal_size;
144
145 /*
146 * SLAB_KASAN is used to mark caches as ones that are sanitized by
147 * KASAN. Currently this flag is used in two places:
148 * 1. In slab_ksize() when calculating the size of the accessible
149 * memory within the object.
150 * 2. In slab_common.c to prevent merging of sanitized caches.
151 */
152 *flags |= SLAB_KASAN;
153
154 if (!kasan_stack_collection_enabled())
155 return;
156
157 ok_size = *size;
158
159 /* Add alloc meta into redzone. */
160 cache->kasan_info.alloc_meta_offset = *size;
161 *size += sizeof(struct kasan_alloc_meta);
162
163 /*
164 * If alloc meta doesn't fit, don't add it.
165 * This can only happen with SLAB, as it has KMALLOC_MAX_SIZE equal
166 * to KMALLOC_MAX_CACHE_SIZE and doesn't fall back to page_alloc for
167 * larger sizes.
168 */
169 if (*size > KMALLOC_MAX_SIZE) {
170 cache->kasan_info.alloc_meta_offset = 0;
171 *size = ok_size;
172 /* Continue, since free meta might still fit. */
173 }
174
175 /* Only the generic mode uses free meta or flexible redzones. */
176 if (!IS_ENABLED(CONFIG_KASAN_GENERIC)) {
177 cache->kasan_info.free_meta_offset = KASAN_NO_FREE_META;
178 return;
179 }
180
181 /*
182 * Add free meta into redzone when it's not possible to store
183 * it in the object. This is the case when:
184 * 1. Object is SLAB_TYPESAFE_BY_RCU, which means that it can
185 * be touched after it was freed, or
186 * 2. Object has a constructor, which means it's expected to
187 * retain its content until the next allocation, or
188 * 3. Object is too small.
189 * Otherwise cache->kasan_info.free_meta_offset = 0 is implied.
190 */
191 if ((cache->flags & SLAB_TYPESAFE_BY_RCU) || cache->ctor ||
192 cache->object_size < sizeof(struct kasan_free_meta)) {
193 ok_size = *size;
194
195 cache->kasan_info.free_meta_offset = *size;
196 *size += sizeof(struct kasan_free_meta);
197
198 /* If free meta doesn't fit, don't add it. */
199 if (*size > KMALLOC_MAX_SIZE) {
200 cache->kasan_info.free_meta_offset = KASAN_NO_FREE_META;
201 *size = ok_size;
202 }
203 }
204
205 /* Calculate size with optimal redzone. */
206 optimal_size = cache->object_size + optimal_redzone(cache->object_size);
207 /* Limit it with KMALLOC_MAX_SIZE (relevant for SLAB only). */
208 if (optimal_size > KMALLOC_MAX_SIZE)
209 optimal_size = KMALLOC_MAX_SIZE;
210 /* Use optimal size if the size with added metas is not large enough. */
211 if (*size < optimal_size)
212 *size = optimal_size;
213 }
214
__kasan_cache_create_kmalloc(struct kmem_cache * cache)215 void __kasan_cache_create_kmalloc(struct kmem_cache *cache)
216 {
217 cache->kasan_info.is_kmalloc = true;
218 }
219
__kasan_metadata_size(struct kmem_cache * cache)220 size_t __kasan_metadata_size(struct kmem_cache *cache)
221 {
222 if (!kasan_stack_collection_enabled())
223 return 0;
224 return (cache->kasan_info.alloc_meta_offset ?
225 sizeof(struct kasan_alloc_meta) : 0) +
226 (cache->kasan_info.free_meta_offset ?
227 sizeof(struct kasan_free_meta) : 0);
228 }
229
kasan_get_alloc_meta(struct kmem_cache * cache,const void * object)230 struct kasan_alloc_meta *kasan_get_alloc_meta(struct kmem_cache *cache,
231 const void *object)
232 {
233 if (!cache->kasan_info.alloc_meta_offset)
234 return NULL;
235 return kasan_reset_tag(object) + cache->kasan_info.alloc_meta_offset;
236 }
237
238 #ifdef CONFIG_KASAN_GENERIC
kasan_get_free_meta(struct kmem_cache * cache,const void * object)239 struct kasan_free_meta *kasan_get_free_meta(struct kmem_cache *cache,
240 const void *object)
241 {
242 BUILD_BUG_ON(sizeof(struct kasan_free_meta) > 32);
243 if (cache->kasan_info.free_meta_offset == KASAN_NO_FREE_META)
244 return NULL;
245 return kasan_reset_tag(object) + cache->kasan_info.free_meta_offset;
246 }
247 #endif
248
__kasan_poison_slab(struct page * page)249 void __kasan_poison_slab(struct page *page)
250 {
251 unsigned long i;
252
253 for (i = 0; i < compound_nr(page); i++)
254 page_kasan_tag_reset(page + i);
255 kasan_poison(page_address(page), page_size(page),
256 KASAN_KMALLOC_REDZONE, false);
257 }
258
__kasan_unpoison_object_data(struct kmem_cache * cache,void * object)259 void __kasan_unpoison_object_data(struct kmem_cache *cache, void *object)
260 {
261 kasan_unpoison(object, cache->object_size, false);
262 }
263
__kasan_poison_object_data(struct kmem_cache * cache,void * object)264 void __kasan_poison_object_data(struct kmem_cache *cache, void *object)
265 {
266 kasan_poison(object, round_up(cache->object_size, KASAN_GRANULE_SIZE),
267 KASAN_KMALLOC_REDZONE, false);
268 }
269
270 /*
271 * This function assigns a tag to an object considering the following:
272 * 1. A cache might have a constructor, which might save a pointer to a slab
273 * object somewhere (e.g. in the object itself). We preassign a tag for
274 * each object in caches with constructors during slab creation and reuse
275 * the same tag each time a particular object is allocated.
276 * 2. A cache might be SLAB_TYPESAFE_BY_RCU, which means objects can be
277 * accessed after being freed. We preassign tags for objects in these
278 * caches as well.
279 * 3. For SLAB allocator we can't preassign tags randomly since the freelist
280 * is stored as an array of indexes instead of a linked list. Assign tags
281 * based on objects indexes, so that objects that are next to each other
282 * get different tags.
283 */
assign_tag(struct kmem_cache * cache,const void * object,bool init)284 static inline u8 assign_tag(struct kmem_cache *cache,
285 const void *object, bool init)
286 {
287 if (IS_ENABLED(CONFIG_KASAN_GENERIC))
288 return 0xff;
289
290 /*
291 * If the cache neither has a constructor nor has SLAB_TYPESAFE_BY_RCU
292 * set, assign a tag when the object is being allocated (init == false).
293 */
294 if (!cache->ctor && !(cache->flags & SLAB_TYPESAFE_BY_RCU))
295 return init ? KASAN_TAG_KERNEL : kasan_random_tag();
296
297 /* For caches that either have a constructor or SLAB_TYPESAFE_BY_RCU: */
298 #ifdef CONFIG_SLAB
299 /* For SLAB assign tags based on the object index in the freelist. */
300 return (u8)obj_to_index(cache, virt_to_head_page(object), (void *)object);
301 #else
302 /*
303 * For SLUB assign a random tag during slab creation, otherwise reuse
304 * the already assigned tag.
305 */
306 return init ? kasan_random_tag() : get_tag(object);
307 #endif
308 }
309
__kasan_init_slab_obj(struct kmem_cache * cache,const void * object)310 void * __must_check __kasan_init_slab_obj(struct kmem_cache *cache,
311 const void *object)
312 {
313 struct kasan_alloc_meta *alloc_meta;
314
315 if (kasan_stack_collection_enabled()) {
316 alloc_meta = kasan_get_alloc_meta(cache, object);
317 if (alloc_meta)
318 __memset(alloc_meta, 0, sizeof(*alloc_meta));
319 }
320
321 /* Tag is ignored in set_tag() without CONFIG_KASAN_SW/HW_TAGS */
322 object = set_tag(object, assign_tag(cache, object, true));
323
324 return (void *)object;
325 }
326
____kasan_slab_free(struct kmem_cache * cache,void * object,unsigned long ip,bool quarantine,bool init)327 static inline bool ____kasan_slab_free(struct kmem_cache *cache, void *object,
328 unsigned long ip, bool quarantine, bool init)
329 {
330 u8 tag;
331 void *tagged_object;
332
333 if (!kasan_arch_is_ready())
334 return false;
335
336 tag = get_tag(object);
337 tagged_object = object;
338 object = kasan_reset_tag(object);
339
340 if (is_kfence_address(object))
341 return false;
342
343 if (unlikely(nearest_obj(cache, virt_to_head_page(object), object) !=
344 object)) {
345 kasan_report_invalid_free(tagged_object, ip);
346 return true;
347 }
348
349 /* RCU slabs could be legally used after free within the RCU period */
350 if (unlikely(cache->flags & SLAB_TYPESAFE_BY_RCU))
351 return false;
352
353 if (!kasan_byte_accessible(tagged_object)) {
354 kasan_report_invalid_free(tagged_object, ip);
355 return true;
356 }
357
358 kasan_poison(object, round_up(cache->object_size, KASAN_GRANULE_SIZE),
359 KASAN_KMALLOC_FREE, init);
360
361 if ((IS_ENABLED(CONFIG_KASAN_GENERIC) && !quarantine))
362 return false;
363
364 if (kasan_stack_collection_enabled())
365 kasan_set_free_info(cache, object, tag);
366
367 return kasan_quarantine_put(cache, object);
368 }
369
__kasan_slab_free(struct kmem_cache * cache,void * object,unsigned long ip,bool init)370 bool __kasan_slab_free(struct kmem_cache *cache, void *object,
371 unsigned long ip, bool init)
372 {
373 return ____kasan_slab_free(cache, object, ip, true, init);
374 }
375
____kasan_kfree_large(void * ptr,unsigned long ip)376 static inline bool ____kasan_kfree_large(void *ptr, unsigned long ip)
377 {
378 if (ptr != page_address(virt_to_head_page(ptr))) {
379 kasan_report_invalid_free(ptr, ip);
380 return true;
381 }
382
383 if (!kasan_byte_accessible(ptr)) {
384 kasan_report_invalid_free(ptr, ip);
385 return true;
386 }
387
388 /*
389 * The object will be poisoned by kasan_poison_pages() or
390 * kasan_slab_free_mempool().
391 */
392
393 return false;
394 }
395
__kasan_kfree_large(void * ptr,unsigned long ip)396 void __kasan_kfree_large(void *ptr, unsigned long ip)
397 {
398 ____kasan_kfree_large(ptr, ip);
399 }
400
__kasan_slab_free_mempool(void * ptr,unsigned long ip)401 void __kasan_slab_free_mempool(void *ptr, unsigned long ip)
402 {
403 struct page *page;
404
405 page = virt_to_head_page(ptr);
406
407 /*
408 * Even though this function is only called for kmem_cache_alloc and
409 * kmalloc backed mempool allocations, those allocations can still be
410 * !PageSlab() when the size provided to kmalloc is larger than
411 * KMALLOC_MAX_SIZE, and kmalloc falls back onto page_alloc.
412 */
413 if (unlikely(!PageSlab(page))) {
414 if (____kasan_kfree_large(ptr, ip))
415 return;
416 kasan_poison(ptr, page_size(page), KASAN_FREE_PAGE, false);
417 } else {
418 ____kasan_slab_free(page->slab_cache, ptr, ip, false, false);
419 }
420 }
421
set_alloc_info(struct kmem_cache * cache,void * object,gfp_t flags,bool is_kmalloc)422 static void set_alloc_info(struct kmem_cache *cache, void *object,
423 gfp_t flags, bool is_kmalloc)
424 {
425 struct kasan_alloc_meta *alloc_meta;
426
427 /* Don't save alloc info for kmalloc caches in kasan_slab_alloc(). */
428 if (cache->kasan_info.is_kmalloc && !is_kmalloc)
429 return;
430
431 alloc_meta = kasan_get_alloc_meta(cache, object);
432 if (alloc_meta)
433 kasan_set_track(&alloc_meta->alloc_track, flags);
434 }
435
__kasan_slab_alloc(struct kmem_cache * cache,void * object,gfp_t flags,bool init)436 void * __must_check __kasan_slab_alloc(struct kmem_cache *cache,
437 void *object, gfp_t flags, bool init)
438 {
439 u8 tag;
440 void *tagged_object;
441
442 if (gfpflags_allow_blocking(flags))
443 kasan_quarantine_reduce();
444
445 if (unlikely(object == NULL))
446 return NULL;
447
448 if (is_kfence_address(object))
449 return (void *)object;
450
451 /*
452 * Generate and assign random tag for tag-based modes.
453 * Tag is ignored in set_tag() for the generic mode.
454 */
455 tag = assign_tag(cache, object, false);
456 tagged_object = set_tag(object, tag);
457
458 /*
459 * Unpoison the whole object.
460 * For kmalloc() allocations, kasan_kmalloc() will do precise poisoning.
461 */
462 kasan_unpoison(tagged_object, cache->object_size, init);
463
464 /* Save alloc info (if possible) for non-kmalloc() allocations. */
465 if (kasan_stack_collection_enabled())
466 set_alloc_info(cache, (void *)object, flags, false);
467
468 return tagged_object;
469 }
470
____kasan_kmalloc(struct kmem_cache * cache,const void * object,size_t size,gfp_t flags)471 static inline void *____kasan_kmalloc(struct kmem_cache *cache,
472 const void *object, size_t size, gfp_t flags)
473 {
474 unsigned long redzone_start;
475 unsigned long redzone_end;
476
477 if (gfpflags_allow_blocking(flags))
478 kasan_quarantine_reduce();
479
480 if (unlikely(object == NULL))
481 return NULL;
482
483 if (is_kfence_address(kasan_reset_tag(object)))
484 return (void *)object;
485
486 /*
487 * The object has already been unpoisoned by kasan_slab_alloc() for
488 * kmalloc() or by kasan_krealloc() for krealloc().
489 */
490
491 /*
492 * The redzone has byte-level precision for the generic mode.
493 * Partially poison the last object granule to cover the unaligned
494 * part of the redzone.
495 */
496 if (IS_ENABLED(CONFIG_KASAN_GENERIC))
497 kasan_poison_last_granule((void *)object, size);
498
499 /* Poison the aligned part of the redzone. */
500 redzone_start = round_up((unsigned long)(object + size),
501 KASAN_GRANULE_SIZE);
502 redzone_end = round_up((unsigned long)(object + cache->object_size),
503 KASAN_GRANULE_SIZE);
504 kasan_poison((void *)redzone_start, redzone_end - redzone_start,
505 KASAN_KMALLOC_REDZONE, false);
506
507 /*
508 * Save alloc info (if possible) for kmalloc() allocations.
509 * This also rewrites the alloc info when called from kasan_krealloc().
510 */
511 if (kasan_stack_collection_enabled())
512 set_alloc_info(cache, (void *)object, flags, true);
513
514 /* Keep the tag that was set by kasan_slab_alloc(). */
515 return (void *)object;
516 }
517
__kasan_kmalloc(struct kmem_cache * cache,const void * object,size_t size,gfp_t flags)518 void * __must_check __kasan_kmalloc(struct kmem_cache *cache, const void *object,
519 size_t size, gfp_t flags)
520 {
521 return ____kasan_kmalloc(cache, object, size, flags);
522 }
523 EXPORT_SYMBOL(__kasan_kmalloc);
524
__kasan_kmalloc_large(const void * ptr,size_t size,gfp_t flags)525 void * __must_check __kasan_kmalloc_large(const void *ptr, size_t size,
526 gfp_t flags)
527 {
528 unsigned long redzone_start;
529 unsigned long redzone_end;
530
531 if (gfpflags_allow_blocking(flags))
532 kasan_quarantine_reduce();
533
534 if (unlikely(ptr == NULL))
535 return NULL;
536
537 /*
538 * The object has already been unpoisoned by kasan_unpoison_pages() for
539 * alloc_pages() or by kasan_krealloc() for krealloc().
540 */
541
542 /*
543 * The redzone has byte-level precision for the generic mode.
544 * Partially poison the last object granule to cover the unaligned
545 * part of the redzone.
546 */
547 if (IS_ENABLED(CONFIG_KASAN_GENERIC))
548 kasan_poison_last_granule(ptr, size);
549
550 /* Poison the aligned part of the redzone. */
551 redzone_start = round_up((unsigned long)(ptr + size),
552 KASAN_GRANULE_SIZE);
553 redzone_end = (unsigned long)ptr + page_size(virt_to_page(ptr));
554 kasan_poison((void *)redzone_start, redzone_end - redzone_start,
555 KASAN_PAGE_REDZONE, false);
556
557 return (void *)ptr;
558 }
559
__kasan_krealloc(const void * object,size_t size,gfp_t flags)560 void * __must_check __kasan_krealloc(const void *object, size_t size, gfp_t flags)
561 {
562 struct page *page;
563
564 if (unlikely(object == ZERO_SIZE_PTR))
565 return (void *)object;
566
567 /*
568 * Unpoison the object's data.
569 * Part of it might already have been unpoisoned, but it's unknown
570 * how big that part is.
571 */
572 kasan_unpoison(object, size, false);
573
574 page = virt_to_head_page(object);
575
576 /* Piggy-back on kmalloc() instrumentation to poison the redzone. */
577 if (unlikely(!PageSlab(page)))
578 return __kasan_kmalloc_large(object, size, flags);
579 else
580 return ____kasan_kmalloc(page->slab_cache, object, size, flags);
581 }
582
__kasan_check_byte(const void * address,unsigned long ip)583 bool __kasan_check_byte(const void *address, unsigned long ip)
584 {
585 if (!kasan_byte_accessible(address)) {
586 kasan_report((unsigned long)address, 1, false, ip);
587 return false;
588 }
589 return true;
590 }
591