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