xref: /linux/mm/kasan/common.c (revision e212c463eee96b2568d8c85ca4ee63049dbb18f2)
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/clock.h>
24 #include <linux/sched/task_stack.h>
25 #include <linux/slab.h>
26 #include <linux/stackdepot.h>
27 #include <linux/stacktrace.h>
28 #include <linux/string.h>
29 #include <linux/types.h>
30 #include <linux/bug.h>
31 #include <linux/vmalloc.h>
32 
33 #include "kasan.h"
34 #include "../slab.h"
35 
36 #if defined(CONFIG_ARCH_DEFER_KASAN) || defined(CONFIG_KASAN_HW_TAGS)
37 /*
38  * Definition of the unified static key declared in kasan-enabled.h.
39  * This provides consistent runtime enable/disable across KASAN modes.
40  */
41 DEFINE_STATIC_KEY_FALSE(kasan_flag_enabled);
42 EXPORT_SYMBOL_GPL(kasan_flag_enabled);
43 #endif
44 
45 struct slab *kasan_addr_to_slab(const void *addr)
46 {
47 	if (virt_addr_valid(addr))
48 		return virt_to_slab(addr);
49 	return NULL;
50 }
51 
52 depot_stack_handle_t kasan_save_stack(gfp_t flags, depot_flags_t depot_flags)
53 {
54 	unsigned long entries[KASAN_STACK_DEPTH];
55 	unsigned int nr_entries;
56 
57 	nr_entries = stack_trace_save(entries, ARRAY_SIZE(entries), 0);
58 	return stack_depot_save_flags(entries, nr_entries, flags, depot_flags);
59 }
60 
61 void kasan_set_track(struct kasan_track *track, depot_stack_handle_t stack)
62 {
63 #ifdef CONFIG_KASAN_EXTRA_INFO
64 	u32 cpu = raw_smp_processor_id();
65 	u64 ts_nsec = local_clock();
66 
67 	track->cpu = cpu;
68 	track->timestamp = ts_nsec >> 9;
69 #endif /* CONFIG_KASAN_EXTRA_INFO */
70 	track->pid = current->pid;
71 	track->rcu_free = 0;
72 	track->stack = stack;
73 }
74 
75 void kasan_save_track(struct kasan_track *track, gfp_t flags)
76 {
77 	depot_stack_handle_t stack;
78 
79 	stack = kasan_save_stack(flags, STACK_DEPOT_FLAG_CAN_ALLOC);
80 	kasan_set_track(track, stack);
81 }
82 
83 #if defined(CONFIG_KASAN_GENERIC) || defined(CONFIG_KASAN_SW_TAGS)
84 void kasan_enable_current(void)
85 {
86 	current->kasan_depth++;
87 }
88 EXPORT_SYMBOL(kasan_enable_current);
89 
90 void kasan_disable_current(void)
91 {
92 	current->kasan_depth--;
93 }
94 EXPORT_SYMBOL(kasan_disable_current);
95 
96 #endif /* CONFIG_KASAN_GENERIC || CONFIG_KASAN_SW_TAGS */
97 
98 void __kasan_unpoison_range(const void *address, size_t size)
99 {
100 	if (is_kfence_address(address))
101 		return;
102 
103 	kasan_unpoison(address, size, false);
104 }
105 
106 #ifdef CONFIG_KASAN_STACK
107 /* Unpoison the entire stack for a task. */
108 void kasan_unpoison_task_stack(struct task_struct *task)
109 {
110 	void *base = task_stack_page(task);
111 
112 	kasan_unpoison(base, THREAD_SIZE, false);
113 }
114 
115 /* Unpoison the stack for the current task beyond a watermark sp value. */
116 asmlinkage void kasan_unpoison_task_stack_below(const void *watermark)
117 {
118 	void *base;
119 
120 	/*
121 	 * Only the generic mode needs this. In the tag-based mode the
122 	 * compiler fully initializes the shadow of stack variables on
123 	 * function entry, so stale tags left below the watermark are
124 	 * harmless.
125 	 */
126 	if (!IS_ENABLED(CONFIG_KASAN_GENERIC))
127 		return;
128 
129 	/*
130 	 * Calculate the task stack base address.  Avoid using 'current'
131 	 * because this function is called by early resume code which hasn't
132 	 * yet set up the percpu register (%gs).
133 	 */
134 	base = (void *)((unsigned long)watermark & ~(THREAD_SIZE - 1));
135 
136 	kasan_unpoison(base, watermark - base, false);
137 }
138 #endif /* CONFIG_KASAN_STACK */
139 
140 bool __kasan_unpoison_pages(struct page *page, unsigned int order, bool init)
141 {
142 	u8 tag;
143 	unsigned long i;
144 
145 	if (unlikely(PageHighMem(page)))
146 		return false;
147 
148 	if (!kasan_sample_page_alloc(order))
149 		return false;
150 
151 	tag = kasan_random_tag();
152 	kasan_unpoison(set_tag(page_address(page), tag),
153 		       PAGE_SIZE << order, init);
154 	for (i = 0; i < (1 << order); i++)
155 		page_kasan_tag_set(page + i, tag);
156 
157 	return true;
158 }
159 
160 void __kasan_poison_pages(struct page *page, unsigned int order, bool init)
161 {
162 	if (likely(!PageHighMem(page)))
163 		kasan_poison(page_address(page), PAGE_SIZE << order,
164 			     KASAN_PAGE_FREE, init);
165 }
166 
167 void __kasan_poison_slab(struct slab *slab)
168 {
169 	struct page *page = slab_page(slab);
170 	unsigned long i;
171 
172 	for (i = 0; i < compound_nr(page); i++)
173 		page_kasan_tag_reset(page + i);
174 	kasan_poison(page_address(page), page_size(page),
175 		     KASAN_SLAB_REDZONE, false);
176 }
177 
178 void __kasan_unpoison_new_object(struct kmem_cache *cache, void *object)
179 {
180 	kasan_unpoison(object, cache->object_size, false);
181 }
182 
183 void __kasan_poison_new_object(struct kmem_cache *cache, void *object)
184 {
185 	kasan_poison(object, round_up(cache->object_size, KASAN_GRANULE_SIZE),
186 			KASAN_SLAB_REDZONE, false);
187 }
188 
189 /*
190  * This function assigns a tag to an object considering the following:
191  * 1. A cache might have a constructor, which might save a pointer to a slab
192  *    object somewhere (e.g. in the object itself). We preassign a tag for
193  *    each object in caches with constructors during slab creation and reuse
194  *    the same tag each time a particular object is allocated.
195  * 2. A cache might be SLAB_TYPESAFE_BY_RCU, which means objects can be
196  *    accessed after being freed. We preassign tags for objects in these
197  *    caches as well.
198  */
199 static inline u8 assign_tag(struct kmem_cache *cache,
200 					const void *object, bool init)
201 {
202 	if (IS_ENABLED(CONFIG_KASAN_GENERIC))
203 		return 0xff;
204 
205 	/*
206 	 * If the cache neither has a constructor nor has SLAB_TYPESAFE_BY_RCU
207 	 * set, assign a tag when the object is being allocated (init == false).
208 	 */
209 	if (!cache->ctor && !(cache->flags & SLAB_TYPESAFE_BY_RCU))
210 		return init ? KASAN_TAG_KERNEL : kasan_random_tag();
211 
212 	/*
213 	 * For caches that either have a constructor or SLAB_TYPESAFE_BY_RCU,
214 	 * assign a random tag during slab creation, otherwise reuse
215 	 * the already assigned tag.
216 	 */
217 	return init ? kasan_random_tag() : get_tag(object);
218 }
219 
220 void * __must_check __kasan_init_slab_obj(struct kmem_cache *cache,
221 						const void *object)
222 {
223 	/* Initialize per-object metadata if it is present. */
224 	if (kasan_requires_meta())
225 		kasan_init_object_meta(cache, object);
226 
227 	/* Tag is ignored in set_tag() without CONFIG_KASAN_SW/HW_TAGS */
228 	object = set_tag(object, assign_tag(cache, object, true));
229 
230 	return (void *)object;
231 }
232 
233 /* Returns true when freeing the object is not safe. */
234 static bool check_slab_allocation(struct kmem_cache *cache, void *object,
235 				  unsigned long ip, bool after_rcu_delay)
236 {
237 	void *tagged_object = object;
238 
239 	object = kasan_reset_tag(object);
240 
241 	if (unlikely(nearest_obj(cache, virt_to_slab(object), object) != object)) {
242 		kasan_report_invalid_free(tagged_object, ip, KASAN_REPORT_INVALID_FREE);
243 		return true;
244 	}
245 
246 	if (!kasan_byte_accessible(tagged_object) ||
247 	    kasan_check_rcu_free(cache, object, after_rcu_delay)) {
248 		kasan_report_invalid_free(tagged_object, ip, KASAN_REPORT_DOUBLE_FREE);
249 		return true;
250 	}
251 
252 	return false;
253 }
254 
255 static inline void poison_slab_object(struct kmem_cache *cache, void *object,
256 				      bool init)
257 {
258 	void *tagged_object = object;
259 
260 	object = kasan_reset_tag(object);
261 
262 	kasan_poison(object, round_up(cache->object_size, KASAN_GRANULE_SIZE),
263 			KASAN_SLAB_FREE, init);
264 	kasan_clear_rcu_free(cache, object);
265 
266 	if (kasan_stack_collection_enabled())
267 		kasan_save_free_info(cache, tagged_object);
268 }
269 
270 bool __kasan_slab_pre_free(struct kmem_cache *cache, void *object,
271 			   unsigned long ip, bool after_rcu_delay)
272 {
273 	if (is_kfence_address(object))
274 		return false;
275 	return check_slab_allocation(cache, object, ip, after_rcu_delay);
276 }
277 
278 bool __kasan_slab_free(struct kmem_cache *cache, void *object, bool init,
279 		       bool still_accessible, bool no_quarantine)
280 {
281 	if (is_kfence_address(object))
282 		return false;
283 
284 	/*
285 	 * If this point is reached with an object that must still be
286 	 * accessible under RCU, we can't poison it; in that case, also skip the
287 	 * quarantine. This should mostly only happen when CONFIG_SLUB_RCU_DEBUG
288 	 * has been disabled manually.
289 	 *
290 	 * Putting the object on the quarantine wouldn't help catch UAFs (since
291 	 * we can't poison it here), and it would mask bugs caused by
292 	 * SLAB_TYPESAFE_BY_RCU users not being careful enough about object
293 	 * reuse; so overall, putting the object into the quarantine here would
294 	 * be counterproductive.
295 	 */
296 	if (still_accessible)
297 		return false;
298 
299 	poison_slab_object(cache, object, init);
300 
301 	if (no_quarantine)
302 		return false;
303 
304 	/*
305 	 * If the object is put into quarantine, do not let slab put the object
306 	 * onto the freelist for now. The object's metadata is kept until the
307 	 * object gets evicted from quarantine.
308 	 */
309 	if (kasan_quarantine_put(cache, object))
310 		return true;
311 
312 	/*
313 	 * Note: Keep per-object metadata to allow KASAN print stack traces for
314 	 * use-after-free-before-realloc bugs.
315 	 */
316 
317 	/* Let slab put the object onto the freelist. */
318 	return false;
319 }
320 
321 static inline bool check_page_allocation(void *ptr, unsigned long ip)
322 {
323 	if (ptr != page_address(virt_to_head_page(ptr))) {
324 		kasan_report_invalid_free(ptr, ip, KASAN_REPORT_INVALID_FREE);
325 		return true;
326 	}
327 
328 	if (!kasan_byte_accessible(ptr)) {
329 		kasan_report_invalid_free(ptr, ip, KASAN_REPORT_DOUBLE_FREE);
330 		return true;
331 	}
332 
333 	return false;
334 }
335 
336 void __kasan_kfree_large(void *ptr, unsigned long ip)
337 {
338 	check_page_allocation(ptr, ip);
339 
340 	/* The object will be poisoned by kasan_poison_pages(). */
341 }
342 
343 static inline void unpoison_slab_object(struct kmem_cache *cache, void *object,
344 					gfp_t flags, bool init)
345 {
346 	/*
347 	 * Unpoison the whole object. For kmalloc() allocations,
348 	 * poison_kmalloc_redzone() will do precise poisoning.
349 	 */
350 	kasan_unpoison(object, cache->object_size, init);
351 
352 	/* Save alloc info (if possible) for non-kmalloc() allocations. */
353 	if (kasan_stack_collection_enabled() && !is_kmalloc_cache(cache))
354 		kasan_save_alloc_info(cache, object, flags);
355 }
356 
357 void * __must_check __kasan_slab_alloc(struct kmem_cache *cache,
358 					void *object, gfp_t flags, bool init)
359 {
360 	u8 tag;
361 	void *tagged_object;
362 
363 	if (gfpflags_allow_blocking(flags))
364 		kasan_quarantine_reduce();
365 
366 	if (unlikely(object == NULL))
367 		return NULL;
368 
369 	if (is_kfence_address(object))
370 		return (void *)object;
371 
372 	/*
373 	 * Generate and assign random tag for tag-based modes.
374 	 * Tag is ignored in set_tag() for the generic mode.
375 	 */
376 	tag = assign_tag(cache, object, false);
377 	tagged_object = set_tag(object, tag);
378 
379 	/* Unpoison the object and save alloc info for non-kmalloc() allocations. */
380 	unpoison_slab_object(cache, tagged_object, flags, init);
381 
382 	return tagged_object;
383 }
384 
385 static inline void poison_kmalloc_redzone(struct kmem_cache *cache,
386 				const void *object, size_t size, gfp_t flags)
387 {
388 	unsigned long redzone_start;
389 	unsigned long redzone_end;
390 
391 	/*
392 	 * The redzone has byte-level precision for the generic mode.
393 	 * Partially poison the last object granule to cover the unaligned
394 	 * part of the redzone.
395 	 */
396 	if (IS_ENABLED(CONFIG_KASAN_GENERIC))
397 		kasan_poison_last_granule((void *)object, size);
398 
399 	/* Poison the aligned part of the redzone. */
400 	redzone_start = round_up((unsigned long)(object + size),
401 				KASAN_GRANULE_SIZE);
402 	redzone_end = round_up((unsigned long)(object + cache->object_size),
403 				KASAN_GRANULE_SIZE);
404 	kasan_poison((void *)redzone_start, redzone_end - redzone_start,
405 			   KASAN_SLAB_REDZONE, false);
406 
407 	/*
408 	 * Save alloc info (if possible) for kmalloc() allocations.
409 	 * This also rewrites the alloc info when called from kasan_krealloc().
410 	 */
411 	if (kasan_stack_collection_enabled() && is_kmalloc_cache(cache))
412 		kasan_save_alloc_info(cache, (void *)object, flags);
413 
414 }
415 
416 void * __must_check __kasan_kmalloc(struct kmem_cache *cache, const void *object,
417 					size_t size, gfp_t flags)
418 {
419 	if (gfpflags_allow_blocking(flags))
420 		kasan_quarantine_reduce();
421 
422 	if (unlikely(object == NULL))
423 		return NULL;
424 
425 	if (is_kfence_address(object))
426 		return (void *)object;
427 
428 	/* The object has already been unpoisoned by kasan_slab_alloc(). */
429 	poison_kmalloc_redzone(cache, object, size, flags);
430 
431 	/* Keep the tag that was set by kasan_slab_alloc(). */
432 	return (void *)object;
433 }
434 EXPORT_SYMBOL(__kasan_kmalloc);
435 
436 static inline void poison_kmalloc_large_redzone(const void *ptr, size_t size,
437 						gfp_t flags)
438 {
439 	unsigned long redzone_start;
440 	unsigned long redzone_end;
441 
442 	/*
443 	 * The redzone has byte-level precision for the generic mode.
444 	 * Partially poison the last object granule to cover the unaligned
445 	 * part of the redzone.
446 	 */
447 	if (IS_ENABLED(CONFIG_KASAN_GENERIC))
448 		kasan_poison_last_granule(ptr, size);
449 
450 	/* Poison the aligned part of the redzone. */
451 	redzone_start = round_up((unsigned long)(ptr + size), KASAN_GRANULE_SIZE);
452 	redzone_end = (unsigned long)ptr + page_size(virt_to_page(ptr));
453 	kasan_poison((void *)redzone_start, redzone_end - redzone_start,
454 		     KASAN_PAGE_REDZONE, false);
455 }
456 
457 void * __must_check __kasan_kmalloc_large(const void *ptr, size_t size,
458 						gfp_t flags)
459 {
460 	if (gfpflags_allow_blocking(flags))
461 		kasan_quarantine_reduce();
462 
463 	if (unlikely(ptr == NULL))
464 		return NULL;
465 
466 	/* The object has already been unpoisoned by kasan_unpoison_pages(). */
467 	poison_kmalloc_large_redzone(ptr, size, flags);
468 
469 	/* Keep the tag that was set by alloc_pages(). */
470 	return (void *)ptr;
471 }
472 
473 void * __must_check __kasan_krealloc(const void *object, size_t size, gfp_t flags)
474 {
475 	struct slab *slab;
476 
477 	if (gfpflags_allow_blocking(flags))
478 		kasan_quarantine_reduce();
479 
480 	if (unlikely(object == ZERO_SIZE_PTR))
481 		return (void *)object;
482 
483 	if (is_kfence_address(object))
484 		return (void *)object;
485 
486 	/*
487 	 * Unpoison the object's data.
488 	 * Part of it might already have been unpoisoned, but it's unknown
489 	 * how big that part is.
490 	 */
491 	kasan_unpoison(object, size, false);
492 
493 	slab = virt_to_slab(object);
494 
495 	/* Piggy-back on kmalloc() instrumentation to poison the redzone. */
496 	if (unlikely(!slab))
497 		poison_kmalloc_large_redzone(object, size, flags);
498 	else
499 		poison_kmalloc_redzone(slab->slab_cache, object, size, flags);
500 
501 	return (void *)object;
502 }
503 
504 bool __kasan_mempool_poison_pages(struct page *page, unsigned int order,
505 				  unsigned long ip)
506 {
507 	unsigned long *ptr;
508 
509 	if (unlikely(PageHighMem(page)))
510 		return true;
511 
512 	/* Bail out if allocation was excluded due to sampling. */
513 	if (!IS_ENABLED(CONFIG_KASAN_GENERIC) &&
514 	    page_kasan_tag(page) == KASAN_TAG_KERNEL)
515 		return true;
516 
517 	ptr = page_address(page);
518 
519 	if (check_page_allocation(ptr, ip))
520 		return false;
521 
522 	kasan_poison(ptr, PAGE_SIZE << order, KASAN_PAGE_FREE, false);
523 
524 	return true;
525 }
526 
527 void __kasan_mempool_unpoison_pages(struct page *page, unsigned int order,
528 				    unsigned long ip)
529 {
530 	__kasan_unpoison_pages(page, order, false);
531 }
532 
533 bool __kasan_mempool_poison_object(void *ptr, unsigned long ip)
534 {
535 	struct page *page = virt_to_page(ptr);
536 	struct slab *slab;
537 
538 	if (unlikely(PageLargeKmalloc(page))) {
539 		if (check_page_allocation(ptr, ip))
540 			return false;
541 		kasan_poison(ptr, page_size(page), KASAN_PAGE_FREE, false);
542 		return true;
543 	}
544 
545 	if (is_kfence_address(ptr))
546 		return true;
547 
548 	slab = page_slab(page);
549 
550 	if (check_slab_allocation(slab->slab_cache, ptr, ip, false))
551 		return false;
552 
553 	poison_slab_object(slab->slab_cache, ptr, false);
554 	return true;
555 }
556 
557 void __kasan_mempool_unpoison_object(void *ptr, size_t size, unsigned long ip)
558 {
559 	struct slab *slab;
560 	gfp_t flags = 0; /* Might be executing under a lock. */
561 
562 	slab = virt_to_slab(ptr);
563 
564 	/*
565 	 * This function can be called for large kmalloc allocation that get
566 	 * their memory from page_alloc.
567 	 */
568 	if (unlikely(!slab)) {
569 		kasan_unpoison(ptr, size, false);
570 		poison_kmalloc_large_redzone(ptr, size, flags);
571 		return;
572 	}
573 
574 	if (is_kfence_address(ptr))
575 		return;
576 
577 	/* Unpoison the object and save alloc info for non-kmalloc() allocations. */
578 	unpoison_slab_object(slab->slab_cache, ptr, flags, false);
579 
580 	/* Poison the redzone and save alloc info for kmalloc() allocations. */
581 	if (is_kmalloc_cache(slab->slab_cache))
582 		poison_kmalloc_redzone(slab->slab_cache, ptr, size, flags);
583 }
584 
585 bool __kasan_check_byte(const void *address, unsigned long ip)
586 {
587 	if (!kasan_byte_accessible(address)) {
588 		kasan_report(address, 1, false, ip);
589 		return false;
590 	}
591 	return true;
592 }
593 
594 #ifdef CONFIG_KASAN_VMALLOC
595 void __kasan_unpoison_vmap_areas(struct vm_struct **vms, int nr_vms,
596 				 kasan_vmalloc_flags_t flags)
597 {
598 	unsigned long size;
599 	void *addr;
600 	int area;
601 	u8 tag;
602 
603 	/*
604 	 * If KASAN_VMALLOC_KEEP_TAG was set at this point, all vms[] pointers
605 	 * would be unpoisoned with the KASAN_TAG_KERNEL which would disable
606 	 * KASAN checks down the line.
607 	 */
608 	if (WARN_ON_ONCE(flags & KASAN_VMALLOC_KEEP_TAG))
609 		return;
610 
611 	size = vms[0]->size;
612 	addr = vms[0]->addr;
613 	vms[0]->addr = __kasan_unpoison_vmalloc(addr, size, flags);
614 	tag = get_tag(vms[0]->addr);
615 
616 	for (area = 1 ; area < nr_vms ; area++) {
617 		size = vms[area]->size;
618 		addr = set_tag(vms[area]->addr, tag);
619 		vms[area]->addr =
620 			__kasan_unpoison_vmalloc(addr, size, flags | KASAN_VMALLOC_KEEP_TAG);
621 	}
622 }
623 
624 void __kasan_vrealloc(const void *addr, unsigned long old_size,
625 		unsigned long new_size)
626 {
627 	if (new_size < old_size) {
628 		kasan_poison_last_granule(addr, new_size);
629 
630 		new_size = round_up(new_size, KASAN_GRANULE_SIZE);
631 		old_size = round_up(old_size, KASAN_GRANULE_SIZE);
632 		if (new_size < old_size)
633 			__kasan_poison_vmalloc(addr + new_size,
634 					old_size - new_size);
635 	} else if (new_size > old_size) {
636 		old_size = round_down(old_size, KASAN_GRANULE_SIZE);
637 		__kasan_unpoison_vmalloc(addr + old_size,
638 					new_size - old_size,
639 					KASAN_VMALLOC_PROT_NORMAL |
640 					KASAN_VMALLOC_VM_ALLOC |
641 					KASAN_VMALLOC_KEEP_TAG);
642 	}
643 }
644 #endif
645