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