kfence_test.c 24 KB

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