2 * Copyright 2015-2021 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").
19 #include <openssl/crypto.h>
23 #ifndef OPENSSL_NO_SECURE_MEMORY
29 # if defined(OPENSSL_SYS_UNIX)
32 # include <sys/types.h>
33 # if defined(OPENSSL_SYS_UNIX)
34 # include <sys/mman.h>
35 # if defined(__FreeBSD__)
36 # define MADV_DONTDUMP MADV_NOCORE
38 # if !defined(MAP_CONCEAL)
39 # define MAP_CONCEAL 0
42 # if defined(OPENSSL_SYS_LINUX)
43 # include <sys/syscall.h>
44 # if defined(SYS_mlock2)
45 # include <linux/mman.h>
48 # include <sys/param.h>
50 # include <sys/stat.h>
54 #define CLEAR(p, s) OPENSSL_cleanse(p, s)
56 # define PAGE_SIZE 4096
58 #if !defined(MAP_ANON) && defined(MAP_ANONYMOUS)
59 # define MAP_ANON MAP_ANONYMOUS
62 #ifndef OPENSSL_NO_SECURE_MEMORY
63 static size_t secure_mem_used;
65 static int secure_mem_initialized;
67 static CRYPTO_RWLOCK *sec_malloc_lock = NULL;
70 * These are the functions that must be implemented by a secure heap (sh).
72 static int sh_init(size_t size, size_t minsize);
73 static void *sh_malloc(size_t size);
74 static void sh_free(void *ptr);
75 static void sh_done(void);
76 static size_t sh_actual_size(char *ptr);
77 static int sh_allocated(const char *ptr);
80 int CRYPTO_secure_malloc_init(size_t size, size_t minsize)
82 #ifndef OPENSSL_NO_SECURE_MEMORY
85 if (!secure_mem_initialized) {
86 sec_malloc_lock = CRYPTO_THREAD_lock_new();
87 if (sec_malloc_lock == NULL)
89 if ((ret = sh_init(size, minsize)) != 0) {
90 secure_mem_initialized = 1;
92 CRYPTO_THREAD_lock_free(sec_malloc_lock);
93 sec_malloc_lock = NULL;
100 #endif /* OPENSSL_NO_SECURE_MEMORY */
103 int CRYPTO_secure_malloc_done(void)
105 #ifndef OPENSSL_NO_SECURE_MEMORY
106 if (secure_mem_used == 0) {
108 secure_mem_initialized = 0;
109 CRYPTO_THREAD_lock_free(sec_malloc_lock);
110 sec_malloc_lock = NULL;
113 #endif /* OPENSSL_NO_SECURE_MEMORY */
117 int CRYPTO_secure_malloc_initialized(void)
119 #ifndef OPENSSL_NO_SECURE_MEMORY
120 return secure_mem_initialized;
123 #endif /* OPENSSL_NO_SECURE_MEMORY */
126 void *CRYPTO_secure_malloc(size_t num, const char *file, int line)
128 #ifndef OPENSSL_NO_SECURE_MEMORY
132 if (!secure_mem_initialized) {
133 return CRYPTO_malloc(num, file, line);
135 if (!CRYPTO_THREAD_write_lock(sec_malloc_lock))
137 ret = sh_malloc(num);
138 actual_size = ret ? sh_actual_size(ret) : 0;
139 secure_mem_used += actual_size;
140 CRYPTO_THREAD_unlock(sec_malloc_lock);
143 return CRYPTO_malloc(num, file, line);
144 #endif /* OPENSSL_NO_SECURE_MEMORY */
147 void *CRYPTO_secure_zalloc(size_t num, const char *file, int line)
149 #ifndef OPENSSL_NO_SECURE_MEMORY
150 if (secure_mem_initialized)
151 /* CRYPTO_secure_malloc() zeroes allocations when it is implemented */
152 return CRYPTO_secure_malloc(num, file, line);
154 return CRYPTO_zalloc(num, file, line);
157 void CRYPTO_secure_free(void *ptr, const char *file, int line)
159 #ifndef OPENSSL_NO_SECURE_MEMORY
164 if (!CRYPTO_secure_allocated(ptr)) {
165 CRYPTO_free(ptr, file, line);
168 if (!CRYPTO_THREAD_write_lock(sec_malloc_lock))
170 actual_size = sh_actual_size(ptr);
171 CLEAR(ptr, actual_size);
172 secure_mem_used -= actual_size;
174 CRYPTO_THREAD_unlock(sec_malloc_lock);
176 CRYPTO_free(ptr, file, line);
177 #endif /* OPENSSL_NO_SECURE_MEMORY */
180 void CRYPTO_secure_clear_free(void *ptr, size_t num,
181 const char *file, int line)
183 #ifndef OPENSSL_NO_SECURE_MEMORY
188 if (!CRYPTO_secure_allocated(ptr)) {
189 OPENSSL_cleanse(ptr, num);
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);
203 OPENSSL_cleanse(ptr, num);
204 CRYPTO_free(ptr, file, line);
205 #endif /* OPENSSL_NO_SECURE_MEMORY */
208 int CRYPTO_secure_allocated(const void *ptr)
210 #ifndef OPENSSL_NO_SECURE_MEMORY
211 if (!secure_mem_initialized)
214 * Only read accesses to the arena take place in sh_allocated() and this
215 * is only changed by the sh_init() and sh_done() calls which are not
216 * locked. Hence, it is safe to make this check without a lock too.
218 return sh_allocated(ptr);
221 #endif /* OPENSSL_NO_SECURE_MEMORY */
224 size_t CRYPTO_secure_used(void)
226 #ifndef OPENSSL_NO_SECURE_MEMORY
227 return secure_mem_used;
230 #endif /* OPENSSL_NO_SECURE_MEMORY */
233 size_t CRYPTO_secure_actual_size(void *ptr)
235 #ifndef OPENSSL_NO_SECURE_MEMORY
238 if (!CRYPTO_THREAD_write_lock(sec_malloc_lock))
240 actual_size = sh_actual_size(ptr);
241 CRYPTO_THREAD_unlock(sec_malloc_lock);
249 * SECURE HEAP IMPLEMENTATION
251 #ifndef OPENSSL_NO_SECURE_MEMORY
255 * The implementation provided here uses a fixed-sized mmap() heap,
256 * which is locked into memory, not written to core files, and protected
257 * on either side by an unmapped page, which will catch pointer overruns
258 * (or underruns) and an attempt to read data out of the secure heap.
259 * Free'd memory is zero'd or otherwise cleansed.
261 * This is a pretty standard buddy allocator. We keep areas in a multiple
262 * of "sh.minsize" units. The freelist and bitmaps are kept separately,
263 * so all (and only) data is kept in the mmap'd heap.
265 * This code assumes eight-bit bytes. The numbers 3 and 7 are all over the
269 #define ONE ((size_t)1)
271 # define TESTBIT(t, b) (t[(b) >> 3] & (ONE << ((b) & 7)))
272 # define SETBIT(t, b) (t[(b) >> 3] |= (ONE << ((b) & 7)))
273 # define CLEARBIT(t, b) (t[(b) >> 3] &= (0xFF & ~(ONE << ((b) & 7))))
275 #define WITHIN_ARENA(p) \
276 ((char*)(p) >= sh.arena && (char*)(p) < &sh.arena[sh.arena_size])
277 #define WITHIN_FREELIST(p) \
278 ((char*)(p) >= (char*)sh.freelist && (char*)(p) < (char*)&sh.freelist[sh.freelist_size])
281 typedef struct sh_list_st
283 struct sh_list_st *next;
284 struct sh_list_st **p_next;
294 ossl_ssize_t freelist_size;
296 unsigned char *bittable;
297 unsigned char *bitmalloc;
298 size_t bittable_size; /* size in bits */
303 static size_t sh_getlist(char *ptr)
305 ossl_ssize_t list = sh.freelist_size - 1;
306 size_t bit = (sh.arena_size + ptr - sh.arena) / sh.minsize;
308 for (; bit; bit >>= 1, list--) {
309 if (TESTBIT(sh.bittable, bit))
311 OPENSSL_assert((bit & 1) == 0);
318 static int sh_testbit(char *ptr, int list, unsigned char *table)
322 OPENSSL_assert(list >= 0 && list < sh.freelist_size);
323 OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0);
324 bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list));
325 OPENSSL_assert(bit > 0 && bit < sh.bittable_size);
326 return TESTBIT(table, bit);
329 static void sh_clearbit(char *ptr, int list, unsigned char *table)
333 OPENSSL_assert(list >= 0 && list < sh.freelist_size);
334 OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0);
335 bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list));
336 OPENSSL_assert(bit > 0 && bit < sh.bittable_size);
337 OPENSSL_assert(TESTBIT(table, bit));
338 CLEARBIT(table, bit);
341 static void sh_setbit(char *ptr, int list, unsigned char *table)
345 OPENSSL_assert(list >= 0 && list < sh.freelist_size);
346 OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0);
347 bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list));
348 OPENSSL_assert(bit > 0 && bit < sh.bittable_size);
349 OPENSSL_assert(!TESTBIT(table, bit));
353 static void sh_add_to_list(char **list, char *ptr)
357 OPENSSL_assert(WITHIN_FREELIST(list));
358 OPENSSL_assert(WITHIN_ARENA(ptr));
360 temp = (SH_LIST *)ptr;
361 temp->next = *(SH_LIST **)list;
362 OPENSSL_assert(temp->next == NULL || WITHIN_ARENA(temp->next));
363 temp->p_next = (SH_LIST **)list;
365 if (temp->next != NULL) {
366 OPENSSL_assert((char **)temp->next->p_next == list);
367 temp->next->p_next = &(temp->next);
373 static void sh_remove_from_list(char *ptr)
375 SH_LIST *temp, *temp2;
377 temp = (SH_LIST *)ptr;
378 if (temp->next != NULL)
379 temp->next->p_next = temp->p_next;
380 *temp->p_next = temp->next;
381 if (temp->next == NULL)
385 OPENSSL_assert(WITHIN_FREELIST(temp2->p_next) || WITHIN_ARENA(temp2->p_next));
389 static int sh_init(size_t size, size_t minsize)
397 SYSTEM_INFO systemInfo;
400 memset(&sh, 0, sizeof(sh));
402 /* make sure size is a powers of 2 */
403 OPENSSL_assert(size > 0);
404 OPENSSL_assert((size & (size - 1)) == 0);
405 if (size == 0 || (size & (size - 1)) != 0)
408 if (minsize <= sizeof(SH_LIST)) {
409 OPENSSL_assert(sizeof(SH_LIST) <= 65536);
411 * Compute the minimum possible allocation size.
412 * This must be a power of 2 and at least as large as the SH_LIST
415 minsize = sizeof(SH_LIST) - 1;
416 minsize |= minsize >> 1;
417 minsize |= minsize >> 2;
418 if (sizeof(SH_LIST) > 16)
419 minsize |= minsize >> 4;
420 if (sizeof(SH_LIST) > 256)
421 minsize |= minsize >> 8;
424 /* make sure minsize is a powers of 2 */
425 OPENSSL_assert((minsize & (minsize - 1)) == 0);
426 if ((minsize & (minsize - 1)) != 0)
430 sh.arena_size = size;
431 sh.minsize = minsize;
432 sh.bittable_size = (sh.arena_size / sh.minsize) * 2;
434 /* Prevent allocations of size 0 later on */
435 if (sh.bittable_size >> 3 == 0)
438 sh.freelist_size = -1;
439 for (i = sh.bittable_size; i; i >>= 1)
442 sh.freelist = OPENSSL_zalloc(sh.freelist_size * sizeof(char *));
443 OPENSSL_assert(sh.freelist != NULL);
444 if (sh.freelist == NULL)
447 sh.bittable = OPENSSL_zalloc(sh.bittable_size >> 3);
448 OPENSSL_assert(sh.bittable != NULL);
449 if (sh.bittable == NULL)
452 sh.bitmalloc = OPENSSL_zalloc(sh.bittable_size >> 3);
453 OPENSSL_assert(sh.bitmalloc != NULL);
454 if (sh.bitmalloc == NULL)
457 /* Allocate space for heap, and two extra pages as guards */
458 #if defined(_SC_PAGE_SIZE) || defined (_SC_PAGESIZE)
460 # if defined(_SC_PAGE_SIZE)
461 long tmppgsize = sysconf(_SC_PAGE_SIZE);
463 long tmppgsize = sysconf(_SC_PAGESIZE);
468 pgsize = (size_t)tmppgsize;
470 #elif defined(_WIN32)
471 GetSystemInfo(&systemInfo);
472 pgsize = (size_t)systemInfo.dwPageSize;
476 sh.map_size = pgsize + sh.arena_size + pgsize;
480 sh.map_result = mmap(NULL, sh.map_size,
481 PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE|MAP_CONCEAL, -1, 0);
486 sh.map_result = MAP_FAILED;
487 if ((fd = open("/dev/zero", O_RDWR)) >= 0) {
488 sh.map_result = mmap(NULL, sh.map_size,
489 PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
494 if (sh.map_result == MAP_FAILED)
497 sh.map_result = VirtualAlloc(NULL, sh.map_size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
499 if (sh.map_result == NULL)
503 sh.arena = (char *)(sh.map_result + pgsize);
504 sh_setbit(sh.arena, 0, sh.bittable);
505 sh_add_to_list(&sh.freelist[0], sh.arena);
507 /* Now try to add guard pages and lock into memory. */
511 /* Starting guard is already aligned from mmap. */
512 if (mprotect(sh.map_result, pgsize, PROT_NONE) < 0)
515 if (VirtualProtect(sh.map_result, pgsize, PAGE_NOACCESS, &flOldProtect) == FALSE)
519 /* Ending guard page - need to round up to page boundary */
520 aligned = (pgsize + sh.arena_size + (pgsize - 1)) & ~(pgsize - 1);
522 if (mprotect(sh.map_result + aligned, pgsize, PROT_NONE) < 0)
525 if (VirtualProtect(sh.map_result + aligned, pgsize, PAGE_NOACCESS, &flOldProtect) == FALSE)
529 #if defined(OPENSSL_SYS_LINUX) && defined(MLOCK_ONFAULT) && defined(SYS_mlock2)
530 if (syscall(SYS_mlock2, sh.arena, sh.arena_size, MLOCK_ONFAULT) < 0) {
531 if (errno == ENOSYS) {
532 if (mlock(sh.arena, sh.arena_size) < 0)
538 #elif defined(_WIN32)
539 if (VirtualLock(sh.arena, sh.arena_size) == FALSE)
542 if (mlock(sh.arena, sh.arena_size) < 0)
546 if (madvise(sh.arena, sh.arena_size, MADV_DONTDUMP) < 0)
557 static void sh_done(void)
559 OPENSSL_free(sh.freelist);
560 OPENSSL_free(sh.bittable);
561 OPENSSL_free(sh.bitmalloc);
563 if (sh.map_result != MAP_FAILED && sh.map_size)
564 munmap(sh.map_result, sh.map_size);
566 if (sh.map_result != NULL && sh.map_size)
567 VirtualFree(sh.map_result, 0, MEM_RELEASE);
569 memset(&sh, 0, sizeof(sh));
572 static int sh_allocated(const char *ptr)
574 return WITHIN_ARENA(ptr) ? 1 : 0;
577 static char *sh_find_my_buddy(char *ptr, int list)
582 bit = (ONE << list) + (ptr - sh.arena) / (sh.arena_size >> list);
585 if (TESTBIT(sh.bittable, bit) && !TESTBIT(sh.bitmalloc, bit))
586 chunk = sh.arena + ((bit & ((ONE << list) - 1)) * (sh.arena_size >> list));
591 static void *sh_malloc(size_t size)
593 ossl_ssize_t list, slist;
597 if (size > sh.arena_size)
600 list = sh.freelist_size - 1;
601 for (i = sh.minsize; i < size; i <<= 1)
606 /* try to find a larger entry to split */
607 for (slist = list; slist >= 0; slist--)
608 if (sh.freelist[slist] != NULL)
613 /* split larger entry */
614 while (slist != list) {
615 char *temp = sh.freelist[slist];
617 /* remove from bigger list */
618 OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc));
619 sh_clearbit(temp, slist, sh.bittable);
620 sh_remove_from_list(temp);
621 OPENSSL_assert(temp != sh.freelist[slist]);
623 /* done with bigger list */
626 /* add to smaller list */
627 OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc));
628 sh_setbit(temp, slist, sh.bittable);
629 sh_add_to_list(&sh.freelist[slist], temp);
630 OPENSSL_assert(sh.freelist[slist] == temp);
633 temp += sh.arena_size >> slist;
634 OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc));
635 sh_setbit(temp, slist, sh.bittable);
636 sh_add_to_list(&sh.freelist[slist], temp);
637 OPENSSL_assert(sh.freelist[slist] == temp);
639 OPENSSL_assert(temp-(sh.arena_size >> slist) == sh_find_my_buddy(temp, slist));
642 /* peel off memory to hand back */
643 chunk = sh.freelist[list];
644 OPENSSL_assert(sh_testbit(chunk, list, sh.bittable));
645 sh_setbit(chunk, list, sh.bitmalloc);
646 sh_remove_from_list(chunk);
648 OPENSSL_assert(WITHIN_ARENA(chunk));
650 /* zero the free list header as a precaution against information leakage */
651 memset(chunk, 0, sizeof(SH_LIST));
656 static void sh_free(void *ptr)
663 OPENSSL_assert(WITHIN_ARENA(ptr));
664 if (!WITHIN_ARENA(ptr))
667 list = sh_getlist(ptr);
668 OPENSSL_assert(sh_testbit(ptr, list, sh.bittable));
669 sh_clearbit(ptr, list, sh.bitmalloc);
670 sh_add_to_list(&sh.freelist[list], ptr);
672 /* Try to coalesce two adjacent free areas. */
673 while ((buddy = sh_find_my_buddy(ptr, list)) != NULL) {
674 OPENSSL_assert(ptr == sh_find_my_buddy(buddy, list));
675 OPENSSL_assert(ptr != NULL);
676 OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc));
677 sh_clearbit(ptr, list, sh.bittable);
678 sh_remove_from_list(ptr);
679 OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc));
680 sh_clearbit(buddy, list, sh.bittable);
681 sh_remove_from_list(buddy);
685 /* Zero the higher addressed block's free list pointers */
686 memset(ptr > buddy ? ptr : buddy, 0, sizeof(SH_LIST));
690 OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc));
691 sh_setbit(ptr, list, sh.bittable);
692 sh_add_to_list(&sh.freelist[list], ptr);
693 OPENSSL_assert(sh.freelist[list] == ptr);
697 static size_t sh_actual_size(char *ptr)
701 OPENSSL_assert(WITHIN_ARENA(ptr));
702 if (!WITHIN_ARENA(ptr))
704 list = sh_getlist(ptr);
705 OPENSSL_assert(sh_testbit(ptr, list, sh.bittable));
706 return sh.arena_size / (ONE << list);
708 #endif /* OPENSSL_NO_SECURE_MEMORY */