1 /* Written by Ulf Moeller for the OpenSSL project. */
2 /* ====================================================================
3 * Copyright (c) 1998-2004 The OpenSSL Project. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in
14 * the documentation and/or other materials provided with the
17 * 3. All advertising materials mentioning features or use of this
18 * software must display the following acknowledgment:
19 * "This product includes software developed by the OpenSSL Project
20 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
22 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
23 * endorse or promote products derived from this software without
24 * prior written permission. For written permission, please contact
25 * openssl-core@openssl.org.
27 * 5. Products derived from this software may not be called "OpenSSL"
28 * nor may "OpenSSL" appear in their names without prior written
29 * permission of the OpenSSL Project.
31 * 6. Redistributions of any form whatsoever must retain the following
33 * "This product includes software developed by the OpenSSL Project
34 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
36 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
37 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
38 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
39 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
40 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
42 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
43 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
45 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
46 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
47 * OF THE POSSIBILITY OF SUCH DAMAGE.
48 * ====================================================================
50 * This product includes cryptographic software written by Eric Young
51 * (eay@cryptsoft.com). This product includes software written by Tim
52 * Hudson (tjh@cryptsoft.com).
56 #if !defined(BN_CTX_DEBUG) && !defined(BN_DEBUG)
64 #include "internal/cryptlib.h"
70 * 1. Check a bunch of "(words+1)" type hacks in various bignum functions and
71 * check they can be safely removed.
72 * - Check +1 and other ugliness in BN_from_montgomery()
74 * 2. Consider allowing a BN_new_ex() that, at least, lets you specify an
75 * appropriate 'block' size that will be honoured by bn_expand_internal() to
76 * prevent piddly little reallocations. OTOH, profiling bignum expansions in
77 * BN_CTX doesn't show this to be a big issue.
80 /* How many bignums are in each "pool item"; */
81 #define BN_CTX_POOL_SIZE 16
82 /* The stack frame info is resizing, set a first-time expansion size; */
83 #define BN_CTX_START_FRAMES 32
89 /* A bundle of bignums that can be linked with other bundles */
90 typedef struct bignum_pool_item {
91 /* The bignum values */
92 BIGNUM vals[BN_CTX_POOL_SIZE];
93 /* Linked-list admin */
94 struct bignum_pool_item *prev, *next;
96 /* A linked-list of bignums grouped in bundles */
97 typedef struct bignum_pool {
98 /* Linked-list admin */
99 BN_POOL_ITEM *head, *current, *tail;
100 /* Stack depth and allocation size */
103 static void BN_POOL_init(BN_POOL *);
104 static void BN_POOL_finish(BN_POOL *);
105 static BIGNUM *BN_POOL_get(BN_POOL *, int);
106 static void BN_POOL_release(BN_POOL *, unsigned int);
112 /* A wrapper to manage the "stack frames" */
113 typedef struct bignum_ctx_stack {
114 /* Array of indexes into the bignum stack */
115 unsigned int *indexes;
116 /* Number of stack frames, and the size of the allocated array */
117 unsigned int depth, size;
119 static void BN_STACK_init(BN_STACK *);
120 static void BN_STACK_finish(BN_STACK *);
121 static int BN_STACK_push(BN_STACK *, unsigned int);
122 static unsigned int BN_STACK_pop(BN_STACK *);
128 /* The opaque BN_CTX type */
130 /* The bignum bundles */
132 /* The "stack frames", if you will */
134 /* The number of bignums currently assigned */
136 /* Depth of stack overflow */
138 /* Block "gets" until an "end" (compatibility behaviour) */
144 /* Enable this to find BN_CTX bugs */
146 static const char *ctxdbg_cur = NULL;
147 static void ctxdbg(BN_CTX *ctx)
149 unsigned int bnidx = 0, fpidx = 0;
150 BN_POOL_ITEM *item = ctx->pool.head;
151 BN_STACK *stack = &ctx->stack;
152 fprintf(stderr, "(%16p): ", ctx);
153 while (bnidx < ctx->used) {
154 fprintf(stderr, "%03x ", item->vals[bnidx++ % BN_CTX_POOL_SIZE].dmax);
155 if (!(bnidx % BN_CTX_POOL_SIZE))
158 fprintf(stderr, "\n");
160 fprintf(stderr, " : ");
161 while (fpidx < stack->depth) {
162 while (bnidx++ < stack->indexes[fpidx])
163 fprintf(stderr, " ");
164 fprintf(stderr, "^^^ ");
168 fprintf(stderr, "\n");
171 # define CTXDBG_ENTRY(str, ctx) do { \
172 ctxdbg_cur = (str); \
173 fprintf(stderr,"Starting %s\n", ctxdbg_cur); \
176 # define CTXDBG_EXIT(ctx) do { \
177 fprintf(stderr,"Ending %s\n", ctxdbg_cur); \
180 # define CTXDBG_RET(ctx,ret)
182 # define CTXDBG_ENTRY(str, ctx)
183 # define CTXDBG_EXIT(ctx)
184 # define CTXDBG_RET(ctx,ret)
188 BN_CTX *BN_CTX_new(void)
192 if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) {
193 BNerr(BN_F_BN_CTX_NEW, ERR_R_MALLOC_FAILURE);
196 /* Initialise the structure */
197 BN_POOL_init(&ret->pool);
198 BN_STACK_init(&ret->stack);
202 BN_CTX *BN_CTX_secure_new(void)
204 BN_CTX *ret = BN_CTX_new();
207 ret->flags = BN_FLG_SECURE;
211 void BN_CTX_free(BN_CTX *ctx)
217 BN_POOL_ITEM *pool = ctx->pool.head;
218 fprintf(stderr, "BN_CTX_free, stack-size=%d, pool-bignums=%d\n",
219 ctx->stack.size, ctx->pool.size);
220 fprintf(stderr, "dmaxs: ");
223 while (loop < BN_CTX_POOL_SIZE)
224 fprintf(stderr, "%02x ", pool->vals[loop++].dmax);
227 fprintf(stderr, "\n");
230 BN_STACK_finish(&ctx->stack);
231 BN_POOL_finish(&ctx->pool);
235 void BN_CTX_start(BN_CTX *ctx)
237 CTXDBG_ENTRY("BN_CTX_start", ctx);
238 /* If we're already overflowing ... */
239 if (ctx->err_stack || ctx->too_many)
241 /* (Try to) get a new frame pointer */
242 else if (!BN_STACK_push(&ctx->stack, ctx->used)) {
243 BNerr(BN_F_BN_CTX_START, BN_R_TOO_MANY_TEMPORARY_VARIABLES);
249 void BN_CTX_end(BN_CTX *ctx)
251 CTXDBG_ENTRY("BN_CTX_end", ctx);
255 unsigned int fp = BN_STACK_pop(&ctx->stack);
256 /* Does this stack frame have anything to release? */
258 BN_POOL_release(&ctx->pool, ctx->used - fp);
260 /* Unjam "too_many" in case "get" had failed */
266 BIGNUM *BN_CTX_get(BN_CTX *ctx)
270 CTXDBG_ENTRY("BN_CTX_get", ctx);
271 if (ctx->err_stack || ctx->too_many)
273 if ((ret = BN_POOL_get(&ctx->pool, ctx->flags)) == NULL) {
275 * Setting too_many prevents repeated "get" attempts from cluttering
279 BNerr(BN_F_BN_CTX_GET, BN_R_TOO_MANY_TEMPORARY_VARIABLES);
282 /* OK, make sure the returned bignum is "zero" */
285 CTXDBG_RET(ctx, ret);
293 static void BN_STACK_init(BN_STACK *st)
296 st->depth = st->size = 0;
299 static void BN_STACK_finish(BN_STACK *st)
301 OPENSSL_free(st->indexes);
306 static int BN_STACK_push(BN_STACK *st, unsigned int idx)
308 if (st->depth == st->size) {
310 unsigned int newsize =
311 st->size ? (st->size * 3 / 2) : BN_CTX_START_FRAMES;
312 unsigned int *newitems = OPENSSL_malloc(sizeof(*newitems) * newsize);
313 if (newitems == NULL)
316 memcpy(newitems, st->indexes, sizeof(*newitems) * st->depth);
317 OPENSSL_free(st->indexes);
318 st->indexes = newitems;
321 st->indexes[(st->depth)++] = idx;
325 static unsigned int BN_STACK_pop(BN_STACK *st)
327 return st->indexes[--(st->depth)];
334 static void BN_POOL_init(BN_POOL *p)
336 p->head = p->current = p->tail = NULL;
337 p->used = p->size = 0;
340 static void BN_POOL_finish(BN_POOL *p)
346 for (loop = 0, bn = p->head->vals; loop++ < BN_CTX_POOL_SIZE; bn++)
349 p->current = p->head->next;
350 OPENSSL_free(p->head);
351 p->head = p->current;
356 static BIGNUM *BN_POOL_get(BN_POOL *p, int flag)
361 /* Full; allocate a new pool item and link it in. */
362 if (p->used == p->size) {
363 BN_POOL_ITEM *item = OPENSSL_malloc(sizeof(*item));
366 for (loop = 0, bn = item->vals; loop++ < BN_CTX_POOL_SIZE; bn++) {
368 if ((flag & BN_FLG_SECURE) != 0)
369 BN_set_flags(bn, BN_FLG_SECURE);
371 item->prev = p->tail;
375 p->head = p->current = p->tail = item;
377 p->tail->next = item;
381 p->size += BN_CTX_POOL_SIZE;
383 /* Return the first bignum from the new pool */
388 p->current = p->head;
389 else if ((p->used % BN_CTX_POOL_SIZE) == 0)
390 p->current = p->current->next;
391 return p->current->vals + ((p->used++) % BN_CTX_POOL_SIZE);
394 static void BN_POOL_release(BN_POOL *p, unsigned int num)
396 unsigned int offset = (p->used - 1) % BN_CTX_POOL_SIZE;
400 bn_check_top(p->current->vals + offset);
402 offset = BN_CTX_POOL_SIZE - 1;
403 p->current = p->current->prev;