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