core.c 26 KB

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