kfence_test.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Test cases for KFENCE memory safety error detector. Since the interface with
  4. * which KFENCE's reports are obtained is via the console, this is the output we
  5. * should verify. For each test case checks the presence (or absence) of
  6. * generated reports. Relies on 'console' tracepoint to capture reports as they
  7. * appear in the kernel log.
  8. *
  9. * Copyright (C) 2020, Google LLC.
  10. * Author: Alexander Potapenko <[email protected]>
  11. * Marco Elver <[email protected]>
  12. */
  13. #include <kunit/test.h>
  14. #include <linux/jiffies.h>
  15. #include <linux/kernel.h>
  16. #include <linux/kfence.h>
  17. #include <linux/mm.h>
  18. #include <linux/random.h>
  19. #include <linux/slab.h>
  20. #include <linux/spinlock.h>
  21. #include <linux/string.h>
  22. #include <linux/tracepoint.h>
  23. #include <trace/events/printk.h>
  24. #include <asm/kfence.h>
  25. #include "kfence.h"
  26. /* May be overridden by <asm/kfence.h>. */
  27. #ifndef arch_kfence_test_address
  28. #define arch_kfence_test_address(addr) (addr)
  29. #endif
  30. #define KFENCE_TEST_REQUIRES(test, cond) do { \
  31. if (!(cond)) \
  32. kunit_skip((test), "Test requires: " #cond); \
  33. } while (0)
  34. /* Report as observed from console. */
  35. static struct {
  36. spinlock_t lock;
  37. int nlines;
  38. char lines[2][256];
  39. } observed = {
  40. .lock = __SPIN_LOCK_UNLOCKED(observed.lock),
  41. };
  42. /* Probe for console output: obtains observed lines of interest. */
  43. static void probe_console(void *ignore, const char *buf, size_t len)
  44. {
  45. unsigned long flags;
  46. int nlines;
  47. spin_lock_irqsave(&observed.lock, flags);
  48. nlines = observed.nlines;
  49. if (strnstr(buf, "BUG: KFENCE: ", len) && strnstr(buf, "test_", len)) {
  50. /*
  51. * KFENCE report and related to the test.
  52. *
  53. * The provided @buf is not NUL-terminated; copy no more than
  54. * @len bytes and let strscpy() add the missing NUL-terminator.
  55. */
  56. strscpy(observed.lines[0], buf, min(len + 1, sizeof(observed.lines[0])));
  57. nlines = 1;
  58. } else if (nlines == 1 && (strnstr(buf, "at 0x", len) || strnstr(buf, "of 0x", len))) {
  59. strscpy(observed.lines[nlines++], buf, min(len + 1, sizeof(observed.lines[0])));
  60. }
  61. WRITE_ONCE(observed.nlines, nlines); /* Publish new nlines. */
  62. spin_unlock_irqrestore(&observed.lock, flags);
  63. }
  64. /* Check if a report related to the test exists. */
  65. static bool report_available(void)
  66. {
  67. return READ_ONCE(observed.nlines) == ARRAY_SIZE(observed.lines);
  68. }
  69. /* Information we expect in a report. */
  70. struct expect_report {
  71. enum kfence_error_type type; /* The type or error. */
  72. void *fn; /* Function pointer to expected function where access occurred. */
  73. char *addr; /* Address at which the bad access occurred. */
  74. bool is_write; /* Is access a write. */
  75. };
  76. static const char *get_access_type(const struct expect_report *r)
  77. {
  78. return r->is_write ? "write" : "read";
  79. }
  80. /* Check observed report matches information in @r. */
  81. static bool report_matches(const struct expect_report *r)
  82. {
  83. unsigned long addr = (unsigned long)r->addr;
  84. bool ret = false;
  85. unsigned long flags;
  86. typeof(observed.lines) expect;
  87. const char *end;
  88. char *cur;
  89. /* Doubled-checked locking. */
  90. if (!report_available())
  91. return false;
  92. /* Generate expected report contents. */
  93. /* Title */
  94. cur = expect[0];
  95. end = &expect[0][sizeof(expect[0]) - 1];
  96. switch (r->type) {
  97. case KFENCE_ERROR_OOB:
  98. cur += scnprintf(cur, end - cur, "BUG: KFENCE: out-of-bounds %s",
  99. get_access_type(r));
  100. break;
  101. case KFENCE_ERROR_UAF:
  102. cur += scnprintf(cur, end - cur, "BUG: KFENCE: use-after-free %s",
  103. get_access_type(r));
  104. break;
  105. case KFENCE_ERROR_CORRUPTION:
  106. cur += scnprintf(cur, end - cur, "BUG: KFENCE: memory corruption");
  107. break;
  108. case KFENCE_ERROR_INVALID:
  109. cur += scnprintf(cur, end - cur, "BUG: KFENCE: invalid %s",
  110. get_access_type(r));
  111. break;
  112. case KFENCE_ERROR_INVALID_FREE:
  113. cur += scnprintf(cur, end - cur, "BUG: KFENCE: invalid free");
  114. break;
  115. }
  116. scnprintf(cur, end - cur, " in %pS", r->fn);
  117. /* The exact offset won't match, remove it; also strip module name. */
  118. cur = strchr(expect[0], '+');
  119. if (cur)
  120. *cur = '\0';
  121. /* Access information */
  122. cur = expect[1];
  123. end = &expect[1][sizeof(expect[1]) - 1];
  124. switch (r->type) {
  125. case KFENCE_ERROR_OOB:
  126. cur += scnprintf(cur, end - cur, "Out-of-bounds %s at", get_access_type(r));
  127. addr = arch_kfence_test_address(addr);
  128. break;
  129. case KFENCE_ERROR_UAF:
  130. cur += scnprintf(cur, end - cur, "Use-after-free %s at", get_access_type(r));
  131. addr = arch_kfence_test_address(addr);
  132. break;
  133. case KFENCE_ERROR_CORRUPTION:
  134. cur += scnprintf(cur, end - cur, "Corrupted memory at");
  135. break;
  136. case KFENCE_ERROR_INVALID:
  137. cur += scnprintf(cur, end - cur, "Invalid %s at", get_access_type(r));
  138. addr = arch_kfence_test_address(addr);
  139. break;
  140. case KFENCE_ERROR_INVALID_FREE:
  141. cur += scnprintf(cur, end - cur, "Invalid free of");
  142. break;
  143. }
  144. cur += scnprintf(cur, end - cur, " 0x%p", (void *)addr);
  145. spin_lock_irqsave(&observed.lock, flags);
  146. if (!report_available())
  147. goto out; /* A new report is being captured. */
  148. /* Finally match expected output to what we actually observed. */
  149. ret = strstr(observed.lines[0], expect[0]) && strstr(observed.lines[1], expect[1]);
  150. out:
  151. spin_unlock_irqrestore(&observed.lock, flags);
  152. return ret;
  153. }
  154. /* ===== Test cases ===== */
  155. #define TEST_PRIV_WANT_MEMCACHE ((void *)1)
  156. /* Cache used by tests; if NULL, allocate from kmalloc instead. */
  157. static struct kmem_cache *test_cache;
  158. static size_t setup_test_cache(struct kunit *test, size_t size, slab_flags_t flags,
  159. void (*ctor)(void *))
  160. {
  161. if (test->priv != TEST_PRIV_WANT_MEMCACHE)
  162. return size;
  163. kunit_info(test, "%s: size=%zu, ctor=%ps\n", __func__, size, ctor);
  164. /*
  165. * Use SLAB_NOLEAKTRACE to prevent merging with existing caches. Any
  166. * other flag in SLAB_NEVER_MERGE also works. Use SLAB_ACCOUNT to
  167. * allocate via memcg, if enabled.
  168. */
  169. flags |= SLAB_NOLEAKTRACE | SLAB_ACCOUNT;
  170. test_cache = kmem_cache_create("test", size, 1, flags, ctor);
  171. KUNIT_ASSERT_TRUE_MSG(test, test_cache, "could not create cache");
  172. return size;
  173. }
  174. static void test_cache_destroy(void)
  175. {
  176. if (!test_cache)
  177. return;
  178. kmem_cache_destroy(test_cache);
  179. test_cache = NULL;
  180. }
  181. static inline size_t kmalloc_cache_alignment(size_t size)
  182. {
  183. return kmalloc_caches[kmalloc_type(GFP_KERNEL)][__kmalloc_index(size, false)]->align;
  184. }
  185. /* Must always inline to match stack trace against caller. */
  186. static __always_inline void test_free(void *ptr)
  187. {
  188. if (test_cache)
  189. kmem_cache_free(test_cache, ptr);
  190. else
  191. kfree(ptr);
  192. }
  193. /*
  194. * If this should be a KFENCE allocation, and on which side the allocation and
  195. * the closest guard page should be.
  196. */
  197. enum allocation_policy {
  198. ALLOCATE_ANY, /* KFENCE, any side. */
  199. ALLOCATE_LEFT, /* KFENCE, left side of page. */
  200. ALLOCATE_RIGHT, /* KFENCE, right side of page. */
  201. ALLOCATE_NONE, /* No KFENCE allocation. */
  202. };
  203. /*
  204. * Try to get a guarded allocation from KFENCE. Uses either kmalloc() or the
  205. * current test_cache if set up.
  206. */
  207. static void *test_alloc(struct kunit *test, size_t size, gfp_t gfp, enum allocation_policy policy)
  208. {
  209. void *alloc;
  210. unsigned long timeout, resched_after;
  211. const char *policy_name;
  212. switch (policy) {
  213. case ALLOCATE_ANY:
  214. policy_name = "any";
  215. break;
  216. case ALLOCATE_LEFT:
  217. policy_name = "left";
  218. break;
  219. case ALLOCATE_RIGHT:
  220. policy_name = "right";
  221. break;
  222. case ALLOCATE_NONE:
  223. policy_name = "none";
  224. break;
  225. }
  226. kunit_info(test, "%s: size=%zu, gfp=%x, policy=%s, cache=%i\n", __func__, size, gfp,
  227. policy_name, !!test_cache);
  228. /*
  229. * 100x the sample interval should be more than enough to ensure we get
  230. * a KFENCE allocation eventually.
  231. */
  232. timeout = jiffies + msecs_to_jiffies(100 * kfence_sample_interval);
  233. /*
  234. * Especially for non-preemption kernels, ensure the allocation-gate
  235. * timer can catch up: after @resched_after, every failed allocation
  236. * attempt yields, to ensure the allocation-gate timer is scheduled.
  237. */
  238. resched_after = jiffies + msecs_to_jiffies(kfence_sample_interval);
  239. do {
  240. if (test_cache)
  241. alloc = kmem_cache_alloc(test_cache, gfp);
  242. else
  243. alloc = kmalloc(size, gfp);
  244. if (is_kfence_address(alloc)) {
  245. struct slab *slab = virt_to_slab(alloc);
  246. struct kmem_cache *s = test_cache ?:
  247. kmalloc_caches[kmalloc_type(GFP_KERNEL)][__kmalloc_index(size, false)];
  248. /*
  249. * Verify that various helpers return the right values
  250. * even for KFENCE objects; these are required so that
  251. * memcg accounting works correctly.
  252. */
  253. KUNIT_EXPECT_EQ(test, obj_to_index(s, slab, alloc), 0U);
  254. KUNIT_EXPECT_EQ(test, objs_per_slab(s, slab), 1);
  255. if (policy == ALLOCATE_ANY)
  256. return alloc;
  257. if (policy == ALLOCATE_LEFT && PAGE_ALIGNED(alloc))
  258. return alloc;
  259. if (policy == ALLOCATE_RIGHT && !PAGE_ALIGNED(alloc))
  260. return alloc;
  261. } else if (policy == ALLOCATE_NONE)
  262. return alloc;
  263. test_free(alloc);
  264. if (time_after(jiffies, resched_after))
  265. cond_resched();
  266. } while (time_before(jiffies, timeout));
  267. KUNIT_ASSERT_TRUE_MSG(test, false, "failed to allocate from KFENCE");
  268. return NULL; /* Unreachable. */
  269. }
  270. static void test_out_of_bounds_read(struct kunit *test)
  271. {
  272. size_t size = 32;
  273. struct expect_report expect = {
  274. .type = KFENCE_ERROR_OOB,
  275. .fn = test_out_of_bounds_read,
  276. .is_write = false,
  277. };
  278. char *buf;
  279. setup_test_cache(test, size, 0, NULL);
  280. /*
  281. * If we don't have our own cache, adjust based on alignment, so that we
  282. * actually access guard pages on either side.
  283. */
  284. if (!test_cache)
  285. size = kmalloc_cache_alignment(size);
  286. /* Test both sides. */
  287. buf = test_alloc(test, size, GFP_KERNEL, ALLOCATE_LEFT);
  288. expect.addr = buf - 1;
  289. READ_ONCE(*expect.addr);
  290. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  291. test_free(buf);
  292. buf = test_alloc(test, size, GFP_KERNEL, ALLOCATE_RIGHT);
  293. expect.addr = buf + size;
  294. READ_ONCE(*expect.addr);
  295. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  296. test_free(buf);
  297. }
  298. static void test_out_of_bounds_write(struct kunit *test)
  299. {
  300. size_t size = 32;
  301. struct expect_report expect = {
  302. .type = KFENCE_ERROR_OOB,
  303. .fn = test_out_of_bounds_write,
  304. .is_write = true,
  305. };
  306. char *buf;
  307. setup_test_cache(test, size, 0, NULL);
  308. buf = test_alloc(test, size, GFP_KERNEL, ALLOCATE_LEFT);
  309. expect.addr = buf - 1;
  310. WRITE_ONCE(*expect.addr, 42);
  311. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  312. test_free(buf);
  313. }
  314. static void test_use_after_free_read(struct kunit *test)
  315. {
  316. const size_t size = 32;
  317. struct expect_report expect = {
  318. .type = KFENCE_ERROR_UAF,
  319. .fn = test_use_after_free_read,
  320. .is_write = false,
  321. };
  322. setup_test_cache(test, size, 0, NULL);
  323. expect.addr = test_alloc(test, size, GFP_KERNEL, ALLOCATE_ANY);
  324. test_free(expect.addr);
  325. READ_ONCE(*expect.addr);
  326. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  327. }
  328. static void test_double_free(struct kunit *test)
  329. {
  330. const size_t size = 32;
  331. struct expect_report expect = {
  332. .type = KFENCE_ERROR_INVALID_FREE,
  333. .fn = test_double_free,
  334. };
  335. setup_test_cache(test, size, 0, NULL);
  336. expect.addr = test_alloc(test, size, GFP_KERNEL, ALLOCATE_ANY);
  337. test_free(expect.addr);
  338. test_free(expect.addr); /* Double-free. */
  339. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  340. }
  341. static void test_invalid_addr_free(struct kunit *test)
  342. {
  343. const size_t size = 32;
  344. struct expect_report expect = {
  345. .type = KFENCE_ERROR_INVALID_FREE,
  346. .fn = test_invalid_addr_free,
  347. };
  348. char *buf;
  349. setup_test_cache(test, size, 0, NULL);
  350. buf = test_alloc(test, size, GFP_KERNEL, ALLOCATE_ANY);
  351. expect.addr = buf + 1; /* Free on invalid address. */
  352. test_free(expect.addr); /* Invalid address free. */
  353. test_free(buf); /* No error. */
  354. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  355. }
  356. static void test_corruption(struct kunit *test)
  357. {
  358. size_t size = 32;
  359. struct expect_report expect = {
  360. .type = KFENCE_ERROR_CORRUPTION,
  361. .fn = test_corruption,
  362. };
  363. char *buf;
  364. setup_test_cache(test, size, 0, NULL);
  365. /* Test both sides. */
  366. buf = test_alloc(test, size, GFP_KERNEL, ALLOCATE_LEFT);
  367. expect.addr = buf + size;
  368. WRITE_ONCE(*expect.addr, 42);
  369. test_free(buf);
  370. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  371. buf = test_alloc(test, size, GFP_KERNEL, ALLOCATE_RIGHT);
  372. expect.addr = buf - 1;
  373. WRITE_ONCE(*expect.addr, 42);
  374. test_free(buf);
  375. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  376. }
  377. /*
  378. * KFENCE is unable to detect an OOB if the allocation's alignment requirements
  379. * leave a gap between the object and the guard page. Specifically, an
  380. * allocation of e.g. 73 bytes is aligned on 8 and 128 bytes for SLUB or SLAB
  381. * respectively. Therefore it is impossible for the allocated object to
  382. * contiguously line up with the right guard page.
  383. *
  384. * However, we test that an access to memory beyond the gap results in KFENCE
  385. * detecting an OOB access.
  386. */
  387. static void test_kmalloc_aligned_oob_read(struct kunit *test)
  388. {
  389. const size_t size = 73;
  390. const size_t align = kmalloc_cache_alignment(size);
  391. struct expect_report expect = {
  392. .type = KFENCE_ERROR_OOB,
  393. .fn = test_kmalloc_aligned_oob_read,
  394. .is_write = false,
  395. };
  396. char *buf;
  397. buf = test_alloc(test, size, GFP_KERNEL, ALLOCATE_RIGHT);
  398. /*
  399. * The object is offset to the right, so there won't be an OOB to the
  400. * left of it.
  401. */
  402. READ_ONCE(*(buf - 1));
  403. KUNIT_EXPECT_FALSE(test, report_available());
  404. /*
  405. * @buf must be aligned on @align, therefore buf + size belongs to the
  406. * same page -> no OOB.
  407. */
  408. READ_ONCE(*(buf + size));
  409. KUNIT_EXPECT_FALSE(test, report_available());
  410. /* Overflowing by @align bytes will result in an OOB. */
  411. expect.addr = buf + size + align;
  412. READ_ONCE(*expect.addr);
  413. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  414. test_free(buf);
  415. }
  416. static void test_kmalloc_aligned_oob_write(struct kunit *test)
  417. {
  418. const size_t size = 73;
  419. struct expect_report expect = {
  420. .type = KFENCE_ERROR_CORRUPTION,
  421. .fn = test_kmalloc_aligned_oob_write,
  422. };
  423. char *buf;
  424. buf = test_alloc(test, size, GFP_KERNEL, ALLOCATE_RIGHT);
  425. /*
  426. * The object is offset to the right, so we won't get a page
  427. * fault immediately after it.
  428. */
  429. expect.addr = buf + size;
  430. WRITE_ONCE(*expect.addr, READ_ONCE(*expect.addr) + 1);
  431. KUNIT_EXPECT_FALSE(test, report_available());
  432. test_free(buf);
  433. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  434. }
  435. /* Test cache shrinking and destroying with KFENCE. */
  436. static void test_shrink_memcache(struct kunit *test)
  437. {
  438. const size_t size = 32;
  439. void *buf;
  440. setup_test_cache(test, size, 0, NULL);
  441. KUNIT_EXPECT_TRUE(test, test_cache);
  442. buf = test_alloc(test, size, GFP_KERNEL, ALLOCATE_ANY);
  443. kmem_cache_shrink(test_cache);
  444. test_free(buf);
  445. KUNIT_EXPECT_FALSE(test, report_available());
  446. }
  447. static void ctor_set_x(void *obj)
  448. {
  449. /* Every object has at least 8 bytes. */
  450. memset(obj, 'x', 8);
  451. }
  452. /* Ensure that SL*B does not modify KFENCE objects on bulk free. */
  453. static void test_free_bulk(struct kunit *test)
  454. {
  455. int iter;
  456. for (iter = 0; iter < 5; iter++) {
  457. const size_t size = setup_test_cache(test, 8 + prandom_u32_max(300), 0,
  458. (iter & 1) ? ctor_set_x : NULL);
  459. void *objects[] = {
  460. test_alloc(test, size, GFP_KERNEL, ALLOCATE_RIGHT),
  461. test_alloc(test, size, GFP_KERNEL, ALLOCATE_NONE),
  462. test_alloc(test, size, GFP_KERNEL, ALLOCATE_LEFT),
  463. test_alloc(test, size, GFP_KERNEL, ALLOCATE_NONE),
  464. test_alloc(test, size, GFP_KERNEL, ALLOCATE_NONE),
  465. };
  466. kmem_cache_free_bulk(test_cache, ARRAY_SIZE(objects), objects);
  467. KUNIT_ASSERT_FALSE(test, report_available());
  468. test_cache_destroy();
  469. }
  470. }
  471. /* Test init-on-free works. */
  472. static void test_init_on_free(struct kunit *test)
  473. {
  474. const size_t size = 32;
  475. struct expect_report expect = {
  476. .type = KFENCE_ERROR_UAF,
  477. .fn = test_init_on_free,
  478. .is_write = false,
  479. };
  480. int i;
  481. KFENCE_TEST_REQUIRES(test, IS_ENABLED(CONFIG_INIT_ON_FREE_DEFAULT_ON));
  482. /* Assume it hasn't been disabled on command line. */
  483. setup_test_cache(test, size, 0, NULL);
  484. expect.addr = test_alloc(test, size, GFP_KERNEL, ALLOCATE_ANY);
  485. for (i = 0; i < size; i++)
  486. expect.addr[i] = i + 1;
  487. test_free(expect.addr);
  488. for (i = 0; i < size; i++) {
  489. /*
  490. * This may fail if the page was recycled by KFENCE and then
  491. * written to again -- this however, is near impossible with a
  492. * default config.
  493. */
  494. KUNIT_EXPECT_EQ(test, expect.addr[i], (char)0);
  495. if (!i) /* Only check first access to not fail test if page is ever re-protected. */
  496. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  497. }
  498. }
  499. /* Ensure that constructors work properly. */
  500. static void test_memcache_ctor(struct kunit *test)
  501. {
  502. const size_t size = 32;
  503. char *buf;
  504. int i;
  505. setup_test_cache(test, size, 0, ctor_set_x);
  506. buf = test_alloc(test, size, GFP_KERNEL, ALLOCATE_ANY);
  507. for (i = 0; i < 8; i++)
  508. KUNIT_EXPECT_EQ(test, buf[i], (char)'x');
  509. test_free(buf);
  510. KUNIT_EXPECT_FALSE(test, report_available());
  511. }
  512. /* Test that memory is zeroed if requested. */
  513. static void test_gfpzero(struct kunit *test)
  514. {
  515. const size_t size = PAGE_SIZE; /* PAGE_SIZE so we can use ALLOCATE_ANY. */
  516. char *buf1, *buf2;
  517. int i;
  518. /* Skip if we think it'd take too long. */
  519. KFENCE_TEST_REQUIRES(test, kfence_sample_interval <= 100);
  520. setup_test_cache(test, size, 0, NULL);
  521. buf1 = test_alloc(test, size, GFP_KERNEL, ALLOCATE_ANY);
  522. for (i = 0; i < size; i++)
  523. buf1[i] = i + 1;
  524. test_free(buf1);
  525. /* Try to get same address again -- this can take a while. */
  526. for (i = 0;; i++) {
  527. buf2 = test_alloc(test, size, GFP_KERNEL | __GFP_ZERO, ALLOCATE_ANY);
  528. if (buf1 == buf2)
  529. break;
  530. test_free(buf2);
  531. if (kthread_should_stop() || (i == CONFIG_KFENCE_NUM_OBJECTS)) {
  532. kunit_warn(test, "giving up ... cannot get same object back\n");
  533. return;
  534. }
  535. cond_resched();
  536. }
  537. for (i = 0; i < size; i++)
  538. KUNIT_EXPECT_EQ(test, buf2[i], (char)0);
  539. test_free(buf2);
  540. KUNIT_EXPECT_FALSE(test, report_available());
  541. }
  542. static void test_invalid_access(struct kunit *test)
  543. {
  544. const struct expect_report expect = {
  545. .type = KFENCE_ERROR_INVALID,
  546. .fn = test_invalid_access,
  547. .addr = &__kfence_pool[10],
  548. .is_write = false,
  549. };
  550. READ_ONCE(__kfence_pool[10]);
  551. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  552. }
  553. /* Test SLAB_TYPESAFE_BY_RCU works. */
  554. static void test_memcache_typesafe_by_rcu(struct kunit *test)
  555. {
  556. const size_t size = 32;
  557. struct expect_report expect = {
  558. .type = KFENCE_ERROR_UAF,
  559. .fn = test_memcache_typesafe_by_rcu,
  560. .is_write = false,
  561. };
  562. setup_test_cache(test, size, SLAB_TYPESAFE_BY_RCU, NULL);
  563. KUNIT_EXPECT_TRUE(test, test_cache); /* Want memcache. */
  564. expect.addr = test_alloc(test, size, GFP_KERNEL, ALLOCATE_ANY);
  565. *expect.addr = 42;
  566. rcu_read_lock();
  567. test_free(expect.addr);
  568. KUNIT_EXPECT_EQ(test, *expect.addr, (char)42);
  569. /*
  570. * Up to this point, memory should not have been freed yet, and
  571. * therefore there should be no KFENCE report from the above access.
  572. */
  573. rcu_read_unlock();
  574. /* Above access to @expect.addr should not have generated a report! */
  575. KUNIT_EXPECT_FALSE(test, report_available());
  576. /* Only after rcu_barrier() is the memory guaranteed to be freed. */
  577. rcu_barrier();
  578. /* Expect use-after-free. */
  579. KUNIT_EXPECT_EQ(test, *expect.addr, (char)42);
  580. KUNIT_EXPECT_TRUE(test, report_matches(&expect));
  581. }
  582. /* Test krealloc(). */
  583. static void test_krealloc(struct kunit *test)
  584. {
  585. const size_t size = 32;
  586. const struct expect_report expect = {
  587. .type = KFENCE_ERROR_UAF,
  588. .fn = test_krealloc,
  589. .addr = test_alloc(test, size, GFP_KERNEL, ALLOCATE_ANY),
  590. .is_write = false,
  591. };
  592. char *buf = expect.addr;
  593. int i;
  594. KUNIT_EXPECT_FALSE(test, test_cache);
  595. KUNIT_EXPECT_EQ(test, ksize(buf), size); /* Precise size match after KFENCE alloc. */
  596. for (i = 0; i < size; i++)
  597. buf[i] = i + 1;
  598. /* Check that we successfully change the size. */
  599. buf = krealloc(buf, size * 3, GFP_KERNEL); /* Grow. */
  600. /* Note: Might no longer be a KFENCE alloc. */
  601. KUNIT_EXPECT_GE(test, ksize(buf), size * 3);
  602. for (i = 0; i < size; i++)
  603. KUNIT_EXPECT_EQ(test, buf[i], (char)(i + 1));
  604. for (; i < size * 3; i++) /* Fill to extra bytes. */
  605. buf[i] = i + 1;
  606. buf = krealloc(buf, size * 2, GFP_KERNEL); /* Shrink. */
  607. KUNIT_EXPECT_GE(test, ksize(buf), size * 2);
  608. for (i = 0; i < size * 2; i++)
  609. KUNIT_EXPECT_EQ(test, buf[i], (char)(i + 1));
  610. buf = krealloc(buf, 0, GFP_KERNEL); /* Free. */
  611. KUNIT_EXPECT_EQ(test, (unsigned long)buf, (unsigned long)ZERO_SIZE_PTR);
  612. KUNIT_ASSERT_FALSE(test, report_available()); /* No reports yet! */
  613. READ_ONCE(*expect.addr); /* Ensure krealloc() actually freed earlier KFENCE object. */
  614. KUNIT_ASSERT_TRUE(test, report_matches(&expect));
  615. }
  616. /* Test that some objects from a bulk allocation belong to KFENCE pool. */
  617. static void test_memcache_alloc_bulk(struct kunit *test)
  618. {
  619. const size_t size = 32;
  620. bool pass = false;
  621. unsigned long timeout;
  622. setup_test_cache(test, size, 0, NULL);
  623. KUNIT_EXPECT_TRUE(test, test_cache); /* Want memcache. */
  624. /*
  625. * 100x the sample interval should be more than enough to ensure we get
  626. * a KFENCE allocation eventually.
  627. */
  628. timeout = jiffies + msecs_to_jiffies(100 * kfence_sample_interval);
  629. do {
  630. void *objects[100];
  631. int i, num = kmem_cache_alloc_bulk(test_cache, GFP_ATOMIC, ARRAY_SIZE(objects),
  632. objects);
  633. if (!num)
  634. continue;
  635. for (i = 0; i < ARRAY_SIZE(objects); i++) {
  636. if (is_kfence_address(objects[i])) {
  637. pass = true;
  638. break;
  639. }
  640. }
  641. kmem_cache_free_bulk(test_cache, num, objects);
  642. /*
  643. * kmem_cache_alloc_bulk() disables interrupts, and calling it
  644. * in a tight loop may not give KFENCE a chance to switch the
  645. * static branch. Call cond_resched() to let KFENCE chime in.
  646. */
  647. cond_resched();
  648. } while (!pass && time_before(jiffies, timeout));
  649. KUNIT_EXPECT_TRUE(test, pass);
  650. KUNIT_EXPECT_FALSE(test, report_available());
  651. }
  652. /*
  653. * KUnit does not provide a way to provide arguments to tests, and we encode
  654. * additional info in the name. Set up 2 tests per test case, one using the
  655. * default allocator, and another using a custom memcache (suffix '-memcache').
  656. */
  657. #define KFENCE_KUNIT_CASE(test_name) \
  658. { .run_case = test_name, .name = #test_name }, \
  659. { .run_case = test_name, .name = #test_name "-memcache" }
  660. static struct kunit_case kfence_test_cases[] = {
  661. KFENCE_KUNIT_CASE(test_out_of_bounds_read),
  662. KFENCE_KUNIT_CASE(test_out_of_bounds_write),
  663. KFENCE_KUNIT_CASE(test_use_after_free_read),
  664. KFENCE_KUNIT_CASE(test_double_free),
  665. KFENCE_KUNIT_CASE(test_invalid_addr_free),
  666. KFENCE_KUNIT_CASE(test_corruption),
  667. KFENCE_KUNIT_CASE(test_free_bulk),
  668. KFENCE_KUNIT_CASE(test_init_on_free),
  669. KUNIT_CASE(test_kmalloc_aligned_oob_read),
  670. KUNIT_CASE(test_kmalloc_aligned_oob_write),
  671. KUNIT_CASE(test_shrink_memcache),
  672. KUNIT_CASE(test_memcache_ctor),
  673. KUNIT_CASE(test_invalid_access),
  674. KUNIT_CASE(test_gfpzero),
  675. KUNIT_CASE(test_memcache_typesafe_by_rcu),
  676. KUNIT_CASE(test_krealloc),
  677. KUNIT_CASE(test_memcache_alloc_bulk),
  678. {},
  679. };
  680. /* ===== End test cases ===== */
  681. static int test_init(struct kunit *test)
  682. {
  683. unsigned long flags;
  684. int i;
  685. if (!__kfence_pool)
  686. return -EINVAL;
  687. spin_lock_irqsave(&observed.lock, flags);
  688. for (i = 0; i < ARRAY_SIZE(observed.lines); i++)
  689. observed.lines[i][0] = '\0';
  690. observed.nlines = 0;
  691. spin_unlock_irqrestore(&observed.lock, flags);
  692. /* Any test with 'memcache' in its name will want a memcache. */
  693. if (strstr(test->name, "memcache"))
  694. test->priv = TEST_PRIV_WANT_MEMCACHE;
  695. else
  696. test->priv = NULL;
  697. return 0;
  698. }
  699. static void test_exit(struct kunit *test)
  700. {
  701. test_cache_destroy();
  702. }
  703. static void register_tracepoints(struct tracepoint *tp, void *ignore)
  704. {
  705. check_trace_callback_type_console(probe_console);
  706. if (!strcmp(tp->name, "console"))
  707. WARN_ON(tracepoint_probe_register(tp, probe_console, NULL));
  708. }
  709. static void unregister_tracepoints(struct tracepoint *tp, void *ignore)
  710. {
  711. if (!strcmp(tp->name, "console"))
  712. tracepoint_probe_unregister(tp, probe_console, NULL);
  713. }
  714. static int kfence_suite_init(struct kunit_suite *suite)
  715. {
  716. /*
  717. * Because we want to be able to build the test as a module, we need to
  718. * iterate through all known tracepoints, since the static registration
  719. * won't work here.
  720. */
  721. for_each_kernel_tracepoint(register_tracepoints, NULL);
  722. return 0;
  723. }
  724. static void kfence_suite_exit(struct kunit_suite *suite)
  725. {
  726. for_each_kernel_tracepoint(unregister_tracepoints, NULL);
  727. tracepoint_synchronize_unregister();
  728. }
  729. static struct kunit_suite kfence_test_suite = {
  730. .name = "kfence",
  731. .test_cases = kfence_test_cases,
  732. .init = test_init,
  733. .exit = test_exit,
  734. .suite_init = kfence_suite_init,
  735. .suite_exit = kfence_suite_exit,
  736. };
  737. kunit_test_suites(&kfence_test_suite);
  738. MODULE_LICENSE("GPL v2");
  739. MODULE_AUTHOR("Alexander Potapenko <[email protected]>, Marco Elver <[email protected]>");