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