xref: /openbmc/linux/mm/kasan/report.c (revision 8938c48f)
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/mm.h>
17 #include <linux/printk.h>
18 #include <linux/sched.h>
19 #include <linux/slab.h>
20 #include <linux/stackdepot.h>
21 #include <linux/stacktrace.h>
22 #include <linux/string.h>
23 #include <linux/types.h>
24 #include <linux/kasan.h>
25 #include <linux/module.h>
26 #include <linux/sched/task_stack.h>
27 #include <linux/uaccess.h>
28 #include <trace/events/error_report.h>
29 
30 #include <asm/sections.h>
31 
32 #include <kunit/test.h>
33 
34 #include "kasan.h"
35 #include "../slab.h"
36 
37 static unsigned long kasan_flags;
38 
39 #define KASAN_BIT_REPORTED	0
40 #define KASAN_BIT_MULTI_SHOT	1
41 
42 bool kasan_save_enable_multi_shot(void)
43 {
44 	return test_and_set_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags);
45 }
46 EXPORT_SYMBOL_GPL(kasan_save_enable_multi_shot);
47 
48 void kasan_restore_multi_shot(bool enabled)
49 {
50 	if (!enabled)
51 		clear_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags);
52 }
53 EXPORT_SYMBOL_GPL(kasan_restore_multi_shot);
54 
55 static int __init kasan_set_multi_shot(char *str)
56 {
57 	set_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags);
58 	return 1;
59 }
60 __setup("kasan_multi_shot", kasan_set_multi_shot);
61 
62 static void print_error_description(struct kasan_access_info *info)
63 {
64 	pr_err("BUG: KASAN: %s in %pS\n",
65 		kasan_get_bug_type(info), (void *)info->ip);
66 	if (info->access_size)
67 		pr_err("%s of size %zu at addr %px by task %s/%d\n",
68 			info->is_write ? "Write" : "Read", info->access_size,
69 			info->access_addr, current->comm, task_pid_nr(current));
70 	else
71 		pr_err("%s at addr %px by task %s/%d\n",
72 			info->is_write ? "Write" : "Read",
73 			info->access_addr, current->comm, task_pid_nr(current));
74 }
75 
76 static DEFINE_SPINLOCK(report_lock);
77 
78 static void start_report(unsigned long *flags)
79 {
80 	/*
81 	 * Make sure we don't end up in loop.
82 	 */
83 	kasan_disable_current();
84 	spin_lock_irqsave(&report_lock, *flags);
85 	pr_err("==================================================================\n");
86 }
87 
88 static void end_report(unsigned long *flags, unsigned long addr)
89 {
90 	trace_error_report_end(ERROR_DETECTOR_KASAN, addr);
91 	pr_err("==================================================================\n");
92 	add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
93 	spin_unlock_irqrestore(&report_lock, *flags);
94 	if (panic_on_warn && !test_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags)) {
95 		/*
96 		 * This thread may hit another WARN() in the panic path.
97 		 * Resetting this prevents additional WARN() from panicking the
98 		 * system on this thread.  Other threads are blocked by the
99 		 * panic_mutex in panic().
100 		 */
101 		panic_on_warn = 0;
102 		panic("panic_on_warn set ...\n");
103 	}
104 #ifdef CONFIG_KASAN_HW_TAGS
105 	if (kasan_flag_panic)
106 		panic("kasan.fault=panic set ...\n");
107 #endif
108 	kasan_enable_current();
109 }
110 
111 static void print_stack(depot_stack_handle_t stack)
112 {
113 	unsigned long *entries;
114 	unsigned int nr_entries;
115 
116 	nr_entries = stack_depot_fetch(stack, &entries);
117 	stack_trace_print(entries, nr_entries, 0);
118 }
119 
120 static void print_track(struct kasan_track *track, const char *prefix)
121 {
122 	pr_err("%s by task %u:\n", prefix, track->pid);
123 	if (track->stack) {
124 		print_stack(track->stack);
125 	} else {
126 		pr_err("(stack is not available)\n");
127 	}
128 }
129 
130 struct page *kasan_addr_to_page(const void *addr)
131 {
132 	if ((addr >= (void *)PAGE_OFFSET) &&
133 			(addr < high_memory))
134 		return virt_to_head_page(addr);
135 	return NULL;
136 }
137 
138 static void describe_object_addr(struct kmem_cache *cache, void *object,
139 				const void *addr)
140 {
141 	unsigned long access_addr = (unsigned long)addr;
142 	unsigned long object_addr = (unsigned long)object;
143 	const char *rel_type;
144 	int rel_bytes;
145 
146 	pr_err("The buggy address belongs to the object at %px\n"
147 	       " which belongs to the cache %s of size %d\n",
148 		object, cache->name, cache->object_size);
149 
150 	if (!addr)
151 		return;
152 
153 	if (access_addr < object_addr) {
154 		rel_type = "to the left";
155 		rel_bytes = object_addr - access_addr;
156 	} else if (access_addr >= object_addr + cache->object_size) {
157 		rel_type = "to the right";
158 		rel_bytes = access_addr - (object_addr + cache->object_size);
159 	} else {
160 		rel_type = "inside";
161 		rel_bytes = access_addr - object_addr;
162 	}
163 
164 	pr_err("The buggy address is located %d bytes %s of\n"
165 	       " %d-byte region [%px, %px)\n",
166 		rel_bytes, rel_type, cache->object_size, (void *)object_addr,
167 		(void *)(object_addr + cache->object_size));
168 }
169 
170 static void describe_object_stacks(struct kmem_cache *cache, void *object,
171 					const void *addr, u8 tag)
172 {
173 	struct kasan_alloc_meta *alloc_meta;
174 	struct kasan_track *free_track;
175 
176 	alloc_meta = kasan_get_alloc_meta(cache, object);
177 	if (alloc_meta) {
178 		print_track(&alloc_meta->alloc_track, "Allocated");
179 		pr_err("\n");
180 	}
181 
182 	free_track = kasan_get_free_track(cache, object, tag);
183 	if (free_track) {
184 		print_track(free_track, "Freed");
185 		pr_err("\n");
186 	}
187 
188 #ifdef CONFIG_KASAN_GENERIC
189 	if (!alloc_meta)
190 		return;
191 	if (alloc_meta->aux_stack[0]) {
192 		pr_err("Last potentially related work creation:\n");
193 		print_stack(alloc_meta->aux_stack[0]);
194 		pr_err("\n");
195 	}
196 	if (alloc_meta->aux_stack[1]) {
197 		pr_err("Second to last potentially related work creation:\n");
198 		print_stack(alloc_meta->aux_stack[1]);
199 		pr_err("\n");
200 	}
201 #endif
202 }
203 
204 static void describe_object(struct kmem_cache *cache, void *object,
205 				const void *addr, u8 tag)
206 {
207 	if (kasan_stack_collection_enabled())
208 		describe_object_stacks(cache, object, addr, tag);
209 	describe_object_addr(cache, object, addr);
210 }
211 
212 static inline bool kernel_or_module_addr(const void *addr)
213 {
214 	if (addr >= (void *)_stext && addr < (void *)_end)
215 		return true;
216 	if (is_module_address((unsigned long)addr))
217 		return true;
218 	return false;
219 }
220 
221 static inline bool init_task_stack_addr(const void *addr)
222 {
223 	return addr >= (void *)&init_thread_union.stack &&
224 		(addr <= (void *)&init_thread_union.stack +
225 			sizeof(init_thread_union.stack));
226 }
227 
228 static void print_address_description(void *addr, u8 tag)
229 {
230 	struct page *page = kasan_addr_to_page(addr);
231 
232 	dump_stack();
233 	pr_err("\n");
234 
235 	if (page && PageSlab(page)) {
236 		struct kmem_cache *cache = page->slab_cache;
237 		void *object = nearest_obj(cache, page,	addr);
238 
239 		describe_object(cache, object, addr, tag);
240 	}
241 
242 	if (kernel_or_module_addr(addr) && !init_task_stack_addr(addr)) {
243 		pr_err("The buggy address belongs to the variable:\n");
244 		pr_err(" %pS\n", addr);
245 	}
246 
247 	if (page) {
248 		pr_err("The buggy address belongs to the page:\n");
249 		dump_page(page, "kasan: bad access detected");
250 	}
251 
252 	kasan_print_address_stack_frame(addr);
253 }
254 
255 static bool meta_row_is_guilty(const void *row, const void *addr)
256 {
257 	return (row <= addr) && (addr < row + META_MEM_BYTES_PER_ROW);
258 }
259 
260 static int meta_pointer_offset(const void *row, const void *addr)
261 {
262 	/*
263 	 * Memory state around the buggy address:
264 	 *  ff00ff00ff00ff00: 00 00 00 05 fe fe fe fe fe fe fe fe fe fe fe fe
265 	 *  ...
266 	 *
267 	 * The length of ">ff00ff00ff00ff00: " is
268 	 *    3 + (BITS_PER_LONG / 8) * 2 chars.
269 	 * The length of each granule metadata is 2 bytes
270 	 *    plus 1 byte for space.
271 	 */
272 	return 3 + (BITS_PER_LONG / 8) * 2 +
273 		(addr - row) / KASAN_GRANULE_SIZE * 3 + 1;
274 }
275 
276 static void print_memory_metadata(const void *addr)
277 {
278 	int i;
279 	void *row;
280 
281 	row = (void *)round_down((unsigned long)addr, META_MEM_BYTES_PER_ROW)
282 			- META_ROWS_AROUND_ADDR * META_MEM_BYTES_PER_ROW;
283 
284 	pr_err("Memory state around the buggy address:\n");
285 
286 	for (i = -META_ROWS_AROUND_ADDR; i <= META_ROWS_AROUND_ADDR; i++) {
287 		char buffer[4 + (BITS_PER_LONG / 8) * 2];
288 		char metadata[META_BYTES_PER_ROW];
289 
290 		snprintf(buffer, sizeof(buffer),
291 				(i == 0) ? ">%px: " : " %px: ", row);
292 
293 		/*
294 		 * We should not pass a shadow pointer to generic
295 		 * function, because generic functions may try to
296 		 * access kasan mapping for the passed address.
297 		 */
298 		kasan_metadata_fetch_row(&metadata[0], row);
299 
300 		print_hex_dump(KERN_ERR, buffer,
301 			DUMP_PREFIX_NONE, META_BYTES_PER_ROW, 1,
302 			metadata, META_BYTES_PER_ROW, 0);
303 
304 		if (meta_row_is_guilty(row, addr))
305 			pr_err("%*c\n", meta_pointer_offset(row, addr), '^');
306 
307 		row += META_MEM_BYTES_PER_ROW;
308 	}
309 }
310 
311 static bool report_enabled(void)
312 {
313 #if defined(CONFIG_KASAN_GENERIC) || defined(CONFIG_KASAN_SW_TAGS)
314 	if (current->kasan_depth)
315 		return false;
316 #endif
317 	if (test_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags))
318 		return true;
319 	return !test_and_set_bit(KASAN_BIT_REPORTED, &kasan_flags);
320 }
321 
322 #if IS_ENABLED(CONFIG_KUNIT)
323 static void kasan_update_kunit_status(struct kunit *cur_test)
324 {
325 	struct kunit_resource *resource;
326 	struct kunit_kasan_expectation *kasan_data;
327 
328 	resource = kunit_find_named_resource(cur_test, "kasan_data");
329 
330 	if (!resource) {
331 		kunit_set_failure(cur_test);
332 		return;
333 	}
334 
335 	kasan_data = (struct kunit_kasan_expectation *)resource->data;
336 	WRITE_ONCE(kasan_data->report_found, true);
337 	kunit_put_resource(resource);
338 }
339 #endif /* IS_ENABLED(CONFIG_KUNIT) */
340 
341 void kasan_report_invalid_free(void *object, unsigned long ip)
342 {
343 	unsigned long flags;
344 	u8 tag = get_tag(object);
345 
346 	object = kasan_reset_tag(object);
347 
348 #if IS_ENABLED(CONFIG_KUNIT)
349 	if (current->kunit_test)
350 		kasan_update_kunit_status(current->kunit_test);
351 #endif /* IS_ENABLED(CONFIG_KUNIT) */
352 
353 	start_report(&flags);
354 	pr_err("BUG: KASAN: double-free or invalid-free in %pS\n", (void *)ip);
355 	kasan_print_tags(tag, object);
356 	pr_err("\n");
357 	print_address_description(object, tag);
358 	pr_err("\n");
359 	print_memory_metadata(object);
360 	end_report(&flags, (unsigned long)object);
361 }
362 
363 static void __kasan_report(unsigned long addr, size_t size, bool is_write,
364 				unsigned long ip)
365 {
366 	struct kasan_access_info info;
367 	void *tagged_addr;
368 	void *untagged_addr;
369 	unsigned long flags;
370 
371 #if IS_ENABLED(CONFIG_KUNIT)
372 	if (current->kunit_test)
373 		kasan_update_kunit_status(current->kunit_test);
374 #endif /* IS_ENABLED(CONFIG_KUNIT) */
375 
376 	disable_trace_on_warning();
377 
378 	tagged_addr = (void *)addr;
379 	untagged_addr = kasan_reset_tag(tagged_addr);
380 
381 	info.access_addr = tagged_addr;
382 	if (addr_has_metadata(untagged_addr))
383 		info.first_bad_addr =
384 			kasan_find_first_bad_addr(tagged_addr, size);
385 	else
386 		info.first_bad_addr = untagged_addr;
387 	info.access_size = size;
388 	info.is_write = is_write;
389 	info.ip = ip;
390 
391 	start_report(&flags);
392 
393 	print_error_description(&info);
394 	if (addr_has_metadata(untagged_addr))
395 		kasan_print_tags(get_tag(tagged_addr), info.first_bad_addr);
396 	pr_err("\n");
397 
398 	if (addr_has_metadata(untagged_addr)) {
399 		print_address_description(untagged_addr, get_tag(tagged_addr));
400 		pr_err("\n");
401 		print_memory_metadata(info.first_bad_addr);
402 	} else {
403 		dump_stack();
404 	}
405 
406 	end_report(&flags, addr);
407 }
408 
409 bool kasan_report(unsigned long addr, size_t size, bool is_write,
410 			unsigned long ip)
411 {
412 	unsigned long flags = user_access_save();
413 	bool ret = false;
414 
415 	if (likely(report_enabled())) {
416 		__kasan_report(addr, size, is_write, ip);
417 		ret = true;
418 	}
419 
420 	user_access_restore(flags);
421 
422 	return ret;
423 }
424 
425 #ifdef CONFIG_KASAN_INLINE
426 /*
427  * With CONFIG_KASAN_INLINE, accesses to bogus pointers (outside the high
428  * canonical half of the address space) cause out-of-bounds shadow memory reads
429  * before the actual access. For addresses in the low canonical half of the
430  * address space, as well as most non-canonical addresses, that out-of-bounds
431  * shadow memory access lands in the non-canonical part of the address space.
432  * Help the user figure out what the original bogus pointer was.
433  */
434 void kasan_non_canonical_hook(unsigned long addr)
435 {
436 	unsigned long orig_addr;
437 	const char *bug_type;
438 
439 	if (addr < KASAN_SHADOW_OFFSET)
440 		return;
441 
442 	orig_addr = (addr - KASAN_SHADOW_OFFSET) << KASAN_SHADOW_SCALE_SHIFT;
443 	/*
444 	 * For faults near the shadow address for NULL, we can be fairly certain
445 	 * that this is a KASAN shadow memory access.
446 	 * For faults that correspond to shadow for low canonical addresses, we
447 	 * can still be pretty sure - that shadow region is a fairly narrow
448 	 * chunk of the non-canonical address space.
449 	 * But faults that look like shadow for non-canonical addresses are a
450 	 * really large chunk of the address space. In that case, we still
451 	 * print the decoded address, but make it clear that this is not
452 	 * necessarily what's actually going on.
453 	 */
454 	if (orig_addr < PAGE_SIZE)
455 		bug_type = "null-ptr-deref";
456 	else if (orig_addr < TASK_SIZE)
457 		bug_type = "probably user-memory-access";
458 	else
459 		bug_type = "maybe wild-memory-access";
460 	pr_alert("KASAN: %s in range [0x%016lx-0x%016lx]\n", bug_type,
461 		 orig_addr, orig_addr + KASAN_GRANULE_SIZE - 1);
462 }
463 #endif
464