memguard.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. /*-
  2. * SPDX-License-Identifier: BSD-2-Clause
  3. *
  4. * Copyright (c) 2005, Bosko Milekic <bmilekic@FreeBSD.org>.
  5. * Copyright (c) 2010 Isilon Systems, Inc. (http://www.isilon.com/)
  6. * All rights reserved.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions
  10. * are met:
  11. * 1. Redistributions of source code must retain the above copyright
  12. * notice unmodified, this list of conditions, and the following
  13. * disclaimer.
  14. * 2. Redistributions in binary form must reproduce the above copyright
  15. * notice, this list of conditions and the following disclaimer in the
  16. * documentation and/or other materials provided with the distribution.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  19. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  20. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  21. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  22. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  23. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  24. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  25. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  27. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. */
  29. #include <sys/cdefs.h>
  30. /*
  31. * MemGuard is a simple replacement allocator for debugging only
  32. * which provides ElectricFence-style memory barrier protection on
  33. * objects being allocated, and is used to detect tampering-after-free
  34. * scenarios.
  35. *
  36. * See the memguard(9) man page for more information on using MemGuard.
  37. */
  38. #include "opt_vm.h"
  39. #include <sys/param.h>
  40. #include <sys/systm.h>
  41. #include <sys/kernel.h>
  42. #include <sys/types.h>
  43. #include <sys/queue.h>
  44. #include <sys/lock.h>
  45. #include <sys/mutex.h>
  46. #include <sys/malloc.h>
  47. #include <sys/sysctl.h>
  48. #include <sys/vmem.h>
  49. #include <sys/vmmeter.h>
  50. #include <vm/vm.h>
  51. #include <vm/uma.h>
  52. #include <vm/vm_param.h>
  53. #include <vm/vm_page.h>
  54. #include <vm/vm_map.h>
  55. #include <vm/vm_object.h>
  56. #include <vm/vm_kern.h>
  57. #include <vm/vm_extern.h>
  58. #include <vm/uma_int.h>
  59. #include <vm/memguard.h>
  60. static SYSCTL_NODE(_vm, OID_AUTO, memguard, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
  61. "MemGuard data");
  62. /*
  63. * The vm_memguard_divisor variable controls how much of kernel_arena should be
  64. * reserved for MemGuard.
  65. */
  66. static u_int vm_memguard_divisor;
  67. SYSCTL_UINT(_vm_memguard, OID_AUTO, divisor, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
  68. &vm_memguard_divisor,
  69. 0, "(kmem_size/memguard_divisor) == memguard submap size");
  70. /*
  71. * Short description (ks_shortdesc) of memory type to monitor.
  72. */
  73. static char vm_memguard_desc[128] = "";
  74. static struct malloc_type *vm_memguard_mtype = NULL;
  75. TUNABLE_STR("vm.memguard.desc", vm_memguard_desc, sizeof(vm_memguard_desc));
  76. static int
  77. memguard_sysctl_desc(SYSCTL_HANDLER_ARGS)
  78. {
  79. char desc[sizeof(vm_memguard_desc)];
  80. int error;
  81. strlcpy(desc, vm_memguard_desc, sizeof(desc));
  82. error = sysctl_handle_string(oidp, desc, sizeof(desc), req);
  83. if (error != 0 || req->newptr == NULL)
  84. return (error);
  85. mtx_lock(&malloc_mtx);
  86. /* If mtp is NULL, it will be initialized in memguard_cmp() */
  87. vm_memguard_mtype = malloc_desc2type(desc);
  88. strlcpy(vm_memguard_desc, desc, sizeof(vm_memguard_desc));
  89. mtx_unlock(&malloc_mtx);
  90. return (error);
  91. }
  92. SYSCTL_PROC(_vm_memguard, OID_AUTO, desc,
  93. CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 0,
  94. memguard_sysctl_desc, "A", "Short description of memory type to monitor");
  95. static int
  96. memguard_sysctl_mapused(SYSCTL_HANDLER_ARGS)
  97. {
  98. vmem_size_t size;
  99. size = vmem_size(memguard_arena, VMEM_ALLOC);
  100. return (sysctl_handle_long(oidp, &size, sizeof(size), req));
  101. }
  102. static vm_offset_t memguard_base;
  103. static vm_size_t memguard_mapsize;
  104. static vm_size_t memguard_physlimit;
  105. static u_long memguard_wasted;
  106. static u_long memguard_succ;
  107. static u_long memguard_fail_kva;
  108. static u_long memguard_fail_pgs;
  109. SYSCTL_ULONG(_vm_memguard, OID_AUTO, mapsize, CTLFLAG_RD,
  110. &memguard_mapsize, 0, "MemGuard private arena size");
  111. SYSCTL_ULONG(_vm_memguard, OID_AUTO, phys_limit, CTLFLAG_RD,
  112. &memguard_physlimit, 0, "Limit on MemGuard memory consumption");
  113. SYSCTL_ULONG(_vm_memguard, OID_AUTO, wasted, CTLFLAG_RD,
  114. &memguard_wasted, 0, "Excess memory used through page promotion");
  115. SYSCTL_ULONG(_vm_memguard, OID_AUTO, numalloc, CTLFLAG_RD,
  116. &memguard_succ, 0, "Count of successful MemGuard allocations");
  117. SYSCTL_ULONG(_vm_memguard, OID_AUTO, fail_kva, CTLFLAG_RD,
  118. &memguard_fail_kva, 0, "MemGuard failures due to lack of KVA");
  119. SYSCTL_ULONG(_vm_memguard, OID_AUTO, fail_pgs, CTLFLAG_RD,
  120. &memguard_fail_pgs, 0, "MemGuard failures due to lack of pages");
  121. #define MG_GUARD_AROUND 0x001
  122. #define MG_GUARD_ALLLARGE 0x002
  123. #define MG_GUARD_NOFREE 0x004
  124. static int memguard_options = MG_GUARD_AROUND;
  125. SYSCTL_INT(_vm_memguard, OID_AUTO, options, CTLFLAG_RWTUN,
  126. &memguard_options, 0,
  127. "MemGuard options:\n"
  128. "\t0x001 - add guard pages around each allocation\n"
  129. "\t0x002 - always use MemGuard for allocations over a page\n"
  130. "\t0x004 - guard uma(9) zones with UMA_ZONE_NOFREE flag");
  131. static u_int memguard_minsize;
  132. static u_long memguard_minsize_reject;
  133. SYSCTL_UINT(_vm_memguard, OID_AUTO, minsize, CTLFLAG_RW,
  134. &memguard_minsize, 0, "Minimum size for page promotion");
  135. SYSCTL_ULONG(_vm_memguard, OID_AUTO, minsize_reject, CTLFLAG_RD,
  136. &memguard_minsize_reject, 0, "# times rejected for size");
  137. static u_int memguard_frequency;
  138. static u_long memguard_frequency_hits;
  139. SYSCTL_UINT(_vm_memguard, OID_AUTO, frequency, CTLFLAG_RWTUN,
  140. &memguard_frequency, 0, "Times in 100000 that MemGuard will randomly run");
  141. SYSCTL_ULONG(_vm_memguard, OID_AUTO, frequency_hits, CTLFLAG_RD,
  142. &memguard_frequency_hits, 0, "# times MemGuard randomly chose");
  143. /*
  144. * Return a fudged value to be used for vm_kmem_size for allocating
  145. * the kernel_arena.
  146. */
  147. unsigned long
  148. memguard_fudge(unsigned long km_size, const struct vm_map *parent_map)
  149. {
  150. u_long mem_pgs, parent_size;
  151. vm_memguard_divisor = 10;
  152. /* CTFLAG_RDTUN doesn't work during the early boot process. */
  153. TUNABLE_INT_FETCH("vm.memguard.divisor", &vm_memguard_divisor);
  154. parent_size = vm_map_max(parent_map) - vm_map_min(parent_map) +
  155. PAGE_SIZE;
  156. /* Pick a conservative value if provided value sucks. */
  157. if ((vm_memguard_divisor <= 0) ||
  158. ((parent_size / vm_memguard_divisor) == 0))
  159. vm_memguard_divisor = 10;
  160. /*
  161. * Limit consumption of physical pages to
  162. * 1/vm_memguard_divisor of system memory. If the KVA is
  163. * smaller than this then the KVA limit comes into play first.
  164. * This prevents memguard's page promotions from completely
  165. * using up memory, since most malloc(9) calls are sub-page.
  166. */
  167. mem_pgs = vm_cnt.v_page_count;
  168. memguard_physlimit = (mem_pgs / vm_memguard_divisor) * PAGE_SIZE;
  169. /*
  170. * We want as much KVA as we can take safely. Use at most our
  171. * allotted fraction of the parent map's size. Limit this to
  172. * twice the physical memory to avoid using too much memory as
  173. * pagetable pages (size must be multiple of PAGE_SIZE).
  174. */
  175. memguard_mapsize = round_page(parent_size / vm_memguard_divisor);
  176. if (memguard_mapsize / (2 * PAGE_SIZE) > mem_pgs)
  177. memguard_mapsize = mem_pgs * 2 * PAGE_SIZE;
  178. if (km_size + memguard_mapsize > parent_size)
  179. memguard_mapsize = 0;
  180. return (km_size + memguard_mapsize);
  181. }
  182. /*
  183. * Initialize the MemGuard mock allocator. All objects from MemGuard come
  184. * out of a single contiguous chunk of kernel address space that is managed
  185. * by a vmem arena.
  186. */
  187. void
  188. memguard_init(vmem_t *parent)
  189. {
  190. vm_offset_t base;
  191. vmem_alloc(parent, memguard_mapsize, M_BESTFIT | M_WAITOK, &base);
  192. vmem_init(memguard_arena, "memguard arena", base, memguard_mapsize,
  193. PAGE_SIZE, 0, M_WAITOK);
  194. memguard_base = base;
  195. printf("MEMGUARD DEBUGGING ALLOCATOR INITIALIZED:\n");
  196. printf("\tMEMGUARD map base: 0x%lx\n", (u_long)base);
  197. printf("\tMEMGUARD map size: %jd KBytes\n",
  198. (uintmax_t)memguard_mapsize >> 10);
  199. }
  200. /*
  201. * Run things that can't be done as early as memguard_init().
  202. */
  203. static void
  204. memguard_sysinit(void)
  205. {
  206. struct sysctl_oid_list *parent;
  207. parent = SYSCTL_STATIC_CHILDREN(_vm_memguard);
  208. SYSCTL_ADD_UAUTO(NULL, parent, OID_AUTO, "mapstart",
  209. CTLFLAG_RD, &memguard_base,
  210. "MemGuard KVA base");
  211. SYSCTL_ADD_UAUTO(NULL, parent, OID_AUTO, "maplimit",
  212. CTLFLAG_RD, &memguard_mapsize,
  213. "MemGuard KVA size");
  214. SYSCTL_ADD_PROC(NULL, parent, OID_AUTO, "mapused",
  215. CTLFLAG_RD | CTLFLAG_MPSAFE | CTLTYPE_ULONG, NULL, 0, memguard_sysctl_mapused, "LU",
  216. "MemGuard KVA used");
  217. }
  218. SYSINIT(memguard, SI_SUB_KLD, SI_ORDER_ANY, memguard_sysinit, NULL);
  219. /*
  220. * v2sizep() converts a virtual address of the first page allocated for
  221. * an item to a pointer to u_long recording the size of the original
  222. * allocation request.
  223. *
  224. * This routine is very similar to those defined by UMA in uma_int.h.
  225. * The difference is that this routine stores the originally allocated
  226. * size in one of the page's fields that is unused when the page is
  227. * wired rather than the object field, which is used.
  228. */
  229. static u_long *
  230. v2sizep(vm_offset_t va)
  231. {
  232. vm_paddr_t pa;
  233. struct vm_page *p;
  234. pa = pmap_kextract(va);
  235. if (pa == 0)
  236. panic("MemGuard detected double-free of %p", (void *)va);
  237. p = PHYS_TO_VM_PAGE(pa);
  238. KASSERT(vm_page_wired(p) && p->a.queue == PQ_NONE,
  239. ("MEMGUARD: Expected wired page %p in vtomgfifo!", p));
  240. return (&p->plinks.memguard.p);
  241. }
  242. static u_long *
  243. v2sizev(vm_offset_t va)
  244. {
  245. vm_paddr_t pa;
  246. struct vm_page *p;
  247. pa = pmap_kextract(va);
  248. if (pa == 0)
  249. panic("MemGuard detected double-free of %p", (void *)va);
  250. p = PHYS_TO_VM_PAGE(pa);
  251. KASSERT(vm_page_wired(p) && p->a.queue == PQ_NONE,
  252. ("MEMGUARD: Expected wired page %p in vtomgfifo!", p));
  253. return (&p->plinks.memguard.v);
  254. }
  255. /*
  256. * Allocate a single object of specified size with specified flags
  257. * (either M_WAITOK or M_NOWAIT).
  258. */
  259. void *
  260. memguard_alloc(unsigned long req_size, int flags)
  261. {
  262. vm_offset_t addr, origaddr;
  263. u_long size_p, size_v;
  264. int do_guard, error, rv;
  265. size_p = round_page(req_size);
  266. if (size_p == 0)
  267. return (NULL);
  268. /*
  269. * To ensure there are holes on both sides of the allocation,
  270. * request 2 extra pages of KVA. Save the value of memguard_options
  271. * so that we use a consistent value throughout this function.
  272. */
  273. size_v = size_p;
  274. do_guard = (memguard_options & MG_GUARD_AROUND) != 0;
  275. if (do_guard)
  276. size_v += 2 * PAGE_SIZE;
  277. /*
  278. * When we pass our memory limit, reject sub-page allocations.
  279. * Page-size and larger allocations will use the same amount
  280. * of physical memory whether we allocate or hand off to
  281. * malloc_large(), so keep those.
  282. */
  283. if (vmem_size(memguard_arena, VMEM_ALLOC) >= memguard_physlimit &&
  284. req_size < PAGE_SIZE) {
  285. addr = (vm_offset_t)NULL;
  286. memguard_fail_pgs++;
  287. goto out;
  288. }
  289. /*
  290. * Attempt to avoid address reuse for as long as possible, to increase
  291. * the likelihood of catching a use-after-free.
  292. */
  293. error = vmem_alloc(memguard_arena, size_v, M_NEXTFIT | M_NOWAIT,
  294. &origaddr);
  295. if (error != 0) {
  296. memguard_fail_kva++;
  297. addr = (vm_offset_t)NULL;
  298. goto out;
  299. }
  300. addr = origaddr;
  301. if (do_guard)
  302. addr += PAGE_SIZE;
  303. rv = kmem_back(kernel_object, addr, size_p, flags);
  304. if (rv != KERN_SUCCESS) {
  305. vmem_xfree(memguard_arena, origaddr, size_v);
  306. memguard_fail_pgs++;
  307. addr = (vm_offset_t)NULL;
  308. goto out;
  309. }
  310. *v2sizep(trunc_page(addr)) = req_size;
  311. *v2sizev(trunc_page(addr)) = size_v;
  312. memguard_succ++;
  313. if (req_size < PAGE_SIZE) {
  314. memguard_wasted += (PAGE_SIZE - req_size);
  315. if (do_guard) {
  316. /*
  317. * Align the request to 16 bytes, and return
  318. * an address near the end of the page, to
  319. * better detect array overrun.
  320. */
  321. req_size = roundup2(req_size, 16);
  322. addr += (PAGE_SIZE - req_size);
  323. }
  324. }
  325. out:
  326. return ((void *)addr);
  327. }
  328. int
  329. is_memguard_addr(void *addr)
  330. {
  331. vm_offset_t a = (vm_offset_t)(uintptr_t)addr;
  332. return (a >= memguard_base && a < memguard_base + memguard_mapsize);
  333. }
  334. /*
  335. * Free specified single object.
  336. */
  337. void
  338. memguard_free(void *ptr)
  339. {
  340. vm_offset_t addr;
  341. u_long req_size, size, sizev;
  342. char *temp;
  343. int i;
  344. addr = trunc_page((uintptr_t)ptr);
  345. req_size = *v2sizep(addr);
  346. sizev = *v2sizev(addr);
  347. size = round_page(req_size);
  348. /*
  349. * Page should not be guarded right now, so force a write.
  350. * The purpose of this is to increase the likelihood of
  351. * catching a double-free, but not necessarily a
  352. * tamper-after-free (the second thread freeing might not
  353. * write before freeing, so this forces it to and,
  354. * subsequently, trigger a fault).
  355. */
  356. temp = ptr;
  357. for (i = 0; i < size; i += PAGE_SIZE)
  358. temp[i] = 'M';
  359. /*
  360. * This requires carnal knowledge of the implementation of
  361. * kmem_free(), but since we've already replaced kmem_malloc()
  362. * above, it's not really any worse. We want to use the
  363. * vm_map lock to serialize updates to memguard_wasted, since
  364. * we had the lock at increment.
  365. */
  366. kmem_unback(kernel_object, addr, size);
  367. if (sizev > size)
  368. addr -= PAGE_SIZE;
  369. vmem_xfree(memguard_arena, addr, sizev);
  370. if (req_size < PAGE_SIZE)
  371. memguard_wasted -= (PAGE_SIZE - req_size);
  372. }
  373. /*
  374. * Re-allocate an allocation that was originally guarded.
  375. */
  376. void *
  377. memguard_realloc(void *addr, unsigned long size, struct malloc_type *mtp,
  378. int flags)
  379. {
  380. void *newaddr;
  381. u_long old_size;
  382. /*
  383. * Allocate the new block. Force the allocation to be guarded
  384. * as the original may have been guarded through random
  385. * chance, and that should be preserved.
  386. */
  387. if ((newaddr = memguard_alloc(size, flags)) == NULL)
  388. return (NULL);
  389. /* Copy over original contents. */
  390. old_size = *v2sizep(trunc_page((uintptr_t)addr));
  391. bcopy(addr, newaddr, min(size, old_size));
  392. memguard_free(addr);
  393. return (newaddr);
  394. }
  395. static int
  396. memguard_cmp(unsigned long size)
  397. {
  398. if (size < memguard_minsize) {
  399. memguard_minsize_reject++;
  400. return (0);
  401. }
  402. if ((memguard_options & MG_GUARD_ALLLARGE) != 0 && size >= PAGE_SIZE)
  403. return (1);
  404. if (memguard_frequency > 0 &&
  405. (random() % 100000) < memguard_frequency) {
  406. memguard_frequency_hits++;
  407. return (1);
  408. }
  409. return (0);
  410. }
  411. int
  412. memguard_cmp_mtp(struct malloc_type *mtp, unsigned long size)
  413. {
  414. if (memguard_cmp(size))
  415. return(1);
  416. #if 1
  417. /*
  418. * The safest way of comparison is to always compare short description
  419. * string of memory type, but it is also the slowest way.
  420. */
  421. return (strcmp(mtp->ks_shortdesc, vm_memguard_desc) == 0);
  422. #else
  423. /*
  424. * If we compare pointers, there are two possible problems:
  425. * 1. Memory type was unloaded and new memory type was allocated at the
  426. * same address.
  427. * 2. Memory type was unloaded and loaded again, but allocated at a
  428. * different address.
  429. */
  430. if (vm_memguard_mtype != NULL)
  431. return (mtp == vm_memguard_mtype);
  432. if (strcmp(mtp->ks_shortdesc, vm_memguard_desc) == 0) {
  433. vm_memguard_mtype = mtp;
  434. return (1);
  435. }
  436. return (0);
  437. #endif
  438. }
  439. int
  440. memguard_cmp_zone(uma_zone_t zone)
  441. {
  442. if ((memguard_options & MG_GUARD_NOFREE) == 0 &&
  443. zone->uz_flags & UMA_ZONE_NOFREE)
  444. return (0);
  445. if (memguard_cmp(zone->uz_size))
  446. return (1);
  447. /*
  448. * The safest way of comparison is to always compare zone name,
  449. * but it is also the slowest way.
  450. */
  451. return (strcmp(zone->uz_name, vm_memguard_desc) == 0);
  452. }
  453. unsigned long
  454. memguard_get_req_size(const void *addr)
  455. {
  456. return (*v2sizep(trunc_page((uintptr_t)addr)));
  457. }