1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * This file contains common KASAN error reporting 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/bitops.h>
13 #include <linux/ftrace.h>
14 #include <linux/init.h>
15 #include <linux/kernel.h>
16 #include <linux/lockdep.h>
17 #include <linux/mm.h>
18 #include <linux/printk.h>
19 #include <linux/sched.h>
20 #include <linux/slab.h>
21 #include <linux/stackdepot.h>
22 #include <linux/stacktrace.h>
23 #include <linux/string.h>
24 #include <linux/types.h>
25 #include <linux/kasan.h>
26 #include <linux/module.h>
27 #include <linux/sched/task_stack.h>
28 #include <linux/uaccess.h>
29 #include <trace/events/error_report.h>
30 
31 #include <asm/sections.h>
32 
33 #include <kunit/test.h>
34 
35 #include "kasan.h"
36 #include "../slab.h"
37 
38 static unsigned long kasan_flags;
39 
40 #define KASAN_BIT_REPORTED	0
41 #define KASAN_BIT_MULTI_SHOT	1
42 
43 enum kasan_arg_fault {
44 	KASAN_ARG_FAULT_DEFAULT,
45 	KASAN_ARG_FAULT_REPORT,
46 	KASAN_ARG_FAULT_PANIC,
47 };
48 
49 static enum kasan_arg_fault kasan_arg_fault __ro_after_init = KASAN_ARG_FAULT_DEFAULT;
50 
51 /* kasan.fault=report/panic */
early_kasan_fault(char * arg)52 static int __init early_kasan_fault(char *arg)
53 {
54 	if (!arg)
55 		return -EINVAL;
56 
57 	if (!strcmp(arg, "report"))
58 		kasan_arg_fault = KASAN_ARG_FAULT_REPORT;
59 	else if (!strcmp(arg, "panic"))
60 		kasan_arg_fault = KASAN_ARG_FAULT_PANIC;
61 	else
62 		return -EINVAL;
63 
64 	return 0;
65 }
66 early_param("kasan.fault", early_kasan_fault);
67 
kasan_set_multi_shot(char * str)68 static int __init kasan_set_multi_shot(char *str)
69 {
70 	set_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags);
71 	return 1;
72 }
73 __setup("kasan_multi_shot", kasan_set_multi_shot);
74 
75 /*
76  * Used to suppress reports within kasan_disable/enable_current() critical
77  * sections, which are used for marking accesses to slab metadata.
78  */
report_suppressed(void)79 static bool report_suppressed(void)
80 {
81 #if defined(CONFIG_KASAN_GENERIC) || defined(CONFIG_KASAN_SW_TAGS)
82 	if (current->kasan_depth)
83 		return true;
84 #endif
85 	return false;
86 }
87 
88 /*
89  * Used to avoid reporting more than one KASAN bug unless kasan_multi_shot
90  * is enabled. Note that KASAN tests effectively enable kasan_multi_shot
91  * for their duration.
92  */
report_enabled(void)93 static bool report_enabled(void)
94 {
95 	if (test_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags))
96 		return true;
97 	return !test_and_set_bit(KASAN_BIT_REPORTED, &kasan_flags);
98 }
99 
100 #if IS_ENABLED(CONFIG_KASAN_KUNIT_TEST) || IS_ENABLED(CONFIG_KASAN_MODULE_TEST)
101 
kasan_save_enable_multi_shot(void)102 bool kasan_save_enable_multi_shot(void)
103 {
104 	return test_and_set_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags);
105 }
106 EXPORT_SYMBOL_GPL(kasan_save_enable_multi_shot);
107 
kasan_restore_multi_shot(bool enabled)108 void kasan_restore_multi_shot(bool enabled)
109 {
110 	if (!enabled)
111 		clear_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags);
112 }
113 EXPORT_SYMBOL_GPL(kasan_restore_multi_shot);
114 
115 #endif
116 
117 #if IS_ENABLED(CONFIG_KASAN_KUNIT_TEST)
update_kunit_status(bool sync)118 static void update_kunit_status(bool sync)
119 {
120 	struct kunit *test;
121 	struct kunit_resource *resource;
122 	struct kunit_kasan_status *status;
123 
124 	test = current->kunit_test;
125 	if (!test)
126 		return;
127 
128 	resource = kunit_find_named_resource(test, "kasan_status");
129 	if (!resource) {
130 		kunit_set_failure(test);
131 		return;
132 	}
133 
134 	status = (struct kunit_kasan_status *)resource->data;
135 	WRITE_ONCE(status->report_found, true);
136 	WRITE_ONCE(status->sync_fault, sync);
137 
138 	kunit_put_resource(resource);
139 }
140 #else
update_kunit_status(bool sync)141 static void update_kunit_status(bool sync) { }
142 #endif
143 
144 static DEFINE_SPINLOCK(report_lock);
145 
start_report(unsigned long * flags,bool sync)146 static void start_report(unsigned long *flags, bool sync)
147 {
148 	/* Respect the /proc/sys/kernel/traceoff_on_warning interface. */
149 	disable_trace_on_warning();
150 	/* Update status of the currently running KASAN test. */
151 	update_kunit_status(sync);
152 	/* Do not allow LOCKDEP mangling KASAN reports. */
153 	lockdep_off();
154 	/* Make sure we don't end up in loop. */
155 	kasan_disable_current();
156 	spin_lock_irqsave(&report_lock, *flags);
157 	pr_err("==================================================================\n");
158 }
159 
end_report(unsigned long * flags,void * addr)160 static void end_report(unsigned long *flags, void *addr)
161 {
162 	if (addr)
163 		trace_error_report_end(ERROR_DETECTOR_KASAN,
164 				       (unsigned long)addr);
165 	pr_err("==================================================================\n");
166 	spin_unlock_irqrestore(&report_lock, *flags);
167 	if (!test_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags))
168 		check_panic_on_warn("KASAN");
169 	if (kasan_arg_fault == KASAN_ARG_FAULT_PANIC)
170 		panic("kasan.fault=panic set ...\n");
171 	add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
172 	lockdep_on();
173 	kasan_enable_current();
174 }
175 
print_error_description(struct kasan_report_info * info)176 static void print_error_description(struct kasan_report_info *info)
177 {
178 	pr_err("BUG: KASAN: %s in %pS\n", info->bug_type, (void *)info->ip);
179 
180 	if (info->type != KASAN_REPORT_ACCESS) {
181 		pr_err("Free of addr %px by task %s/%d\n",
182 			info->access_addr, current->comm, task_pid_nr(current));
183 		return;
184 	}
185 
186 	if (info->access_size)
187 		pr_err("%s of size %zu at addr %px by task %s/%d\n",
188 			info->is_write ? "Write" : "Read", info->access_size,
189 			info->access_addr, current->comm, task_pid_nr(current));
190 	else
191 		pr_err("%s at addr %px by task %s/%d\n",
192 			info->is_write ? "Write" : "Read",
193 			info->access_addr, current->comm, task_pid_nr(current));
194 }
195 
print_track(struct kasan_track * track,const char * prefix)196 static void print_track(struct kasan_track *track, const char *prefix)
197 {
198 	pr_err("%s by task %u:\n", prefix, track->pid);
199 	if (track->stack)
200 		stack_depot_print(track->stack);
201 	else
202 		pr_err("(stack is not available)\n");
203 }
204 
addr_to_page(const void * addr)205 static inline struct page *addr_to_page(const void *addr)
206 {
207 	if (virt_addr_valid(addr))
208 		return virt_to_head_page(addr);
209 	return NULL;
210 }
211 
describe_object_addr(const void * addr,struct kmem_cache * cache,void * object)212 static void describe_object_addr(const void *addr, struct kmem_cache *cache,
213 				 void *object)
214 {
215 	unsigned long access_addr = (unsigned long)addr;
216 	unsigned long object_addr = (unsigned long)object;
217 	const char *rel_type;
218 	int rel_bytes;
219 
220 	pr_err("The buggy address belongs to the object at %px\n"
221 	       " which belongs to the cache %s of size %d\n",
222 		object, cache->name, cache->object_size);
223 
224 	if (access_addr < object_addr) {
225 		rel_type = "to the left";
226 		rel_bytes = object_addr - access_addr;
227 	} else if (access_addr >= object_addr + cache->object_size) {
228 		rel_type = "to the right";
229 		rel_bytes = access_addr - (object_addr + cache->object_size);
230 	} else {
231 		rel_type = "inside";
232 		rel_bytes = access_addr - object_addr;
233 	}
234 
235 	pr_err("The buggy address is located %d bytes %s of\n"
236 	       " %d-byte region [%px, %px)\n",
237 		rel_bytes, rel_type, cache->object_size, (void *)object_addr,
238 		(void *)(object_addr + cache->object_size));
239 }
240 
describe_object_stacks(struct kasan_report_info * info)241 static void describe_object_stacks(struct kasan_report_info *info)
242 {
243 	if (info->alloc_track.stack) {
244 		print_track(&info->alloc_track, "Allocated");
245 		pr_err("\n");
246 	}
247 
248 	if (info->free_track.stack) {
249 		print_track(&info->free_track, "Freed");
250 		pr_err("\n");
251 	}
252 
253 	kasan_print_aux_stacks(info->cache, info->object);
254 }
255 
describe_object(const void * addr,struct kasan_report_info * info)256 static void describe_object(const void *addr, struct kasan_report_info *info)
257 {
258 	if (kasan_stack_collection_enabled())
259 		describe_object_stacks(info);
260 	describe_object_addr(addr, info->cache, info->object);
261 }
262 
kernel_or_module_addr(const void * addr)263 static inline bool kernel_or_module_addr(const void *addr)
264 {
265 	if (is_kernel((unsigned long)addr))
266 		return true;
267 	if (is_module_address((unsigned long)addr))
268 		return true;
269 	return false;
270 }
271 
init_task_stack_addr(const void * addr)272 static inline bool init_task_stack_addr(const void *addr)
273 {
274 	return addr >= (void *)&init_thread_union.stack &&
275 		(addr <= (void *)&init_thread_union.stack +
276 			sizeof(init_thread_union.stack));
277 }
278 
print_address_description(void * addr,u8 tag,struct kasan_report_info * info)279 static void print_address_description(void *addr, u8 tag,
280 				      struct kasan_report_info *info)
281 {
282 	struct page *page = addr_to_page(addr);
283 
284 	dump_stack_lvl(KERN_ERR);
285 	pr_err("\n");
286 
287 	if (info->cache && info->object) {
288 		describe_object(addr, info);
289 		pr_err("\n");
290 	}
291 
292 	if (kernel_or_module_addr(addr) && !init_task_stack_addr(addr)) {
293 		pr_err("The buggy address belongs to the variable:\n");
294 		pr_err(" %pS\n", addr);
295 		pr_err("\n");
296 	}
297 
298 	if (object_is_on_stack(addr)) {
299 		/*
300 		 * Currently, KASAN supports printing frame information only
301 		 * for accesses to the task's own stack.
302 		 */
303 		kasan_print_address_stack_frame(addr);
304 		pr_err("\n");
305 	}
306 
307 	if (is_vmalloc_addr(addr)) {
308 		struct vm_struct *va = find_vm_area(addr);
309 
310 		if (va) {
311 			pr_err("The buggy address belongs to the virtual mapping at\n"
312 			       " [%px, %px) created by:\n"
313 			       " %pS\n",
314 			       va->addr, va->addr + va->size, va->caller);
315 			pr_err("\n");
316 
317 			page = vmalloc_to_page(addr);
318 		}
319 	}
320 
321 	if (page) {
322 		pr_err("The buggy address belongs to the physical page:\n");
323 		dump_page(page, "kasan: bad access detected");
324 		pr_err("\n");
325 	}
326 }
327 
meta_row_is_guilty(const void * row,const void * addr)328 static bool meta_row_is_guilty(const void *row, const void *addr)
329 {
330 	return (row <= addr) && (addr < row + META_MEM_BYTES_PER_ROW);
331 }
332 
meta_pointer_offset(const void * row,const void * addr)333 static int meta_pointer_offset(const void *row, const void *addr)
334 {
335 	/*
336 	 * Memory state around the buggy address:
337 	 *  ff00ff00ff00ff00: 00 00 00 05 fe fe fe fe fe fe fe fe fe fe fe fe
338 	 *  ...
339 	 *
340 	 * The length of ">ff00ff00ff00ff00: " is
341 	 *    3 + (BITS_PER_LONG / 8) * 2 chars.
342 	 * The length of each granule metadata is 2 bytes
343 	 *    plus 1 byte for space.
344 	 */
345 	return 3 + (BITS_PER_LONG / 8) * 2 +
346 		(addr - row) / KASAN_GRANULE_SIZE * 3 + 1;
347 }
348 
print_memory_metadata(const void * addr)349 static void print_memory_metadata(const void *addr)
350 {
351 	int i;
352 	void *row;
353 
354 	row = (void *)round_down((unsigned long)addr, META_MEM_BYTES_PER_ROW)
355 			- META_ROWS_AROUND_ADDR * META_MEM_BYTES_PER_ROW;
356 
357 	pr_err("Memory state around the buggy address:\n");
358 
359 	for (i = -META_ROWS_AROUND_ADDR; i <= META_ROWS_AROUND_ADDR; i++) {
360 		char buffer[4 + (BITS_PER_LONG / 8) * 2];
361 		char metadata[META_BYTES_PER_ROW];
362 
363 		snprintf(buffer, sizeof(buffer),
364 				(i == 0) ? ">%px: " : " %px: ", row);
365 
366 		/*
367 		 * We should not pass a shadow pointer to generic
368 		 * function, because generic functions may try to
369 		 * access kasan mapping for the passed address.
370 		 */
371 		kasan_metadata_fetch_row(&metadata[0], row);
372 
373 		print_hex_dump(KERN_ERR, buffer,
374 			DUMP_PREFIX_NONE, META_BYTES_PER_ROW, 1,
375 			metadata, META_BYTES_PER_ROW, 0);
376 
377 		if (meta_row_is_guilty(row, addr))
378 			pr_err("%*c\n", meta_pointer_offset(row, addr), '^');
379 
380 		row += META_MEM_BYTES_PER_ROW;
381 	}
382 }
383 
print_report(struct kasan_report_info * info)384 static void print_report(struct kasan_report_info *info)
385 {
386 	void *addr = kasan_reset_tag(info->access_addr);
387 	u8 tag = get_tag(info->access_addr);
388 
389 	print_error_description(info);
390 	if (addr_has_metadata(addr))
391 		kasan_print_tags(tag, info->first_bad_addr);
392 	pr_err("\n");
393 
394 	if (addr_has_metadata(addr)) {
395 		print_address_description(addr, tag, info);
396 		print_memory_metadata(info->first_bad_addr);
397 	} else {
398 		dump_stack_lvl(KERN_ERR);
399 	}
400 }
401 
complete_report_info(struct kasan_report_info * info)402 static void complete_report_info(struct kasan_report_info *info)
403 {
404 	void *addr = kasan_reset_tag(info->access_addr);
405 	struct slab *slab;
406 
407 	if (info->type == KASAN_REPORT_ACCESS)
408 		info->first_bad_addr = kasan_find_first_bad_addr(
409 					info->access_addr, info->access_size);
410 	else
411 		info->first_bad_addr = addr;
412 
413 	slab = kasan_addr_to_slab(addr);
414 	if (slab) {
415 		info->cache = slab->slab_cache;
416 		info->object = nearest_obj(info->cache, slab, addr);
417 	} else
418 		info->cache = info->object = NULL;
419 
420 	switch (info->type) {
421 	case KASAN_REPORT_INVALID_FREE:
422 		info->bug_type = "invalid-free";
423 		break;
424 	case KASAN_REPORT_DOUBLE_FREE:
425 		info->bug_type = "double-free";
426 		break;
427 	default:
428 		/* bug_type filled in by kasan_complete_mode_report_info. */
429 		break;
430 	}
431 
432 	/* Fill in mode-specific report info fields. */
433 	kasan_complete_mode_report_info(info);
434 }
435 
kasan_report_invalid_free(void * ptr,unsigned long ip,enum kasan_report_type type)436 void kasan_report_invalid_free(void *ptr, unsigned long ip, enum kasan_report_type type)
437 {
438 	unsigned long flags;
439 	struct kasan_report_info info;
440 
441 	/*
442 	 * Do not check report_suppressed(), as an invalid-free cannot be
443 	 * caused by accessing slab metadata and thus should not be
444 	 * suppressed by kasan_disable/enable_current() critical sections.
445 	 */
446 	if (unlikely(!report_enabled()))
447 		return;
448 
449 	start_report(&flags, true);
450 
451 	memset(&info, 0, sizeof(info));
452 	info.type = type;
453 	info.access_addr = ptr;
454 	info.access_size = 0;
455 	info.is_write = false;
456 	info.ip = ip;
457 
458 	complete_report_info(&info);
459 
460 	print_report(&info);
461 
462 	end_report(&flags, ptr);
463 }
464 
465 /*
466  * kasan_report() is the only reporting function that uses
467  * user_access_save/restore(): kasan_report_invalid_free() cannot be called
468  * from a UACCESS region, and kasan_report_async() is not used on x86.
469  */
kasan_report(unsigned long addr,size_t size,bool is_write,unsigned long ip)470 bool kasan_report(unsigned long addr, size_t size, bool is_write,
471 			unsigned long ip)
472 {
473 	bool ret = true;
474 	void *ptr = (void *)addr;
475 	unsigned long ua_flags = user_access_save();
476 	unsigned long irq_flags;
477 	struct kasan_report_info info;
478 
479 	if (unlikely(report_suppressed()) || unlikely(!report_enabled())) {
480 		ret = false;
481 		goto out;
482 	}
483 
484 	start_report(&irq_flags, true);
485 
486 	memset(&info, 0, sizeof(info));
487 	info.type = KASAN_REPORT_ACCESS;
488 	info.access_addr = ptr;
489 	info.access_size = size;
490 	info.is_write = is_write;
491 	info.ip = ip;
492 
493 	complete_report_info(&info);
494 
495 	print_report(&info);
496 
497 	end_report(&irq_flags, ptr);
498 
499 out:
500 	user_access_restore(ua_flags);
501 
502 	return ret;
503 }
504 
505 #ifdef CONFIG_KASAN_HW_TAGS
kasan_report_async(void)506 void kasan_report_async(void)
507 {
508 	unsigned long flags;
509 
510 	/*
511 	 * Do not check report_suppressed(), as kasan_disable/enable_current()
512 	 * critical sections do not affect Hardware Tag-Based KASAN.
513 	 */
514 	if (unlikely(!report_enabled()))
515 		return;
516 
517 	start_report(&flags, false);
518 	pr_err("BUG: KASAN: invalid-access\n");
519 	pr_err("Asynchronous fault: no details available\n");
520 	pr_err("\n");
521 	dump_stack_lvl(KERN_ERR);
522 	end_report(&flags, NULL);
523 }
524 #endif /* CONFIG_KASAN_HW_TAGS */
525 
526 #ifdef CONFIG_KASAN_INLINE
527 /*
528  * With CONFIG_KASAN_INLINE, accesses to bogus pointers (outside the high
529  * canonical half of the address space) cause out-of-bounds shadow memory reads
530  * before the actual access. For addresses in the low canonical half of the
531  * address space, as well as most non-canonical addresses, that out-of-bounds
532  * shadow memory access lands in the non-canonical part of the address space.
533  * Help the user figure out what the original bogus pointer was.
534  */
kasan_non_canonical_hook(unsigned long addr)535 void kasan_non_canonical_hook(unsigned long addr)
536 {
537 	unsigned long orig_addr;
538 	const char *bug_type;
539 
540 	if (addr < KASAN_SHADOW_OFFSET)
541 		return;
542 
543 	orig_addr = (addr - KASAN_SHADOW_OFFSET) << KASAN_SHADOW_SCALE_SHIFT;
544 	/*
545 	 * For faults near the shadow address for NULL, we can be fairly certain
546 	 * that this is a KASAN shadow memory access.
547 	 * For faults that correspond to shadow for low canonical addresses, we
548 	 * can still be pretty sure - that shadow region is a fairly narrow
549 	 * chunk of the non-canonical address space.
550 	 * But faults that look like shadow for non-canonical addresses are a
551 	 * really large chunk of the address space. In that case, we still
552 	 * print the decoded address, but make it clear that this is not
553 	 * necessarily what's actually going on.
554 	 */
555 	if (orig_addr < PAGE_SIZE)
556 		bug_type = "null-ptr-deref";
557 	else if (orig_addr < TASK_SIZE)
558 		bug_type = "probably user-memory-access";
559 	else
560 		bug_type = "maybe wild-memory-access";
561 	pr_alert("KASAN: %s in range [0x%016lx-0x%016lx]\n", bug_type,
562 		 orig_addr, orig_addr + KASAN_GRANULE_SIZE - 1);
563 }
564 #endif
565