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