OSSL_STORE: spell error reason correctly
[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 <openssl/crypto.h>
19 #include <e_os.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_lock_new();
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 int CRYPTO_secure_allocated(const void *ptr)
161 {
162 #ifdef IMPLEMENTED
163     int ret;
164
165     if (!secure_mem_initialized)
166         return 0;
167     CRYPTO_THREAD_write_lock(sec_malloc_lock);
168     ret = sh_allocated(ptr);
169     CRYPTO_THREAD_unlock(sec_malloc_lock);
170     return ret;
171 #else
172     return 0;
173 #endif /* IMPLEMENTED */
174 }
175
176 size_t CRYPTO_secure_used()
177 {
178 #ifdef IMPLEMENTED
179     return secure_mem_used;
180 #else
181     return 0;
182 #endif /* IMPLEMENTED */
183 }
184
185 size_t CRYPTO_secure_actual_size(void *ptr)
186 {
187 #ifdef IMPLEMENTED
188     size_t actual_size;
189
190     CRYPTO_THREAD_write_lock(sec_malloc_lock);
191     actual_size = sh_actual_size(ptr);
192     CRYPTO_THREAD_unlock(sec_malloc_lock);
193     return actual_size;
194 #else
195     return 0;
196 #endif
197 }
198 /* END OF PAGE ...
199
200    ... START OF PAGE */
201
202 /*
203  * SECURE HEAP IMPLEMENTATION
204  */
205 #ifdef IMPLEMENTED
206
207
208 /*
209  * The implementation provided here uses a fixed-sized mmap() heap,
210  * which is locked into memory, not written to core files, and protected
211  * on either side by an unmapped page, which will catch pointer overruns
212  * (or underruns) and an attempt to read data out of the secure heap.
213  * Free'd memory is zero'd or otherwise cleansed.
214  *
215  * This is a pretty standard buddy allocator.  We keep areas in a multiple
216  * of "sh.minsize" units.  The freelist and bitmaps are kept separately,
217  * so all (and only) data is kept in the mmap'd heap.
218  *
219  * This code assumes eight-bit bytes.  The numbers 3 and 7 are all over the
220  * place.
221  */
222
223 #define ONE ((size_t)1)
224
225 # define TESTBIT(t, b)  (t[(b) >> 3] &  (ONE << ((b) & 7)))
226 # define SETBIT(t, b)   (t[(b) >> 3] |= (ONE << ((b) & 7)))
227 # define CLEARBIT(t, b) (t[(b) >> 3] &= (0xFF & ~(ONE << ((b) & 7))))
228
229 #define WITHIN_ARENA(p) \
230     ((char*)(p) >= sh.arena && (char*)(p) < &sh.arena[sh.arena_size])
231 #define WITHIN_FREELIST(p) \
232     ((char*)(p) >= (char*)sh.freelist && (char*)(p) < (char*)&sh.freelist[sh.freelist_size])
233
234
235 typedef struct sh_list_st
236 {
237     struct sh_list_st *next;
238     struct sh_list_st **p_next;
239 } SH_LIST;
240
241 typedef struct sh_st
242 {
243     char* map_result;
244     size_t map_size;
245     char *arena;
246     size_t arena_size;
247     char **freelist;
248     ossl_ssize_t freelist_size;
249     size_t minsize;
250     unsigned char *bittable;
251     unsigned char *bitmalloc;
252     size_t bittable_size; /* size in bits */
253 } SH;
254
255 static SH sh;
256
257 static size_t sh_getlist(char *ptr)
258 {
259     ossl_ssize_t list = sh.freelist_size - 1;
260     size_t bit = (sh.arena_size + ptr - sh.arena) / sh.minsize;
261
262     for (; bit; bit >>= 1, list--) {
263         if (TESTBIT(sh.bittable, bit))
264             break;
265         OPENSSL_assert((bit & 1) == 0);
266     }
267
268     return list;
269 }
270
271
272 static int sh_testbit(char *ptr, int list, unsigned char *table)
273 {
274     size_t bit;
275
276     OPENSSL_assert(list >= 0 && list < sh.freelist_size);
277     OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0);
278     bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list));
279     OPENSSL_assert(bit > 0 && bit < sh.bittable_size);
280     return TESTBIT(table, bit);
281 }
282
283 static void sh_clearbit(char *ptr, int list, unsigned char *table)
284 {
285     size_t bit;
286
287     OPENSSL_assert(list >= 0 && list < sh.freelist_size);
288     OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0);
289     bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list));
290     OPENSSL_assert(bit > 0 && bit < sh.bittable_size);
291     OPENSSL_assert(TESTBIT(table, bit));
292     CLEARBIT(table, bit);
293 }
294
295 static void sh_setbit(char *ptr, int list, unsigned char *table)
296 {
297     size_t bit;
298
299     OPENSSL_assert(list >= 0 && list < sh.freelist_size);
300     OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0);
301     bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list));
302     OPENSSL_assert(bit > 0 && bit < sh.bittable_size);
303     OPENSSL_assert(!TESTBIT(table, bit));
304     SETBIT(table, bit);
305 }
306
307 static void sh_add_to_list(char **list, char *ptr)
308 {
309     SH_LIST *temp;
310
311     OPENSSL_assert(WITHIN_FREELIST(list));
312     OPENSSL_assert(WITHIN_ARENA(ptr));
313
314     temp = (SH_LIST *)ptr;
315     temp->next = *(SH_LIST **)list;
316     OPENSSL_assert(temp->next == NULL || WITHIN_ARENA(temp->next));
317     temp->p_next = (SH_LIST **)list;
318
319     if (temp->next != NULL) {
320         OPENSSL_assert((char **)temp->next->p_next == list);
321         temp->next->p_next = &(temp->next);
322     }
323
324     *list = ptr;
325 }
326
327 static void sh_remove_from_list(char *ptr)
328 {
329     SH_LIST *temp, *temp2;
330
331     temp = (SH_LIST *)ptr;
332     if (temp->next != NULL)
333         temp->next->p_next = temp->p_next;
334     *temp->p_next = temp->next;
335     if (temp->next == NULL)
336         return;
337
338     temp2 = temp->next;
339     OPENSSL_assert(WITHIN_FREELIST(temp2->p_next) || WITHIN_ARENA(temp2->p_next));
340 }
341
342
343 static int sh_init(size_t size, int minsize)
344 {
345     int ret;
346     size_t i;
347     size_t pgsize;
348     size_t aligned;
349
350     memset(&sh, 0, sizeof sh);
351
352     /* make sure size and minsize are powers of 2 */
353     OPENSSL_assert(size > 0);
354     OPENSSL_assert((size & (size - 1)) == 0);
355     OPENSSL_assert(minsize > 0);
356     OPENSSL_assert((minsize & (minsize - 1)) == 0);
357     if (size <= 0 || (size & (size - 1)) != 0)
358         goto err;
359     if (minsize <= 0 || (minsize & (minsize - 1)) != 0)
360         goto err;
361
362     while (minsize < (int)sizeof(SH_LIST))
363         minsize *= 2;
364
365     sh.arena_size = size;
366     sh.minsize = minsize;
367     sh.bittable_size = (sh.arena_size / sh.minsize) * 2;
368
369     /* Prevent allocations of size 0 later on */
370     if (sh.bittable_size >> 3 == 0)
371         goto err;
372
373     sh.freelist_size = -1;
374     for (i = sh.bittable_size; i; i >>= 1)
375         sh.freelist_size++;
376
377     sh.freelist = OPENSSL_zalloc(sh.freelist_size * sizeof (char *));
378     OPENSSL_assert(sh.freelist != NULL);
379     if (sh.freelist == NULL)
380         goto err;
381
382     sh.bittable = OPENSSL_zalloc(sh.bittable_size >> 3);
383     OPENSSL_assert(sh.bittable != NULL);
384     if (sh.bittable == NULL)
385         goto err;
386
387     sh.bitmalloc = OPENSSL_zalloc(sh.bittable_size >> 3);
388     OPENSSL_assert(sh.bitmalloc != NULL);
389     if (sh.bitmalloc == NULL)
390         goto err;
391
392     /* Allocate space for heap, and two extra pages as guards */
393 #if defined(_SC_PAGE_SIZE) || defined (_SC_PAGESIZE)
394     {
395 # if defined(_SC_PAGE_SIZE)
396         long tmppgsize = sysconf(_SC_PAGE_SIZE);
397 # else
398         long tmppgsize = sysconf(_SC_PAGESIZE);
399 # endif
400         if (tmppgsize < 1)
401             pgsize = PAGE_SIZE;
402         else
403             pgsize = (size_t)tmppgsize;
404     }
405 #else
406     pgsize = PAGE_SIZE;
407 #endif
408     sh.map_size = pgsize + sh.arena_size + pgsize;
409     if (1) {
410 #ifdef MAP_ANON
411         sh.map_result = mmap(NULL, sh.map_size,
412                              PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
413     } else {
414 #endif
415         int fd;
416
417         sh.map_result = MAP_FAILED;
418         if ((fd = open("/dev/zero", O_RDWR)) >= 0) {
419             sh.map_result = mmap(NULL, sh.map_size,
420                                  PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
421             close(fd);
422         }
423     }
424     if (sh.map_result == MAP_FAILED)
425         goto err;
426     sh.arena = (char *)(sh.map_result + pgsize);
427     sh_setbit(sh.arena, 0, sh.bittable);
428     sh_add_to_list(&sh.freelist[0], sh.arena);
429
430     /* Now try to add guard pages and lock into memory. */
431     ret = 1;
432
433     /* Starting guard is already aligned from mmap. */
434     if (mprotect(sh.map_result, pgsize, PROT_NONE) < 0)
435         ret = 2;
436
437     /* Ending guard page - need to round up to page boundary */
438     aligned = (pgsize + sh.arena_size + (pgsize - 1)) & ~(pgsize - 1);
439     if (mprotect(sh.map_result + aligned, pgsize, PROT_NONE) < 0)
440         ret = 2;
441
442 #if defined(OPENSSL_SYS_LINUX) && defined(MLOCK_ONFAULT) && defined(SYS_mlock2)
443     if (syscall(SYS_mlock2, sh.arena, sh.arena_size, MLOCK_ONFAULT) < 0) {
444         if (errno == ENOSYS) {
445             if (mlock(sh.arena, sh.arena_size) < 0)
446                 ret = 2;
447         } else {
448             ret = 2;
449         }
450     }
451 #else
452     if (mlock(sh.arena, sh.arena_size) < 0)
453         ret = 2;
454 #endif
455 #ifdef MADV_DONTDUMP
456     if (madvise(sh.arena, sh.arena_size, MADV_DONTDUMP) < 0)
457         ret = 2;
458 #endif
459
460     return ret;
461
462  err:
463     sh_done();
464     return 0;
465 }
466
467 static void sh_done()
468 {
469     OPENSSL_free(sh.freelist);
470     OPENSSL_free(sh.bittable);
471     OPENSSL_free(sh.bitmalloc);
472     if (sh.map_result != NULL && sh.map_size)
473         munmap(sh.map_result, sh.map_size);
474     memset(&sh, 0, sizeof sh);
475 }
476
477 static int sh_allocated(const char *ptr)
478 {
479     return WITHIN_ARENA(ptr) ? 1 : 0;
480 }
481
482 static char *sh_find_my_buddy(char *ptr, int list)
483 {
484     size_t bit;
485     char *chunk = NULL;
486
487     bit = (ONE << list) + (ptr - sh.arena) / (sh.arena_size >> list);
488     bit ^= 1;
489
490     if (TESTBIT(sh.bittable, bit) && !TESTBIT(sh.bitmalloc, bit))
491         chunk = sh.arena + ((bit & ((ONE << list) - 1)) * (sh.arena_size >> list));
492
493     return chunk;
494 }
495
496 static void *sh_malloc(size_t size)
497 {
498     ossl_ssize_t list, slist;
499     size_t i;
500     char *chunk;
501
502     if (size > sh.arena_size)
503         return NULL;
504
505     list = sh.freelist_size - 1;
506     for (i = sh.minsize; i < size; i <<= 1)
507         list--;
508     if (list < 0)
509         return NULL;
510
511     /* try to find a larger entry to split */
512     for (slist = list; slist >= 0; slist--)
513         if (sh.freelist[slist] != NULL)
514             break;
515     if (slist < 0)
516         return NULL;
517
518     /* split larger entry */
519     while (slist != list) {
520         char *temp = sh.freelist[slist];
521
522         /* remove from bigger list */
523         OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc));
524         sh_clearbit(temp, slist, sh.bittable);
525         sh_remove_from_list(temp);
526         OPENSSL_assert(temp != sh.freelist[slist]);
527
528         /* done with bigger list */
529         slist++;
530
531         /* add to smaller list */
532         OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc));
533         sh_setbit(temp, slist, sh.bittable);
534         sh_add_to_list(&sh.freelist[slist], temp);
535         OPENSSL_assert(sh.freelist[slist] == temp);
536
537         /* split in 2 */
538         temp += sh.arena_size >> slist;
539         OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc));
540         sh_setbit(temp, slist, sh.bittable);
541         sh_add_to_list(&sh.freelist[slist], temp);
542         OPENSSL_assert(sh.freelist[slist] == temp);
543
544         OPENSSL_assert(temp-(sh.arena_size >> slist) == sh_find_my_buddy(temp, slist));
545     }
546
547     /* peel off memory to hand back */
548     chunk = sh.freelist[list];
549     OPENSSL_assert(sh_testbit(chunk, list, sh.bittable));
550     sh_setbit(chunk, list, sh.bitmalloc);
551     sh_remove_from_list(chunk);
552
553     OPENSSL_assert(WITHIN_ARENA(chunk));
554
555     return chunk;
556 }
557
558 static void sh_free(void *ptr)
559 {
560     size_t list;
561     void *buddy;
562
563     if (ptr == NULL)
564         return;
565     OPENSSL_assert(WITHIN_ARENA(ptr));
566     if (!WITHIN_ARENA(ptr))
567         return;
568
569     list = sh_getlist(ptr);
570     OPENSSL_assert(sh_testbit(ptr, list, sh.bittable));
571     sh_clearbit(ptr, list, sh.bitmalloc);
572     sh_add_to_list(&sh.freelist[list], ptr);
573
574     /* Try to coalesce two adjacent free areas. */
575     while ((buddy = sh_find_my_buddy(ptr, list)) != NULL) {
576         OPENSSL_assert(ptr == sh_find_my_buddy(buddy, list));
577         OPENSSL_assert(ptr != NULL);
578         OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc));
579         sh_clearbit(ptr, list, sh.bittable);
580         sh_remove_from_list(ptr);
581         OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc));
582         sh_clearbit(buddy, list, sh.bittable);
583         sh_remove_from_list(buddy);
584
585         list--;
586
587         if (ptr > buddy)
588             ptr = buddy;
589
590         OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc));
591         sh_setbit(ptr, list, sh.bittable);
592         sh_add_to_list(&sh.freelist[list], ptr);
593         OPENSSL_assert(sh.freelist[list] == ptr);
594     }
595 }
596
597 static size_t sh_actual_size(char *ptr)
598 {
599     int list;
600
601     OPENSSL_assert(WITHIN_ARENA(ptr));
602     if (!WITHIN_ARENA(ptr))
603         return 0;
604     list = sh_getlist(ptr);
605     OPENSSL_assert(sh_testbit(ptr, list, sh.bittable));
606     return sh.arena_size / (ONE << list);
607 }
608 #endif /* IMPLEMENTED */