xref: /openbmc/linux/mm/kasan/report.c (revision 29c37341)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * This file contains common generic and tag-based 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  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License version 2 as
13  * published by the Free Software Foundation.
14  *
15  */
16 
17 #include <linux/bitops.h>
18 #include <linux/ftrace.h>
19 #include <linux/init.h>
20 #include <linux/kernel.h>
21 #include <linux/mm.h>
22 #include <linux/printk.h>
23 #include <linux/sched.h>
24 #include <linux/slab.h>
25 #include <linux/stackdepot.h>
26 #include <linux/stacktrace.h>
27 #include <linux/string.h>
28 #include <linux/types.h>
29 #include <linux/kasan.h>
30 #include <linux/module.h>
31 #include <linux/sched/task_stack.h>
32 #include <linux/uaccess.h>
33 
34 #include <asm/sections.h>
35 
36 #include "kasan.h"
37 #include "../slab.h"
38 
39 /* Shadow layout customization. */
40 #define SHADOW_BYTES_PER_BLOCK 1
41 #define SHADOW_BLOCKS_PER_ROW 16
42 #define SHADOW_BYTES_PER_ROW (SHADOW_BLOCKS_PER_ROW * SHADOW_BYTES_PER_BLOCK)
43 #define SHADOW_ROWS_AROUND_ADDR 2
44 
45 static unsigned long kasan_flags;
46 
47 #define KASAN_BIT_REPORTED	0
48 #define KASAN_BIT_MULTI_SHOT	1
49 
50 bool kasan_save_enable_multi_shot(void)
51 {
52 	return test_and_set_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags);
53 }
54 EXPORT_SYMBOL_GPL(kasan_save_enable_multi_shot);
55 
56 void kasan_restore_multi_shot(bool enabled)
57 {
58 	if (!enabled)
59 		clear_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags);
60 }
61 EXPORT_SYMBOL_GPL(kasan_restore_multi_shot);
62 
63 static int __init kasan_set_multi_shot(char *str)
64 {
65 	set_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags);
66 	return 1;
67 }
68 __setup("kasan_multi_shot", kasan_set_multi_shot);
69 
70 static void print_error_description(struct kasan_access_info *info)
71 {
72 	pr_err("BUG: KASAN: %s in %pS\n",
73 		get_bug_type(info), (void *)info->ip);
74 	pr_err("%s of size %zu at addr %px by task %s/%d\n",
75 		info->is_write ? "Write" : "Read", info->access_size,
76 		info->access_addr, current->comm, task_pid_nr(current));
77 }
78 
79 static DEFINE_SPINLOCK(report_lock);
80 
81 static void start_report(unsigned long *flags)
82 {
83 	/*
84 	 * Make sure we don't end up in loop.
85 	 */
86 	kasan_disable_current();
87 	spin_lock_irqsave(&report_lock, *flags);
88 	pr_err("==================================================================\n");
89 }
90 
91 static void end_report(unsigned long *flags)
92 {
93 	pr_err("==================================================================\n");
94 	add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
95 	spin_unlock_irqrestore(&report_lock, *flags);
96 	if (panic_on_warn) {
97 		/*
98 		 * This thread may hit another WARN() in the panic path.
99 		 * Resetting this prevents additional WARN() from panicking the
100 		 * system on this thread.  Other threads are blocked by the
101 		 * panic_mutex in panic().
102 		 */
103 		panic_on_warn = 0;
104 		panic("panic_on_warn set ...\n");
105 	}
106 	kasan_enable_current();
107 }
108 
109 static void print_stack(depot_stack_handle_t stack)
110 {
111 	unsigned long *entries;
112 	unsigned int nr_entries;
113 
114 	nr_entries = stack_depot_fetch(stack, &entries);
115 	stack_trace_print(entries, nr_entries, 0);
116 }
117 
118 static void print_track(struct kasan_track *track, const char *prefix)
119 {
120 	pr_err("%s by task %u:\n", prefix, track->pid);
121 	if (track->stack) {
122 		print_stack(track->stack);
123 	} else {
124 		pr_err("(stack is not available)\n");
125 	}
126 }
127 
128 struct page *kasan_addr_to_page(const void *addr)
129 {
130 	if ((addr >= (void *)PAGE_OFFSET) &&
131 			(addr < high_memory))
132 		return virt_to_head_page(addr);
133 	return NULL;
134 }
135 
136 static void describe_object_addr(struct kmem_cache *cache, void *object,
137 				const void *addr)
138 {
139 	unsigned long access_addr = (unsigned long)addr;
140 	unsigned long object_addr = (unsigned long)object;
141 	const char *rel_type;
142 	int rel_bytes;
143 
144 	pr_err("The buggy address belongs to the object at %px\n"
145 	       " which belongs to the cache %s of size %d\n",
146 		object, cache->name, cache->object_size);
147 
148 	if (!addr)
149 		return;
150 
151 	if (access_addr < object_addr) {
152 		rel_type = "to the left";
153 		rel_bytes = object_addr - access_addr;
154 	} else if (access_addr >= object_addr + cache->object_size) {
155 		rel_type = "to the right";
156 		rel_bytes = access_addr - (object_addr + cache->object_size);
157 	} else {
158 		rel_type = "inside";
159 		rel_bytes = access_addr - object_addr;
160 	}
161 
162 	pr_err("The buggy address is located %d bytes %s of\n"
163 	       " %d-byte region [%px, %px)\n",
164 		rel_bytes, rel_type, cache->object_size, (void *)object_addr,
165 		(void *)(object_addr + cache->object_size));
166 }
167 
168 static void describe_object(struct kmem_cache *cache, void *object,
169 				const void *addr, u8 tag)
170 {
171 	struct kasan_alloc_meta *alloc_info = get_alloc_info(cache, object);
172 
173 	if (cache->flags & SLAB_KASAN) {
174 		struct kasan_track *free_track;
175 
176 		print_track(&alloc_info->alloc_track, "Allocated");
177 		pr_err("\n");
178 		free_track = kasan_get_free_track(cache, object, tag);
179 		if (free_track) {
180 			print_track(free_track, "Freed");
181 			pr_err("\n");
182 		}
183 
184 #ifdef CONFIG_KASAN_GENERIC
185 		if (alloc_info->aux_stack[0]) {
186 			pr_err("Last call_rcu():\n");
187 			print_stack(alloc_info->aux_stack[0]);
188 			pr_err("\n");
189 		}
190 		if (alloc_info->aux_stack[1]) {
191 			pr_err("Second to last call_rcu():\n");
192 			print_stack(alloc_info->aux_stack[1]);
193 			pr_err("\n");
194 		}
195 #endif
196 	}
197 
198 	describe_object_addr(cache, object, addr);
199 }
200 
201 static inline bool kernel_or_module_addr(const void *addr)
202 {
203 	if (addr >= (void *)_stext && addr < (void *)_end)
204 		return true;
205 	if (is_module_address((unsigned long)addr))
206 		return true;
207 	return false;
208 }
209 
210 static inline bool init_task_stack_addr(const void *addr)
211 {
212 	return addr >= (void *)&init_thread_union.stack &&
213 		(addr <= (void *)&init_thread_union.stack +
214 			sizeof(init_thread_union.stack));
215 }
216 
217 static bool __must_check tokenize_frame_descr(const char **frame_descr,
218 					      char *token, size_t max_tok_len,
219 					      unsigned long *value)
220 {
221 	const char *sep = strchr(*frame_descr, ' ');
222 
223 	if (sep == NULL)
224 		sep = *frame_descr + strlen(*frame_descr);
225 
226 	if (token != NULL) {
227 		const size_t tok_len = sep - *frame_descr;
228 
229 		if (tok_len + 1 > max_tok_len) {
230 			pr_err("KASAN internal error: frame description too long: %s\n",
231 			       *frame_descr);
232 			return false;
233 		}
234 
235 		/* Copy token (+ 1 byte for '\0'). */
236 		strlcpy(token, *frame_descr, tok_len + 1);
237 	}
238 
239 	/* Advance frame_descr past separator. */
240 	*frame_descr = sep + 1;
241 
242 	if (value != NULL && kstrtoul(token, 10, value)) {
243 		pr_err("KASAN internal error: not a valid number: %s\n", token);
244 		return false;
245 	}
246 
247 	return true;
248 }
249 
250 static void print_decoded_frame_descr(const char *frame_descr)
251 {
252 	/*
253 	 * We need to parse the following string:
254 	 *    "n alloc_1 alloc_2 ... alloc_n"
255 	 * where alloc_i looks like
256 	 *    "offset size len name"
257 	 * or "offset size len name:line".
258 	 */
259 
260 	char token[64];
261 	unsigned long num_objects;
262 
263 	if (!tokenize_frame_descr(&frame_descr, token, sizeof(token),
264 				  &num_objects))
265 		return;
266 
267 	pr_err("\n");
268 	pr_err("this frame has %lu %s:\n", num_objects,
269 	       num_objects == 1 ? "object" : "objects");
270 
271 	while (num_objects--) {
272 		unsigned long offset;
273 		unsigned long size;
274 
275 		/* access offset */
276 		if (!tokenize_frame_descr(&frame_descr, token, sizeof(token),
277 					  &offset))
278 			return;
279 		/* access size */
280 		if (!tokenize_frame_descr(&frame_descr, token, sizeof(token),
281 					  &size))
282 			return;
283 		/* name length (unused) */
284 		if (!tokenize_frame_descr(&frame_descr, NULL, 0, NULL))
285 			return;
286 		/* object name */
287 		if (!tokenize_frame_descr(&frame_descr, token, sizeof(token),
288 					  NULL))
289 			return;
290 
291 		/* Strip line number; without filename it's not very helpful. */
292 		strreplace(token, ':', '\0');
293 
294 		/* Finally, print object information. */
295 		pr_err(" [%lu, %lu) '%s'", offset, offset + size, token);
296 	}
297 }
298 
299 static bool __must_check get_address_stack_frame_info(const void *addr,
300 						      unsigned long *offset,
301 						      const char **frame_descr,
302 						      const void **frame_pc)
303 {
304 	unsigned long aligned_addr;
305 	unsigned long mem_ptr;
306 	const u8 *shadow_bottom;
307 	const u8 *shadow_ptr;
308 	const unsigned long *frame;
309 
310 	BUILD_BUG_ON(IS_ENABLED(CONFIG_STACK_GROWSUP));
311 
312 	/*
313 	 * NOTE: We currently only support printing frame information for
314 	 * accesses to the task's own stack.
315 	 */
316 	if (!object_is_on_stack(addr))
317 		return false;
318 
319 	aligned_addr = round_down((unsigned long)addr, sizeof(long));
320 	mem_ptr = round_down(aligned_addr, KASAN_SHADOW_SCALE_SIZE);
321 	shadow_ptr = kasan_mem_to_shadow((void *)aligned_addr);
322 	shadow_bottom = kasan_mem_to_shadow(end_of_stack(current));
323 
324 	while (shadow_ptr >= shadow_bottom && *shadow_ptr != KASAN_STACK_LEFT) {
325 		shadow_ptr--;
326 		mem_ptr -= KASAN_SHADOW_SCALE_SIZE;
327 	}
328 
329 	while (shadow_ptr >= shadow_bottom && *shadow_ptr == KASAN_STACK_LEFT) {
330 		shadow_ptr--;
331 		mem_ptr -= KASAN_SHADOW_SCALE_SIZE;
332 	}
333 
334 	if (shadow_ptr < shadow_bottom)
335 		return false;
336 
337 	frame = (const unsigned long *)(mem_ptr + KASAN_SHADOW_SCALE_SIZE);
338 	if (frame[0] != KASAN_CURRENT_STACK_FRAME_MAGIC) {
339 		pr_err("KASAN internal error: frame info validation failed; invalid marker: %lu\n",
340 		       frame[0]);
341 		return false;
342 	}
343 
344 	*offset = (unsigned long)addr - (unsigned long)frame;
345 	*frame_descr = (const char *)frame[1];
346 	*frame_pc = (void *)frame[2];
347 
348 	return true;
349 }
350 
351 static void print_address_stack_frame(const void *addr)
352 {
353 	unsigned long offset;
354 	const char *frame_descr;
355 	const void *frame_pc;
356 
357 	if (IS_ENABLED(CONFIG_KASAN_SW_TAGS))
358 		return;
359 
360 	if (!get_address_stack_frame_info(addr, &offset, &frame_descr,
361 					  &frame_pc))
362 		return;
363 
364 	/*
365 	 * get_address_stack_frame_info only returns true if the given addr is
366 	 * on the current task's stack.
367 	 */
368 	pr_err("\n");
369 	pr_err("addr %px is located in stack of task %s/%d at offset %lu in frame:\n",
370 	       addr, current->comm, task_pid_nr(current), offset);
371 	pr_err(" %pS\n", frame_pc);
372 
373 	if (!frame_descr)
374 		return;
375 
376 	print_decoded_frame_descr(frame_descr);
377 }
378 
379 static void print_address_description(void *addr, u8 tag)
380 {
381 	struct page *page = kasan_addr_to_page(addr);
382 
383 	dump_stack();
384 	pr_err("\n");
385 
386 	if (page && PageSlab(page)) {
387 		struct kmem_cache *cache = page->slab_cache;
388 		void *object = nearest_obj(cache, page,	addr);
389 
390 		describe_object(cache, object, addr, tag);
391 	}
392 
393 	if (kernel_or_module_addr(addr) && !init_task_stack_addr(addr)) {
394 		pr_err("The buggy address belongs to the variable:\n");
395 		pr_err(" %pS\n", addr);
396 	}
397 
398 	if (page) {
399 		pr_err("The buggy address belongs to the page:\n");
400 		dump_page(page, "kasan: bad access detected");
401 	}
402 
403 	print_address_stack_frame(addr);
404 }
405 
406 static bool row_is_guilty(const void *row, const void *guilty)
407 {
408 	return (row <= guilty) && (guilty < row + SHADOW_BYTES_PER_ROW);
409 }
410 
411 static int shadow_pointer_offset(const void *row, const void *shadow)
412 {
413 	/* The length of ">ff00ff00ff00ff00: " is
414 	 *    3 + (BITS_PER_LONG/8)*2 chars.
415 	 */
416 	return 3 + (BITS_PER_LONG/8)*2 + (shadow - row)*2 +
417 		(shadow - row) / SHADOW_BYTES_PER_BLOCK + 1;
418 }
419 
420 static void print_shadow_for_address(const void *addr)
421 {
422 	int i;
423 	const void *shadow = kasan_mem_to_shadow(addr);
424 	const void *shadow_row;
425 
426 	shadow_row = (void *)round_down((unsigned long)shadow,
427 					SHADOW_BYTES_PER_ROW)
428 		- SHADOW_ROWS_AROUND_ADDR * SHADOW_BYTES_PER_ROW;
429 
430 	pr_err("Memory state around the buggy address:\n");
431 
432 	for (i = -SHADOW_ROWS_AROUND_ADDR; i <= SHADOW_ROWS_AROUND_ADDR; i++) {
433 		const void *kaddr = kasan_shadow_to_mem(shadow_row);
434 		char buffer[4 + (BITS_PER_LONG/8)*2];
435 		char shadow_buf[SHADOW_BYTES_PER_ROW];
436 
437 		snprintf(buffer, sizeof(buffer),
438 			(i == 0) ? ">%px: " : " %px: ", kaddr);
439 		/*
440 		 * We should not pass a shadow pointer to generic
441 		 * function, because generic functions may try to
442 		 * access kasan mapping for the passed address.
443 		 */
444 		memcpy(shadow_buf, shadow_row, SHADOW_BYTES_PER_ROW);
445 		print_hex_dump(KERN_ERR, buffer,
446 			DUMP_PREFIX_NONE, SHADOW_BYTES_PER_ROW, 1,
447 			shadow_buf, SHADOW_BYTES_PER_ROW, 0);
448 
449 		if (row_is_guilty(shadow_row, shadow))
450 			pr_err("%*c\n",
451 				shadow_pointer_offset(shadow_row, shadow),
452 				'^');
453 
454 		shadow_row += SHADOW_BYTES_PER_ROW;
455 	}
456 }
457 
458 static bool report_enabled(void)
459 {
460 	if (current->kasan_depth)
461 		return false;
462 	if (test_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags))
463 		return true;
464 	return !test_and_set_bit(KASAN_BIT_REPORTED, &kasan_flags);
465 }
466 
467 void kasan_report_invalid_free(void *object, unsigned long ip)
468 {
469 	unsigned long flags;
470 	u8 tag = get_tag(object);
471 
472 	object = reset_tag(object);
473 	start_report(&flags);
474 	pr_err("BUG: KASAN: double-free or invalid-free in %pS\n", (void *)ip);
475 	print_tags(tag, object);
476 	pr_err("\n");
477 	print_address_description(object, tag);
478 	pr_err("\n");
479 	print_shadow_for_address(object);
480 	end_report(&flags);
481 }
482 
483 static void __kasan_report(unsigned long addr, size_t size, bool is_write,
484 				unsigned long ip)
485 {
486 	struct kasan_access_info info;
487 	void *tagged_addr;
488 	void *untagged_addr;
489 	unsigned long flags;
490 
491 	disable_trace_on_warning();
492 
493 	tagged_addr = (void *)addr;
494 	untagged_addr = reset_tag(tagged_addr);
495 
496 	info.access_addr = tagged_addr;
497 	if (addr_has_shadow(untagged_addr))
498 		info.first_bad_addr = find_first_bad_addr(tagged_addr, size);
499 	else
500 		info.first_bad_addr = untagged_addr;
501 	info.access_size = size;
502 	info.is_write = is_write;
503 	info.ip = ip;
504 
505 	start_report(&flags);
506 
507 	print_error_description(&info);
508 	if (addr_has_shadow(untagged_addr))
509 		print_tags(get_tag(tagged_addr), info.first_bad_addr);
510 	pr_err("\n");
511 
512 	if (addr_has_shadow(untagged_addr)) {
513 		print_address_description(untagged_addr, get_tag(tagged_addr));
514 		pr_err("\n");
515 		print_shadow_for_address(info.first_bad_addr);
516 	} else {
517 		dump_stack();
518 	}
519 
520 	end_report(&flags);
521 }
522 
523 bool kasan_report(unsigned long addr, size_t size, bool is_write,
524 			unsigned long ip)
525 {
526 	unsigned long flags = user_access_save();
527 	bool ret = false;
528 
529 	if (likely(report_enabled())) {
530 		__kasan_report(addr, size, is_write, ip);
531 		ret = true;
532 	}
533 
534 	user_access_restore(flags);
535 
536 	return ret;
537 }
538 
539 #ifdef CONFIG_KASAN_INLINE
540 /*
541  * With CONFIG_KASAN_INLINE, accesses to bogus pointers (outside the high
542  * canonical half of the address space) cause out-of-bounds shadow memory reads
543  * before the actual access. For addresses in the low canonical half of the
544  * address space, as well as most non-canonical addresses, that out-of-bounds
545  * shadow memory access lands in the non-canonical part of the address space.
546  * Help the user figure out what the original bogus pointer was.
547  */
548 void kasan_non_canonical_hook(unsigned long addr)
549 {
550 	unsigned long orig_addr;
551 	const char *bug_type;
552 
553 	if (addr < KASAN_SHADOW_OFFSET)
554 		return;
555 
556 	orig_addr = (addr - KASAN_SHADOW_OFFSET) << KASAN_SHADOW_SCALE_SHIFT;
557 	/*
558 	 * For faults near the shadow address for NULL, we can be fairly certain
559 	 * that this is a KASAN shadow memory access.
560 	 * For faults that correspond to shadow for low canonical addresses, we
561 	 * can still be pretty sure - that shadow region is a fairly narrow
562 	 * chunk of the non-canonical address space.
563 	 * But faults that look like shadow for non-canonical addresses are a
564 	 * really large chunk of the address space. In that case, we still
565 	 * print the decoded address, but make it clear that this is not
566 	 * necessarily what's actually going on.
567 	 */
568 	if (orig_addr < PAGE_SIZE)
569 		bug_type = "null-ptr-deref";
570 	else if (orig_addr < TASK_SIZE)
571 		bug_type = "probably user-memory-access";
572 	else
573 		bug_type = "maybe wild-memory-access";
574 	pr_alert("KASAN: %s in range [0x%016lx-0x%016lx]\n", bug_type,
575 		 orig_addr, orig_addr + KASAN_SHADOW_MASK);
576 }
577 #endif
578