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