blob: db01814f8ff058be151957258cacfd1a80d9edff [file] [log] [blame]
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -08001// SPDX-License-Identifier: GPL-2.0
2/*
3 * KFENCE guarded object allocator and fault handling.
4 *
5 * Copyright (C) 2020, Google LLC.
6 */
7
8#define pr_fmt(fmt) "kfence: " fmt
9
10#include <linux/atomic.h>
11#include <linux/bug.h>
12#include <linux/debugfs.h>
Marco Elver407f1d82021-05-04 18:40:21 -070013#include <linux/irq_work.h>
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -080014#include <linux/kcsan-checks.h>
15#include <linux/kfence.h>
Marco Elver95511582021-03-24 21:37:47 -070016#include <linux/kmemleak.h>
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -080017#include <linux/list.h>
18#include <linux/lockdep.h>
19#include <linux/memblock.h>
20#include <linux/moduleparam.h>
21#include <linux/random.h>
22#include <linux/rcupdate.h>
Marco Elver4bbf04a2021-09-07 19:56:21 -070023#include <linux/sched/clock.h>
Marco Elver37c92842021-05-04 18:40:24 -070024#include <linux/sched/sysctl.h>
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -080025#include <linux/seq_file.h>
26#include <linux/slab.h>
27#include <linux/spinlock.h>
28#include <linux/string.h>
29
30#include <asm/kfence.h>
31
32#include "kfence.h"
33
34/* Disables KFENCE on the first warning assuming an irrecoverable error. */
35#define KFENCE_WARN_ON(cond) \
36 ({ \
37 const bool __cond = WARN_ON(cond); \
38 if (unlikely(__cond)) \
39 WRITE_ONCE(kfence_enabled, false); \
40 __cond; \
41 })
42
43/* === Data ================================================================= */
44
45static bool kfence_enabled __read_mostly;
46
47static unsigned long kfence_sample_interval __read_mostly = CONFIG_KFENCE_SAMPLE_INTERVAL;
48
49#ifdef MODULE_PARAM_PREFIX
50#undef MODULE_PARAM_PREFIX
51#endif
52#define MODULE_PARAM_PREFIX "kfence."
53
54static int param_set_sample_interval(const char *val, const struct kernel_param *kp)
55{
56 unsigned long num;
57 int ret = kstrtoul(val, 0, &num);
58
59 if (ret < 0)
60 return ret;
61
62 if (!num) /* Using 0 to indicate KFENCE is disabled. */
63 WRITE_ONCE(kfence_enabled, false);
64 else if (!READ_ONCE(kfence_enabled) && system_state != SYSTEM_BOOTING)
65 return -EINVAL; /* Cannot (re-)enable KFENCE on-the-fly. */
66
67 *((unsigned long *)kp->arg) = num;
68 return 0;
69}
70
71static int param_get_sample_interval(char *buffer, const struct kernel_param *kp)
72{
73 if (!READ_ONCE(kfence_enabled))
74 return sprintf(buffer, "0\n");
75
76 return param_get_ulong(buffer, kp);
77}
78
79static const struct kernel_param_ops sample_interval_param_ops = {
80 .set = param_set_sample_interval,
81 .get = param_get_sample_interval,
82};
83module_param_cb(sample_interval, &sample_interval_param_ops, &kfence_sample_interval, 0600);
84
85/* The pool of pages used for guard pages and objects. */
86char *__kfence_pool __ro_after_init;
87EXPORT_SYMBOL(__kfence_pool); /* Export for test modules. */
88
89/*
90 * Per-object metadata, with one-to-one mapping of object metadata to
91 * backing pages (in __kfence_pool).
92 */
93static_assert(CONFIG_KFENCE_NUM_OBJECTS > 0);
94struct kfence_metadata kfence_metadata[CONFIG_KFENCE_NUM_OBJECTS];
95
96/* Freelist with available objects. */
97static struct list_head kfence_freelist = LIST_HEAD_INIT(kfence_freelist);
98static DEFINE_RAW_SPINLOCK(kfence_freelist_lock); /* Lock protecting freelist. */
99
100#ifdef CONFIG_KFENCE_STATIC_KEYS
101/* The static key to set up a KFENCE allocation. */
102DEFINE_STATIC_KEY_FALSE(kfence_allocation_key);
103#endif
104
105/* Gates the allocation, ensuring only one succeeds in a given period. */
106atomic_t kfence_allocation_gate = ATOMIC_INIT(1);
107
108/* Statistics counters for debugfs. */
109enum kfence_counter_id {
110 KFENCE_COUNTER_ALLOCATED,
111 KFENCE_COUNTER_ALLOCS,
112 KFENCE_COUNTER_FREES,
113 KFENCE_COUNTER_ZOMBIES,
114 KFENCE_COUNTER_BUGS,
Marco Elver9a19aeb2021-11-05 13:45:28 -0700115 KFENCE_COUNTER_SKIP_INCOMPAT,
116 KFENCE_COUNTER_SKIP_CAPACITY,
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800117 KFENCE_COUNTER_COUNT,
118};
119static atomic_long_t counters[KFENCE_COUNTER_COUNT];
120static const char *const counter_names[] = {
121 [KFENCE_COUNTER_ALLOCATED] = "currently allocated",
122 [KFENCE_COUNTER_ALLOCS] = "total allocations",
123 [KFENCE_COUNTER_FREES] = "total frees",
124 [KFENCE_COUNTER_ZOMBIES] = "zombie allocations",
125 [KFENCE_COUNTER_BUGS] = "total bugs",
Marco Elver9a19aeb2021-11-05 13:45:28 -0700126 [KFENCE_COUNTER_SKIP_INCOMPAT] = "skipped allocations (incompatible)",
127 [KFENCE_COUNTER_SKIP_CAPACITY] = "skipped allocations (capacity)",
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800128};
129static_assert(ARRAY_SIZE(counter_names) == KFENCE_COUNTER_COUNT);
130
131/* === Internals ============================================================ */
132
133static bool kfence_protect(unsigned long addr)
134{
135 return !KFENCE_WARN_ON(!kfence_protect_page(ALIGN_DOWN(addr, PAGE_SIZE), true));
136}
137
138static bool kfence_unprotect(unsigned long addr)
139{
140 return !KFENCE_WARN_ON(!kfence_protect_page(ALIGN_DOWN(addr, PAGE_SIZE), false));
141}
142
143static inline struct kfence_metadata *addr_to_metadata(unsigned long addr)
144{
145 long index;
146
147 /* The checks do not affect performance; only called from slow-paths. */
148
149 if (!is_kfence_address((void *)addr))
150 return NULL;
151
152 /*
153 * May be an invalid index if called with an address at the edge of
154 * __kfence_pool, in which case we would report an "invalid access"
155 * error.
156 */
157 index = (addr - (unsigned long)__kfence_pool) / (PAGE_SIZE * 2) - 1;
158 if (index < 0 || index >= CONFIG_KFENCE_NUM_OBJECTS)
159 return NULL;
160
161 return &kfence_metadata[index];
162}
163
164static inline unsigned long metadata_to_pageaddr(const struct kfence_metadata *meta)
165{
166 unsigned long offset = (meta - kfence_metadata + 1) * PAGE_SIZE * 2;
167 unsigned long pageaddr = (unsigned long)&__kfence_pool[offset];
168
169 /* The checks do not affect performance; only called from slow-paths. */
170
171 /* Only call with a pointer into kfence_metadata. */
172 if (KFENCE_WARN_ON(meta < kfence_metadata ||
173 meta >= kfence_metadata + CONFIG_KFENCE_NUM_OBJECTS))
174 return 0;
175
176 /*
177 * This metadata object only ever maps to 1 page; verify that the stored
178 * address is in the expected range.
179 */
180 if (KFENCE_WARN_ON(ALIGN_DOWN(meta->addr, PAGE_SIZE) != pageaddr))
181 return 0;
182
183 return pageaddr;
184}
185
186/*
187 * Update the object's metadata state, including updating the alloc/free stacks
188 * depending on the state transition.
189 */
Marco Elvera9ab52b2021-11-05 13:45:31 -0700190static noinline void
191metadata_update_state(struct kfence_metadata *meta, enum kfence_object_state next,
192 unsigned long *stack_entries, size_t num_stack_entries)
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800193{
194 struct kfence_track *track =
195 next == KFENCE_OBJECT_FREED ? &meta->free_track : &meta->alloc_track;
196
197 lockdep_assert_held(&meta->lock);
198
Marco Elvera9ab52b2021-11-05 13:45:31 -0700199 if (stack_entries) {
200 memcpy(track->stack_entries, stack_entries,
201 num_stack_entries * sizeof(stack_entries[0]));
202 } else {
203 /*
204 * Skip over 1 (this) functions; noinline ensures we do not
205 * accidentally skip over the caller by never inlining.
206 */
207 num_stack_entries = stack_trace_save(track->stack_entries, KFENCE_STACK_DEPTH, 1);
208 }
209 track->num_stack_entries = num_stack_entries;
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800210 track->pid = task_pid_nr(current);
Marco Elver4bbf04a2021-09-07 19:56:21 -0700211 track->cpu = raw_smp_processor_id();
212 track->ts_nsec = local_clock(); /* Same source as printk timestamps. */
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800213
214 /*
215 * Pairs with READ_ONCE() in
216 * kfence_shutdown_cache(),
217 * kfence_handle_page_fault().
218 */
219 WRITE_ONCE(meta->state, next);
220}
221
222/* Write canary byte to @addr. */
223static inline bool set_canary_byte(u8 *addr)
224{
225 *addr = KFENCE_CANARY_PATTERN(addr);
226 return true;
227}
228
229/* Check canary byte at @addr. */
230static inline bool check_canary_byte(u8 *addr)
231{
232 if (likely(*addr == KFENCE_CANARY_PATTERN(addr)))
233 return true;
234
235 atomic_long_inc(&counters[KFENCE_COUNTER_BUGS]);
Marco Elverbc8fbc52021-02-25 17:19:31 -0800236 kfence_report_error((unsigned long)addr, false, NULL, addr_to_metadata((unsigned long)addr),
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800237 KFENCE_ERROR_CORRUPTION);
238 return false;
239}
240
241/* __always_inline this to ensure we won't do an indirect call to fn. */
242static __always_inline void for_each_canary(const struct kfence_metadata *meta, bool (*fn)(u8 *))
243{
244 const unsigned long pageaddr = ALIGN_DOWN(meta->addr, PAGE_SIZE);
245 unsigned long addr;
246
247 lockdep_assert_held(&meta->lock);
248
249 /*
250 * We'll iterate over each canary byte per-side until fn() returns
251 * false. However, we'll still iterate over the canary bytes to the
252 * right of the object even if there was an error in the canary bytes to
253 * the left of the object. Specifically, if check_canary_byte()
254 * generates an error, showing both sides might give more clues as to
255 * what the error is about when displaying which bytes were corrupted.
256 */
257
258 /* Apply to left of object. */
259 for (addr = pageaddr; addr < meta->addr; addr++) {
260 if (!fn((u8 *)addr))
261 break;
262 }
263
264 /* Apply to right of object. */
265 for (addr = meta->addr + meta->size; addr < pageaddr + PAGE_SIZE; addr++) {
266 if (!fn((u8 *)addr))
267 break;
268 }
269}
270
Marco Elvera9ab52b2021-11-05 13:45:31 -0700271static void *kfence_guarded_alloc(struct kmem_cache *cache, size_t size, gfp_t gfp,
272 unsigned long *stack_entries, size_t num_stack_entries)
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800273{
274 struct kfence_metadata *meta = NULL;
275 unsigned long flags;
276 struct page *page;
277 void *addr;
278
279 /* Try to obtain a free object. */
280 raw_spin_lock_irqsave(&kfence_freelist_lock, flags);
281 if (!list_empty(&kfence_freelist)) {
282 meta = list_entry(kfence_freelist.next, struct kfence_metadata, list);
283 list_del_init(&meta->list);
284 }
285 raw_spin_unlock_irqrestore(&kfence_freelist_lock, flags);
Marco Elver9a19aeb2021-11-05 13:45:28 -0700286 if (!meta) {
287 atomic_long_inc(&counters[KFENCE_COUNTER_SKIP_CAPACITY]);
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800288 return NULL;
Marco Elver9a19aeb2021-11-05 13:45:28 -0700289 }
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800290
291 if (unlikely(!raw_spin_trylock_irqsave(&meta->lock, flags))) {
292 /*
293 * This is extremely unlikely -- we are reporting on a
294 * use-after-free, which locked meta->lock, and the reporting
295 * code via printk calls kmalloc() which ends up in
296 * kfence_alloc() and tries to grab the same object that we're
297 * reporting on. While it has never been observed, lockdep does
298 * report that there is a possibility of deadlock. Fix it by
299 * using trylock and bailing out gracefully.
300 */
301 raw_spin_lock_irqsave(&kfence_freelist_lock, flags);
302 /* Put the object back on the freelist. */
303 list_add_tail(&meta->list, &kfence_freelist);
304 raw_spin_unlock_irqrestore(&kfence_freelist_lock, flags);
305
306 return NULL;
307 }
308
309 meta->addr = metadata_to_pageaddr(meta);
310 /* Unprotect if we're reusing this page. */
311 if (meta->state == KFENCE_OBJECT_FREED)
312 kfence_unprotect(meta->addr);
313
314 /*
315 * Note: for allocations made before RNG initialization, will always
316 * return zero. We still benefit from enabling KFENCE as early as
317 * possible, even when the RNG is not yet available, as this will allow
318 * KFENCE to detect bugs due to earlier allocations. The only downside
319 * is that the out-of-bounds accesses detected are deterministic for
320 * such allocations.
321 */
322 if (prandom_u32_max(2)) {
323 /* Allocate on the "right" side, re-calculate address. */
324 meta->addr += PAGE_SIZE - size;
325 meta->addr = ALIGN_DOWN(meta->addr, cache->align);
326 }
327
328 addr = (void *)meta->addr;
329
330 /* Update remaining metadata. */
Marco Elvera9ab52b2021-11-05 13:45:31 -0700331 metadata_update_state(meta, KFENCE_OBJECT_ALLOCATED, stack_entries, num_stack_entries);
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800332 /* Pairs with READ_ONCE() in kfence_shutdown_cache(). */
333 WRITE_ONCE(meta->cache, cache);
334 meta->size = size;
335 for_each_canary(meta, set_canary_byte);
336
337 /* Set required struct page fields. */
338 page = virt_to_page(meta->addr);
339 page->slab_cache = cache;
Alexander Potapenkob89fb5e2021-02-25 17:19:16 -0800340 if (IS_ENABLED(CONFIG_SLUB))
341 page->objects = 1;
Alexander Potapenkod3fb45f2021-02-25 17:19:11 -0800342 if (IS_ENABLED(CONFIG_SLAB))
343 page->s_mem = addr;
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800344
345 raw_spin_unlock_irqrestore(&meta->lock, flags);
346
347 /* Memory initialization. */
348
349 /*
350 * We check slab_want_init_on_alloc() ourselves, rather than letting
351 * SL*B do the initialization, as otherwise we might overwrite KFENCE's
352 * redzone.
353 */
354 if (unlikely(slab_want_init_on_alloc(gfp, cache)))
355 memzero_explicit(addr, size);
356 if (cache->ctor)
357 cache->ctor(addr);
358
359 if (CONFIG_KFENCE_STRESS_TEST_FAULTS && !prandom_u32_max(CONFIG_KFENCE_STRESS_TEST_FAULTS))
360 kfence_protect(meta->addr); /* Random "faults" by protecting the object. */
361
362 atomic_long_inc(&counters[KFENCE_COUNTER_ALLOCATED]);
363 atomic_long_inc(&counters[KFENCE_COUNTER_ALLOCS]);
364
365 return addr;
366}
367
368static void kfence_guarded_free(void *addr, struct kfence_metadata *meta, bool zombie)
369{
370 struct kcsan_scoped_access assert_page_exclusive;
371 unsigned long flags;
372
373 raw_spin_lock_irqsave(&meta->lock, flags);
374
375 if (meta->state != KFENCE_OBJECT_ALLOCATED || meta->addr != (unsigned long)addr) {
376 /* Invalid or double-free, bail out. */
377 atomic_long_inc(&counters[KFENCE_COUNTER_BUGS]);
Marco Elverbc8fbc52021-02-25 17:19:31 -0800378 kfence_report_error((unsigned long)addr, false, NULL, meta,
379 KFENCE_ERROR_INVALID_FREE);
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800380 raw_spin_unlock_irqrestore(&meta->lock, flags);
381 return;
382 }
383
384 /* Detect racy use-after-free, or incorrect reallocation of this page by KFENCE. */
385 kcsan_begin_scoped_access((void *)ALIGN_DOWN((unsigned long)addr, PAGE_SIZE), PAGE_SIZE,
386 KCSAN_ACCESS_SCOPED | KCSAN_ACCESS_WRITE | KCSAN_ACCESS_ASSERT,
387 &assert_page_exclusive);
388
389 if (CONFIG_KFENCE_STRESS_TEST_FAULTS)
390 kfence_unprotect((unsigned long)addr); /* To check canary bytes. */
391
392 /* Restore page protection if there was an OOB access. */
393 if (meta->unprotected_page) {
Marco Elver94868a12021-05-04 18:40:18 -0700394 memzero_explicit((void *)ALIGN_DOWN(meta->unprotected_page, PAGE_SIZE), PAGE_SIZE);
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800395 kfence_protect(meta->unprotected_page);
396 meta->unprotected_page = 0;
397 }
398
399 /* Check canary bytes for memory corruption. */
400 for_each_canary(meta, check_canary_byte);
401
402 /*
403 * Clear memory if init-on-free is set. While we protect the page, the
404 * data is still there, and after a use-after-free is detected, we
405 * unprotect the page, so the data is still accessible.
406 */
407 if (!zombie && unlikely(slab_want_init_on_free(meta->cache)))
408 memzero_explicit(addr, meta->size);
409
410 /* Mark the object as freed. */
Marco Elvera9ab52b2021-11-05 13:45:31 -0700411 metadata_update_state(meta, KFENCE_OBJECT_FREED, NULL, 0);
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800412
413 raw_spin_unlock_irqrestore(&meta->lock, flags);
414
415 /* Protect to detect use-after-frees. */
416 kfence_protect((unsigned long)addr);
417
418 kcsan_end_scoped_access(&assert_page_exclusive);
419 if (!zombie) {
420 /* Add it to the tail of the freelist for reuse. */
421 raw_spin_lock_irqsave(&kfence_freelist_lock, flags);
422 KFENCE_WARN_ON(!list_empty(&meta->list));
423 list_add_tail(&meta->list, &kfence_freelist);
424 raw_spin_unlock_irqrestore(&kfence_freelist_lock, flags);
425
426 atomic_long_dec(&counters[KFENCE_COUNTER_ALLOCATED]);
427 atomic_long_inc(&counters[KFENCE_COUNTER_FREES]);
428 } else {
429 /* See kfence_shutdown_cache(). */
430 atomic_long_inc(&counters[KFENCE_COUNTER_ZOMBIES]);
431 }
432}
433
434static void rcu_guarded_free(struct rcu_head *h)
435{
436 struct kfence_metadata *meta = container_of(h, struct kfence_metadata, rcu_head);
437
438 kfence_guarded_free((void *)meta->addr, meta, false);
439}
440
441static bool __init kfence_init_pool(void)
442{
443 unsigned long addr = (unsigned long)__kfence_pool;
444 struct page *pages;
445 int i;
446
447 if (!__kfence_pool)
448 return false;
449
450 if (!arch_kfence_init_pool())
451 goto err;
452
453 pages = virt_to_page(addr);
454
455 /*
456 * Set up object pages: they must have PG_slab set, to avoid freeing
457 * these as real pages.
458 *
459 * We also want to avoid inserting kfence_free() in the kfree()
460 * fast-path in SLUB, and therefore need to ensure kfree() correctly
461 * enters __slab_free() slow-path.
462 */
463 for (i = 0; i < KFENCE_POOL_SIZE / PAGE_SIZE; i++) {
464 if (!i || (i % 2))
465 continue;
466
467 /* Verify we do not have a compound head page. */
468 if (WARN_ON(compound_head(&pages[i]) != &pages[i]))
469 goto err;
470
471 __SetPageSlab(&pages[i]);
472 }
473
474 /*
475 * Protect the first 2 pages. The first page is mostly unnecessary, and
476 * merely serves as an extended guard page. However, adding one
477 * additional page in the beginning gives us an even number of pages,
478 * which simplifies the mapping of address to metadata index.
479 */
480 for (i = 0; i < 2; i++) {
481 if (unlikely(!kfence_protect(addr)))
482 goto err;
483
484 addr += PAGE_SIZE;
485 }
486
487 for (i = 0; i < CONFIG_KFENCE_NUM_OBJECTS; i++) {
488 struct kfence_metadata *meta = &kfence_metadata[i];
489
490 /* Initialize metadata. */
491 INIT_LIST_HEAD(&meta->list);
492 raw_spin_lock_init(&meta->lock);
493 meta->state = KFENCE_OBJECT_UNUSED;
494 meta->addr = addr; /* Initialize for validation in metadata_to_pageaddr(). */
495 list_add_tail(&meta->list, &kfence_freelist);
496
497 /* Protect the right redzone. */
498 if (unlikely(!kfence_protect(addr + PAGE_SIZE)))
499 goto err;
500
501 addr += 2 * PAGE_SIZE;
502 }
503
Marco Elver95511582021-03-24 21:37:47 -0700504 /*
505 * The pool is live and will never be deallocated from this point on.
506 * Remove the pool object from the kmemleak object tree, as it would
507 * otherwise overlap with allocations returned by kfence_alloc(), which
508 * are registered with kmemleak through the slab post-alloc hook.
509 */
510 kmemleak_free(__kfence_pool);
511
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800512 return true;
513
514err:
515 /*
516 * Only release unprotected pages, and do not try to go back and change
517 * page attributes due to risk of failing to do so as well. If changing
518 * page attributes for some pages fails, it is very likely that it also
519 * fails for the first page, and therefore expect addr==__kfence_pool in
520 * most failure cases.
521 */
522 memblock_free_late(__pa(addr), KFENCE_POOL_SIZE - (addr - (unsigned long)__kfence_pool));
523 __kfence_pool = NULL;
524 return false;
525}
526
527/* === DebugFS Interface ==================================================== */
528
529static int stats_show(struct seq_file *seq, void *v)
530{
531 int i;
532
533 seq_printf(seq, "enabled: %i\n", READ_ONCE(kfence_enabled));
534 for (i = 0; i < KFENCE_COUNTER_COUNT; i++)
535 seq_printf(seq, "%s: %ld\n", counter_names[i], atomic_long_read(&counters[i]));
536
537 return 0;
538}
539DEFINE_SHOW_ATTRIBUTE(stats);
540
541/*
542 * debugfs seq_file operations for /sys/kernel/debug/kfence/objects.
543 * start_object() and next_object() return the object index + 1, because NULL is used
544 * to stop iteration.
545 */
546static void *start_object(struct seq_file *seq, loff_t *pos)
547{
548 if (*pos < CONFIG_KFENCE_NUM_OBJECTS)
549 return (void *)((long)*pos + 1);
550 return NULL;
551}
552
553static void stop_object(struct seq_file *seq, void *v)
554{
555}
556
557static void *next_object(struct seq_file *seq, void *v, loff_t *pos)
558{
559 ++*pos;
560 if (*pos < CONFIG_KFENCE_NUM_OBJECTS)
561 return (void *)((long)*pos + 1);
562 return NULL;
563}
564
565static int show_object(struct seq_file *seq, void *v)
566{
567 struct kfence_metadata *meta = &kfence_metadata[(long)v - 1];
568 unsigned long flags;
569
570 raw_spin_lock_irqsave(&meta->lock, flags);
571 kfence_print_object(seq, meta);
572 raw_spin_unlock_irqrestore(&meta->lock, flags);
573 seq_puts(seq, "---------------------------------\n");
574
575 return 0;
576}
577
578static const struct seq_operations object_seqops = {
579 .start = start_object,
580 .next = next_object,
581 .stop = stop_object,
582 .show = show_object,
583};
584
585static int open_objects(struct inode *inode, struct file *file)
586{
587 return seq_open(file, &object_seqops);
588}
589
590static const struct file_operations objects_fops = {
591 .open = open_objects,
592 .read = seq_read,
593 .llseek = seq_lseek,
594};
595
596static int __init kfence_debugfs_init(void)
597{
598 struct dentry *kfence_dir = debugfs_create_dir("kfence", NULL);
599
600 debugfs_create_file("stats", 0444, kfence_dir, NULL, &stats_fops);
601 debugfs_create_file("objects", 0400, kfence_dir, NULL, &objects_fops);
602 return 0;
603}
604
605late_initcall(kfence_debugfs_init);
606
607/* === Allocation Gate Timer ================================================ */
608
Marco Elver407f1d82021-05-04 18:40:21 -0700609#ifdef CONFIG_KFENCE_STATIC_KEYS
610/* Wait queue to wake up allocation-gate timer task. */
611static DECLARE_WAIT_QUEUE_HEAD(allocation_wait);
612
613static void wake_up_kfence_timer(struct irq_work *work)
614{
615 wake_up(&allocation_wait);
616}
617static DEFINE_IRQ_WORK(wake_up_kfence_timer_work, wake_up_kfence_timer);
618#endif
619
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800620/*
621 * Set up delayed work, which will enable and disable the static key. We need to
622 * use a work queue (rather than a simple timer), since enabling and disabling a
623 * static key cannot be done from an interrupt.
624 *
625 * Note: Toggling a static branch currently causes IPIs, and here we'll end up
626 * with a total of 2 IPIs to all CPUs. If this ends up a problem in future (with
627 * more aggressive sampling intervals), we could get away with a variant that
628 * avoids IPIs, at the cost of not immediately capturing allocations if the
629 * instructions remain cached.
630 */
631static struct delayed_work kfence_timer;
632static void toggle_allocation_gate(struct work_struct *work)
633{
634 if (!READ_ONCE(kfence_enabled))
635 return;
636
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800637 atomic_set(&kfence_allocation_gate, 0);
638#ifdef CONFIG_KFENCE_STATIC_KEYS
Marco Elver407f1d82021-05-04 18:40:21 -0700639 /* Enable static key, and await allocation to happen. */
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800640 static_branch_enable(&kfence_allocation_key);
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800641
Marco Elver37c92842021-05-04 18:40:24 -0700642 if (sysctl_hung_task_timeout_secs) {
643 /*
644 * During low activity with no allocations we might wait a
645 * while; let's avoid the hung task warning.
646 */
Marco Elver8fd0e992021-06-04 20:01:11 -0700647 wait_event_idle_timeout(allocation_wait, atomic_read(&kfence_allocation_gate),
648 sysctl_hung_task_timeout_secs * HZ / 2);
Marco Elver37c92842021-05-04 18:40:24 -0700649 } else {
Marco Elver8fd0e992021-06-04 20:01:11 -0700650 wait_event_idle(allocation_wait, atomic_read(&kfence_allocation_gate));
Marco Elver37c92842021-05-04 18:40:24 -0700651 }
Marco Elver407f1d82021-05-04 18:40:21 -0700652
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800653 /* Disable static key and reset timer. */
654 static_branch_disable(&kfence_allocation_key);
655#endif
Marco Elverff06e452021-06-30 18:54:03 -0700656 queue_delayed_work(system_unbound_wq, &kfence_timer,
Marco Elver36f0b352021-05-04 18:40:27 -0700657 msecs_to_jiffies(kfence_sample_interval));
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800658}
659static DECLARE_DELAYED_WORK(kfence_timer, toggle_allocation_gate);
660
661/* === Public interface ===================================================== */
662
663void __init kfence_alloc_pool(void)
664{
665 if (!kfence_sample_interval)
666 return;
667
668 __kfence_pool = memblock_alloc(KFENCE_POOL_SIZE, PAGE_SIZE);
669
670 if (!__kfence_pool)
671 pr_err("failed to allocate pool\n");
672}
673
674void __init kfence_init(void)
675{
676 /* Setting kfence_sample_interval to 0 on boot disables KFENCE. */
677 if (!kfence_sample_interval)
678 return;
679
680 if (!kfence_init_pool()) {
681 pr_err("%s failed\n", __func__);
682 return;
683 }
684
685 WRITE_ONCE(kfence_enabled, true);
Marco Elverff06e452021-06-30 18:54:03 -0700686 queue_delayed_work(system_unbound_wq, &kfence_timer, 0);
Marco Elver35beccf2021-02-25 17:19:40 -0800687 pr_info("initialized - using %lu bytes for %d objects at 0x%p-0x%p\n", KFENCE_POOL_SIZE,
688 CONFIG_KFENCE_NUM_OBJECTS, (void *)__kfence_pool,
689 (void *)(__kfence_pool + KFENCE_POOL_SIZE));
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800690}
691
692void kfence_shutdown_cache(struct kmem_cache *s)
693{
694 unsigned long flags;
695 struct kfence_metadata *meta;
696 int i;
697
698 for (i = 0; i < CONFIG_KFENCE_NUM_OBJECTS; i++) {
699 bool in_use;
700
701 meta = &kfence_metadata[i];
702
703 /*
704 * If we observe some inconsistent cache and state pair where we
705 * should have returned false here, cache destruction is racing
706 * with either kmem_cache_alloc() or kmem_cache_free(). Taking
707 * the lock will not help, as different critical section
708 * serialization will have the same outcome.
709 */
710 if (READ_ONCE(meta->cache) != s ||
711 READ_ONCE(meta->state) != KFENCE_OBJECT_ALLOCATED)
712 continue;
713
714 raw_spin_lock_irqsave(&meta->lock, flags);
715 in_use = meta->cache == s && meta->state == KFENCE_OBJECT_ALLOCATED;
716 raw_spin_unlock_irqrestore(&meta->lock, flags);
717
718 if (in_use) {
719 /*
720 * This cache still has allocations, and we should not
721 * release them back into the freelist so they can still
722 * safely be used and retain the kernel's default
723 * behaviour of keeping the allocations alive (leak the
724 * cache); however, they effectively become "zombie
725 * allocations" as the KFENCE objects are the only ones
726 * still in use and the owning cache is being destroyed.
727 *
728 * We mark them freed, so that any subsequent use shows
729 * more useful error messages that will include stack
730 * traces of the user of the object, the original
731 * allocation, and caller to shutdown_cache().
732 */
733 kfence_guarded_free((void *)meta->addr, meta, /*zombie=*/true);
734 }
735 }
736
737 for (i = 0; i < CONFIG_KFENCE_NUM_OBJECTS; i++) {
738 meta = &kfence_metadata[i];
739
740 /* See above. */
741 if (READ_ONCE(meta->cache) != s || READ_ONCE(meta->state) != KFENCE_OBJECT_FREED)
742 continue;
743
744 raw_spin_lock_irqsave(&meta->lock, flags);
745 if (meta->cache == s && meta->state == KFENCE_OBJECT_FREED)
746 meta->cache = NULL;
747 raw_spin_unlock_irqrestore(&meta->lock, flags);
748 }
749}
750
751void *__kfence_alloc(struct kmem_cache *s, size_t size, gfp_t flags)
752{
Marco Elvera9ab52b2021-11-05 13:45:31 -0700753 unsigned long stack_entries[KFENCE_STACK_DEPTH];
754 size_t num_stack_entries;
755
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800756 /*
Alexander Potapenko235a85c2021-07-23 15:50:11 -0700757 * Perform size check before switching kfence_allocation_gate, so that
758 * we don't disable KFENCE without making an allocation.
759 */
Marco Elver9a19aeb2021-11-05 13:45:28 -0700760 if (size > PAGE_SIZE) {
761 atomic_long_inc(&counters[KFENCE_COUNTER_SKIP_INCOMPAT]);
Alexander Potapenko235a85c2021-07-23 15:50:11 -0700762 return NULL;
Marco Elver9a19aeb2021-11-05 13:45:28 -0700763 }
Alexander Potapenko235a85c2021-07-23 15:50:11 -0700764
765 /*
Alexander Potapenko236e9f12021-07-23 15:50:14 -0700766 * Skip allocations from non-default zones, including DMA. We cannot
767 * guarantee that pages in the KFENCE pool will have the requested
768 * properties (e.g. reside in DMAable memory).
769 */
770 if ((flags & GFP_ZONEMASK) ||
Marco Elver9a19aeb2021-11-05 13:45:28 -0700771 (s->flags & (SLAB_CACHE_DMA | SLAB_CACHE_DMA32))) {
772 atomic_long_inc(&counters[KFENCE_COUNTER_SKIP_INCOMPAT]);
Alexander Potapenko236e9f12021-07-23 15:50:14 -0700773 return NULL;
Marco Elver9a19aeb2021-11-05 13:45:28 -0700774 }
Alexander Potapenko236e9f12021-07-23 15:50:14 -0700775
776 /*
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800777 * allocation_gate only needs to become non-zero, so it doesn't make
778 * sense to continue writing to it and pay the associated contention
779 * cost, in case we have a large number of concurrent allocations.
780 */
781 if (atomic_read(&kfence_allocation_gate) || atomic_inc_return(&kfence_allocation_gate) > 1)
782 return NULL;
Marco Elver407f1d82021-05-04 18:40:21 -0700783#ifdef CONFIG_KFENCE_STATIC_KEYS
784 /*
785 * waitqueue_active() is fully ordered after the update of
786 * kfence_allocation_gate per atomic_inc_return().
787 */
788 if (waitqueue_active(&allocation_wait)) {
789 /*
790 * Calling wake_up() here may deadlock when allocations happen
791 * from within timer code. Use an irq_work to defer it.
792 */
793 irq_work_queue(&wake_up_kfence_timer_work);
794 }
795#endif
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800796
797 if (!READ_ONCE(kfence_enabled))
798 return NULL;
799
Marco Elvera9ab52b2021-11-05 13:45:31 -0700800 num_stack_entries = stack_trace_save(stack_entries, KFENCE_STACK_DEPTH, 0);
801
802 return kfence_guarded_alloc(s, size, flags, stack_entries, num_stack_entries);
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800803}
804
805size_t kfence_ksize(const void *addr)
806{
807 const struct kfence_metadata *meta = addr_to_metadata((unsigned long)addr);
808
809 /*
810 * Read locklessly -- if there is a race with __kfence_alloc(), this is
811 * either a use-after-free or invalid access.
812 */
813 return meta ? meta->size : 0;
814}
815
816void *kfence_object_start(const void *addr)
817{
818 const struct kfence_metadata *meta = addr_to_metadata((unsigned long)addr);
819
820 /*
821 * Read locklessly -- if there is a race with __kfence_alloc(), this is
822 * either a use-after-free or invalid access.
823 */
824 return meta ? (void *)meta->addr : NULL;
825}
826
827void __kfence_free(void *addr)
828{
829 struct kfence_metadata *meta = addr_to_metadata((unsigned long)addr);
830
831 /*
832 * If the objects of the cache are SLAB_TYPESAFE_BY_RCU, defer freeing
833 * the object, as the object page may be recycled for other-typed
834 * objects once it has been freed. meta->cache may be NULL if the cache
835 * was destroyed.
836 */
837 if (unlikely(meta->cache && (meta->cache->flags & SLAB_TYPESAFE_BY_RCU)))
838 call_rcu(&meta->rcu_head, rcu_guarded_free);
839 else
840 kfence_guarded_free(addr, meta, false);
841}
842
Marco Elverbc8fbc52021-02-25 17:19:31 -0800843bool kfence_handle_page_fault(unsigned long addr, bool is_write, struct pt_regs *regs)
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800844{
845 const int page_index = (addr - (unsigned long)__kfence_pool) / PAGE_SIZE;
846 struct kfence_metadata *to_report = NULL;
847 enum kfence_error_type error_type;
848 unsigned long flags;
849
850 if (!is_kfence_address((void *)addr))
851 return false;
852
853 if (!READ_ONCE(kfence_enabled)) /* If disabled at runtime ... */
854 return kfence_unprotect(addr); /* ... unprotect and proceed. */
855
856 atomic_long_inc(&counters[KFENCE_COUNTER_BUGS]);
857
858 if (page_index % 2) {
859 /* This is a redzone, report a buffer overflow. */
860 struct kfence_metadata *meta;
861 int distance = 0;
862
863 meta = addr_to_metadata(addr - PAGE_SIZE);
864 if (meta && READ_ONCE(meta->state) == KFENCE_OBJECT_ALLOCATED) {
865 to_report = meta;
866 /* Data race ok; distance calculation approximate. */
867 distance = addr - data_race(meta->addr + meta->size);
868 }
869
870 meta = addr_to_metadata(addr + PAGE_SIZE);
871 if (meta && READ_ONCE(meta->state) == KFENCE_OBJECT_ALLOCATED) {
872 /* Data race ok; distance calculation approximate. */
873 if (!to_report || distance > data_race(meta->addr) - addr)
874 to_report = meta;
875 }
876
877 if (!to_report)
878 goto out;
879
880 raw_spin_lock_irqsave(&to_report->lock, flags);
881 to_report->unprotected_page = addr;
882 error_type = KFENCE_ERROR_OOB;
883
884 /*
885 * If the object was freed before we took the look we can still
886 * report this as an OOB -- the report will simply show the
887 * stacktrace of the free as well.
888 */
889 } else {
890 to_report = addr_to_metadata(addr);
891 if (!to_report)
892 goto out;
893
894 raw_spin_lock_irqsave(&to_report->lock, flags);
895 error_type = KFENCE_ERROR_UAF;
896 /*
897 * We may race with __kfence_alloc(), and it is possible that a
898 * freed object may be reallocated. We simply report this as a
899 * use-after-free, with the stack trace showing the place where
900 * the object was re-allocated.
901 */
902 }
903
904out:
905 if (to_report) {
Marco Elverbc8fbc52021-02-25 17:19:31 -0800906 kfence_report_error(addr, is_write, regs, to_report, error_type);
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800907 raw_spin_unlock_irqrestore(&to_report->lock, flags);
908 } else {
909 /* This may be a UAF or OOB access, but we can't be sure. */
Marco Elverbc8fbc52021-02-25 17:19:31 -0800910 kfence_report_error(addr, is_write, regs, NULL, KFENCE_ERROR_INVALID);
Alexander Potapenko0ce20dd2021-02-25 17:18:53 -0800911 }
912
913 return kfence_unprotect(addr); /* Unprotect and let access proceed. */
914}