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