2 * Copyright 2015-2022 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright 2004-2014, Akamai Technologies. All Rights Reserved.
5 * Licensed under the Apache License 2.0 (the "License"). You may not use
6 * this file except in compliance with the License. You can obtain a copy
7 * in the file LICENSE in the source distribution or at
8 * https://www.openssl.org/source/license.html
12 * This file is in two halves. The first half implements the public API
13 * to be used by external consumers, and to be used by OpenSSL to store
14 * data in a "secure arena." The second half implements the secure arena.
15 * For details on that implementation, see below (look for uppercase
16 * "SECURE HEAP IMPLEMENTATION").
18 #include "internal/e_os.h"
19 #include <openssl/crypto.h>
23 #ifndef OPENSSL_NO_SECURE_MEMORY
26 # if defined(WINAPI_FAMILY_PARTITION) \
27 && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_SYSTEM)
29 * While VirtualLock is available under the app partition (e.g. UWP),
30 * the headers do not define the API. Define it ourselves instead.
36 _In_ LPVOID lpAddress,
43 # if defined(OPENSSL_SYS_UNIX)
46 # include <sys/types.h>
47 # if defined(OPENSSL_SYS_UNIX)
48 # include <sys/mman.h>
49 # if defined(__FreeBSD__)
50 # define MADV_DONTDUMP MADV_NOCORE
52 # if !defined(MAP_CONCEAL)
53 # define MAP_CONCEAL 0
56 # if defined(OPENSSL_SYS_LINUX)
57 # include <sys/syscall.h>
58 # if defined(SYS_mlock2)
59 # include <linux/mman.h>
62 # include <sys/param.h>
64 # include <sys/stat.h>
68 #define CLEAR(p, s) OPENSSL_cleanse(p, s)
70 # define PAGE_SIZE 4096
72 #if !defined(MAP_ANON) && defined(MAP_ANONYMOUS)
73 # define MAP_ANON MAP_ANONYMOUS
76 #ifndef OPENSSL_NO_SECURE_MEMORY
77 static size_t secure_mem_used;
79 static int secure_mem_initialized;
81 static CRYPTO_RWLOCK *sec_malloc_lock = NULL;
84 * These are the functions that must be implemented by a secure heap (sh).
86 static int sh_init(size_t size, size_t minsize);
87 static void *sh_malloc(size_t size);
88 static void sh_free(void *ptr);
89 static void sh_done(void);
90 static size_t sh_actual_size(char *ptr);
91 static int sh_allocated(const char *ptr);
94 int CRYPTO_secure_malloc_init(size_t size, size_t minsize)
96 #ifndef OPENSSL_NO_SECURE_MEMORY
99 if (!secure_mem_initialized) {
100 sec_malloc_lock = CRYPTO_THREAD_lock_new();
101 if (sec_malloc_lock == NULL)
103 if ((ret = sh_init(size, minsize)) != 0) {
104 secure_mem_initialized = 1;
106 CRYPTO_THREAD_lock_free(sec_malloc_lock);
107 sec_malloc_lock = NULL;
114 #endif /* OPENSSL_NO_SECURE_MEMORY */
117 int CRYPTO_secure_malloc_done(void)
119 #ifndef OPENSSL_NO_SECURE_MEMORY
120 if (secure_mem_used == 0) {
122 secure_mem_initialized = 0;
123 CRYPTO_THREAD_lock_free(sec_malloc_lock);
124 sec_malloc_lock = NULL;
127 #endif /* OPENSSL_NO_SECURE_MEMORY */
131 int CRYPTO_secure_malloc_initialized(void)
133 #ifndef OPENSSL_NO_SECURE_MEMORY
134 return secure_mem_initialized;
137 #endif /* OPENSSL_NO_SECURE_MEMORY */
140 void *CRYPTO_secure_malloc(size_t num, const char *file, int line)
142 #ifndef OPENSSL_NO_SECURE_MEMORY
146 if (!secure_mem_initialized) {
147 return CRYPTO_malloc(num, file, line);
149 if (!CRYPTO_THREAD_write_lock(sec_malloc_lock))
151 ret = sh_malloc(num);
152 actual_size = ret ? sh_actual_size(ret) : 0;
153 secure_mem_used += actual_size;
154 CRYPTO_THREAD_unlock(sec_malloc_lock);
157 return CRYPTO_malloc(num, file, line);
158 #endif /* OPENSSL_NO_SECURE_MEMORY */
161 void *CRYPTO_secure_zalloc(size_t num, const char *file, int line)
163 #ifndef OPENSSL_NO_SECURE_MEMORY
164 if (secure_mem_initialized)
165 /* CRYPTO_secure_malloc() zeroes allocations when it is implemented */
166 return CRYPTO_secure_malloc(num, file, line);
168 return CRYPTO_zalloc(num, file, line);
171 void CRYPTO_secure_free(void *ptr, const char *file, int line)
173 #ifndef OPENSSL_NO_SECURE_MEMORY
178 if (!CRYPTO_secure_allocated(ptr)) {
179 CRYPTO_free(ptr, file, line);
182 if (!CRYPTO_THREAD_write_lock(sec_malloc_lock))
184 actual_size = sh_actual_size(ptr);
185 CLEAR(ptr, actual_size);
186 secure_mem_used -= actual_size;
188 CRYPTO_THREAD_unlock(sec_malloc_lock);
190 CRYPTO_free(ptr, file, line);
191 #endif /* OPENSSL_NO_SECURE_MEMORY */
194 void CRYPTO_secure_clear_free(void *ptr, size_t num,
195 const char *file, int line)
197 #ifndef OPENSSL_NO_SECURE_MEMORY
202 if (!CRYPTO_secure_allocated(ptr)) {
203 OPENSSL_cleanse(ptr, num);
204 CRYPTO_free(ptr, file, line);
207 if (!CRYPTO_THREAD_write_lock(sec_malloc_lock))
209 actual_size = sh_actual_size(ptr);
210 CLEAR(ptr, actual_size);
211 secure_mem_used -= actual_size;
213 CRYPTO_THREAD_unlock(sec_malloc_lock);
217 OPENSSL_cleanse(ptr, num);
218 CRYPTO_free(ptr, file, line);
219 #endif /* OPENSSL_NO_SECURE_MEMORY */
222 int CRYPTO_secure_allocated(const void *ptr)
224 #ifndef OPENSSL_NO_SECURE_MEMORY
225 if (!secure_mem_initialized)
228 * Only read accesses to the arena take place in sh_allocated() and this
229 * is only changed by the sh_init() and sh_done() calls which are not
230 * locked. Hence, it is safe to make this check without a lock too.
232 return sh_allocated(ptr);
235 #endif /* OPENSSL_NO_SECURE_MEMORY */
238 size_t CRYPTO_secure_used(void)
240 #ifndef OPENSSL_NO_SECURE_MEMORY
241 return secure_mem_used;
244 #endif /* OPENSSL_NO_SECURE_MEMORY */
247 size_t CRYPTO_secure_actual_size(void *ptr)
249 #ifndef OPENSSL_NO_SECURE_MEMORY
252 if (!CRYPTO_THREAD_write_lock(sec_malloc_lock))
254 actual_size = sh_actual_size(ptr);
255 CRYPTO_THREAD_unlock(sec_malloc_lock);
263 * SECURE HEAP IMPLEMENTATION
265 #ifndef OPENSSL_NO_SECURE_MEMORY
269 * The implementation provided here uses a fixed-sized mmap() heap,
270 * which is locked into memory, not written to core files, and protected
271 * on either side by an unmapped page, which will catch pointer overruns
272 * (or underruns) and an attempt to read data out of the secure heap.
273 * Free'd memory is zero'd or otherwise cleansed.
275 * This is a pretty standard buddy allocator. We keep areas in a multiple
276 * of "sh.minsize" units. The freelist and bitmaps are kept separately,
277 * so all (and only) data is kept in the mmap'd heap.
279 * This code assumes eight-bit bytes. The numbers 3 and 7 are all over the
283 #define ONE ((size_t)1)
285 # define TESTBIT(t, b) (t[(b) >> 3] & (ONE << ((b) & 7)))
286 # define SETBIT(t, b) (t[(b) >> 3] |= (ONE << ((b) & 7)))
287 # define CLEARBIT(t, b) (t[(b) >> 3] &= (0xFF & ~(ONE << ((b) & 7))))
289 #define WITHIN_ARENA(p) \
290 ((char*)(p) >= sh.arena && (char*)(p) < &sh.arena[sh.arena_size])
291 #define WITHIN_FREELIST(p) \
292 ((char*)(p) >= (char*)sh.freelist && (char*)(p) < (char*)&sh.freelist[sh.freelist_size])
295 typedef struct sh_list_st
297 struct sh_list_st *next;
298 struct sh_list_st **p_next;
308 ossl_ssize_t freelist_size;
310 unsigned char *bittable;
311 unsigned char *bitmalloc;
312 size_t bittable_size; /* size in bits */
317 static size_t sh_getlist(char *ptr)
319 ossl_ssize_t list = sh.freelist_size - 1;
320 size_t bit = (sh.arena_size + ptr - sh.arena) / sh.minsize;
322 for (; bit; bit >>= 1, list--) {
323 if (TESTBIT(sh.bittable, bit))
325 OPENSSL_assert((bit & 1) == 0);
332 static int sh_testbit(char *ptr, int list, unsigned char *table)
336 OPENSSL_assert(list >= 0 && list < sh.freelist_size);
337 OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0);
338 bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list));
339 OPENSSL_assert(bit > 0 && bit < sh.bittable_size);
340 return TESTBIT(table, bit);
343 static void sh_clearbit(char *ptr, int list, unsigned char *table)
347 OPENSSL_assert(list >= 0 && list < sh.freelist_size);
348 OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0);
349 bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list));
350 OPENSSL_assert(bit > 0 && bit < sh.bittable_size);
351 OPENSSL_assert(TESTBIT(table, bit));
352 CLEARBIT(table, bit);
355 static void sh_setbit(char *ptr, int list, unsigned char *table)
359 OPENSSL_assert(list >= 0 && list < sh.freelist_size);
360 OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0);
361 bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list));
362 OPENSSL_assert(bit > 0 && bit < sh.bittable_size);
363 OPENSSL_assert(!TESTBIT(table, bit));
367 static void sh_add_to_list(char **list, char *ptr)
371 OPENSSL_assert(WITHIN_FREELIST(list));
372 OPENSSL_assert(WITHIN_ARENA(ptr));
374 temp = (SH_LIST *)ptr;
375 temp->next = *(SH_LIST **)list;
376 OPENSSL_assert(temp->next == NULL || WITHIN_ARENA(temp->next));
377 temp->p_next = (SH_LIST **)list;
379 if (temp->next != NULL) {
380 OPENSSL_assert((char **)temp->next->p_next == list);
381 temp->next->p_next = &(temp->next);
387 static void sh_remove_from_list(char *ptr)
389 SH_LIST *temp, *temp2;
391 temp = (SH_LIST *)ptr;
392 if (temp->next != NULL)
393 temp->next->p_next = temp->p_next;
394 *temp->p_next = temp->next;
395 if (temp->next == NULL)
399 OPENSSL_assert(WITHIN_FREELIST(temp2->p_next) || WITHIN_ARENA(temp2->p_next));
403 static int sh_init(size_t size, size_t minsize)
411 SYSTEM_INFO systemInfo;
414 memset(&sh, 0, sizeof(sh));
416 /* make sure size is a powers of 2 */
417 OPENSSL_assert(size > 0);
418 OPENSSL_assert((size & (size - 1)) == 0);
419 if (size == 0 || (size & (size - 1)) != 0)
422 if (minsize <= sizeof(SH_LIST)) {
423 OPENSSL_assert(sizeof(SH_LIST) <= 65536);
425 * Compute the minimum possible allocation size.
426 * This must be a power of 2 and at least as large as the SH_LIST
429 minsize = sizeof(SH_LIST) - 1;
430 minsize |= minsize >> 1;
431 minsize |= minsize >> 2;
432 if (sizeof(SH_LIST) > 16)
433 minsize |= minsize >> 4;
434 if (sizeof(SH_LIST) > 256)
435 minsize |= minsize >> 8;
438 /* make sure minsize is a powers of 2 */
439 OPENSSL_assert((minsize & (minsize - 1)) == 0);
440 if ((minsize & (minsize - 1)) != 0)
444 sh.arena_size = size;
445 sh.minsize = minsize;
446 sh.bittable_size = (sh.arena_size / sh.minsize) * 2;
448 /* Prevent allocations of size 0 later on */
449 if (sh.bittable_size >> 3 == 0)
452 sh.freelist_size = -1;
453 for (i = sh.bittable_size; i; i >>= 1)
456 sh.freelist = OPENSSL_zalloc(sh.freelist_size * sizeof(char *));
457 OPENSSL_assert(sh.freelist != NULL);
458 if (sh.freelist == NULL)
461 sh.bittable = OPENSSL_zalloc(sh.bittable_size >> 3);
462 OPENSSL_assert(sh.bittable != NULL);
463 if (sh.bittable == NULL)
466 sh.bitmalloc = OPENSSL_zalloc(sh.bittable_size >> 3);
467 OPENSSL_assert(sh.bitmalloc != NULL);
468 if (sh.bitmalloc == NULL)
471 /* Allocate space for heap, and two extra pages as guards */
472 #if defined(_SC_PAGE_SIZE) || defined (_SC_PAGESIZE)
474 # if defined(_SC_PAGE_SIZE)
475 long tmppgsize = sysconf(_SC_PAGE_SIZE);
477 long tmppgsize = sysconf(_SC_PAGESIZE);
482 pgsize = (size_t)tmppgsize;
484 #elif defined(_WIN32)
485 GetSystemInfo(&systemInfo);
486 pgsize = (size_t)systemInfo.dwPageSize;
490 sh.map_size = pgsize + sh.arena_size + pgsize;
494 sh.map_result = mmap(NULL, sh.map_size,
495 PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE|MAP_CONCEAL, -1, 0);
500 sh.map_result = MAP_FAILED;
501 if ((fd = open("/dev/zero", O_RDWR)) >= 0) {
502 sh.map_result = mmap(NULL, sh.map_size,
503 PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
508 if (sh.map_result == MAP_FAILED)
511 sh.map_result = VirtualAlloc(NULL, sh.map_size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
513 if (sh.map_result == NULL)
517 sh.arena = (char *)(sh.map_result + pgsize);
518 sh_setbit(sh.arena, 0, sh.bittable);
519 sh_add_to_list(&sh.freelist[0], sh.arena);
521 /* Now try to add guard pages and lock into memory. */
525 /* Starting guard is already aligned from mmap. */
526 if (mprotect(sh.map_result, pgsize, PROT_NONE) < 0)
529 if (VirtualProtect(sh.map_result, pgsize, PAGE_NOACCESS, &flOldProtect) == FALSE)
533 /* Ending guard page - need to round up to page boundary */
534 aligned = (pgsize + sh.arena_size + (pgsize - 1)) & ~(pgsize - 1);
536 if (mprotect(sh.map_result + aligned, pgsize, PROT_NONE) < 0)
539 if (VirtualProtect(sh.map_result + aligned, pgsize, PAGE_NOACCESS, &flOldProtect) == FALSE)
543 #if defined(OPENSSL_SYS_LINUX) && defined(MLOCK_ONFAULT) && defined(SYS_mlock2)
544 if (syscall(SYS_mlock2, sh.arena, sh.arena_size, MLOCK_ONFAULT) < 0) {
545 if (errno == ENOSYS) {
546 if (mlock(sh.arena, sh.arena_size) < 0)
552 #elif defined(_WIN32)
553 if (VirtualLock(sh.arena, sh.arena_size) == FALSE)
556 if (mlock(sh.arena, sh.arena_size) < 0)
560 if (madvise(sh.arena, sh.arena_size, MADV_DONTDUMP) < 0)
571 static void sh_done(void)
573 OPENSSL_free(sh.freelist);
574 OPENSSL_free(sh.bittable);
575 OPENSSL_free(sh.bitmalloc);
577 if (sh.map_result != MAP_FAILED && sh.map_size)
578 munmap(sh.map_result, sh.map_size);
580 if (sh.map_result != NULL && sh.map_size)
581 VirtualFree(sh.map_result, 0, MEM_RELEASE);
583 memset(&sh, 0, sizeof(sh));
586 static int sh_allocated(const char *ptr)
588 return WITHIN_ARENA(ptr) ? 1 : 0;
591 static char *sh_find_my_buddy(char *ptr, int list)
596 bit = (ONE << list) + (ptr - sh.arena) / (sh.arena_size >> list);
599 if (TESTBIT(sh.bittable, bit) && !TESTBIT(sh.bitmalloc, bit))
600 chunk = sh.arena + ((bit & ((ONE << list) - 1)) * (sh.arena_size >> list));
605 static void *sh_malloc(size_t size)
607 ossl_ssize_t list, slist;
611 if (size > sh.arena_size)
614 list = sh.freelist_size - 1;
615 for (i = sh.minsize; i < size; i <<= 1)
620 /* try to find a larger entry to split */
621 for (slist = list; slist >= 0; slist--)
622 if (sh.freelist[slist] != NULL)
627 /* split larger entry */
628 while (slist != list) {
629 char *temp = sh.freelist[slist];
631 /* remove from bigger list */
632 OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc));
633 sh_clearbit(temp, slist, sh.bittable);
634 sh_remove_from_list(temp);
635 OPENSSL_assert(temp != sh.freelist[slist]);
637 /* done with bigger list */
640 /* add to smaller list */
641 OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc));
642 sh_setbit(temp, slist, sh.bittable);
643 sh_add_to_list(&sh.freelist[slist], temp);
644 OPENSSL_assert(sh.freelist[slist] == temp);
647 temp += sh.arena_size >> slist;
648 OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc));
649 sh_setbit(temp, slist, sh.bittable);
650 sh_add_to_list(&sh.freelist[slist], temp);
651 OPENSSL_assert(sh.freelist[slist] == temp);
653 OPENSSL_assert(temp-(sh.arena_size >> slist) == sh_find_my_buddy(temp, slist));
656 /* peel off memory to hand back */
657 chunk = sh.freelist[list];
658 OPENSSL_assert(sh_testbit(chunk, list, sh.bittable));
659 sh_setbit(chunk, list, sh.bitmalloc);
660 sh_remove_from_list(chunk);
662 OPENSSL_assert(WITHIN_ARENA(chunk));
664 /* zero the free list header as a precaution against information leakage */
665 memset(chunk, 0, sizeof(SH_LIST));
670 static void sh_free(void *ptr)
677 OPENSSL_assert(WITHIN_ARENA(ptr));
678 if (!WITHIN_ARENA(ptr))
681 list = sh_getlist(ptr);
682 OPENSSL_assert(sh_testbit(ptr, list, sh.bittable));
683 sh_clearbit(ptr, list, sh.bitmalloc);
684 sh_add_to_list(&sh.freelist[list], ptr);
686 /* Try to coalesce two adjacent free areas. */
687 while ((buddy = sh_find_my_buddy(ptr, list)) != NULL) {
688 OPENSSL_assert(ptr == sh_find_my_buddy(buddy, list));
689 OPENSSL_assert(ptr != NULL);
690 OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc));
691 sh_clearbit(ptr, list, sh.bittable);
692 sh_remove_from_list(ptr);
693 OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc));
694 sh_clearbit(buddy, list, sh.bittable);
695 sh_remove_from_list(buddy);
699 /* Zero the higher addressed block's free list pointers */
700 memset(ptr > buddy ? ptr : buddy, 0, sizeof(SH_LIST));
704 OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc));
705 sh_setbit(ptr, list, sh.bittable);
706 sh_add_to_list(&sh.freelist[list], ptr);
707 OPENSSL_assert(sh.freelist[list] == ptr);
711 static size_t sh_actual_size(char *ptr)
715 OPENSSL_assert(WITHIN_ARENA(ptr));
716 if (!WITHIN_ARENA(ptr))
718 list = sh_getlist(ptr);
719 OPENSSL_assert(sh_testbit(ptr, list, sh.bittable));
720 return sh.arena_size / (ONE << list);
722 #endif /* OPENSSL_NO_SECURE_MEMORY */