7202aef326d336c346f35d38559a40ed9ffb5b31
[openssl.git] / crypto / bn / bn_ctx.c
1 /*
2  * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include "internal/cryptlib.h"
11 #include "bn_lcl.h"
12
13 /*-
14  * TODO list
15  *
16  * 1. Check a bunch of "(words+1)" type hacks in various bignum functions and
17  * check they can be safely removed.
18  *  - Check +1 and other ugliness in BN_from_montgomery()
19  *
20  * 2. Consider allowing a BN_new_ex() that, at least, lets you specify an
21  * appropriate 'block' size that will be honoured by bn_expand_internal() to
22  * prevent piddly little reallocations. OTOH, profiling bignum expansions in
23  * BN_CTX doesn't show this to be a big issue.
24  */
25
26 /* How many bignums are in each "pool item"; */
27 #define BN_CTX_POOL_SIZE        16
28 /* The stack frame info is resizing, set a first-time expansion size; */
29 #define BN_CTX_START_FRAMES     32
30
31 /***********/
32 /* BN_POOL */
33 /***********/
34
35 /* A bundle of bignums that can be linked with other bundles */
36 typedef struct bignum_pool_item {
37     /* The bignum values */
38     BIGNUM vals[BN_CTX_POOL_SIZE];
39     /* Linked-list admin */
40     struct bignum_pool_item *prev, *next;
41 } BN_POOL_ITEM;
42 /* A linked-list of bignums grouped in bundles */
43 typedef struct bignum_pool {
44     /* Linked-list admin */
45     BN_POOL_ITEM *head, *current, *tail;
46     /* Stack depth and allocation size */
47     unsigned used, size;
48 } BN_POOL;
49 static void BN_POOL_init(BN_POOL *);
50 static void BN_POOL_finish(BN_POOL *);
51 static BIGNUM *BN_POOL_get(BN_POOL *, int);
52 static void BN_POOL_release(BN_POOL *, unsigned int);
53
54 /************/
55 /* BN_STACK */
56 /************/
57
58 /* A wrapper to manage the "stack frames" */
59 typedef struct bignum_ctx_stack {
60     /* Array of indexes into the bignum stack */
61     unsigned int *indexes;
62     /* Number of stack frames, and the size of the allocated array */
63     unsigned int depth, size;
64 } BN_STACK;
65 static void BN_STACK_init(BN_STACK *);
66 static void BN_STACK_finish(BN_STACK *);
67 static int BN_STACK_push(BN_STACK *, unsigned int);
68 static unsigned int BN_STACK_pop(BN_STACK *);
69
70 /**********/
71 /* BN_CTX */
72 /**********/
73
74 /* The opaque BN_CTX type */
75 struct bignum_ctx {
76     /* The bignum bundles */
77     BN_POOL pool;
78     /* The "stack frames", if you will */
79     BN_STACK stack;
80     /* The number of bignums currently assigned */
81     unsigned int used;
82     /* Depth of stack overflow */
83     int err_stack;
84     /* Block "gets" until an "end" (compatibility behaviour) */
85     int too_many;
86     /* Flags. */
87     int flags;
88 };
89
90 /* Enable this to find BN_CTX bugs */
91 #ifdef BN_CTX_DEBUG
92 static const char *ctxdbg_cur = NULL;
93 static void ctxdbg(BN_CTX *ctx)
94 {
95     unsigned int bnidx = 0, fpidx = 0;
96     BN_POOL_ITEM *item = ctx->pool.head;
97     BN_STACK *stack = &ctx->stack;
98     fprintf(stderr, "(%16p): ", ctx);
99     while (bnidx < ctx->used) {
100         fprintf(stderr, "%03x ", item->vals[bnidx++ % BN_CTX_POOL_SIZE].dmax);
101         if (!(bnidx % BN_CTX_POOL_SIZE))
102             item = item->next;
103     }
104     fprintf(stderr, "\n");
105     bnidx = 0;
106     fprintf(stderr, "          : ");
107     while (fpidx < stack->depth) {
108         while (bnidx++ < stack->indexes[fpidx])
109             fprintf(stderr, "    ");
110         fprintf(stderr, "^^^ ");
111         bnidx++;
112         fpidx++;
113     }
114     fprintf(stderr, "\n");
115 }
116
117 # define CTXDBG_ENTRY(str, ctx)  do { \
118                                 ctxdbg_cur = (str); \
119                                 fprintf(stderr,"Starting %s\n", ctxdbg_cur); \
120                                 ctxdbg(ctx); \
121                                 } while(0)
122 # define CTXDBG_EXIT(ctx)        do { \
123                                 fprintf(stderr,"Ending %s\n", ctxdbg_cur); \
124                                 ctxdbg(ctx); \
125                                 } while(0)
126 # define CTXDBG_RET(ctx,ret)
127 #else
128 # define CTXDBG_ENTRY(str, ctx)
129 # define CTXDBG_EXIT(ctx)
130 # define CTXDBG_RET(ctx,ret)
131 #endif
132
133
134 BN_CTX *BN_CTX_new(void)
135 {
136     BN_CTX *ret;
137
138     if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) {
139         BNerr(BN_F_BN_CTX_NEW, ERR_R_MALLOC_FAILURE);
140         return NULL;
141     }
142     /* Initialise the structure */
143     BN_POOL_init(&ret->pool);
144     BN_STACK_init(&ret->stack);
145     return ret;
146 }
147
148 BN_CTX *BN_CTX_secure_new(void)
149 {
150     BN_CTX *ret = BN_CTX_new();
151
152     if (ret != NULL)
153         ret->flags = BN_FLG_SECURE;
154     return ret;
155 }
156
157 void BN_CTX_free(BN_CTX *ctx)
158 {
159 #ifdef BN_CTX_DEBUG
160     {
161         BN_POOL_ITEM *pool = ctx->pool.head;
162         fprintf(stderr, "BN_CTX_free, stack-size=%d, pool-bignums=%d\n",
163                 ctx->stack.size, ctx->pool.size);
164         fprintf(stderr, "dmaxs: ");
165         while (pool) {
166             unsigned loop = 0;
167             while (loop < BN_CTX_POOL_SIZE)
168                 fprintf(stderr, "%02x ", pool->vals[loop++].dmax);
169             pool = pool->next;
170         }
171         fprintf(stderr, "\n");
172     }
173 #endif
174     BN_STACK_finish(&ctx->stack);
175     BN_POOL_finish(&ctx->pool);
176     OPENSSL_free(ctx);
177 }
178
179 void BN_CTX_start(BN_CTX *ctx)
180 {
181     CTXDBG_ENTRY("BN_CTX_start", ctx);
182     /* If we're already overflowing ... */
183     if (ctx->err_stack || ctx->too_many)
184         ctx->err_stack++;
185     /* (Try to) get a new frame pointer */
186     else if (!BN_STACK_push(&ctx->stack, ctx->used)) {
187         BNerr(BN_F_BN_CTX_START, BN_R_TOO_MANY_TEMPORARY_VARIABLES);
188         ctx->err_stack++;
189     }
190     CTXDBG_EXIT(ctx);
191 }
192
193 void BN_CTX_end(BN_CTX *ctx)
194 {
195     CTXDBG_ENTRY("BN_CTX_end", ctx);
196     if (ctx->err_stack)
197         ctx->err_stack--;
198     else {
199         unsigned int fp = BN_STACK_pop(&ctx->stack);
200         /* Does this stack frame have anything to release? */
201         if (fp < ctx->used)
202             BN_POOL_release(&ctx->pool, ctx->used - fp);
203         ctx->used = fp;
204         /* Unjam "too_many" in case "get" had failed */
205         ctx->too_many = 0;
206     }
207     CTXDBG_EXIT(ctx);
208 }
209
210 BIGNUM *BN_CTX_get(BN_CTX *ctx)
211 {
212     BIGNUM *ret;
213
214     CTXDBG_ENTRY("BN_CTX_get", ctx);
215     if (ctx->err_stack || ctx->too_many)
216         return NULL;
217     if ((ret = BN_POOL_get(&ctx->pool, ctx->flags)) == NULL) {
218         /*
219          * Setting too_many prevents repeated "get" attempts from cluttering
220          * the error stack.
221          */
222         ctx->too_many = 1;
223         BNerr(BN_F_BN_CTX_GET, BN_R_TOO_MANY_TEMPORARY_VARIABLES);
224         return NULL;
225     }
226     /* OK, make sure the returned bignum is "zero" */
227     BN_zero(ret);
228     ctx->used++;
229     CTXDBG_RET(ctx, ret);
230     return ret;
231 }
232
233 /************/
234 /* BN_STACK */
235 /************/
236
237 static void BN_STACK_init(BN_STACK *st)
238 {
239     st->indexes = NULL;
240     st->depth = st->size = 0;
241 }
242
243 static void BN_STACK_finish(BN_STACK *st)
244 {
245     OPENSSL_free(st->indexes);
246     st->indexes = NULL;
247 }
248
249
250 static int BN_STACK_push(BN_STACK *st, unsigned int idx)
251 {
252     if (st->depth == st->size) {
253         /* Need to expand */
254         unsigned int newsize =
255             st->size ? (st->size * 3 / 2) : BN_CTX_START_FRAMES;
256         unsigned int *newitems = OPENSSL_malloc(sizeof(*newitems) * newsize);
257         if (newitems == NULL)
258             return 0;
259         if (st->depth)
260             memcpy(newitems, st->indexes, sizeof(*newitems) * st->depth);
261         OPENSSL_free(st->indexes);
262         st->indexes = newitems;
263         st->size = newsize;
264     }
265     st->indexes[(st->depth)++] = idx;
266     return 1;
267 }
268
269 static unsigned int BN_STACK_pop(BN_STACK *st)
270 {
271     return st->indexes[--(st->depth)];
272 }
273
274 /***********/
275 /* BN_POOL */
276 /***********/
277
278 static void BN_POOL_init(BN_POOL *p)
279 {
280     p->head = p->current = p->tail = NULL;
281     p->used = p->size = 0;
282 }
283
284 static void BN_POOL_finish(BN_POOL *p)
285 {
286     unsigned int loop;
287     BIGNUM *bn;
288
289     while (p->head) {
290         for (loop = 0, bn = p->head->vals; loop++ < BN_CTX_POOL_SIZE; bn++)
291             if (bn->d)
292                 BN_clear_free(bn);
293         p->current = p->head->next;
294         OPENSSL_free(p->head);
295         p->head = p->current;
296     }
297 }
298
299
300 static BIGNUM *BN_POOL_get(BN_POOL *p, int flag)
301 {
302     BIGNUM *bn;
303     unsigned int loop;
304
305     /* Full; allocate a new pool item and link it in. */
306     if (p->used == p->size) {
307         BN_POOL_ITEM *item = OPENSSL_malloc(sizeof(*item));
308         if (item == NULL)
309             return NULL;
310         for (loop = 0, bn = item->vals; loop++ < BN_CTX_POOL_SIZE; bn++) {
311             bn_init(bn);
312             if ((flag & BN_FLG_SECURE) != 0)
313                 BN_set_flags(bn, BN_FLG_SECURE);
314         }
315         item->prev = p->tail;
316         item->next = NULL;
317
318         if (p->head == NULL)
319             p->head = p->current = p->tail = item;
320         else {
321             p->tail->next = item;
322             p->tail = item;
323             p->current = item;
324         }
325         p->size += BN_CTX_POOL_SIZE;
326         p->used++;
327         /* Return the first bignum from the new pool */
328         return item->vals;
329     }
330
331     if (!p->used)
332         p->current = p->head;
333     else if ((p->used % BN_CTX_POOL_SIZE) == 0)
334         p->current = p->current->next;
335     return p->current->vals + ((p->used++) % BN_CTX_POOL_SIZE);
336 }
337
338 static void BN_POOL_release(BN_POOL *p, unsigned int num)
339 {
340     unsigned int offset = (p->used - 1) % BN_CTX_POOL_SIZE;
341
342     p->used -= num;
343     while (num--) {
344         bn_check_top(p->current->vals + offset);
345         if (offset == 0) {
346             offset = BN_CTX_POOL_SIZE - 1;
347             p->current = p->current->prev;
348         } else
349             offset--;
350     }
351 }