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