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