]> git.ipfire.org Git - thirdparty/openssl.git/blob - crypto/bn/bn_ctx.c
Remove outdated DEBUG flags.
[thirdparty/openssl.git] / crypto / bn / bn_ctx.c
1 /* Written by Ulf Moeller for the OpenSSL project. */
2 /* ====================================================================
3 * Copyright (c) 1998-2004 The OpenSSL Project. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 *
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
15 * distribution.
16 *
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/)"
21 *
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.
26 *
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.
30 *
31 * 6. Redistributions of any form whatsoever must retain the following
32 * acknowledgment:
33 * "This product includes software developed by the OpenSSL Project
34 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
35 *
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 * ====================================================================
49 *
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).
53 *
54 */
55
56 #include "internal/cryptlib.h"
57 #include "bn_lcl.h"
58
59 /*-
60 * TODO list
61 *
62 * 1. Check a bunch of "(words+1)" type hacks in various bignum functions and
63 * check they can be safely removed.
64 * - Check +1 and other ugliness in BN_from_montgomery()
65 *
66 * 2. Consider allowing a BN_new_ex() that, at least, lets you specify an
67 * appropriate 'block' size that will be honoured by bn_expand_internal() to
68 * prevent piddly little reallocations. OTOH, profiling bignum expansions in
69 * BN_CTX doesn't show this to be a big issue.
70 */
71
72 /* How many bignums are in each "pool item"; */
73 #define BN_CTX_POOL_SIZE 16
74 /* The stack frame info is resizing, set a first-time expansion size; */
75 #define BN_CTX_START_FRAMES 32
76
77 /***********/
78 /* BN_POOL */
79 /***********/
80
81 /* A bundle of bignums that can be linked with other bundles */
82 typedef struct bignum_pool_item {
83 /* The bignum values */
84 BIGNUM vals[BN_CTX_POOL_SIZE];
85 /* Linked-list admin */
86 struct bignum_pool_item *prev, *next;
87 } BN_POOL_ITEM;
88 /* A linked-list of bignums grouped in bundles */
89 typedef struct bignum_pool {
90 /* Linked-list admin */
91 BN_POOL_ITEM *head, *current, *tail;
92 /* Stack depth and allocation size */
93 unsigned used, size;
94 } BN_POOL;
95 static void BN_POOL_init(BN_POOL *);
96 static void BN_POOL_finish(BN_POOL *);
97 static BIGNUM *BN_POOL_get(BN_POOL *, int);
98 static void BN_POOL_release(BN_POOL *, unsigned int);
99
100 /************/
101 /* BN_STACK */
102 /************/
103
104 /* A wrapper to manage the "stack frames" */
105 typedef struct bignum_ctx_stack {
106 /* Array of indexes into the bignum stack */
107 unsigned int *indexes;
108 /* Number of stack frames, and the size of the allocated array */
109 unsigned int depth, size;
110 } BN_STACK;
111 static void BN_STACK_init(BN_STACK *);
112 static void BN_STACK_finish(BN_STACK *);
113 static int BN_STACK_push(BN_STACK *, unsigned int);
114 static unsigned int BN_STACK_pop(BN_STACK *);
115
116 /**********/
117 /* BN_CTX */
118 /**********/
119
120 /* The opaque BN_CTX type */
121 struct bignum_ctx {
122 /* The bignum bundles */
123 BN_POOL pool;
124 /* The "stack frames", if you will */
125 BN_STACK stack;
126 /* The number of bignums currently assigned */
127 unsigned int used;
128 /* Depth of stack overflow */
129 int err_stack;
130 /* Block "gets" until an "end" (compatibility behaviour) */
131 int too_many;
132 /* Flags. */
133 int flags;
134 };
135
136 /* Enable this to find BN_CTX bugs */
137 #ifdef BN_CTX_DEBUG
138 static const char *ctxdbg_cur = NULL;
139 static void ctxdbg(BN_CTX *ctx)
140 {
141 unsigned int bnidx = 0, fpidx = 0;
142 BN_POOL_ITEM *item = ctx->pool.head;
143 BN_STACK *stack = &ctx->stack;
144 fprintf(stderr, "(%16p): ", ctx);
145 while (bnidx < ctx->used) {
146 fprintf(stderr, "%03x ", item->vals[bnidx++ % BN_CTX_POOL_SIZE].dmax);
147 if (!(bnidx % BN_CTX_POOL_SIZE))
148 item = item->next;
149 }
150 fprintf(stderr, "\n");
151 bnidx = 0;
152 fprintf(stderr, " : ");
153 while (fpidx < stack->depth) {
154 while (bnidx++ < stack->indexes[fpidx])
155 fprintf(stderr, " ");
156 fprintf(stderr, "^^^ ");
157 bnidx++;
158 fpidx++;
159 }
160 fprintf(stderr, "\n");
161 }
162
163 # define CTXDBG_ENTRY(str, ctx) do { \
164 ctxdbg_cur = (str); \
165 fprintf(stderr,"Starting %s\n", ctxdbg_cur); \
166 ctxdbg(ctx); \
167 } while(0)
168 # define CTXDBG_EXIT(ctx) do { \
169 fprintf(stderr,"Ending %s\n", ctxdbg_cur); \
170 ctxdbg(ctx); \
171 } while(0)
172 # define CTXDBG_RET(ctx,ret)
173 #else
174 # define CTXDBG_ENTRY(str, ctx)
175 # define CTXDBG_EXIT(ctx)
176 # define CTXDBG_RET(ctx,ret)
177 #endif
178
179
180 BN_CTX *BN_CTX_new(void)
181 {
182 BN_CTX *ret;
183
184 if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) {
185 BNerr(BN_F_BN_CTX_NEW, ERR_R_MALLOC_FAILURE);
186 return NULL;
187 }
188 /* Initialise the structure */
189 BN_POOL_init(&ret->pool);
190 BN_STACK_init(&ret->stack);
191 return ret;
192 }
193
194 BN_CTX *BN_CTX_secure_new(void)
195 {
196 BN_CTX *ret = BN_CTX_new();
197
198 if (ret != NULL)
199 ret->flags = BN_FLG_SECURE;
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
262 CTXDBG_ENTRY("BN_CTX_get", ctx);
263 if (ctx->err_stack || ctx->too_many)
264 return NULL;
265 if ((ret = BN_POOL_get(&ctx->pool, ctx->flags)) == NULL) {
266 /*
267 * Setting too_many prevents repeated "get" attempts from cluttering
268 * the error stack.
269 */
270 ctx->too_many = 1;
271 BNerr(BN_F_BN_CTX_GET, BN_R_TOO_MANY_TEMPORARY_VARIABLES);
272 return NULL;
273 }
274 /* OK, make sure the returned bignum is "zero" */
275 BN_zero(ret);
276 ctx->used++;
277 CTXDBG_RET(ctx, ret);
278 return ret;
279 }
280
281 /************/
282 /* BN_STACK */
283 /************/
284
285 static void BN_STACK_init(BN_STACK *st)
286 {
287 st->indexes = NULL;
288 st->depth = st->size = 0;
289 }
290
291 static void BN_STACK_finish(BN_STACK *st)
292 {
293 OPENSSL_free(st->indexes);
294 st->indexes = NULL;
295 }
296
297
298 static int BN_STACK_push(BN_STACK *st, unsigned int idx)
299 {
300 if (st->depth == st->size) {
301 /* Need to expand */
302 unsigned int newsize =
303 st->size ? (st->size * 3 / 2) : BN_CTX_START_FRAMES;
304 unsigned int *newitems = OPENSSL_malloc(sizeof(*newitems) * newsize);
305 if (newitems == NULL)
306 return 0;
307 if (st->depth)
308 memcpy(newitems, st->indexes, sizeof(*newitems) * st->depth);
309 OPENSSL_free(st->indexes);
310 st->indexes = newitems;
311 st->size = newsize;
312 }
313 st->indexes[(st->depth)++] = idx;
314 return 1;
315 }
316
317 static unsigned int BN_STACK_pop(BN_STACK *st)
318 {
319 return st->indexes[--(st->depth)];
320 }
321
322 /***********/
323 /* BN_POOL */
324 /***********/
325
326 static void BN_POOL_init(BN_POOL *p)
327 {
328 p->head = p->current = p->tail = NULL;
329 p->used = p->size = 0;
330 }
331
332 static void BN_POOL_finish(BN_POOL *p)
333 {
334 unsigned int loop;
335 BIGNUM *bn;
336
337 while (p->head) {
338 for (loop = 0, bn = p->head->vals; loop++ < BN_CTX_POOL_SIZE; bn++)
339 if (bn->d)
340 BN_clear_free(bn);
341 p->current = p->head->next;
342 OPENSSL_free(p->head);
343 p->head = p->current;
344 }
345 }
346
347
348 static BIGNUM *BN_POOL_get(BN_POOL *p, int flag)
349 {
350 BIGNUM *bn;
351 unsigned int loop;
352
353 /* Full; allocate a new pool item and link it in. */
354 if (p->used == p->size) {
355 BN_POOL_ITEM *item = OPENSSL_malloc(sizeof(*item));
356 if (item == NULL)
357 return NULL;
358 for (loop = 0, bn = item->vals; loop++ < BN_CTX_POOL_SIZE; bn++) {
359 bn_init(bn);
360 if ((flag & BN_FLG_SECURE) != 0)
361 BN_set_flags(bn, BN_FLG_SECURE);
362 }
363 item->prev = p->tail;
364 item->next = NULL;
365
366 if (p->head == NULL)
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
379 if (!p->used)
380 p->current = p->head;
381 else if ((p->used % BN_CTX_POOL_SIZE) == 0)
382 p->current = p->current->next;
383 return p->current->vals + ((p->used++) % BN_CTX_POOL_SIZE);
384 }
385
386 static void BN_POOL_release(BN_POOL *p, unsigned int num)
387 {
388 unsigned int offset = (p->used - 1) % BN_CTX_POOL_SIZE;
389
390 p->used -= num;
391 while (num--) {
392 bn_check_top(p->current->vals + offset);
393 if (offset == 0) {
394 offset = BN_CTX_POOL_SIZE - 1;
395 p->current = p->current->prev;
396 } else
397 offset--;
398 }
399 }