kfence: report sensitive information based on no_hash_pointers
[platform/kernel/linux-starfive.git] / mm / kfence / report.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * KFENCE reporting.
4  *
5  * Copyright (C) 2020, Google LLC.
6  */
7
8 #include <stdarg.h>
9
10 #include <linux/kernel.h>
11 #include <linux/lockdep.h>
12 #include <linux/printk.h>
13 #include <linux/sched/debug.h>
14 #include <linux/seq_file.h>
15 #include <linux/stacktrace.h>
16 #include <linux/string.h>
17
18 #include <asm/kfence.h>
19
20 #include "kfence.h"
21
22 extern bool no_hash_pointers;
23
24 /* Helper function to either print to a seq_file or to console. */
25 __printf(2, 3)
26 static void seq_con_printf(struct seq_file *seq, const char *fmt, ...)
27 {
28         va_list args;
29
30         va_start(args, fmt);
31         if (seq)
32                 seq_vprintf(seq, fmt, args);
33         else
34                 vprintk(fmt, args);
35         va_end(args);
36 }
37
38 /*
39  * Get the number of stack entries to skip to get out of MM internals. @type is
40  * optional, and if set to NULL, assumes an allocation or free stack.
41  */
42 static int get_stack_skipnr(const unsigned long stack_entries[], int num_entries,
43                             const enum kfence_error_type *type)
44 {
45         char buf[64];
46         int skipnr, fallback = 0;
47
48         if (type) {
49                 /* Depending on error type, find different stack entries. */
50                 switch (*type) {
51                 case KFENCE_ERROR_UAF:
52                 case KFENCE_ERROR_OOB:
53                 case KFENCE_ERROR_INVALID:
54                         /*
55                          * kfence_handle_page_fault() may be called with pt_regs
56                          * set to NULL; in that case we'll simply show the full
57                          * stack trace.
58                          */
59                         return 0;
60                 case KFENCE_ERROR_CORRUPTION:
61                 case KFENCE_ERROR_INVALID_FREE:
62                         break;
63                 }
64         }
65
66         for (skipnr = 0; skipnr < num_entries; skipnr++) {
67                 int len = scnprintf(buf, sizeof(buf), "%ps", (void *)stack_entries[skipnr]);
68
69                 if (str_has_prefix(buf, "kfence_") || str_has_prefix(buf, "__kfence_") ||
70                     !strncmp(buf, "__slab_free", len)) {
71                         /*
72                          * In case of tail calls from any of the below
73                          * to any of the above.
74                          */
75                         fallback = skipnr + 1;
76                 }
77
78                 /* Also the *_bulk() variants by only checking prefixes. */
79                 if (str_has_prefix(buf, "kfree") ||
80                     str_has_prefix(buf, "kmem_cache_free") ||
81                     str_has_prefix(buf, "__kmalloc") ||
82                     str_has_prefix(buf, "kmem_cache_alloc"))
83                         goto found;
84         }
85         if (fallback < num_entries)
86                 return fallback;
87 found:
88         skipnr++;
89         return skipnr < num_entries ? skipnr : 0;
90 }
91
92 static void kfence_print_stack(struct seq_file *seq, const struct kfence_metadata *meta,
93                                bool show_alloc)
94 {
95         const struct kfence_track *track = show_alloc ? &meta->alloc_track : &meta->free_track;
96
97         if (track->num_stack_entries) {
98                 /* Skip allocation/free internals stack. */
99                 int i = get_stack_skipnr(track->stack_entries, track->num_stack_entries, NULL);
100
101                 /* stack_trace_seq_print() does not exist; open code our own. */
102                 for (; i < track->num_stack_entries; i++)
103                         seq_con_printf(seq, " %pS\n", (void *)track->stack_entries[i]);
104         } else {
105                 seq_con_printf(seq, " no %s stack\n", show_alloc ? "allocation" : "deallocation");
106         }
107 }
108
109 void kfence_print_object(struct seq_file *seq, const struct kfence_metadata *meta)
110 {
111         const int size = abs(meta->size);
112         const unsigned long start = meta->addr;
113         const struct kmem_cache *const cache = meta->cache;
114
115         lockdep_assert_held(&meta->lock);
116
117         if (meta->state == KFENCE_OBJECT_UNUSED) {
118                 seq_con_printf(seq, "kfence-#%zd unused\n", meta - kfence_metadata);
119                 return;
120         }
121
122         seq_con_printf(seq,
123                        "kfence-#%zd [0x%p-0x%p"
124                        ", size=%d, cache=%s] allocated by task %d:\n",
125                        meta - kfence_metadata, (void *)start, (void *)(start + size - 1), size,
126                        (cache && cache->name) ? cache->name : "<destroyed>", meta->alloc_track.pid);
127         kfence_print_stack(seq, meta, true);
128
129         if (meta->state == KFENCE_OBJECT_FREED) {
130                 seq_con_printf(seq, "\nfreed by task %d:\n", meta->free_track.pid);
131                 kfence_print_stack(seq, meta, false);
132         }
133 }
134
135 /*
136  * Show bytes at @addr that are different from the expected canary values, up to
137  * @max_bytes.
138  */
139 static void print_diff_canary(unsigned long address, size_t bytes_to_show,
140                               const struct kfence_metadata *meta)
141 {
142         const unsigned long show_until_addr = address + bytes_to_show;
143         const u8 *cur, *end;
144
145         /* Do not show contents of object nor read into following guard page. */
146         end = (const u8 *)(address < meta->addr ? min(show_until_addr, meta->addr)
147                                                 : min(show_until_addr, PAGE_ALIGN(address)));
148
149         pr_cont("[");
150         for (cur = (const u8 *)address; cur < end; cur++) {
151                 if (*cur == KFENCE_CANARY_PATTERN(cur))
152                         pr_cont(" .");
153                 else if (no_hash_pointers)
154                         pr_cont(" 0x%02x", *cur);
155                 else /* Do not leak kernel memory in non-debug builds. */
156                         pr_cont(" !");
157         }
158         pr_cont(" ]");
159 }
160
161 static const char *get_access_type(bool is_write)
162 {
163         return is_write ? "write" : "read";
164 }
165
166 void kfence_report_error(unsigned long address, bool is_write, struct pt_regs *regs,
167                          const struct kfence_metadata *meta, enum kfence_error_type type)
168 {
169         unsigned long stack_entries[KFENCE_STACK_DEPTH] = { 0 };
170         const ptrdiff_t object_index = meta ? meta - kfence_metadata : -1;
171         int num_stack_entries;
172         int skipnr = 0;
173
174         if (regs) {
175                 num_stack_entries = stack_trace_save_regs(regs, stack_entries, KFENCE_STACK_DEPTH, 0);
176         } else {
177                 num_stack_entries = stack_trace_save(stack_entries, KFENCE_STACK_DEPTH, 1);
178                 skipnr = get_stack_skipnr(stack_entries, num_stack_entries, &type);
179         }
180
181         /* Require non-NULL meta, except if KFENCE_ERROR_INVALID. */
182         if (WARN_ON(type != KFENCE_ERROR_INVALID && !meta))
183                 return;
184
185         if (meta)
186                 lockdep_assert_held(&meta->lock);
187         /*
188          * Because we may generate reports in printk-unfriendly parts of the
189          * kernel, such as scheduler code, the use of printk() could deadlock.
190          * Until such time that all printing code here is safe in all parts of
191          * the kernel, accept the risk, and just get our message out (given the
192          * system might already behave unpredictably due to the memory error).
193          * As such, also disable lockdep to hide warnings, and avoid disabling
194          * lockdep for the rest of the kernel.
195          */
196         lockdep_off();
197
198         pr_err("==================================================================\n");
199         /* Print report header. */
200         switch (type) {
201         case KFENCE_ERROR_OOB: {
202                 const bool left_of_object = address < meta->addr;
203
204                 pr_err("BUG: KFENCE: out-of-bounds %s in %pS\n\n", get_access_type(is_write),
205                        (void *)stack_entries[skipnr]);
206                 pr_err("Out-of-bounds %s at 0x%p (%luB %s of kfence-#%zd):\n",
207                        get_access_type(is_write), (void *)address,
208                        left_of_object ? meta->addr - address : address - meta->addr,
209                        left_of_object ? "left" : "right", object_index);
210                 break;
211         }
212         case KFENCE_ERROR_UAF:
213                 pr_err("BUG: KFENCE: use-after-free %s in %pS\n\n", get_access_type(is_write),
214                        (void *)stack_entries[skipnr]);
215                 pr_err("Use-after-free %s at 0x%p (in kfence-#%zd):\n",
216                        get_access_type(is_write), (void *)address, object_index);
217                 break;
218         case KFENCE_ERROR_CORRUPTION:
219                 pr_err("BUG: KFENCE: memory corruption in %pS\n\n", (void *)stack_entries[skipnr]);
220                 pr_err("Corrupted memory at 0x%p ", (void *)address);
221                 print_diff_canary(address, 16, meta);
222                 pr_cont(" (in kfence-#%zd):\n", object_index);
223                 break;
224         case KFENCE_ERROR_INVALID:
225                 pr_err("BUG: KFENCE: invalid %s in %pS\n\n", get_access_type(is_write),
226                        (void *)stack_entries[skipnr]);
227                 pr_err("Invalid %s at 0x%p:\n", get_access_type(is_write),
228                        (void *)address);
229                 break;
230         case KFENCE_ERROR_INVALID_FREE:
231                 pr_err("BUG: KFENCE: invalid free in %pS\n\n", (void *)stack_entries[skipnr]);
232                 pr_err("Invalid free of 0x%p (in kfence-#%zd):\n", (void *)address,
233                        object_index);
234                 break;
235         }
236
237         /* Print stack trace and object info. */
238         stack_trace_print(stack_entries + skipnr, num_stack_entries - skipnr, 0);
239
240         if (meta) {
241                 pr_err("\n");
242                 kfence_print_object(NULL, meta);
243         }
244
245         /* Print report footer. */
246         pr_err("\n");
247         if (no_hash_pointers && regs)
248                 show_regs(regs);
249         else
250                 dump_stack_print_info(KERN_ERR);
251         pr_err("==================================================================\n");
252
253         lockdep_on();
254
255         if (panic_on_warn)
256                 panic("panic_on_warn set ...\n");
257
258         /* We encountered a memory unsafety error, taint the kernel! */
259         add_taint(TAINT_BAD_PAGE, LOCKDEP_STILL_OK);
260 }