]> git.ipfire.org Git - thirdparty/openssl.git/blob - crypto/bn/bn_ctx.c
Identify and move common internal libcrypto header files
[thirdparty/openssl.git] / crypto / bn / bn_ctx.c
1 /* crypto/bn/bn_ctx.c */
2 /* Written by Ulf Moeller for the OpenSSL project. */
3 /* ====================================================================
4 * Copyright (c) 1998-2004 The OpenSSL Project. All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 *
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in
15 * the documentation and/or other materials provided with the
16 * distribution.
17 *
18 * 3. All advertising materials mentioning features or use of this
19 * software must display the following acknowledgment:
20 * "This product includes software developed by the OpenSSL Project
21 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
22 *
23 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
24 * endorse or promote products derived from this software without
25 * prior written permission. For written permission, please contact
26 * openssl-core@openssl.org.
27 *
28 * 5. Products derived from this software may not be called "OpenSSL"
29 * nor may "OpenSSL" appear in their names without prior written
30 * permission of the OpenSSL Project.
31 *
32 * 6. Redistributions of any form whatsoever must retain the following
33 * acknowledgment:
34 * "This product includes software developed by the OpenSSL Project
35 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
36 *
37 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
38 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
39 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
40 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
41 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
43 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
44 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
45 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
46 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
47 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
48 * OF THE POSSIBILITY OF SUCH DAMAGE.
49 * ====================================================================
50 *
51 * This product includes cryptographic software written by Eric Young
52 * (eay@cryptsoft.com). This product includes software written by Tim
53 * Hudson (tjh@cryptsoft.com).
54 *
55 */
56
57 #if !defined(BN_CTX_DEBUG) && !defined(BN_DEBUG)
58 # ifndef NDEBUG
59 # define NDEBUG
60 # endif
61 #endif
62
63 #include <assert.h>
64
65 #include "internal/cryptlib.h"
66 #include "bn_lcl.h"
67
68 /*-
69 * TODO list
70 *
71 * 1. Check a bunch of "(words+1)" type hacks in various bignum functions and
72 * check they can be safely removed.
73 * - Check +1 and other ugliness in BN_from_montgomery()
74 *
75 * 2. Consider allowing a BN_new_ex() that, at least, lets you specify an
76 * appropriate 'block' size that will be honoured by bn_expand_internal() to
77 * prevent piddly little reallocations. OTOH, profiling bignum expansions in
78 * BN_CTX doesn't show this to be a big issue.
79 */
80
81 /* How many bignums are in each "pool item"; */
82 #define BN_CTX_POOL_SIZE 16
83 /* The stack frame info is resizing, set a first-time expansion size; */
84 #define BN_CTX_START_FRAMES 32
85
86 /***********/
87 /* BN_POOL */
88 /***********/
89
90 /* A bundle of bignums that can be linked with other bundles */
91 typedef struct bignum_pool_item {
92 /* The bignum values */
93 BIGNUM vals[BN_CTX_POOL_SIZE];
94 /* Linked-list admin */
95 struct bignum_pool_item *prev, *next;
96 } BN_POOL_ITEM;
97 /* A linked-list of bignums grouped in bundles */
98 typedef struct bignum_pool {
99 /* Linked-list admin */
100 BN_POOL_ITEM *head, *current, *tail;
101 /* Stack depth and allocation size */
102 unsigned used, size;
103 } BN_POOL;
104 static void BN_POOL_init(BN_POOL *);
105 static void BN_POOL_finish(BN_POOL *);
106 static BIGNUM *BN_POOL_get(BN_POOL *);
107 static void BN_POOL_release(BN_POOL *, unsigned int);
108
109 /************/
110 /* BN_STACK */
111 /************/
112
113 /* A wrapper to manage the "stack frames" */
114 typedef struct bignum_ctx_stack {
115 /* Array of indexes into the bignum stack */
116 unsigned int *indexes;
117 /* Number of stack frames, and the size of the allocated array */
118 unsigned int depth, size;
119 } BN_STACK;
120 static void BN_STACK_init(BN_STACK *);
121 static void BN_STACK_finish(BN_STACK *);
122 static int BN_STACK_push(BN_STACK *, unsigned int);
123 static unsigned int BN_STACK_pop(BN_STACK *);
124
125 /**********/
126 /* BN_CTX */
127 /**********/
128
129 /* The opaque BN_CTX type */
130 struct bignum_ctx {
131 /* The bignum bundles */
132 BN_POOL pool;
133 /* The "stack frames", if you will */
134 BN_STACK stack;
135 /* The number of bignums currently assigned */
136 unsigned int used;
137 /* Depth of stack overflow */
138 int err_stack;
139 /* Block "gets" until an "end" (compatibility behaviour) */
140 int too_many;
141 };
142
143 /* Enable this to find BN_CTX bugs */
144 #ifdef BN_CTX_DEBUG
145 static const char *ctxdbg_cur = NULL;
146 static void ctxdbg(BN_CTX *ctx)
147 {
148 unsigned int bnidx = 0, fpidx = 0;
149 BN_POOL_ITEM *item = ctx->pool.head;
150 BN_STACK *stack = &ctx->stack;
151 fprintf(stderr, "(%16p): ", ctx);
152 while (bnidx < ctx->used) {
153 fprintf(stderr, "%03x ", item->vals[bnidx++ % BN_CTX_POOL_SIZE].dmax);
154 if (!(bnidx % BN_CTX_POOL_SIZE))
155 item = item->next;
156 }
157 fprintf(stderr, "\n");
158 bnidx = 0;
159 fprintf(stderr, " : ");
160 while (fpidx < stack->depth) {
161 while (bnidx++ < stack->indexes[fpidx])
162 fprintf(stderr, " ");
163 fprintf(stderr, "^^^ ");
164 bnidx++;
165 fpidx++;
166 }
167 fprintf(stderr, "\n");
168 }
169
170 # define CTXDBG_ENTRY(str, ctx) do { \
171 ctxdbg_cur = (str); \
172 fprintf(stderr,"Starting %s\n", ctxdbg_cur); \
173 ctxdbg(ctx); \
174 } while(0)
175 # define CTXDBG_EXIT(ctx) do { \
176 fprintf(stderr,"Ending %s\n", ctxdbg_cur); \
177 ctxdbg(ctx); \
178 } while(0)
179 # define CTXDBG_RET(ctx,ret)
180 #else
181 # define CTXDBG_ENTRY(str, ctx)
182 # define CTXDBG_EXIT(ctx)
183 # define CTXDBG_RET(ctx,ret)
184 #endif
185
186
187 BN_CTX *BN_CTX_new(void)
188 {
189 BN_CTX *ret = OPENSSL_malloc(sizeof(*ret));
190 if (!ret) {
191 BNerr(BN_F_BN_CTX_NEW, ERR_R_MALLOC_FAILURE);
192 return NULL;
193 }
194 /* Initialise the structure */
195 BN_POOL_init(&ret->pool);
196 BN_STACK_init(&ret->stack);
197 ret->used = 0;
198 ret->err_stack = 0;
199 ret->too_many = 0;
200 return ret;
201 }
202
203 void BN_CTX_free(BN_CTX *ctx)
204 {
205 if (ctx == NULL)
206 return;
207 #ifdef BN_CTX_DEBUG
208 {
209 BN_POOL_ITEM *pool = ctx->pool.head;
210 fprintf(stderr, "BN_CTX_free, stack-size=%d, pool-bignums=%d\n",
211 ctx->stack.size, ctx->pool.size);
212 fprintf(stderr, "dmaxs: ");
213 while (pool) {
214 unsigned loop = 0;
215 while (loop < BN_CTX_POOL_SIZE)
216 fprintf(stderr, "%02x ", pool->vals[loop++].dmax);
217 pool = pool->next;
218 }
219 fprintf(stderr, "\n");
220 }
221 #endif
222 BN_STACK_finish(&ctx->stack);
223 BN_POOL_finish(&ctx->pool);
224 OPENSSL_free(ctx);
225 }
226
227 void BN_CTX_start(BN_CTX *ctx)
228 {
229 CTXDBG_ENTRY("BN_CTX_start", ctx);
230 /* If we're already overflowing ... */
231 if (ctx->err_stack || ctx->too_many)
232 ctx->err_stack++;
233 /* (Try to) get a new frame pointer */
234 else if (!BN_STACK_push(&ctx->stack, ctx->used)) {
235 BNerr(BN_F_BN_CTX_START, BN_R_TOO_MANY_TEMPORARY_VARIABLES);
236 ctx->err_stack++;
237 }
238 CTXDBG_EXIT(ctx);
239 }
240
241 void BN_CTX_end(BN_CTX *ctx)
242 {
243 CTXDBG_ENTRY("BN_CTX_end", ctx);
244 if (ctx->err_stack)
245 ctx->err_stack--;
246 else {
247 unsigned int fp = BN_STACK_pop(&ctx->stack);
248 /* Does this stack frame have anything to release? */
249 if (fp < ctx->used)
250 BN_POOL_release(&ctx->pool, ctx->used - fp);
251 ctx->used = fp;
252 /* Unjam "too_many" in case "get" had failed */
253 ctx->too_many = 0;
254 }
255 CTXDBG_EXIT(ctx);
256 }
257
258 BIGNUM *BN_CTX_get(BN_CTX *ctx)
259 {
260 BIGNUM *ret;
261 CTXDBG_ENTRY("BN_CTX_get", ctx);
262 if (ctx->err_stack || ctx->too_many)
263 return NULL;
264 if ((ret = BN_POOL_get(&ctx->pool)) == NULL) {
265 /*
266 * Setting too_many prevents repeated "get" attempts from cluttering
267 * the error stack.
268 */
269 ctx->too_many = 1;
270 BNerr(BN_F_BN_CTX_GET, BN_R_TOO_MANY_TEMPORARY_VARIABLES);
271 return NULL;
272 }
273 /* OK, make sure the returned bignum is "zero" */
274 BN_zero(ret);
275 ctx->used++;
276 CTXDBG_RET(ctx, ret);
277 return ret;
278 }
279
280 /************/
281 /* BN_STACK */
282 /************/
283
284 static void BN_STACK_init(BN_STACK *st)
285 {
286 st->indexes = NULL;
287 st->depth = st->size = 0;
288 }
289
290 static void BN_STACK_finish(BN_STACK *st)
291 {
292 if (st->size)
293 OPENSSL_free(st->indexes);
294 }
295
296
297 static int BN_STACK_push(BN_STACK *st, unsigned int idx)
298 {
299 if (st->depth == st->size)
300 /* Need to expand */
301 {
302 unsigned int newsize = (st->size ?
303 (st->size * 3 / 2) : BN_CTX_START_FRAMES);
304 unsigned int *newitems = OPENSSL_malloc(newsize *
305 sizeof(unsigned int));
306 if (!newitems)
307 return 0;
308 if (st->depth)
309 memcpy(newitems, st->indexes, st->depth * sizeof(unsigned int));
310 if (st->size)
311 OPENSSL_free(st->indexes);
312 st->indexes = newitems;
313 st->size = newsize;
314 }
315 st->indexes[(st->depth)++] = idx;
316 return 1;
317 }
318
319 static unsigned int BN_STACK_pop(BN_STACK *st)
320 {
321 return st->indexes[--(st->depth)];
322 }
323
324 /***********/
325 /* BN_POOL */
326 /***********/
327
328 static void BN_POOL_init(BN_POOL *p)
329 {
330 p->head = p->current = p->tail = NULL;
331 p->used = p->size = 0;
332 }
333
334 static void BN_POOL_finish(BN_POOL *p)
335 {
336 while (p->head) {
337 unsigned int loop = 0;
338 BIGNUM *bn = p->head->vals;
339 while (loop++ < BN_CTX_POOL_SIZE) {
340 if (bn->d)
341 BN_clear_free(bn);
342 bn++;
343 }
344 p->current = p->head->next;
345 OPENSSL_free(p->head);
346 p->head = p->current;
347 }
348 }
349
350
351 static BIGNUM *BN_POOL_get(BN_POOL *p)
352 {
353 if (p->used == p->size) {
354 BIGNUM *bn;
355 unsigned int loop = 0;
356 BN_POOL_ITEM *item = OPENSSL_malloc(sizeof(*item));
357 if (!item)
358 return NULL;
359 /* Initialise the structure */
360 bn = item->vals;
361 while (loop++ < BN_CTX_POOL_SIZE)
362 BN_init(bn++);
363 item->prev = p->tail;
364 item->next = NULL;
365 /* Link it in */
366 if (!p->head)
367 p->head = p->current = p->tail = item;
368 else {
369 p->tail->next = item;
370 p->tail = item;
371 p->current = item;
372 }
373 p->size += BN_CTX_POOL_SIZE;
374 p->used++;
375 /* Return the first bignum from the new pool */
376 return item->vals;
377 }
378 if (!p->used)
379 p->current = p->head;
380 else if ((p->used % BN_CTX_POOL_SIZE) == 0)
381 p->current = p->current->next;
382 return p->current->vals + ((p->used++) % BN_CTX_POOL_SIZE);
383 }
384
385 static void BN_POOL_release(BN_POOL *p, unsigned int num)
386 {
387 unsigned int offset = (p->used - 1) % BN_CTX_POOL_SIZE;
388 p->used -= num;
389 while (num--) {
390 bn_check_top(p->current->vals + offset);
391 if (!offset) {
392 offset = BN_CTX_POOL_SIZE - 1;
393 p->current = p->current->prev;
394 } else
395 offset--;
396 }
397 }