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