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