core.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  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/hash.h>
  12. #include <linux/irq_work.h>
  13. #include <linux/jhash.h>
  14. #include <linux/kcsan-checks.h>
  15. #include <linux/kfence.h>
  16. #include <linux/kmemleak.h>
  17. #include <linux/list.h>
  18. #include <linux/lockdep.h>
  19. #include <linux/log2.h>
  20. #include <linux/memblock.h>
  21. #include <linux/moduleparam.h>
  22. #include <linux/notifier.h>
  23. #include <linux/panic_notifier.h>
  24. #include <linux/random.h>
  25. #include <linux/rcupdate.h>
  26. #include <linux/sched/clock.h>
  27. #include <linux/sched/sysctl.h>
  28. #include <linux/seq_file.h>
  29. #include <linux/slab.h>
  30. #include <linux/spinlock.h>
  31. #include <linux/string.h>
  32. #include <asm/kfence.h>
  33. #include "kfence.h"
  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. disabled_by_warn = true; \
  41. } \
  42. __cond; \
  43. })
  44. /* === Data ================================================================= */
  45. static bool kfence_enabled __read_mostly;
  46. static bool disabled_by_warn __read_mostly;
  47. unsigned long kfence_sample_interval __read_mostly = CONFIG_KFENCE_SAMPLE_INTERVAL;
  48. EXPORT_SYMBOL_GPL(kfence_sample_interval); /* Export for test modules. */
  49. #ifdef MODULE_PARAM_PREFIX
  50. #undef MODULE_PARAM_PREFIX
  51. #endif
  52. #define MODULE_PARAM_PREFIX "kfence."
  53. static int kfence_enable_late(void);
  54. static 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. if (ret < 0)
  59. return ret;
  60. /* Using 0 to indicate KFENCE is disabled. */
  61. if (!num && READ_ONCE(kfence_enabled)) {
  62. pr_info("disabled\n");
  63. WRITE_ONCE(kfence_enabled, false);
  64. }
  65. *((unsigned long *)kp->arg) = num;
  66. if (num && !READ_ONCE(kfence_enabled) && system_state != SYSTEM_BOOTING)
  67. return disabled_by_warn ? -EINVAL : kfence_enable_late();
  68. return 0;
  69. }
  70. static int param_get_sample_interval(char *buffer, const struct kernel_param *kp)
  71. {
  72. if (!READ_ONCE(kfence_enabled))
  73. return sprintf(buffer, "0\n");
  74. return param_get_ulong(buffer, kp);
  75. }
  76. static const struct kernel_param_ops sample_interval_param_ops = {
  77. .set = param_set_sample_interval,
  78. .get = param_get_sample_interval,
  79. };
  80. module_param_cb(sample_interval, &sample_interval_param_ops, &kfence_sample_interval, 0600);
  81. /* Pool usage% threshold when currently covered allocations are skipped. */
  82. static unsigned long kfence_skip_covered_thresh __read_mostly = 75;
  83. module_param_named(skip_covered_thresh, kfence_skip_covered_thresh, ulong, 0644);
  84. /* If true, use a deferrable timer. */
  85. static bool kfence_deferrable __read_mostly = IS_ENABLED(CONFIG_KFENCE_DEFERRABLE);
  86. module_param_named(deferrable, kfence_deferrable, bool, 0444);
  87. /* If true, check all canary bytes on panic. */
  88. static bool kfence_check_on_panic __read_mostly;
  89. module_param_named(check_on_panic, kfence_check_on_panic, bool, 0444);
  90. /* The pool of pages used for guard pages and objects. */
  91. char *__kfence_pool __read_mostly;
  92. EXPORT_SYMBOL(__kfence_pool); /* Export for test modules. */
  93. /*
  94. * Per-object metadata, with one-to-one mapping of object metadata to
  95. * backing pages (in __kfence_pool).
  96. */
  97. static_assert(CONFIG_KFENCE_NUM_OBJECTS > 0);
  98. struct kfence_metadata kfence_metadata[CONFIG_KFENCE_NUM_OBJECTS];
  99. /* Freelist with available objects. */
  100. static struct list_head kfence_freelist = LIST_HEAD_INIT(kfence_freelist);
  101. static DEFINE_RAW_SPINLOCK(kfence_freelist_lock); /* Lock protecting freelist. */
  102. /*
  103. * The static key to set up a KFENCE allocation; or if static keys are not used
  104. * to gate allocations, to avoid a load and compare if KFENCE is disabled.
  105. */
  106. DEFINE_STATIC_KEY_FALSE(kfence_allocation_key);
  107. /* Gates the allocation, ensuring only one succeeds in a given period. */
  108. atomic_t kfence_allocation_gate = ATOMIC_INIT(1);
  109. /*
  110. * A Counting Bloom filter of allocation coverage: limits currently covered
  111. * allocations of the same source filling up the pool.
  112. *
  113. * Assuming a range of 15%-85% unique allocations in the pool at any point in
  114. * time, the below parameters provide a probablity of 0.02-0.33 for false
  115. * positive hits respectively:
  116. *
  117. * P(alloc_traces) = (1 - e^(-HNUM * (alloc_traces / SIZE)) ^ HNUM
  118. */
  119. #define ALLOC_COVERED_HNUM 2
  120. #define ALLOC_COVERED_ORDER (const_ilog2(CONFIG_KFENCE_NUM_OBJECTS) + 2)
  121. #define ALLOC_COVERED_SIZE (1 << ALLOC_COVERED_ORDER)
  122. #define ALLOC_COVERED_HNEXT(h) hash_32(h, ALLOC_COVERED_ORDER)
  123. #define ALLOC_COVERED_MASK (ALLOC_COVERED_SIZE - 1)
  124. static atomic_t alloc_covered[ALLOC_COVERED_SIZE];
  125. /* Stack depth used to determine uniqueness of an allocation. */
  126. #define UNIQUE_ALLOC_STACK_DEPTH ((size_t)8)
  127. /*
  128. * Randomness for stack hashes, making the same collisions across reboots and
  129. * different machines less likely.
  130. */
  131. static u32 stack_hash_seed __ro_after_init;
  132. /* Statistics counters for debugfs. */
  133. enum kfence_counter_id {
  134. KFENCE_COUNTER_ALLOCATED,
  135. KFENCE_COUNTER_ALLOCS,
  136. KFENCE_COUNTER_FREES,
  137. KFENCE_COUNTER_ZOMBIES,
  138. KFENCE_COUNTER_BUGS,
  139. KFENCE_COUNTER_SKIP_INCOMPAT,
  140. KFENCE_COUNTER_SKIP_CAPACITY,
  141. KFENCE_COUNTER_SKIP_COVERED,
  142. KFENCE_COUNTER_COUNT,
  143. };
  144. static atomic_long_t counters[KFENCE_COUNTER_COUNT];
  145. static const char *const counter_names[] = {
  146. [KFENCE_COUNTER_ALLOCATED] = "currently allocated",
  147. [KFENCE_COUNTER_ALLOCS] = "total allocations",
  148. [KFENCE_COUNTER_FREES] = "total frees",
  149. [KFENCE_COUNTER_ZOMBIES] = "zombie allocations",
  150. [KFENCE_COUNTER_BUGS] = "total bugs",
  151. [KFENCE_COUNTER_SKIP_INCOMPAT] = "skipped allocations (incompatible)",
  152. [KFENCE_COUNTER_SKIP_CAPACITY] = "skipped allocations (capacity)",
  153. [KFENCE_COUNTER_SKIP_COVERED] = "skipped allocations (covered)",
  154. };
  155. static_assert(ARRAY_SIZE(counter_names) == KFENCE_COUNTER_COUNT);
  156. /* === Internals ============================================================ */
  157. static inline bool should_skip_covered(void)
  158. {
  159. unsigned long thresh = (CONFIG_KFENCE_NUM_OBJECTS * kfence_skip_covered_thresh) / 100;
  160. return atomic_long_read(&counters[KFENCE_COUNTER_ALLOCATED]) > thresh;
  161. }
  162. static u32 get_alloc_stack_hash(unsigned long *stack_entries, size_t num_entries)
  163. {
  164. num_entries = min(num_entries, UNIQUE_ALLOC_STACK_DEPTH);
  165. num_entries = filter_irq_stacks(stack_entries, num_entries);
  166. return jhash(stack_entries, num_entries * sizeof(stack_entries[0]), stack_hash_seed);
  167. }
  168. /*
  169. * Adds (or subtracts) count @val for allocation stack trace hash
  170. * @alloc_stack_hash from Counting Bloom filter.
  171. */
  172. static void alloc_covered_add(u32 alloc_stack_hash, int val)
  173. {
  174. int i;
  175. for (i = 0; i < ALLOC_COVERED_HNUM; i++) {
  176. atomic_add(val, &alloc_covered[alloc_stack_hash & ALLOC_COVERED_MASK]);
  177. alloc_stack_hash = ALLOC_COVERED_HNEXT(alloc_stack_hash);
  178. }
  179. }
  180. /*
  181. * Returns true if the allocation stack trace hash @alloc_stack_hash is
  182. * currently contained (non-zero count) in Counting Bloom filter.
  183. */
  184. static bool alloc_covered_contains(u32 alloc_stack_hash)
  185. {
  186. int i;
  187. for (i = 0; i < ALLOC_COVERED_HNUM; i++) {
  188. if (!atomic_read(&alloc_covered[alloc_stack_hash & ALLOC_COVERED_MASK]))
  189. return false;
  190. alloc_stack_hash = ALLOC_COVERED_HNEXT(alloc_stack_hash);
  191. }
  192. return true;
  193. }
  194. static bool kfence_protect(unsigned long addr)
  195. {
  196. return !KFENCE_WARN_ON(!kfence_protect_page(ALIGN_DOWN(addr, PAGE_SIZE), true));
  197. }
  198. static bool kfence_unprotect(unsigned long addr)
  199. {
  200. return !KFENCE_WARN_ON(!kfence_protect_page(ALIGN_DOWN(addr, PAGE_SIZE), false));
  201. }
  202. static inline unsigned long metadata_to_pageaddr(const struct kfence_metadata *meta)
  203. {
  204. unsigned long offset = (meta - kfence_metadata + 1) * PAGE_SIZE * 2;
  205. unsigned long pageaddr = (unsigned long)&__kfence_pool[offset];
  206. /* The checks do not affect performance; only called from slow-paths. */
  207. /* Only call with a pointer into kfence_metadata. */
  208. if (KFENCE_WARN_ON(meta < kfence_metadata ||
  209. meta >= kfence_metadata + CONFIG_KFENCE_NUM_OBJECTS))
  210. return 0;
  211. /*
  212. * This metadata object only ever maps to 1 page; verify that the stored
  213. * address is in the expected range.
  214. */
  215. if (KFENCE_WARN_ON(ALIGN_DOWN(meta->addr, PAGE_SIZE) != pageaddr))
  216. return 0;
  217. return pageaddr;
  218. }
  219. /*
  220. * Update the object's metadata state, including updating the alloc/free stacks
  221. * depending on the state transition.
  222. */
  223. static noinline void
  224. metadata_update_state(struct kfence_metadata *meta, enum kfence_object_state next,
  225. unsigned long *stack_entries, size_t num_stack_entries)
  226. {
  227. struct kfence_track *track =
  228. next == KFENCE_OBJECT_FREED ? &meta->free_track : &meta->alloc_track;
  229. lockdep_assert_held(&meta->lock);
  230. if (stack_entries) {
  231. memcpy(track->stack_entries, stack_entries,
  232. num_stack_entries * sizeof(stack_entries[0]));
  233. } else {
  234. /*
  235. * Skip over 1 (this) functions; noinline ensures we do not
  236. * accidentally skip over the caller by never inlining.
  237. */
  238. num_stack_entries = stack_trace_save(track->stack_entries, KFENCE_STACK_DEPTH, 1);
  239. }
  240. track->num_stack_entries = num_stack_entries;
  241. track->pid = task_pid_nr(current);
  242. track->cpu = raw_smp_processor_id();
  243. track->ts_nsec = local_clock(); /* Same source as printk timestamps. */
  244. /*
  245. * Pairs with READ_ONCE() in
  246. * kfence_shutdown_cache(),
  247. * kfence_handle_page_fault().
  248. */
  249. WRITE_ONCE(meta->state, next);
  250. }
  251. /* Write canary byte to @addr. */
  252. static inline bool set_canary_byte(u8 *addr)
  253. {
  254. *addr = KFENCE_CANARY_PATTERN(addr);
  255. return true;
  256. }
  257. /* Check canary byte at @addr. */
  258. static inline bool check_canary_byte(u8 *addr)
  259. {
  260. struct kfence_metadata *meta;
  261. unsigned long flags;
  262. if (likely(*addr == KFENCE_CANARY_PATTERN(addr)))
  263. return true;
  264. atomic_long_inc(&counters[KFENCE_COUNTER_BUGS]);
  265. meta = addr_to_metadata((unsigned long)addr);
  266. raw_spin_lock_irqsave(&meta->lock, flags);
  267. kfence_report_error((unsigned long)addr, false, NULL, meta, KFENCE_ERROR_CORRUPTION);
  268. raw_spin_unlock_irqrestore(&meta->lock, flags);
  269. return false;
  270. }
  271. /* __always_inline this to ensure we won't do an indirect call to fn. */
  272. static __always_inline void for_each_canary(const struct kfence_metadata *meta, bool (*fn)(u8 *))
  273. {
  274. const unsigned long pageaddr = ALIGN_DOWN(meta->addr, PAGE_SIZE);
  275. unsigned long addr;
  276. /*
  277. * We'll iterate over each canary byte per-side until fn() returns
  278. * false. However, we'll still iterate over the canary bytes to the
  279. * right of the object even if there was an error in the canary bytes to
  280. * the left of the object. Specifically, if check_canary_byte()
  281. * generates an error, showing both sides might give more clues as to
  282. * what the error is about when displaying which bytes were corrupted.
  283. */
  284. /* Apply to left of object. */
  285. for (addr = pageaddr; addr < meta->addr; addr++) {
  286. if (!fn((u8 *)addr))
  287. break;
  288. }
  289. /* Apply to right of object. */
  290. for (addr = meta->addr + meta->size; addr < pageaddr + PAGE_SIZE; addr++) {
  291. if (!fn((u8 *)addr))
  292. break;
  293. }
  294. }
  295. static void *kfence_guarded_alloc(struct kmem_cache *cache, size_t size, gfp_t gfp,
  296. unsigned long *stack_entries, size_t num_stack_entries,
  297. u32 alloc_stack_hash)
  298. {
  299. struct kfence_metadata *meta = NULL;
  300. unsigned long flags;
  301. struct slab *slab;
  302. void *addr;
  303. const bool random_right_allocate = prandom_u32_max(2);
  304. const bool random_fault = CONFIG_KFENCE_STRESS_TEST_FAULTS &&
  305. !prandom_u32_max(CONFIG_KFENCE_STRESS_TEST_FAULTS);
  306. /* Try to obtain a free object. */
  307. raw_spin_lock_irqsave(&kfence_freelist_lock, flags);
  308. if (!list_empty(&kfence_freelist)) {
  309. meta = list_entry(kfence_freelist.next, struct kfence_metadata, list);
  310. list_del_init(&meta->list);
  311. }
  312. raw_spin_unlock_irqrestore(&kfence_freelist_lock, flags);
  313. if (!meta) {
  314. atomic_long_inc(&counters[KFENCE_COUNTER_SKIP_CAPACITY]);
  315. return NULL;
  316. }
  317. if (unlikely(!raw_spin_trylock_irqsave(&meta->lock, flags))) {
  318. /*
  319. * This is extremely unlikely -- we are reporting on a
  320. * use-after-free, which locked meta->lock, and the reporting
  321. * code via printk calls kmalloc() which ends up in
  322. * kfence_alloc() and tries to grab the same object that we're
  323. * reporting on. While it has never been observed, lockdep does
  324. * report that there is a possibility of deadlock. Fix it by
  325. * using trylock and bailing out gracefully.
  326. */
  327. raw_spin_lock_irqsave(&kfence_freelist_lock, flags);
  328. /* Put the object back on the freelist. */
  329. list_add_tail(&meta->list, &kfence_freelist);
  330. raw_spin_unlock_irqrestore(&kfence_freelist_lock, flags);
  331. return NULL;
  332. }
  333. meta->addr = metadata_to_pageaddr(meta);
  334. /* Unprotect if we're reusing this page. */
  335. if (meta->state == KFENCE_OBJECT_FREED)
  336. kfence_unprotect(meta->addr);
  337. /*
  338. * Note: for allocations made before RNG initialization, will always
  339. * return zero. We still benefit from enabling KFENCE as early as
  340. * possible, even when the RNG is not yet available, as this will allow
  341. * KFENCE to detect bugs due to earlier allocations. The only downside
  342. * is that the out-of-bounds accesses detected are deterministic for
  343. * such allocations.
  344. */
  345. if (random_right_allocate) {
  346. /* Allocate on the "right" side, re-calculate address. */
  347. meta->addr += PAGE_SIZE - size;
  348. meta->addr = ALIGN_DOWN(meta->addr, cache->align);
  349. }
  350. addr = (void *)meta->addr;
  351. /* Update remaining metadata. */
  352. metadata_update_state(meta, KFENCE_OBJECT_ALLOCATED, stack_entries, num_stack_entries);
  353. /* Pairs with READ_ONCE() in kfence_shutdown_cache(). */
  354. WRITE_ONCE(meta->cache, cache);
  355. meta->size = size;
  356. meta->alloc_stack_hash = alloc_stack_hash;
  357. raw_spin_unlock_irqrestore(&meta->lock, flags);
  358. alloc_covered_add(alloc_stack_hash, 1);
  359. /* Set required slab fields. */
  360. slab = virt_to_slab((void *)meta->addr);
  361. slab->slab_cache = cache;
  362. #if defined(CONFIG_SLUB)
  363. slab->objects = 1;
  364. #elif defined(CONFIG_SLAB)
  365. slab->s_mem = addr;
  366. #endif
  367. /* Memory initialization. */
  368. for_each_canary(meta, set_canary_byte);
  369. /*
  370. * We check slab_want_init_on_alloc() ourselves, rather than letting
  371. * SL*B do the initialization, as otherwise we might overwrite KFENCE's
  372. * redzone.
  373. */
  374. if (unlikely(slab_want_init_on_alloc(gfp, cache)))
  375. memzero_explicit(addr, size);
  376. if (cache->ctor)
  377. cache->ctor(addr);
  378. if (random_fault)
  379. kfence_protect(meta->addr); /* Random "faults" by protecting the object. */
  380. atomic_long_inc(&counters[KFENCE_COUNTER_ALLOCATED]);
  381. atomic_long_inc(&counters[KFENCE_COUNTER_ALLOCS]);
  382. return addr;
  383. }
  384. static void kfence_guarded_free(void *addr, struct kfence_metadata *meta, bool zombie)
  385. {
  386. struct kcsan_scoped_access assert_page_exclusive;
  387. unsigned long flags;
  388. bool init;
  389. raw_spin_lock_irqsave(&meta->lock, flags);
  390. if (meta->state != KFENCE_OBJECT_ALLOCATED || meta->addr != (unsigned long)addr) {
  391. /* Invalid or double-free, bail out. */
  392. atomic_long_inc(&counters[KFENCE_COUNTER_BUGS]);
  393. kfence_report_error((unsigned long)addr, false, NULL, meta,
  394. KFENCE_ERROR_INVALID_FREE);
  395. raw_spin_unlock_irqrestore(&meta->lock, flags);
  396. return;
  397. }
  398. /* Detect racy use-after-free, or incorrect reallocation of this page by KFENCE. */
  399. kcsan_begin_scoped_access((void *)ALIGN_DOWN((unsigned long)addr, PAGE_SIZE), PAGE_SIZE,
  400. KCSAN_ACCESS_SCOPED | KCSAN_ACCESS_WRITE | KCSAN_ACCESS_ASSERT,
  401. &assert_page_exclusive);
  402. if (CONFIG_KFENCE_STRESS_TEST_FAULTS)
  403. kfence_unprotect((unsigned long)addr); /* To check canary bytes. */
  404. /* Restore page protection if there was an OOB access. */
  405. if (meta->unprotected_page) {
  406. memzero_explicit((void *)ALIGN_DOWN(meta->unprotected_page, PAGE_SIZE), PAGE_SIZE);
  407. kfence_protect(meta->unprotected_page);
  408. meta->unprotected_page = 0;
  409. }
  410. /* Mark the object as freed. */
  411. metadata_update_state(meta, KFENCE_OBJECT_FREED, NULL, 0);
  412. init = slab_want_init_on_free(meta->cache);
  413. raw_spin_unlock_irqrestore(&meta->lock, flags);
  414. alloc_covered_add(meta->alloc_stack_hash, -1);
  415. /* Check canary bytes for memory corruption. */
  416. for_each_canary(meta, check_canary_byte);
  417. /*
  418. * Clear memory if init-on-free is set. While we protect the page, the
  419. * data is still there, and after a use-after-free is detected, we
  420. * unprotect the page, so the data is still accessible.
  421. */
  422. if (!zombie && unlikely(init))
  423. memzero_explicit(addr, meta->size);
  424. /* Protect to detect use-after-frees. */
  425. kfence_protect((unsigned long)addr);
  426. kcsan_end_scoped_access(&assert_page_exclusive);
  427. if (!zombie) {
  428. /* Add it to the tail of the freelist for reuse. */
  429. raw_spin_lock_irqsave(&kfence_freelist_lock, flags);
  430. KFENCE_WARN_ON(!list_empty(&meta->list));
  431. list_add_tail(&meta->list, &kfence_freelist);
  432. raw_spin_unlock_irqrestore(&kfence_freelist_lock, flags);
  433. atomic_long_dec(&counters[KFENCE_COUNTER_ALLOCATED]);
  434. atomic_long_inc(&counters[KFENCE_COUNTER_FREES]);
  435. } else {
  436. /* See kfence_shutdown_cache(). */
  437. atomic_long_inc(&counters[KFENCE_COUNTER_ZOMBIES]);
  438. }
  439. }
  440. static void rcu_guarded_free(struct rcu_head *h)
  441. {
  442. struct kfence_metadata *meta = container_of(h, struct kfence_metadata, rcu_head);
  443. kfence_guarded_free((void *)meta->addr, meta, false);
  444. }
  445. /*
  446. * Initialization of the KFENCE pool after its allocation.
  447. * Returns 0 on success; otherwise returns the address up to
  448. * which partial initialization succeeded.
  449. */
  450. static unsigned long kfence_init_pool(void)
  451. {
  452. unsigned long addr = (unsigned long)__kfence_pool;
  453. struct page *pages;
  454. int i;
  455. if (!arch_kfence_init_pool())
  456. return addr;
  457. pages = virt_to_page(__kfence_pool);
  458. /*
  459. * Set up object pages: they must have PG_slab set, to avoid freeing
  460. * these as real pages.
  461. *
  462. * We also want to avoid inserting kfence_free() in the kfree()
  463. * fast-path in SLUB, and therefore need to ensure kfree() correctly
  464. * enters __slab_free() slow-path.
  465. */
  466. for (i = 0; i < KFENCE_POOL_SIZE / PAGE_SIZE; i++) {
  467. struct slab *slab = page_slab(nth_page(pages, i));
  468. if (!i || (i % 2))
  469. continue;
  470. __folio_set_slab(slab_folio(slab));
  471. #ifdef CONFIG_MEMCG
  472. slab->memcg_data = (unsigned long)&kfence_metadata[i / 2 - 1].objcg |
  473. MEMCG_DATA_OBJCGS;
  474. #endif
  475. }
  476. /*
  477. * Protect the first 2 pages. The first page is mostly unnecessary, and
  478. * merely serves as an extended guard page. However, adding one
  479. * additional page in the beginning gives us an even number of pages,
  480. * which simplifies the mapping of address to metadata index.
  481. */
  482. for (i = 0; i < 2; i++) {
  483. if (unlikely(!kfence_protect(addr)))
  484. return addr;
  485. addr += PAGE_SIZE;
  486. }
  487. for (i = 0; i < CONFIG_KFENCE_NUM_OBJECTS; i++) {
  488. struct kfence_metadata *meta = &kfence_metadata[i];
  489. /* Initialize metadata. */
  490. INIT_LIST_HEAD(&meta->list);
  491. raw_spin_lock_init(&meta->lock);
  492. meta->state = KFENCE_OBJECT_UNUSED;
  493. meta->addr = addr; /* Initialize for validation in metadata_to_pageaddr(). */
  494. list_add_tail(&meta->list, &kfence_freelist);
  495. /* Protect the right redzone. */
  496. if (unlikely(!kfence_protect(addr + PAGE_SIZE)))
  497. goto reset_slab;
  498. addr += 2 * PAGE_SIZE;
  499. }
  500. return 0;
  501. reset_slab:
  502. for (i = 0; i < KFENCE_POOL_SIZE / PAGE_SIZE; i++) {
  503. struct slab *slab = page_slab(nth_page(pages, i));
  504. if (!i || (i % 2))
  505. continue;
  506. #ifdef CONFIG_MEMCG
  507. slab->memcg_data = 0;
  508. #endif
  509. __folio_clear_slab(slab_folio(slab));
  510. }
  511. return addr;
  512. }
  513. static bool __init kfence_init_pool_early(void)
  514. {
  515. unsigned long addr;
  516. if (!__kfence_pool)
  517. return false;
  518. addr = kfence_init_pool();
  519. if (!addr) {
  520. /*
  521. * The pool is live and will never be deallocated from this point on.
  522. * Ignore the pool object from the kmemleak phys object tree, as it would
  523. * otherwise overlap with allocations returned by kfence_alloc(), which
  524. * are registered with kmemleak through the slab post-alloc hook.
  525. */
  526. kmemleak_ignore_phys(__pa(__kfence_pool));
  527. return true;
  528. }
  529. /*
  530. * Only release unprotected pages, and do not try to go back and change
  531. * page attributes due to risk of failing to do so as well. If changing
  532. * page attributes for some pages fails, it is very likely that it also
  533. * fails for the first page, and therefore expect addr==__kfence_pool in
  534. * most failure cases.
  535. */
  536. memblock_free_late(__pa(addr), KFENCE_POOL_SIZE - (addr - (unsigned long)__kfence_pool));
  537. __kfence_pool = NULL;
  538. return false;
  539. }
  540. static bool kfence_init_pool_late(void)
  541. {
  542. unsigned long addr, free_size;
  543. addr = kfence_init_pool();
  544. if (!addr)
  545. return true;
  546. /* Same as above. */
  547. free_size = KFENCE_POOL_SIZE - (addr - (unsigned long)__kfence_pool);
  548. #ifdef CONFIG_CONTIG_ALLOC
  549. free_contig_range(page_to_pfn(virt_to_page((void *)addr)), free_size / PAGE_SIZE);
  550. #else
  551. free_pages_exact((void *)addr, free_size);
  552. #endif
  553. __kfence_pool = NULL;
  554. return false;
  555. }
  556. /* === DebugFS Interface ==================================================== */
  557. static int stats_show(struct seq_file *seq, void *v)
  558. {
  559. int i;
  560. seq_printf(seq, "enabled: %i\n", READ_ONCE(kfence_enabled));
  561. for (i = 0; i < KFENCE_COUNTER_COUNT; i++)
  562. seq_printf(seq, "%s: %ld\n", counter_names[i], atomic_long_read(&counters[i]));
  563. return 0;
  564. }
  565. DEFINE_SHOW_ATTRIBUTE(stats);
  566. /*
  567. * debugfs seq_file operations for /sys/kernel/debug/kfence/objects.
  568. * start_object() and next_object() return the object index + 1, because NULL is used
  569. * to stop iteration.
  570. */
  571. static void *start_object(struct seq_file *seq, loff_t *pos)
  572. {
  573. if (*pos < CONFIG_KFENCE_NUM_OBJECTS)
  574. return (void *)((long)*pos + 1);
  575. return NULL;
  576. }
  577. static void stop_object(struct seq_file *seq, void *v)
  578. {
  579. }
  580. static void *next_object(struct seq_file *seq, void *v, loff_t *pos)
  581. {
  582. ++*pos;
  583. if (*pos < CONFIG_KFENCE_NUM_OBJECTS)
  584. return (void *)((long)*pos + 1);
  585. return NULL;
  586. }
  587. static int show_object(struct seq_file *seq, void *v)
  588. {
  589. struct kfence_metadata *meta = &kfence_metadata[(long)v - 1];
  590. unsigned long flags;
  591. raw_spin_lock_irqsave(&meta->lock, flags);
  592. kfence_print_object(seq, meta);
  593. raw_spin_unlock_irqrestore(&meta->lock, flags);
  594. seq_puts(seq, "---------------------------------\n");
  595. return 0;
  596. }
  597. static const struct seq_operations objects_sops = {
  598. .start = start_object,
  599. .next = next_object,
  600. .stop = stop_object,
  601. .show = show_object,
  602. };
  603. DEFINE_SEQ_ATTRIBUTE(objects);
  604. static int kfence_debugfs_init(void)
  605. {
  606. struct dentry *kfence_dir;
  607. if (!READ_ONCE(kfence_enabled))
  608. return 0;
  609. kfence_dir = debugfs_create_dir("kfence", NULL);
  610. debugfs_create_file("stats", 0444, kfence_dir, NULL, &stats_fops);
  611. debugfs_create_file("objects", 0400, kfence_dir, NULL, &objects_fops);
  612. return 0;
  613. }
  614. late_initcall(kfence_debugfs_init);
  615. /* === Panic Notifier ====================================================== */
  616. static void kfence_check_all_canary(void)
  617. {
  618. int i;
  619. for (i = 0; i < CONFIG_KFENCE_NUM_OBJECTS; i++) {
  620. struct kfence_metadata *meta = &kfence_metadata[i];
  621. if (meta->state == KFENCE_OBJECT_ALLOCATED)
  622. for_each_canary(meta, check_canary_byte);
  623. }
  624. }
  625. static int kfence_check_canary_callback(struct notifier_block *nb,
  626. unsigned long reason, void *arg)
  627. {
  628. kfence_check_all_canary();
  629. return NOTIFY_OK;
  630. }
  631. static struct notifier_block kfence_check_canary_notifier = {
  632. .notifier_call = kfence_check_canary_callback,
  633. };
  634. /* === Allocation Gate Timer ================================================ */
  635. static struct delayed_work kfence_timer;
  636. #ifdef CONFIG_KFENCE_STATIC_KEYS
  637. /* Wait queue to wake up allocation-gate timer task. */
  638. static DECLARE_WAIT_QUEUE_HEAD(allocation_wait);
  639. static void wake_up_kfence_timer(struct irq_work *work)
  640. {
  641. wake_up(&allocation_wait);
  642. }
  643. static DEFINE_IRQ_WORK(wake_up_kfence_timer_work, wake_up_kfence_timer);
  644. #endif
  645. /*
  646. * Set up delayed work, which will enable and disable the static key. We need to
  647. * use a work queue (rather than a simple timer), since enabling and disabling a
  648. * static key cannot be done from an interrupt.
  649. *
  650. * Note: Toggling a static branch currently causes IPIs, and here we'll end up
  651. * with a total of 2 IPIs to all CPUs. If this ends up a problem in future (with
  652. * more aggressive sampling intervals), we could get away with a variant that
  653. * avoids IPIs, at the cost of not immediately capturing allocations if the
  654. * instructions remain cached.
  655. */
  656. static void toggle_allocation_gate(struct work_struct *work)
  657. {
  658. if (!READ_ONCE(kfence_enabled))
  659. return;
  660. atomic_set(&kfence_allocation_gate, 0);
  661. #ifdef CONFIG_KFENCE_STATIC_KEYS
  662. /* Enable static key, and await allocation to happen. */
  663. static_branch_enable(&kfence_allocation_key);
  664. if (sysctl_hung_task_timeout_secs) {
  665. /*
  666. * During low activity with no allocations we might wait a
  667. * while; let's avoid the hung task warning.
  668. */
  669. wait_event_idle_timeout(allocation_wait, atomic_read(&kfence_allocation_gate),
  670. sysctl_hung_task_timeout_secs * HZ / 2);
  671. } else {
  672. wait_event_idle(allocation_wait, atomic_read(&kfence_allocation_gate));
  673. }
  674. /* Disable static key and reset timer. */
  675. static_branch_disable(&kfence_allocation_key);
  676. #endif
  677. queue_delayed_work(system_unbound_wq, &kfence_timer,
  678. msecs_to_jiffies(kfence_sample_interval));
  679. }
  680. /* === Public interface ===================================================== */
  681. void __init kfence_alloc_pool(void)
  682. {
  683. if (!kfence_sample_interval)
  684. return;
  685. /* if the pool has already been initialized by arch, skip the below. */
  686. if (__kfence_pool)
  687. return;
  688. __kfence_pool = memblock_alloc(KFENCE_POOL_SIZE, PAGE_SIZE);
  689. if (!__kfence_pool)
  690. pr_err("failed to allocate pool\n");
  691. }
  692. static void kfence_init_enable(void)
  693. {
  694. if (!IS_ENABLED(CONFIG_KFENCE_STATIC_KEYS))
  695. static_branch_enable(&kfence_allocation_key);
  696. if (kfence_deferrable)
  697. INIT_DEFERRABLE_WORK(&kfence_timer, toggle_allocation_gate);
  698. else
  699. INIT_DELAYED_WORK(&kfence_timer, toggle_allocation_gate);
  700. if (kfence_check_on_panic)
  701. atomic_notifier_chain_register(&panic_notifier_list, &kfence_check_canary_notifier);
  702. WRITE_ONCE(kfence_enabled, true);
  703. queue_delayed_work(system_unbound_wq, &kfence_timer, 0);
  704. pr_info("initialized - using %lu bytes for %d objects at 0x%p-0x%p\n", KFENCE_POOL_SIZE,
  705. CONFIG_KFENCE_NUM_OBJECTS, (void *)__kfence_pool,
  706. (void *)(__kfence_pool + KFENCE_POOL_SIZE));
  707. }
  708. void __init kfence_init(void)
  709. {
  710. stack_hash_seed = get_random_u32();
  711. /* Setting kfence_sample_interval to 0 on boot disables KFENCE. */
  712. if (!kfence_sample_interval)
  713. return;
  714. if (!kfence_init_pool_early()) {
  715. pr_err("%s failed\n", __func__);
  716. return;
  717. }
  718. kfence_init_enable();
  719. }
  720. static int kfence_init_late(void)
  721. {
  722. const unsigned long nr_pages = KFENCE_POOL_SIZE / PAGE_SIZE;
  723. #ifdef CONFIG_CONTIG_ALLOC
  724. struct page *pages;
  725. pages = alloc_contig_pages(nr_pages, GFP_KERNEL, first_online_node, NULL);
  726. if (!pages)
  727. return -ENOMEM;
  728. __kfence_pool = page_to_virt(pages);
  729. #else
  730. if (nr_pages > MAX_ORDER_NR_PAGES) {
  731. pr_warn("KFENCE_NUM_OBJECTS too large for buddy allocator\n");
  732. return -EINVAL;
  733. }
  734. __kfence_pool = alloc_pages_exact(KFENCE_POOL_SIZE, GFP_KERNEL);
  735. if (!__kfence_pool)
  736. return -ENOMEM;
  737. #endif
  738. if (!kfence_init_pool_late()) {
  739. pr_err("%s failed\n", __func__);
  740. return -EBUSY;
  741. }
  742. kfence_init_enable();
  743. kfence_debugfs_init();
  744. return 0;
  745. }
  746. static int kfence_enable_late(void)
  747. {
  748. if (!__kfence_pool)
  749. return kfence_init_late();
  750. WRITE_ONCE(kfence_enabled, true);
  751. queue_delayed_work(system_unbound_wq, &kfence_timer, 0);
  752. pr_info("re-enabled\n");
  753. return 0;
  754. }
  755. void kfence_shutdown_cache(struct kmem_cache *s)
  756. {
  757. unsigned long flags;
  758. struct kfence_metadata *meta;
  759. int i;
  760. for (i = 0; i < CONFIG_KFENCE_NUM_OBJECTS; i++) {
  761. bool in_use;
  762. meta = &kfence_metadata[i];
  763. /*
  764. * If we observe some inconsistent cache and state pair where we
  765. * should have returned false here, cache destruction is racing
  766. * with either kmem_cache_alloc() or kmem_cache_free(). Taking
  767. * the lock will not help, as different critical section
  768. * serialization will have the same outcome.
  769. */
  770. if (READ_ONCE(meta->cache) != s ||
  771. READ_ONCE(meta->state) != KFENCE_OBJECT_ALLOCATED)
  772. continue;
  773. raw_spin_lock_irqsave(&meta->lock, flags);
  774. in_use = meta->cache == s && meta->state == KFENCE_OBJECT_ALLOCATED;
  775. raw_spin_unlock_irqrestore(&meta->lock, flags);
  776. if (in_use) {
  777. /*
  778. * This cache still has allocations, and we should not
  779. * release them back into the freelist so they can still
  780. * safely be used and retain the kernel's default
  781. * behaviour of keeping the allocations alive (leak the
  782. * cache); however, they effectively become "zombie
  783. * allocations" as the KFENCE objects are the only ones
  784. * still in use and the owning cache is being destroyed.
  785. *
  786. * We mark them freed, so that any subsequent use shows
  787. * more useful error messages that will include stack
  788. * traces of the user of the object, the original
  789. * allocation, and caller to shutdown_cache().
  790. */
  791. kfence_guarded_free((void *)meta->addr, meta, /*zombie=*/true);
  792. }
  793. }
  794. for (i = 0; i < CONFIG_KFENCE_NUM_OBJECTS; i++) {
  795. meta = &kfence_metadata[i];
  796. /* See above. */
  797. if (READ_ONCE(meta->cache) != s || READ_ONCE(meta->state) != KFENCE_OBJECT_FREED)
  798. continue;
  799. raw_spin_lock_irqsave(&meta->lock, flags);
  800. if (meta->cache == s && meta->state == KFENCE_OBJECT_FREED)
  801. meta->cache = NULL;
  802. raw_spin_unlock_irqrestore(&meta->lock, flags);
  803. }
  804. }
  805. void *__kfence_alloc(struct kmem_cache *s, size_t size, gfp_t flags)
  806. {
  807. unsigned long stack_entries[KFENCE_STACK_DEPTH];
  808. size_t num_stack_entries;
  809. u32 alloc_stack_hash;
  810. /*
  811. * Perform size check before switching kfence_allocation_gate, so that
  812. * we don't disable KFENCE without making an allocation.
  813. */
  814. if (size > PAGE_SIZE) {
  815. atomic_long_inc(&counters[KFENCE_COUNTER_SKIP_INCOMPAT]);
  816. return NULL;
  817. }
  818. /*
  819. * Skip allocations from non-default zones, including DMA. We cannot
  820. * guarantee that pages in the KFENCE pool will have the requested
  821. * properties (e.g. reside in DMAable memory).
  822. */
  823. if ((flags & GFP_ZONEMASK) ||
  824. (s->flags & (SLAB_CACHE_DMA | SLAB_CACHE_DMA32))) {
  825. atomic_long_inc(&counters[KFENCE_COUNTER_SKIP_INCOMPAT]);
  826. return NULL;
  827. }
  828. /*
  829. * Skip allocations for this slab, if KFENCE has been disabled for
  830. * this slab.
  831. */
  832. if (s->flags & SLAB_SKIP_KFENCE)
  833. return NULL;
  834. if (atomic_inc_return(&kfence_allocation_gate) > 1)
  835. return NULL;
  836. #ifdef CONFIG_KFENCE_STATIC_KEYS
  837. /*
  838. * waitqueue_active() is fully ordered after the update of
  839. * kfence_allocation_gate per atomic_inc_return().
  840. */
  841. if (waitqueue_active(&allocation_wait)) {
  842. /*
  843. * Calling wake_up() here may deadlock when allocations happen
  844. * from within timer code. Use an irq_work to defer it.
  845. */
  846. irq_work_queue(&wake_up_kfence_timer_work);
  847. }
  848. #endif
  849. if (!READ_ONCE(kfence_enabled))
  850. return NULL;
  851. num_stack_entries = stack_trace_save(stack_entries, KFENCE_STACK_DEPTH, 0);
  852. /*
  853. * Do expensive check for coverage of allocation in slow-path after
  854. * allocation_gate has already become non-zero, even though it might
  855. * mean not making any allocation within a given sample interval.
  856. *
  857. * This ensures reasonable allocation coverage when the pool is almost
  858. * full, including avoiding long-lived allocations of the same source
  859. * filling up the pool (e.g. pagecache allocations).
  860. */
  861. alloc_stack_hash = get_alloc_stack_hash(stack_entries, num_stack_entries);
  862. if (should_skip_covered() && alloc_covered_contains(alloc_stack_hash)) {
  863. atomic_long_inc(&counters[KFENCE_COUNTER_SKIP_COVERED]);
  864. return NULL;
  865. }
  866. return kfence_guarded_alloc(s, size, flags, stack_entries, num_stack_entries,
  867. alloc_stack_hash);
  868. }
  869. size_t kfence_ksize(const void *addr)
  870. {
  871. const struct kfence_metadata *meta = addr_to_metadata((unsigned long)addr);
  872. /*
  873. * Read locklessly -- if there is a race with __kfence_alloc(), this is
  874. * either a use-after-free or invalid access.
  875. */
  876. return meta ? meta->size : 0;
  877. }
  878. void *kfence_object_start(const void *addr)
  879. {
  880. const struct kfence_metadata *meta = addr_to_metadata((unsigned long)addr);
  881. /*
  882. * Read locklessly -- if there is a race with __kfence_alloc(), this is
  883. * either a use-after-free or invalid access.
  884. */
  885. return meta ? (void *)meta->addr : NULL;
  886. }
  887. void __kfence_free(void *addr)
  888. {
  889. struct kfence_metadata *meta = addr_to_metadata((unsigned long)addr);
  890. #ifdef CONFIG_MEMCG
  891. KFENCE_WARN_ON(meta->objcg);
  892. #endif
  893. /*
  894. * If the objects of the cache are SLAB_TYPESAFE_BY_RCU, defer freeing
  895. * the object, as the object page may be recycled for other-typed
  896. * objects once it has been freed. meta->cache may be NULL if the cache
  897. * was destroyed.
  898. */
  899. if (unlikely(meta->cache && (meta->cache->flags & SLAB_TYPESAFE_BY_RCU)))
  900. call_rcu(&meta->rcu_head, rcu_guarded_free);
  901. else
  902. kfence_guarded_free(addr, meta, false);
  903. }
  904. bool kfence_handle_page_fault(unsigned long addr, bool is_write, struct pt_regs *regs)
  905. {
  906. const int page_index = (addr - (unsigned long)__kfence_pool) / PAGE_SIZE;
  907. struct kfence_metadata *to_report = NULL;
  908. enum kfence_error_type error_type;
  909. unsigned long flags;
  910. if (!is_kfence_address((void *)addr))
  911. return false;
  912. if (!READ_ONCE(kfence_enabled)) /* If disabled at runtime ... */
  913. return kfence_unprotect(addr); /* ... unprotect and proceed. */
  914. atomic_long_inc(&counters[KFENCE_COUNTER_BUGS]);
  915. if (page_index % 2) {
  916. /* This is a redzone, report a buffer overflow. */
  917. struct kfence_metadata *meta;
  918. int distance = 0;
  919. meta = addr_to_metadata(addr - PAGE_SIZE);
  920. if (meta && READ_ONCE(meta->state) == KFENCE_OBJECT_ALLOCATED) {
  921. to_report = meta;
  922. /* Data race ok; distance calculation approximate. */
  923. distance = addr - data_race(meta->addr + meta->size);
  924. }
  925. meta = addr_to_metadata(addr + PAGE_SIZE);
  926. if (meta && READ_ONCE(meta->state) == KFENCE_OBJECT_ALLOCATED) {
  927. /* Data race ok; distance calculation approximate. */
  928. if (!to_report || distance > data_race(meta->addr) - addr)
  929. to_report = meta;
  930. }
  931. if (!to_report)
  932. goto out;
  933. raw_spin_lock_irqsave(&to_report->lock, flags);
  934. to_report->unprotected_page = addr;
  935. error_type = KFENCE_ERROR_OOB;
  936. /*
  937. * If the object was freed before we took the look we can still
  938. * report this as an OOB -- the report will simply show the
  939. * stacktrace of the free as well.
  940. */
  941. } else {
  942. to_report = addr_to_metadata(addr);
  943. if (!to_report)
  944. goto out;
  945. raw_spin_lock_irqsave(&to_report->lock, flags);
  946. error_type = KFENCE_ERROR_UAF;
  947. /*
  948. * We may race with __kfence_alloc(), and it is possible that a
  949. * freed object may be reallocated. We simply report this as a
  950. * use-after-free, with the stack trace showing the place where
  951. * the object was re-allocated.
  952. */
  953. }
  954. out:
  955. if (to_report) {
  956. kfence_report_error(addr, is_write, regs, to_report, error_type);
  957. raw_spin_unlock_irqrestore(&to_report->lock, flags);
  958. } else {
  959. /* This may be a UAF or OOB access, but we can't be sure. */
  960. kfence_report_error(addr, is_write, regs, NULL, KFENCE_ERROR_INVALID);
  961. }
  962. return kfence_unprotect(addr); /* Unprotect and let access proceed. */
  963. }