Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 /*
0003  * This file contains common KASAN error reporting code.
0004  *
0005  * Copyright (c) 2014 Samsung Electronics Co., Ltd.
0006  * Author: Andrey Ryabinin <ryabinin.a.a@gmail.com>
0007  *
0008  * Some code borrowed from https://github.com/xairy/kasan-prototype by
0009  *        Andrey Konovalov <andreyknvl@gmail.com>
0010  */
0011 
0012 #include <linux/bitops.h>
0013 #include <linux/ftrace.h>
0014 #include <linux/init.h>
0015 #include <linux/kernel.h>
0016 #include <linux/lockdep.h>
0017 #include <linux/mm.h>
0018 #include <linux/printk.h>
0019 #include <linux/sched.h>
0020 #include <linux/slab.h>
0021 #include <linux/stackdepot.h>
0022 #include <linux/stacktrace.h>
0023 #include <linux/string.h>
0024 #include <linux/types.h>
0025 #include <linux/kasan.h>
0026 #include <linux/module.h>
0027 #include <linux/sched/task_stack.h>
0028 #include <linux/uaccess.h>
0029 #include <trace/events/error_report.h>
0030 
0031 #include <asm/sections.h>
0032 
0033 #include <kunit/test.h>
0034 
0035 #include "kasan.h"
0036 #include "../slab.h"
0037 
0038 static unsigned long kasan_flags;
0039 
0040 #define KASAN_BIT_REPORTED  0
0041 #define KASAN_BIT_MULTI_SHOT    1
0042 
0043 enum kasan_arg_fault {
0044     KASAN_ARG_FAULT_DEFAULT,
0045     KASAN_ARG_FAULT_REPORT,
0046     KASAN_ARG_FAULT_PANIC,
0047 };
0048 
0049 static enum kasan_arg_fault kasan_arg_fault __ro_after_init = KASAN_ARG_FAULT_DEFAULT;
0050 
0051 /* kasan.fault=report/panic */
0052 static int __init early_kasan_fault(char *arg)
0053 {
0054     if (!arg)
0055         return -EINVAL;
0056 
0057     if (!strcmp(arg, "report"))
0058         kasan_arg_fault = KASAN_ARG_FAULT_REPORT;
0059     else if (!strcmp(arg, "panic"))
0060         kasan_arg_fault = KASAN_ARG_FAULT_PANIC;
0061     else
0062         return -EINVAL;
0063 
0064     return 0;
0065 }
0066 early_param("kasan.fault", early_kasan_fault);
0067 
0068 static int __init kasan_set_multi_shot(char *str)
0069 {
0070     set_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags);
0071     return 1;
0072 }
0073 __setup("kasan_multi_shot", kasan_set_multi_shot);
0074 
0075 /*
0076  * Used to suppress reports within kasan_disable/enable_current() critical
0077  * sections, which are used for marking accesses to slab metadata.
0078  */
0079 static bool report_suppressed(void)
0080 {
0081 #if defined(CONFIG_KASAN_GENERIC) || defined(CONFIG_KASAN_SW_TAGS)
0082     if (current->kasan_depth)
0083         return true;
0084 #endif
0085     return false;
0086 }
0087 
0088 /*
0089  * Used to avoid reporting more than one KASAN bug unless kasan_multi_shot
0090  * is enabled. Note that KASAN tests effectively enable kasan_multi_shot
0091  * for their duration.
0092  */
0093 static bool report_enabled(void)
0094 {
0095     if (test_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags))
0096         return true;
0097     return !test_and_set_bit(KASAN_BIT_REPORTED, &kasan_flags);
0098 }
0099 
0100 #if IS_ENABLED(CONFIG_KASAN_KUNIT_TEST) || IS_ENABLED(CONFIG_KASAN_MODULE_TEST)
0101 
0102 bool kasan_save_enable_multi_shot(void)
0103 {
0104     return test_and_set_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags);
0105 }
0106 EXPORT_SYMBOL_GPL(kasan_save_enable_multi_shot);
0107 
0108 void kasan_restore_multi_shot(bool enabled)
0109 {
0110     if (!enabled)
0111         clear_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags);
0112 }
0113 EXPORT_SYMBOL_GPL(kasan_restore_multi_shot);
0114 
0115 #endif
0116 
0117 #if IS_ENABLED(CONFIG_KASAN_KUNIT_TEST)
0118 static void update_kunit_status(bool sync)
0119 {
0120     struct kunit *test;
0121     struct kunit_resource *resource;
0122     struct kunit_kasan_status *status;
0123 
0124     test = current->kunit_test;
0125     if (!test)
0126         return;
0127 
0128     resource = kunit_find_named_resource(test, "kasan_status");
0129     if (!resource) {
0130         kunit_set_failure(test);
0131         return;
0132     }
0133 
0134     status = (struct kunit_kasan_status *)resource->data;
0135     WRITE_ONCE(status->report_found, true);
0136     WRITE_ONCE(status->sync_fault, sync);
0137 
0138     kunit_put_resource(resource);
0139 }
0140 #else
0141 static void update_kunit_status(bool sync) { }
0142 #endif
0143 
0144 static DEFINE_SPINLOCK(report_lock);
0145 
0146 static void start_report(unsigned long *flags, bool sync)
0147 {
0148     /* Respect the /proc/sys/kernel/traceoff_on_warning interface. */
0149     disable_trace_on_warning();
0150     /* Update status of the currently running KASAN test. */
0151     update_kunit_status(sync);
0152     /* Do not allow LOCKDEP mangling KASAN reports. */
0153     lockdep_off();
0154     /* Make sure we don't end up in loop. */
0155     kasan_disable_current();
0156     spin_lock_irqsave(&report_lock, *flags);
0157     pr_err("==================================================================\n");
0158 }
0159 
0160 static void end_report(unsigned long *flags, void *addr)
0161 {
0162     if (addr)
0163         trace_error_report_end(ERROR_DETECTOR_KASAN,
0164                        (unsigned long)addr);
0165     pr_err("==================================================================\n");
0166     spin_unlock_irqrestore(&report_lock, *flags);
0167     if (panic_on_warn && !test_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags))
0168         panic("panic_on_warn set ...\n");
0169     if (kasan_arg_fault == KASAN_ARG_FAULT_PANIC)
0170         panic("kasan.fault=panic set ...\n");
0171     add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
0172     lockdep_on();
0173     kasan_enable_current();
0174 }
0175 
0176 static void print_error_description(struct kasan_report_info *info)
0177 {
0178     if (info->type == KASAN_REPORT_INVALID_FREE) {
0179         pr_err("BUG: KASAN: invalid-free in %pS\n", (void *)info->ip);
0180         return;
0181     }
0182 
0183     if (info->type == KASAN_REPORT_DOUBLE_FREE) {
0184         pr_err("BUG: KASAN: double-free in %pS\n", (void *)info->ip);
0185         return;
0186     }
0187 
0188     pr_err("BUG: KASAN: %s in %pS\n",
0189         kasan_get_bug_type(info), (void *)info->ip);
0190     if (info->access_size)
0191         pr_err("%s of size %zu at addr %px by task %s/%d\n",
0192             info->is_write ? "Write" : "Read", info->access_size,
0193             info->access_addr, current->comm, task_pid_nr(current));
0194     else
0195         pr_err("%s at addr %px by task %s/%d\n",
0196             info->is_write ? "Write" : "Read",
0197             info->access_addr, current->comm, task_pid_nr(current));
0198 }
0199 
0200 static void print_track(struct kasan_track *track, const char *prefix)
0201 {
0202     pr_err("%s by task %u:\n", prefix, track->pid);
0203     if (track->stack) {
0204         stack_depot_print(track->stack);
0205     } else {
0206         pr_err("(stack is not available)\n");
0207     }
0208 }
0209 
0210 struct page *kasan_addr_to_page(const void *addr)
0211 {
0212     if ((addr >= (void *)PAGE_OFFSET) &&
0213             (addr < high_memory))
0214         return virt_to_head_page(addr);
0215     return NULL;
0216 }
0217 
0218 struct slab *kasan_addr_to_slab(const void *addr)
0219 {
0220     if ((addr >= (void *)PAGE_OFFSET) &&
0221             (addr < high_memory))
0222         return virt_to_slab(addr);
0223     return NULL;
0224 }
0225 
0226 static void describe_object_addr(struct kmem_cache *cache, void *object,
0227                 const void *addr)
0228 {
0229     unsigned long access_addr = (unsigned long)addr;
0230     unsigned long object_addr = (unsigned long)object;
0231     const char *rel_type;
0232     int rel_bytes;
0233 
0234     pr_err("The buggy address belongs to the object at %px\n"
0235            " which belongs to the cache %s of size %d\n",
0236         object, cache->name, cache->object_size);
0237 
0238     if (access_addr < object_addr) {
0239         rel_type = "to the left";
0240         rel_bytes = object_addr - access_addr;
0241     } else if (access_addr >= object_addr + cache->object_size) {
0242         rel_type = "to the right";
0243         rel_bytes = access_addr - (object_addr + cache->object_size);
0244     } else {
0245         rel_type = "inside";
0246         rel_bytes = access_addr - object_addr;
0247     }
0248 
0249     pr_err("The buggy address is located %d bytes %s of\n"
0250            " %d-byte region [%px, %px)\n",
0251         rel_bytes, rel_type, cache->object_size, (void *)object_addr,
0252         (void *)(object_addr + cache->object_size));
0253 }
0254 
0255 static void describe_object_stacks(struct kmem_cache *cache, void *object,
0256                     const void *addr, u8 tag)
0257 {
0258     struct kasan_alloc_meta *alloc_meta;
0259     struct kasan_track *free_track;
0260 
0261     alloc_meta = kasan_get_alloc_meta(cache, object);
0262     if (alloc_meta) {
0263         print_track(&alloc_meta->alloc_track, "Allocated");
0264         pr_err("\n");
0265     }
0266 
0267     free_track = kasan_get_free_track(cache, object, tag);
0268     if (free_track) {
0269         print_track(free_track, "Freed");
0270         pr_err("\n");
0271     }
0272 
0273 #ifdef CONFIG_KASAN_GENERIC
0274     if (!alloc_meta)
0275         return;
0276     if (alloc_meta->aux_stack[0]) {
0277         pr_err("Last potentially related work creation:\n");
0278         stack_depot_print(alloc_meta->aux_stack[0]);
0279         pr_err("\n");
0280     }
0281     if (alloc_meta->aux_stack[1]) {
0282         pr_err("Second to last potentially related work creation:\n");
0283         stack_depot_print(alloc_meta->aux_stack[1]);
0284         pr_err("\n");
0285     }
0286 #endif
0287 }
0288 
0289 static void describe_object(struct kmem_cache *cache, void *object,
0290                 const void *addr, u8 tag)
0291 {
0292     if (kasan_stack_collection_enabled())
0293         describe_object_stacks(cache, object, addr, tag);
0294     describe_object_addr(cache, object, addr);
0295 }
0296 
0297 static inline bool kernel_or_module_addr(const void *addr)
0298 {
0299     if (is_kernel((unsigned long)addr))
0300         return true;
0301     if (is_module_address((unsigned long)addr))
0302         return true;
0303     return false;
0304 }
0305 
0306 static inline bool init_task_stack_addr(const void *addr)
0307 {
0308     return addr >= (void *)&init_thread_union.stack &&
0309         (addr <= (void *)&init_thread_union.stack +
0310             sizeof(init_thread_union.stack));
0311 }
0312 
0313 static void print_address_description(void *addr, u8 tag)
0314 {
0315     struct page *page = kasan_addr_to_page(addr);
0316 
0317     dump_stack_lvl(KERN_ERR);
0318     pr_err("\n");
0319 
0320     if (page && PageSlab(page)) {
0321         struct slab *slab = page_slab(page);
0322         struct kmem_cache *cache = slab->slab_cache;
0323         void *object = nearest_obj(cache, slab, addr);
0324 
0325         describe_object(cache, object, addr, tag);
0326         pr_err("\n");
0327     }
0328 
0329     if (kernel_or_module_addr(addr) && !init_task_stack_addr(addr)) {
0330         pr_err("The buggy address belongs to the variable:\n");
0331         pr_err(" %pS\n", addr);
0332         pr_err("\n");
0333     }
0334 
0335     if (object_is_on_stack(addr)) {
0336         /*
0337          * Currently, KASAN supports printing frame information only
0338          * for accesses to the task's own stack.
0339          */
0340         kasan_print_address_stack_frame(addr);
0341         pr_err("\n");
0342     }
0343 
0344     if (is_vmalloc_addr(addr)) {
0345         struct vm_struct *va = find_vm_area(addr);
0346 
0347         if (va) {
0348             pr_err("The buggy address belongs to the virtual mapping at\n"
0349                    " [%px, %px) created by:\n"
0350                    " %pS\n",
0351                    va->addr, va->addr + va->size, va->caller);
0352             pr_err("\n");
0353 
0354             page = vmalloc_to_page(addr);
0355         }
0356     }
0357 
0358     if (page) {
0359         pr_err("The buggy address belongs to the physical page:\n");
0360         dump_page(page, "kasan: bad access detected");
0361         pr_err("\n");
0362     }
0363 }
0364 
0365 static bool meta_row_is_guilty(const void *row, const void *addr)
0366 {
0367     return (row <= addr) && (addr < row + META_MEM_BYTES_PER_ROW);
0368 }
0369 
0370 static int meta_pointer_offset(const void *row, const void *addr)
0371 {
0372     /*
0373      * Memory state around the buggy address:
0374      *  ff00ff00ff00ff00: 00 00 00 05 fe fe fe fe fe fe fe fe fe fe fe fe
0375      *  ...
0376      *
0377      * The length of ">ff00ff00ff00ff00: " is
0378      *    3 + (BITS_PER_LONG / 8) * 2 chars.
0379      * The length of each granule metadata is 2 bytes
0380      *    plus 1 byte for space.
0381      */
0382     return 3 + (BITS_PER_LONG / 8) * 2 +
0383         (addr - row) / KASAN_GRANULE_SIZE * 3 + 1;
0384 }
0385 
0386 static void print_memory_metadata(const void *addr)
0387 {
0388     int i;
0389     void *row;
0390 
0391     row = (void *)round_down((unsigned long)addr, META_MEM_BYTES_PER_ROW)
0392             - META_ROWS_AROUND_ADDR * META_MEM_BYTES_PER_ROW;
0393 
0394     pr_err("Memory state around the buggy address:\n");
0395 
0396     for (i = -META_ROWS_AROUND_ADDR; i <= META_ROWS_AROUND_ADDR; i++) {
0397         char buffer[4 + (BITS_PER_LONG / 8) * 2];
0398         char metadata[META_BYTES_PER_ROW];
0399 
0400         snprintf(buffer, sizeof(buffer),
0401                 (i == 0) ? ">%px: " : " %px: ", row);
0402 
0403         /*
0404          * We should not pass a shadow pointer to generic
0405          * function, because generic functions may try to
0406          * access kasan mapping for the passed address.
0407          */
0408         kasan_metadata_fetch_row(&metadata[0], row);
0409 
0410         print_hex_dump(KERN_ERR, buffer,
0411             DUMP_PREFIX_NONE, META_BYTES_PER_ROW, 1,
0412             metadata, META_BYTES_PER_ROW, 0);
0413 
0414         if (meta_row_is_guilty(row, addr))
0415             pr_err("%*c\n", meta_pointer_offset(row, addr), '^');
0416 
0417         row += META_MEM_BYTES_PER_ROW;
0418     }
0419 }
0420 
0421 static void print_report(struct kasan_report_info *info)
0422 {
0423     void *tagged_addr = info->access_addr;
0424     void *untagged_addr = kasan_reset_tag(tagged_addr);
0425     u8 tag = get_tag(tagged_addr);
0426 
0427     print_error_description(info);
0428     if (addr_has_metadata(untagged_addr))
0429         kasan_print_tags(tag, info->first_bad_addr);
0430     pr_err("\n");
0431 
0432     if (addr_has_metadata(untagged_addr)) {
0433         print_address_description(untagged_addr, tag);
0434         print_memory_metadata(info->first_bad_addr);
0435     } else {
0436         dump_stack_lvl(KERN_ERR);
0437     }
0438 }
0439 
0440 void kasan_report_invalid_free(void *ptr, unsigned long ip, enum kasan_report_type type)
0441 {
0442     unsigned long flags;
0443     struct kasan_report_info info;
0444 
0445     /*
0446      * Do not check report_suppressed(), as an invalid-free cannot be
0447      * caused by accessing slab metadata and thus should not be
0448      * suppressed by kasan_disable/enable_current() critical sections.
0449      */
0450     if (unlikely(!report_enabled()))
0451         return;
0452 
0453     start_report(&flags, true);
0454 
0455     info.type = type;
0456     info.access_addr = ptr;
0457     info.first_bad_addr = kasan_reset_tag(ptr);
0458     info.access_size = 0;
0459     info.is_write = false;
0460     info.ip = ip;
0461 
0462     print_report(&info);
0463 
0464     end_report(&flags, ptr);
0465 }
0466 
0467 /*
0468  * kasan_report() is the only reporting function that uses
0469  * user_access_save/restore(): kasan_report_invalid_free() cannot be called
0470  * from a UACCESS region, and kasan_report_async() is not used on x86.
0471  */
0472 bool kasan_report(unsigned long addr, size_t size, bool is_write,
0473             unsigned long ip)
0474 {
0475     bool ret = true;
0476     void *ptr = (void *)addr;
0477     unsigned long ua_flags = user_access_save();
0478     unsigned long irq_flags;
0479     struct kasan_report_info info;
0480 
0481     if (unlikely(report_suppressed()) || unlikely(!report_enabled())) {
0482         ret = false;
0483         goto out;
0484     }
0485 
0486     start_report(&irq_flags, true);
0487 
0488     info.type = KASAN_REPORT_ACCESS;
0489     info.access_addr = ptr;
0490     info.first_bad_addr = kasan_find_first_bad_addr(ptr, size);
0491     info.access_size = size;
0492     info.is_write = is_write;
0493     info.ip = ip;
0494 
0495     print_report(&info);
0496 
0497     end_report(&irq_flags, ptr);
0498 
0499 out:
0500     user_access_restore(ua_flags);
0501 
0502     return ret;
0503 }
0504 
0505 #ifdef CONFIG_KASAN_HW_TAGS
0506 void kasan_report_async(void)
0507 {
0508     unsigned long flags;
0509 
0510     /*
0511      * Do not check report_suppressed(), as kasan_disable/enable_current()
0512      * critical sections do not affect Hardware Tag-Based KASAN.
0513      */
0514     if (unlikely(!report_enabled()))
0515         return;
0516 
0517     start_report(&flags, false);
0518     pr_err("BUG: KASAN: invalid-access\n");
0519     pr_err("Asynchronous fault: no details available\n");
0520     pr_err("\n");
0521     dump_stack_lvl(KERN_ERR);
0522     end_report(&flags, NULL);
0523 }
0524 #endif /* CONFIG_KASAN_HW_TAGS */
0525 
0526 #ifdef CONFIG_KASAN_INLINE
0527 /*
0528  * With CONFIG_KASAN_INLINE, accesses to bogus pointers (outside the high
0529  * canonical half of the address space) cause out-of-bounds shadow memory reads
0530  * before the actual access. For addresses in the low canonical half of the
0531  * address space, as well as most non-canonical addresses, that out-of-bounds
0532  * shadow memory access lands in the non-canonical part of the address space.
0533  * Help the user figure out what the original bogus pointer was.
0534  */
0535 void kasan_non_canonical_hook(unsigned long addr)
0536 {
0537     unsigned long orig_addr;
0538     const char *bug_type;
0539 
0540     if (addr < KASAN_SHADOW_OFFSET)
0541         return;
0542 
0543     orig_addr = (addr - KASAN_SHADOW_OFFSET) << KASAN_SHADOW_SCALE_SHIFT;
0544     /*
0545      * For faults near the shadow address for NULL, we can be fairly certain
0546      * that this is a KASAN shadow memory access.
0547      * For faults that correspond to shadow for low canonical addresses, we
0548      * can still be pretty sure - that shadow region is a fairly narrow
0549      * chunk of the non-canonical address space.
0550      * But faults that look like shadow for non-canonical addresses are a
0551      * really large chunk of the address space. In that case, we still
0552      * print the decoded address, but make it clear that this is not
0553      * necessarily what's actually going on.
0554      */
0555     if (orig_addr < PAGE_SIZE)
0556         bug_type = "null-ptr-deref";
0557     else if (orig_addr < TASK_SIZE)
0558         bug_type = "probably user-memory-access";
0559     else
0560         bug_type = "maybe wild-memory-access";
0561     pr_alert("KASAN: %s in range [0x%016lx-0x%016lx]\n", bug_type,
0562          orig_addr, orig_addr + KASAN_GRANULE_SIZE - 1);
0563 }
0564 #endif