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>
20 #include <openssl/err.h>
24 #ifndef OPENSSL_NO_SECURE_MEMORY
27 # if defined(WINAPI_FAMILY_PARTITION)
28 # if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_SYSTEM)
30 * While VirtualLock is available under the app partition (e.g. UWP),
31 * the headers do not define the API. Define it ourselves instead.
37 _In_ LPVOID lpAddress,
45 # if defined(OPENSSL_SYS_UNIX)
48 # include <sys/types.h>
49 # if defined(OPENSSL_SYS_UNIX)
50 # include <sys/mman.h>
51 # if defined(__FreeBSD__)
52 # define MADV_DONTDUMP MADV_NOCORE
54 # if !defined(MAP_CONCEAL)
55 # define MAP_CONCEAL 0
58 # if defined(OPENSSL_SYS_LINUX)
59 # include <sys/syscall.h>
60 # if defined(SYS_mlock2)
61 # include <linux/mman.h>
64 # include <sys/param.h>
66 # include <sys/stat.h>
70 #define CLEAR(p, s) OPENSSL_cleanse(p, s)
72 # define PAGE_SIZE 4096
74 #if !defined(MAP_ANON) && defined(MAP_ANONYMOUS)
75 # define MAP_ANON MAP_ANONYMOUS
78 #ifndef OPENSSL_NO_SECURE_MEMORY
79 static size_t secure_mem_used;
81 static int secure_mem_initialized;
83 static CRYPTO_RWLOCK *sec_malloc_lock = NULL;
86 * These are the functions that must be implemented by a secure heap (sh).
88 static int sh_init(size_t size, size_t minsize);
89 static void *sh_malloc(size_t size);
90 static void sh_free(void *ptr);
91 static void sh_done(void);
92 static size_t sh_actual_size(char *ptr);
93 static int sh_allocated(const char *ptr);
96 int CRYPTO_secure_malloc_init(size_t size, size_t minsize)
98 #ifndef OPENSSL_NO_SECURE_MEMORY
101 if (!secure_mem_initialized) {
102 sec_malloc_lock = CRYPTO_THREAD_lock_new();
103 if (sec_malloc_lock == NULL)
105 if ((ret = sh_init(size, minsize)) != 0) {
106 secure_mem_initialized = 1;
108 CRYPTO_THREAD_lock_free(sec_malloc_lock);
109 sec_malloc_lock = NULL;
116 #endif /* OPENSSL_NO_SECURE_MEMORY */
119 int CRYPTO_secure_malloc_done(void)
121 #ifndef OPENSSL_NO_SECURE_MEMORY
122 if (secure_mem_used == 0) {
124 secure_mem_initialized = 0;
125 CRYPTO_THREAD_lock_free(sec_malloc_lock);
126 sec_malloc_lock = NULL;
129 #endif /* OPENSSL_NO_SECURE_MEMORY */
133 int CRYPTO_secure_malloc_initialized(void)
135 #ifndef OPENSSL_NO_SECURE_MEMORY
136 return secure_mem_initialized;
139 #endif /* OPENSSL_NO_SECURE_MEMORY */
142 void *CRYPTO_secure_malloc(size_t num, const char *file, int line)
144 #ifndef OPENSSL_NO_SECURE_MEMORY
147 int reason = CRYPTO_R_SECURE_MALLOC_FAILURE;
149 if (!secure_mem_initialized) {
150 return CRYPTO_malloc(num, file, line);
152 if (!CRYPTO_THREAD_write_lock(sec_malloc_lock)) {
153 reason = ERR_R_CRYPTO_LIB;
156 ret = sh_malloc(num);
157 actual_size = ret ? sh_actual_size(ret) : 0;
158 secure_mem_used += actual_size;
159 CRYPTO_THREAD_unlock(sec_malloc_lock);
161 if (ret == NULL && (file != NULL || line != 0)) {
163 ERR_set_debug(file, line, NULL);
164 ERR_set_error(ERR_LIB_CRYPTO, reason, NULL);
168 return CRYPTO_malloc(num, file, line);
169 #endif /* OPENSSL_NO_SECURE_MEMORY */
172 void *CRYPTO_secure_zalloc(size_t num, const char *file, int line)
174 #ifndef OPENSSL_NO_SECURE_MEMORY
175 if (secure_mem_initialized)
176 /* CRYPTO_secure_malloc() zeroes allocations when it is implemented */
177 return CRYPTO_secure_malloc(num, file, line);
179 return CRYPTO_zalloc(num, file, line);
182 void CRYPTO_secure_free(void *ptr, const char *file, int line)
184 #ifndef OPENSSL_NO_SECURE_MEMORY
189 if (!CRYPTO_secure_allocated(ptr)) {
190 CRYPTO_free(ptr, file, line);
193 if (!CRYPTO_THREAD_write_lock(sec_malloc_lock))
195 actual_size = sh_actual_size(ptr);
196 CLEAR(ptr, actual_size);
197 secure_mem_used -= actual_size;
199 CRYPTO_THREAD_unlock(sec_malloc_lock);
201 CRYPTO_free(ptr, file, line);
202 #endif /* OPENSSL_NO_SECURE_MEMORY */
205 void CRYPTO_secure_clear_free(void *ptr, size_t num,
206 const char *file, int line)
208 #ifndef OPENSSL_NO_SECURE_MEMORY
213 if (!CRYPTO_secure_allocated(ptr)) {
214 OPENSSL_cleanse(ptr, num);
215 CRYPTO_free(ptr, file, line);
218 if (!CRYPTO_THREAD_write_lock(sec_malloc_lock))
220 actual_size = sh_actual_size(ptr);
221 CLEAR(ptr, actual_size);
222 secure_mem_used -= actual_size;
224 CRYPTO_THREAD_unlock(sec_malloc_lock);
228 OPENSSL_cleanse(ptr, num);
229 CRYPTO_free(ptr, file, line);
230 #endif /* OPENSSL_NO_SECURE_MEMORY */
233 int CRYPTO_secure_allocated(const void *ptr)
235 #ifndef OPENSSL_NO_SECURE_MEMORY
236 if (!secure_mem_initialized)
239 * Only read accesses to the arena take place in sh_allocated() and this
240 * is only changed by the sh_init() and sh_done() calls which are not
241 * locked. Hence, it is safe to make this check without a lock too.
243 return sh_allocated(ptr);
246 #endif /* OPENSSL_NO_SECURE_MEMORY */
249 size_t CRYPTO_secure_used(void)
251 #ifndef OPENSSL_NO_SECURE_MEMORY
252 return secure_mem_used;
255 #endif /* OPENSSL_NO_SECURE_MEMORY */
258 size_t CRYPTO_secure_actual_size(void *ptr)
260 #ifndef OPENSSL_NO_SECURE_MEMORY
263 if (!CRYPTO_THREAD_write_lock(sec_malloc_lock))
265 actual_size = sh_actual_size(ptr);
266 CRYPTO_THREAD_unlock(sec_malloc_lock);
274 * SECURE HEAP IMPLEMENTATION
276 #ifndef OPENSSL_NO_SECURE_MEMORY
280 * The implementation provided here uses a fixed-sized mmap() heap,
281 * which is locked into memory, not written to core files, and protected
282 * on either side by an unmapped page, which will catch pointer overruns
283 * (or underruns) and an attempt to read data out of the secure heap.
284 * Free'd memory is zero'd or otherwise cleansed.
286 * This is a pretty standard buddy allocator. We keep areas in a multiple
287 * of "sh.minsize" units. The freelist and bitmaps are kept separately,
288 * so all (and only) data is kept in the mmap'd heap.
290 * This code assumes eight-bit bytes. The numbers 3 and 7 are all over the
294 #define ONE ((size_t)1)
296 # define TESTBIT(t, b) (t[(b) >> 3] & (ONE << ((b) & 7)))
297 # define SETBIT(t, b) (t[(b) >> 3] |= (ONE << ((b) & 7)))
298 # define CLEARBIT(t, b) (t[(b) >> 3] &= (0xFF & ~(ONE << ((b) & 7))))
300 #define WITHIN_ARENA(p) \
301 ((char*)(p) >= sh.arena && (char*)(p) < &sh.arena[sh.arena_size])
302 #define WITHIN_FREELIST(p) \
303 ((char*)(p) >= (char*)sh.freelist && (char*)(p) < (char*)&sh.freelist[sh.freelist_size])
306 typedef struct sh_list_st
308 struct sh_list_st *next;
309 struct sh_list_st **p_next;
319 ossl_ssize_t freelist_size;
321 unsigned char *bittable;
322 unsigned char *bitmalloc;
323 size_t bittable_size; /* size in bits */
328 static size_t sh_getlist(char *ptr)
330 ossl_ssize_t list = sh.freelist_size - 1;
331 size_t bit = (sh.arena_size + ptr - sh.arena) / sh.minsize;
333 for (; bit; bit >>= 1, list--) {
334 if (TESTBIT(sh.bittable, bit))
336 OPENSSL_assert((bit & 1) == 0);
343 static int sh_testbit(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 return TESTBIT(table, bit);
354 static void sh_clearbit(char *ptr, int list, unsigned char *table)
358 OPENSSL_assert(list >= 0 && list < sh.freelist_size);
359 OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0);
360 bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list));
361 OPENSSL_assert(bit > 0 && bit < sh.bittable_size);
362 OPENSSL_assert(TESTBIT(table, bit));
363 CLEARBIT(table, bit);
366 static void sh_setbit(char *ptr, int list, unsigned char *table)
370 OPENSSL_assert(list >= 0 && list < sh.freelist_size);
371 OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0);
372 bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list));
373 OPENSSL_assert(bit > 0 && bit < sh.bittable_size);
374 OPENSSL_assert(!TESTBIT(table, bit));
378 static void sh_add_to_list(char **list, char *ptr)
382 OPENSSL_assert(WITHIN_FREELIST(list));
383 OPENSSL_assert(WITHIN_ARENA(ptr));
385 temp = (SH_LIST *)ptr;
386 temp->next = *(SH_LIST **)list;
387 OPENSSL_assert(temp->next == NULL || WITHIN_ARENA(temp->next));
388 temp->p_next = (SH_LIST **)list;
390 if (temp->next != NULL) {
391 OPENSSL_assert((char **)temp->next->p_next == list);
392 temp->next->p_next = &(temp->next);
398 static void sh_remove_from_list(char *ptr)
400 SH_LIST *temp, *temp2;
402 temp = (SH_LIST *)ptr;
403 if (temp->next != NULL)
404 temp->next->p_next = temp->p_next;
405 *temp->p_next = temp->next;
406 if (temp->next == NULL)
410 OPENSSL_assert(WITHIN_FREELIST(temp2->p_next) || WITHIN_ARENA(temp2->p_next));
414 static int sh_init(size_t size, size_t minsize)
422 SYSTEM_INFO systemInfo;
425 memset(&sh, 0, sizeof(sh));
427 /* make sure size is a powers of 2 */
428 OPENSSL_assert(size > 0);
429 OPENSSL_assert((size & (size - 1)) == 0);
430 if (size == 0 || (size & (size - 1)) != 0)
433 if (minsize <= sizeof(SH_LIST)) {
434 OPENSSL_assert(sizeof(SH_LIST) <= 65536);
436 * Compute the minimum possible allocation size.
437 * This must be a power of 2 and at least as large as the SH_LIST
440 minsize = sizeof(SH_LIST) - 1;
441 minsize |= minsize >> 1;
442 minsize |= minsize >> 2;
443 if (sizeof(SH_LIST) > 16)
444 minsize |= minsize >> 4;
445 if (sizeof(SH_LIST) > 256)
446 minsize |= minsize >> 8;
449 /* make sure minsize is a powers of 2 */
450 OPENSSL_assert((minsize & (minsize - 1)) == 0);
451 if ((minsize & (minsize - 1)) != 0)
455 sh.arena_size = size;
456 sh.minsize = minsize;
457 sh.bittable_size = (sh.arena_size / sh.minsize) * 2;
459 /* Prevent allocations of size 0 later on */
460 if (sh.bittable_size >> 3 == 0)
463 sh.freelist_size = -1;
464 for (i = sh.bittable_size; i; i >>= 1)
467 sh.freelist = OPENSSL_zalloc(sh.freelist_size * sizeof(char *));
468 OPENSSL_assert(sh.freelist != NULL);
469 if (sh.freelist == NULL)
472 sh.bittable = OPENSSL_zalloc(sh.bittable_size >> 3);
473 OPENSSL_assert(sh.bittable != NULL);
474 if (sh.bittable == NULL)
477 sh.bitmalloc = OPENSSL_zalloc(sh.bittable_size >> 3);
478 OPENSSL_assert(sh.bitmalloc != NULL);
479 if (sh.bitmalloc == NULL)
482 /* Allocate space for heap, and two extra pages as guards */
483 #if defined(_SC_PAGE_SIZE) || defined (_SC_PAGESIZE)
485 # if defined(_SC_PAGE_SIZE)
486 long tmppgsize = sysconf(_SC_PAGE_SIZE);
488 long tmppgsize = sysconf(_SC_PAGESIZE);
493 pgsize = (size_t)tmppgsize;
495 #elif defined(_WIN32)
496 GetSystemInfo(&systemInfo);
497 pgsize = (size_t)systemInfo.dwPageSize;
501 sh.map_size = pgsize + sh.arena_size + pgsize;
505 sh.map_result = mmap(NULL, sh.map_size,
506 PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE|MAP_CONCEAL, -1, 0);
511 sh.map_result = MAP_FAILED;
512 if ((fd = open("/dev/zero", O_RDWR)) >= 0) {
513 sh.map_result = mmap(NULL, sh.map_size,
514 PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
519 if (sh.map_result == MAP_FAILED)
522 sh.map_result = VirtualAlloc(NULL, sh.map_size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
524 if (sh.map_result == NULL)
528 sh.arena = (char *)(sh.map_result + pgsize);
529 sh_setbit(sh.arena, 0, sh.bittable);
530 sh_add_to_list(&sh.freelist[0], sh.arena);
532 /* Now try to add guard pages and lock into memory. */
536 /* Starting guard is already aligned from mmap. */
537 if (mprotect(sh.map_result, pgsize, PROT_NONE) < 0)
540 if (VirtualProtect(sh.map_result, pgsize, PAGE_NOACCESS, &flOldProtect) == FALSE)
544 /* Ending guard page - need to round up to page boundary */
545 aligned = (pgsize + sh.arena_size + (pgsize - 1)) & ~(pgsize - 1);
547 if (mprotect(sh.map_result + aligned, pgsize, PROT_NONE) < 0)
550 if (VirtualProtect(sh.map_result + aligned, pgsize, PAGE_NOACCESS, &flOldProtect) == FALSE)
554 #if defined(OPENSSL_SYS_LINUX) && defined(MLOCK_ONFAULT) && defined(SYS_mlock2)
555 if (syscall(SYS_mlock2, sh.arena, sh.arena_size, MLOCK_ONFAULT) < 0) {
556 if (errno == ENOSYS) {
557 if (mlock(sh.arena, sh.arena_size) < 0)
563 #elif defined(_WIN32)
564 if (VirtualLock(sh.arena, sh.arena_size) == FALSE)
567 if (mlock(sh.arena, sh.arena_size) < 0)
571 if (madvise(sh.arena, sh.arena_size, MADV_DONTDUMP) < 0)
582 static void sh_done(void)
584 OPENSSL_free(sh.freelist);
585 OPENSSL_free(sh.bittable);
586 OPENSSL_free(sh.bitmalloc);
588 if (sh.map_result != MAP_FAILED && sh.map_size)
589 munmap(sh.map_result, sh.map_size);
591 if (sh.map_result != NULL && sh.map_size)
592 VirtualFree(sh.map_result, 0, MEM_RELEASE);
594 memset(&sh, 0, sizeof(sh));
597 static int sh_allocated(const char *ptr)
599 return WITHIN_ARENA(ptr) ? 1 : 0;
602 static char *sh_find_my_buddy(char *ptr, int list)
607 bit = (ONE << list) + (ptr - sh.arena) / (sh.arena_size >> list);
610 if (TESTBIT(sh.bittable, bit) && !TESTBIT(sh.bitmalloc, bit))
611 chunk = sh.arena + ((bit & ((ONE << list) - 1)) * (sh.arena_size >> list));
616 static void *sh_malloc(size_t size)
618 ossl_ssize_t list, slist;
622 if (size > sh.arena_size)
625 list = sh.freelist_size - 1;
626 for (i = sh.minsize; i < size; i <<= 1)
631 /* try to find a larger entry to split */
632 for (slist = list; slist >= 0; slist--)
633 if (sh.freelist[slist] != NULL)
638 /* split larger entry */
639 while (slist != list) {
640 char *temp = sh.freelist[slist];
642 /* remove from bigger list */
643 OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc));
644 sh_clearbit(temp, slist, sh.bittable);
645 sh_remove_from_list(temp);
646 OPENSSL_assert(temp != sh.freelist[slist]);
648 /* done with bigger list */
651 /* add to smaller list */
652 OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc));
653 sh_setbit(temp, slist, sh.bittable);
654 sh_add_to_list(&sh.freelist[slist], temp);
655 OPENSSL_assert(sh.freelist[slist] == temp);
658 temp += sh.arena_size >> slist;
659 OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc));
660 sh_setbit(temp, slist, sh.bittable);
661 sh_add_to_list(&sh.freelist[slist], temp);
662 OPENSSL_assert(sh.freelist[slist] == temp);
664 OPENSSL_assert(temp-(sh.arena_size >> slist) == sh_find_my_buddy(temp, slist));
667 /* peel off memory to hand back */
668 chunk = sh.freelist[list];
669 OPENSSL_assert(sh_testbit(chunk, list, sh.bittable));
670 sh_setbit(chunk, list, sh.bitmalloc);
671 sh_remove_from_list(chunk);
673 OPENSSL_assert(WITHIN_ARENA(chunk));
675 /* zero the free list header as a precaution against information leakage */
676 memset(chunk, 0, sizeof(SH_LIST));
681 static void sh_free(void *ptr)
688 OPENSSL_assert(WITHIN_ARENA(ptr));
689 if (!WITHIN_ARENA(ptr))
692 list = sh_getlist(ptr);
693 OPENSSL_assert(sh_testbit(ptr, list, sh.bittable));
694 sh_clearbit(ptr, list, sh.bitmalloc);
695 sh_add_to_list(&sh.freelist[list], ptr);
697 /* Try to coalesce two adjacent free areas. */
698 while ((buddy = sh_find_my_buddy(ptr, list)) != NULL) {
699 OPENSSL_assert(ptr == sh_find_my_buddy(buddy, list));
700 OPENSSL_assert(ptr != NULL);
701 OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc));
702 sh_clearbit(ptr, list, sh.bittable);
703 sh_remove_from_list(ptr);
704 OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc));
705 sh_clearbit(buddy, list, sh.bittable);
706 sh_remove_from_list(buddy);
710 /* Zero the higher addressed block's free list pointers */
711 memset(ptr > buddy ? ptr : buddy, 0, sizeof(SH_LIST));
715 OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc));
716 sh_setbit(ptr, list, sh.bittable);
717 sh_add_to_list(&sh.freelist[list], ptr);
718 OPENSSL_assert(sh.freelist[list] == ptr);
722 static size_t sh_actual_size(char *ptr)
726 OPENSSL_assert(WITHIN_ARENA(ptr));
727 if (!WITHIN_ARENA(ptr))
729 list = sh_getlist(ptr);
730 OPENSSL_assert(sh_testbit(ptr, list, sh.bittable));
731 return sh.arena_size / (ONE << list);
733 #endif /* OPENSSL_NO_SECURE_MEMORY */