mem_sec.c: relax POSIX requirement.
[openssl.git] / crypto / mem_sec.c
1 /*
2  * Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright 2004-2014, Akamai Technologies. All Rights Reserved.
4  *
5  * Licensed under the OpenSSL license (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
9  */
10
11 /*
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").
17  */
18 #include "e_os.h"
19 #include <openssl/crypto.h>
20
21 #include <string.h>
22
23 /* e_os.h includes unistd.h, which defines _POSIX_VERSION */
24 #if !defined(OPENSSL_NO_SECURE_MEMORY) && defined(OPENSSL_SYS_UNIX) \
25     && ( (defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L) \
26          || defined(__sun) || defined(__hpux) || defined(__sgi) \
27          || defined(__osf__) )
28 # define IMPLEMENTED
29 # include <stdlib.h>
30 # include <assert.h>
31 # include <unistd.h>
32 # include <sys/types.h>
33 # include <sys/mman.h>
34 # if defined(OPENSSL_SYS_LINUX)
35 #  include <sys/syscall.h>
36 #  include <linux/mman.h>
37 #  include <errno.h>
38 # endif
39 # include <sys/param.h>
40 # include <sys/stat.h>
41 # include <fcntl.h>
42 #endif
43
44 #define CLEAR(p, s) OPENSSL_cleanse(p, s)
45 #ifndef PAGE_SIZE
46 # define PAGE_SIZE    4096
47 #endif
48
49 #ifdef IMPLEMENTED
50 static size_t secure_mem_used;
51
52 static int secure_mem_initialized;
53
54 static CRYPTO_RWLOCK *sec_malloc_lock = NULL;
55
56 /*
57  * These are the functions that must be implemented by a secure heap (sh).
58  */
59 static int sh_init(size_t size, int minsize);
60 static void *sh_malloc(size_t size);
61 static void sh_free(void *ptr);
62 static void sh_done(void);
63 static size_t sh_actual_size(char *ptr);
64 static int sh_allocated(const char *ptr);
65 #endif
66
67 int CRYPTO_secure_malloc_init(size_t size, int minsize)
68 {
69 #ifdef IMPLEMENTED
70     int ret = 0;
71
72     if (!secure_mem_initialized) {
73         sec_malloc_lock = CRYPTO_THREAD_lock_new();
74         if (sec_malloc_lock == NULL)
75             return 0;
76         if ((ret = sh_init(size, minsize)) != 0) {
77             secure_mem_initialized = 1;
78         } else {
79             CRYPTO_THREAD_lock_free(sec_malloc_lock);
80             sec_malloc_lock = NULL;
81         }
82     }
83
84     return ret;
85 #else
86     return 0;
87 #endif /* IMPLEMENTED */
88 }
89
90 int CRYPTO_secure_malloc_done()
91 {
92 #ifdef IMPLEMENTED
93     if (secure_mem_used == 0) {
94         sh_done();
95         secure_mem_initialized = 0;
96         CRYPTO_THREAD_lock_free(sec_malloc_lock);
97         sec_malloc_lock = NULL;
98         return 1;
99     }
100 #endif /* IMPLEMENTED */
101     return 0;
102 }
103
104 int CRYPTO_secure_malloc_initialized()
105 {
106 #ifdef IMPLEMENTED
107     return secure_mem_initialized;
108 #else
109     return 0;
110 #endif /* IMPLEMENTED */
111 }
112
113 void *CRYPTO_secure_malloc(size_t num, const char *file, int line)
114 {
115 #ifdef IMPLEMENTED
116     void *ret;
117     size_t actual_size;
118
119     if (!secure_mem_initialized) {
120         return CRYPTO_malloc(num, file, line);
121     }
122     CRYPTO_THREAD_write_lock(sec_malloc_lock);
123     ret = sh_malloc(num);
124     actual_size = ret ? sh_actual_size(ret) : 0;
125     secure_mem_used += actual_size;
126     CRYPTO_THREAD_unlock(sec_malloc_lock);
127     return ret;
128 #else
129     return CRYPTO_malloc(num, file, line);
130 #endif /* IMPLEMENTED */
131 }
132
133 void *CRYPTO_secure_zalloc(size_t num, const char *file, int line)
134 {
135     void *ret = CRYPTO_secure_malloc(num, file, line);
136
137     if (ret != NULL)
138         memset(ret, 0, num);
139     return ret;
140 }
141
142 void CRYPTO_secure_free(void *ptr, const char *file, int line)
143 {
144 #ifdef IMPLEMENTED
145     size_t actual_size;
146
147     if (ptr == NULL)
148         return;
149     if (!CRYPTO_secure_allocated(ptr)) {
150         CRYPTO_free(ptr, file, line);
151         return;
152     }
153     CRYPTO_THREAD_write_lock(sec_malloc_lock);
154     actual_size = sh_actual_size(ptr);
155     CLEAR(ptr, actual_size);
156     secure_mem_used -= actual_size;
157     sh_free(ptr);
158     CRYPTO_THREAD_unlock(sec_malloc_lock);
159 #else
160     CRYPTO_free(ptr, file, line);
161 #endif /* IMPLEMENTED */
162 }
163
164 void CRYPTO_secure_clear_free(void *ptr, size_t num,
165                               const char *file, int line)
166 {
167 #ifdef IMPLEMENTED
168     size_t actual_size;
169
170     if (ptr == NULL)
171         return;
172     if (!CRYPTO_secure_allocated(ptr)) {
173         OPENSSL_cleanse(ptr, num);
174         CRYPTO_free(ptr, file, line);
175         return;
176     }
177     CRYPTO_THREAD_write_lock(sec_malloc_lock);
178     actual_size = sh_actual_size(ptr);
179     CLEAR(ptr, actual_size);
180     secure_mem_used -= actual_size;
181     sh_free(ptr);
182     CRYPTO_THREAD_unlock(sec_malloc_lock);
183 #else
184     if (ptr == NULL)
185         return;
186     OPENSSL_cleanse(ptr, num);
187     CRYPTO_free(ptr, file, line);
188 #endif /* IMPLEMENTED */
189 }
190
191 int CRYPTO_secure_allocated(const void *ptr)
192 {
193 #ifdef IMPLEMENTED
194     int ret;
195
196     if (!secure_mem_initialized)
197         return 0;
198     CRYPTO_THREAD_write_lock(sec_malloc_lock);
199     ret = sh_allocated(ptr);
200     CRYPTO_THREAD_unlock(sec_malloc_lock);
201     return ret;
202 #else
203     return 0;
204 #endif /* IMPLEMENTED */
205 }
206
207 size_t CRYPTO_secure_used()
208 {
209 #ifdef IMPLEMENTED
210     return secure_mem_used;
211 #else
212     return 0;
213 #endif /* IMPLEMENTED */
214 }
215
216 size_t CRYPTO_secure_actual_size(void *ptr)
217 {
218 #ifdef IMPLEMENTED
219     size_t actual_size;
220
221     CRYPTO_THREAD_write_lock(sec_malloc_lock);
222     actual_size = sh_actual_size(ptr);
223     CRYPTO_THREAD_unlock(sec_malloc_lock);
224     return actual_size;
225 #else
226     return 0;
227 #endif
228 }
229 /* END OF PAGE ...
230
231    ... START OF PAGE */
232
233 /*
234  * SECURE HEAP IMPLEMENTATION
235  */
236 #ifdef IMPLEMENTED
237
238
239 /*
240  * The implementation provided here uses a fixed-sized mmap() heap,
241  * which is locked into memory, not written to core files, and protected
242  * on either side by an unmapped page, which will catch pointer overruns
243  * (or underruns) and an attempt to read data out of the secure heap.
244  * Free'd memory is zero'd or otherwise cleansed.
245  *
246  * This is a pretty standard buddy allocator.  We keep areas in a multiple
247  * of "sh.minsize" units.  The freelist and bitmaps are kept separately,
248  * so all (and only) data is kept in the mmap'd heap.
249  *
250  * This code assumes eight-bit bytes.  The numbers 3 and 7 are all over the
251  * place.
252  */
253
254 #define ONE ((size_t)1)
255
256 # define TESTBIT(t, b)  (t[(b) >> 3] &  (ONE << ((b) & 7)))
257 # define SETBIT(t, b)   (t[(b) >> 3] |= (ONE << ((b) & 7)))
258 # define CLEARBIT(t, b) (t[(b) >> 3] &= (0xFF & ~(ONE << ((b) & 7))))
259
260 #define WITHIN_ARENA(p) \
261     ((char*)(p) >= sh.arena && (char*)(p) < &sh.arena[sh.arena_size])
262 #define WITHIN_FREELIST(p) \
263     ((char*)(p) >= (char*)sh.freelist && (char*)(p) < (char*)&sh.freelist[sh.freelist_size])
264
265
266 typedef struct sh_list_st
267 {
268     struct sh_list_st *next;
269     struct sh_list_st **p_next;
270 } SH_LIST;
271
272 typedef struct sh_st
273 {
274     char* map_result;
275     size_t map_size;
276     char *arena;
277     size_t arena_size;
278     char **freelist;
279     ossl_ssize_t freelist_size;
280     size_t minsize;
281     unsigned char *bittable;
282     unsigned char *bitmalloc;
283     size_t bittable_size; /* size in bits */
284 } SH;
285
286 static SH sh;
287
288 static size_t sh_getlist(char *ptr)
289 {
290     ossl_ssize_t list = sh.freelist_size - 1;
291     size_t bit = (sh.arena_size + ptr - sh.arena) / sh.minsize;
292
293     for (; bit; bit >>= 1, list--) {
294         if (TESTBIT(sh.bittable, bit))
295             break;
296         OPENSSL_assert((bit & 1) == 0);
297     }
298
299     return list;
300 }
301
302
303 static int sh_testbit(char *ptr, int list, unsigned char *table)
304 {
305     size_t bit;
306
307     OPENSSL_assert(list >= 0 && list < sh.freelist_size);
308     OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0);
309     bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list));
310     OPENSSL_assert(bit > 0 && bit < sh.bittable_size);
311     return TESTBIT(table, bit);
312 }
313
314 static void sh_clearbit(char *ptr, int list, unsigned char *table)
315 {
316     size_t bit;
317
318     OPENSSL_assert(list >= 0 && list < sh.freelist_size);
319     OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0);
320     bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list));
321     OPENSSL_assert(bit > 0 && bit < sh.bittable_size);
322     OPENSSL_assert(TESTBIT(table, bit));
323     CLEARBIT(table, bit);
324 }
325
326 static void sh_setbit(char *ptr, int list, unsigned char *table)
327 {
328     size_t bit;
329
330     OPENSSL_assert(list >= 0 && list < sh.freelist_size);
331     OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0);
332     bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list));
333     OPENSSL_assert(bit > 0 && bit < sh.bittable_size);
334     OPENSSL_assert(!TESTBIT(table, bit));
335     SETBIT(table, bit);
336 }
337
338 static void sh_add_to_list(char **list, char *ptr)
339 {
340     SH_LIST *temp;
341
342     OPENSSL_assert(WITHIN_FREELIST(list));
343     OPENSSL_assert(WITHIN_ARENA(ptr));
344
345     temp = (SH_LIST *)ptr;
346     temp->next = *(SH_LIST **)list;
347     OPENSSL_assert(temp->next == NULL || WITHIN_ARENA(temp->next));
348     temp->p_next = (SH_LIST **)list;
349
350     if (temp->next != NULL) {
351         OPENSSL_assert((char **)temp->next->p_next == list);
352         temp->next->p_next = &(temp->next);
353     }
354
355     *list = ptr;
356 }
357
358 static void sh_remove_from_list(char *ptr)
359 {
360     SH_LIST *temp, *temp2;
361
362     temp = (SH_LIST *)ptr;
363     if (temp->next != NULL)
364         temp->next->p_next = temp->p_next;
365     *temp->p_next = temp->next;
366     if (temp->next == NULL)
367         return;
368
369     temp2 = temp->next;
370     OPENSSL_assert(WITHIN_FREELIST(temp2->p_next) || WITHIN_ARENA(temp2->p_next));
371 }
372
373
374 static int sh_init(size_t size, int minsize)
375 {
376     int ret;
377     size_t i;
378     size_t pgsize;
379     size_t aligned;
380
381     memset(&sh, 0, sizeof(sh));
382
383     /* make sure size and minsize are powers of 2 */
384     OPENSSL_assert(size > 0);
385     OPENSSL_assert((size & (size - 1)) == 0);
386     OPENSSL_assert(minsize > 0);
387     OPENSSL_assert((minsize & (minsize - 1)) == 0);
388     if (size <= 0 || (size & (size - 1)) != 0)
389         goto err;
390     if (minsize <= 0 || (minsize & (minsize - 1)) != 0)
391         goto err;
392
393     while (minsize < (int)sizeof(SH_LIST))
394         minsize *= 2;
395
396     sh.arena_size = size;
397     sh.minsize = minsize;
398     sh.bittable_size = (sh.arena_size / sh.minsize) * 2;
399
400     /* Prevent allocations of size 0 later on */
401     if (sh.bittable_size >> 3 == 0)
402         goto err;
403
404     sh.freelist_size = -1;
405     for (i = sh.bittable_size; i; i >>= 1)
406         sh.freelist_size++;
407
408     sh.freelist = OPENSSL_zalloc(sh.freelist_size * sizeof(char *));
409     OPENSSL_assert(sh.freelist != NULL);
410     if (sh.freelist == NULL)
411         goto err;
412
413     sh.bittable = OPENSSL_zalloc(sh.bittable_size >> 3);
414     OPENSSL_assert(sh.bittable != NULL);
415     if (sh.bittable == NULL)
416         goto err;
417
418     sh.bitmalloc = OPENSSL_zalloc(sh.bittable_size >> 3);
419     OPENSSL_assert(sh.bitmalloc != NULL);
420     if (sh.bitmalloc == NULL)
421         goto err;
422
423     /* Allocate space for heap, and two extra pages as guards */
424 #if defined(_SC_PAGE_SIZE) || defined (_SC_PAGESIZE)
425     {
426 # if defined(_SC_PAGE_SIZE)
427         long tmppgsize = sysconf(_SC_PAGE_SIZE);
428 # else
429         long tmppgsize = sysconf(_SC_PAGESIZE);
430 # endif
431         if (tmppgsize < 1)
432             pgsize = PAGE_SIZE;
433         else
434             pgsize = (size_t)tmppgsize;
435     }
436 #else
437     pgsize = PAGE_SIZE;
438 #endif
439     sh.map_size = pgsize + sh.arena_size + pgsize;
440     if (1) {
441 #ifdef MAP_ANON
442         sh.map_result = mmap(NULL, sh.map_size,
443                              PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
444     } else {
445 #endif
446         int fd;
447
448         sh.map_result = MAP_FAILED;
449         if ((fd = open("/dev/zero", O_RDWR)) >= 0) {
450             sh.map_result = mmap(NULL, sh.map_size,
451                                  PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
452             close(fd);
453         }
454     }
455     if (sh.map_result == MAP_FAILED)
456         goto err;
457     sh.arena = (char *)(sh.map_result + pgsize);
458     sh_setbit(sh.arena, 0, sh.bittable);
459     sh_add_to_list(&sh.freelist[0], sh.arena);
460
461     /* Now try to add guard pages and lock into memory. */
462     ret = 1;
463
464     /* Starting guard is already aligned from mmap. */
465     if (mprotect(sh.map_result, pgsize, PROT_NONE) < 0)
466         ret = 2;
467
468     /* Ending guard page - need to round up to page boundary */
469     aligned = (pgsize + sh.arena_size + (pgsize - 1)) & ~(pgsize - 1);
470     if (mprotect(sh.map_result + aligned, pgsize, PROT_NONE) < 0)
471         ret = 2;
472
473 #if defined(OPENSSL_SYS_LINUX) && defined(MLOCK_ONFAULT) && defined(SYS_mlock2)
474     if (syscall(SYS_mlock2, sh.arena, sh.arena_size, MLOCK_ONFAULT) < 0) {
475         if (errno == ENOSYS) {
476             if (mlock(sh.arena, sh.arena_size) < 0)
477                 ret = 2;
478         } else {
479             ret = 2;
480         }
481     }
482 #else
483     if (mlock(sh.arena, sh.arena_size) < 0)
484         ret = 2;
485 #endif
486 #ifdef MADV_DONTDUMP
487     if (madvise(sh.arena, sh.arena_size, MADV_DONTDUMP) < 0)
488         ret = 2;
489 #endif
490
491     return ret;
492
493  err:
494     sh_done();
495     return 0;
496 }
497
498 static void sh_done()
499 {
500     OPENSSL_free(sh.freelist);
501     OPENSSL_free(sh.bittable);
502     OPENSSL_free(sh.bitmalloc);
503     if (sh.map_result != NULL && sh.map_size)
504         munmap(sh.map_result, sh.map_size);
505     memset(&sh, 0, sizeof(sh));
506 }
507
508 static int sh_allocated(const char *ptr)
509 {
510     return WITHIN_ARENA(ptr) ? 1 : 0;
511 }
512
513 static char *sh_find_my_buddy(char *ptr, int list)
514 {
515     size_t bit;
516     char *chunk = NULL;
517
518     bit = (ONE << list) + (ptr - sh.arena) / (sh.arena_size >> list);
519     bit ^= 1;
520
521     if (TESTBIT(sh.bittable, bit) && !TESTBIT(sh.bitmalloc, bit))
522         chunk = sh.arena + ((bit & ((ONE << list) - 1)) * (sh.arena_size >> list));
523
524     return chunk;
525 }
526
527 static void *sh_malloc(size_t size)
528 {
529     ossl_ssize_t list, slist;
530     size_t i;
531     char *chunk;
532
533     if (size > sh.arena_size)
534         return NULL;
535
536     list = sh.freelist_size - 1;
537     for (i = sh.minsize; i < size; i <<= 1)
538         list--;
539     if (list < 0)
540         return NULL;
541
542     /* try to find a larger entry to split */
543     for (slist = list; slist >= 0; slist--)
544         if (sh.freelist[slist] != NULL)
545             break;
546     if (slist < 0)
547         return NULL;
548
549     /* split larger entry */
550     while (slist != list) {
551         char *temp = sh.freelist[slist];
552
553         /* remove from bigger list */
554         OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc));
555         sh_clearbit(temp, slist, sh.bittable);
556         sh_remove_from_list(temp);
557         OPENSSL_assert(temp != sh.freelist[slist]);
558
559         /* done with bigger list */
560         slist++;
561
562         /* add to smaller list */
563         OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc));
564         sh_setbit(temp, slist, sh.bittable);
565         sh_add_to_list(&sh.freelist[slist], temp);
566         OPENSSL_assert(sh.freelist[slist] == temp);
567
568         /* split in 2 */
569         temp += sh.arena_size >> slist;
570         OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc));
571         sh_setbit(temp, slist, sh.bittable);
572         sh_add_to_list(&sh.freelist[slist], temp);
573         OPENSSL_assert(sh.freelist[slist] == temp);
574
575         OPENSSL_assert(temp-(sh.arena_size >> slist) == sh_find_my_buddy(temp, slist));
576     }
577
578     /* peel off memory to hand back */
579     chunk = sh.freelist[list];
580     OPENSSL_assert(sh_testbit(chunk, list, sh.bittable));
581     sh_setbit(chunk, list, sh.bitmalloc);
582     sh_remove_from_list(chunk);
583
584     OPENSSL_assert(WITHIN_ARENA(chunk));
585
586     return chunk;
587 }
588
589 static void sh_free(void *ptr)
590 {
591     size_t list;
592     void *buddy;
593
594     if (ptr == NULL)
595         return;
596     OPENSSL_assert(WITHIN_ARENA(ptr));
597     if (!WITHIN_ARENA(ptr))
598         return;
599
600     list = sh_getlist(ptr);
601     OPENSSL_assert(sh_testbit(ptr, list, sh.bittable));
602     sh_clearbit(ptr, list, sh.bitmalloc);
603     sh_add_to_list(&sh.freelist[list], ptr);
604
605     /* Try to coalesce two adjacent free areas. */
606     while ((buddy = sh_find_my_buddy(ptr, list)) != NULL) {
607         OPENSSL_assert(ptr == sh_find_my_buddy(buddy, list));
608         OPENSSL_assert(ptr != NULL);
609         OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc));
610         sh_clearbit(ptr, list, sh.bittable);
611         sh_remove_from_list(ptr);
612         OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc));
613         sh_clearbit(buddy, list, sh.bittable);
614         sh_remove_from_list(buddy);
615
616         list--;
617
618         if (ptr > buddy)
619             ptr = buddy;
620
621         OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc));
622         sh_setbit(ptr, list, sh.bittable);
623         sh_add_to_list(&sh.freelist[list], ptr);
624         OPENSSL_assert(sh.freelist[list] == ptr);
625     }
626 }
627
628 static size_t sh_actual_size(char *ptr)
629 {
630     int list;
631
632     OPENSSL_assert(WITHIN_ARENA(ptr));
633     if (!WITHIN_ARENA(ptr))
634         return 0;
635     list = sh_getlist(ptr);
636     OPENSSL_assert(sh_testbit(ptr, list, sh.bittable));
637     return sh.arena_size / (ONE << list);
638 }
639 #endif /* IMPLEMENTED */