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