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