2
0

bn_ctx.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. #if !defined(BN_CTX_DEBUG) && !defined(BN_DEBUG)
  57. #ifndef NDEBUG
  58. #define NDEBUG
  59. #endif
  60. #endif
  61. #define OPENSSL_FIPSAPI
  62. #include <stdio.h>
  63. #include <assert.h>
  64. #include "cryptlib.h"
  65. #include "bn_lcl.h"
  66. /* TODO list
  67. *
  68. * 1. Check a bunch of "(words+1)" type hacks in various bignum functions and
  69. * check they can be safely removed.
  70. * - Check +1 and other ugliness in BN_from_montgomery()
  71. *
  72. * 2. Consider allowing a BN_new_ex() that, at least, lets you specify an
  73. * appropriate 'block' size that will be honoured by bn_expand_internal() to
  74. * prevent piddly little reallocations. OTOH, profiling bignum expansions in
  75. * BN_CTX doesn't show this to be a big issue.
  76. */
  77. /* How many bignums are in each "pool item"; */
  78. #define BN_CTX_POOL_SIZE 16
  79. /* The stack frame info is resizing, set a first-time expansion size; */
  80. #define BN_CTX_START_FRAMES 32
  81. /***********/
  82. /* BN_POOL */
  83. /***********/
  84. /* A bundle of bignums that can be linked with other bundles */
  85. typedef struct bignum_pool_item
  86. {
  87. /* The bignum values */
  88. BIGNUM vals[BN_CTX_POOL_SIZE];
  89. /* Linked-list admin */
  90. struct bignum_pool_item *prev, *next;
  91. } BN_POOL_ITEM;
  92. /* A linked-list of bignums grouped in bundles */
  93. typedef struct bignum_pool
  94. {
  95. /* Linked-list admin */
  96. BN_POOL_ITEM *head, *current, *tail;
  97. /* Stack depth and allocation size */
  98. unsigned used, size;
  99. } BN_POOL;
  100. static void BN_POOL_init(BN_POOL *);
  101. static void BN_POOL_finish(BN_POOL *);
  102. #ifndef OPENSSL_NO_DEPRECATED
  103. static void BN_POOL_reset(BN_POOL *);
  104. #endif
  105. static BIGNUM * BN_POOL_get(BN_POOL *);
  106. static void BN_POOL_release(BN_POOL *, unsigned int);
  107. /************/
  108. /* BN_STACK */
  109. /************/
  110. /* A wrapper to manage the "stack frames" */
  111. typedef struct bignum_ctx_stack
  112. {
  113. /* Array of indexes into the bignum stack */
  114. unsigned int *indexes;
  115. /* Number of stack frames, and the size of the allocated array */
  116. unsigned int depth, size;
  117. } BN_STACK;
  118. static void BN_STACK_init(BN_STACK *);
  119. static void BN_STACK_finish(BN_STACK *);
  120. #ifndef OPENSSL_NO_DEPRECATED
  121. static void BN_STACK_reset(BN_STACK *);
  122. #endif
  123. static int BN_STACK_push(BN_STACK *, unsigned int);
  124. static unsigned int BN_STACK_pop(BN_STACK *);
  125. /**********/
  126. /* BN_CTX */
  127. /**********/
  128. /* The opaque BN_CTX type */
  129. struct bignum_ctx
  130. {
  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. /* Enable this to find BN_CTX bugs */
  143. #ifdef BN_CTX_DEBUG
  144. static const char *ctxdbg_cur = NULL;
  145. static void ctxdbg(BN_CTX *ctx)
  146. {
  147. unsigned int bnidx = 0, fpidx = 0;
  148. BN_POOL_ITEM *item = ctx->pool.head;
  149. BN_STACK *stack = &ctx->stack;
  150. fprintf(stderr,"(%08x): ", (unsigned int)ctx);
  151. while(bnidx < ctx->used)
  152. {
  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. {
  162. while(bnidx++ < stack->indexes[fpidx])
  163. fprintf(stderr," ");
  164. fprintf(stderr,"^^^ ");
  165. bnidx++;
  166. fpidx++;
  167. }
  168. fprintf(stderr,"\n");
  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. /* This function is an evil legacy and should not be used. This implementation
  186. * is WYSIWYG, though I've done my best. */
  187. #ifndef OPENSSL_NO_DEPRECATED
  188. void BN_CTX_init(BN_CTX *ctx)
  189. {
  190. /* Assume the caller obtained the context via BN_CTX_new() and so is
  191. * trying to reset it for use. Nothing else makes sense, least of all
  192. * binary compatibility from a time when they could declare a static
  193. * variable. */
  194. BN_POOL_reset(&ctx->pool);
  195. BN_STACK_reset(&ctx->stack);
  196. ctx->used = 0;
  197. ctx->err_stack = 0;
  198. ctx->too_many = 0;
  199. }
  200. #endif
  201. BN_CTX *BN_CTX_new(void)
  202. {
  203. BN_CTX *ret = OPENSSL_malloc(sizeof(BN_CTX));
  204. if(!ret)
  205. {
  206. BNerr(BN_F_BN_CTX_NEW,ERR_R_MALLOC_FAILURE);
  207. return NULL;
  208. }
  209. /* Initialise the structure */
  210. BN_POOL_init(&ret->pool);
  211. BN_STACK_init(&ret->stack);
  212. ret->used = 0;
  213. ret->err_stack = 0;
  214. ret->too_many = 0;
  215. return ret;
  216. }
  217. void BN_CTX_free(BN_CTX *ctx)
  218. {
  219. if (ctx == NULL)
  220. return;
  221. #ifdef BN_CTX_DEBUG
  222. {
  223. BN_POOL_ITEM *pool = ctx->pool.head;
  224. fprintf(stderr,"BN_CTX_free, stack-size=%d, pool-bignums=%d\n",
  225. ctx->stack.size, ctx->pool.size);
  226. fprintf(stderr,"dmaxs: ");
  227. while(pool) {
  228. unsigned loop = 0;
  229. while(loop < BN_CTX_POOL_SIZE)
  230. fprintf(stderr,"%02x ", pool->vals[loop++].dmax);
  231. pool = pool->next;
  232. }
  233. fprintf(stderr,"\n");
  234. }
  235. #endif
  236. BN_STACK_finish(&ctx->stack);
  237. BN_POOL_finish(&ctx->pool);
  238. OPENSSL_free(ctx);
  239. }
  240. void BN_CTX_start(BN_CTX *ctx)
  241. {
  242. CTXDBG_ENTRY("BN_CTX_start", ctx);
  243. /* If we're already overflowing ... */
  244. if(ctx->err_stack || ctx->too_many)
  245. ctx->err_stack++;
  246. /* (Try to) get a new frame pointer */
  247. else if(!BN_STACK_push(&ctx->stack, ctx->used))
  248. {
  249. BNerr(BN_F_BN_CTX_START,BN_R_TOO_MANY_TEMPORARY_VARIABLES);
  250. ctx->err_stack++;
  251. }
  252. CTXDBG_EXIT(ctx);
  253. }
  254. void BN_CTX_end(BN_CTX *ctx)
  255. {
  256. CTXDBG_ENTRY("BN_CTX_end", ctx);
  257. if(ctx->err_stack)
  258. ctx->err_stack--;
  259. else
  260. {
  261. unsigned int fp = BN_STACK_pop(&ctx->stack);
  262. /* Does this stack frame have anything to release? */
  263. if(fp < ctx->used)
  264. BN_POOL_release(&ctx->pool, ctx->used - fp);
  265. ctx->used = fp;
  266. /* Unjam "too_many" in case "get" had failed */
  267. ctx->too_many = 0;
  268. }
  269. CTXDBG_EXIT(ctx);
  270. }
  271. BIGNUM *BN_CTX_get(BN_CTX *ctx)
  272. {
  273. BIGNUM *ret;
  274. CTXDBG_ENTRY("BN_CTX_get", ctx);
  275. if(ctx->err_stack || ctx->too_many) return NULL;
  276. if((ret = BN_POOL_get(&ctx->pool)) == NULL)
  277. {
  278. /* Setting too_many prevents repeated "get" attempts from
  279. * cluttering the error stack. */
  280. ctx->too_many = 1;
  281. BNerr(BN_F_BN_CTX_GET,BN_R_TOO_MANY_TEMPORARY_VARIABLES);
  282. return NULL;
  283. }
  284. /* OK, make sure the returned bignum is "zero" */
  285. BN_zero(ret);
  286. ctx->used++;
  287. CTXDBG_RET(ctx, ret);
  288. return ret;
  289. }
  290. /************/
  291. /* BN_STACK */
  292. /************/
  293. static void BN_STACK_init(BN_STACK *st)
  294. {
  295. st->indexes = NULL;
  296. st->depth = st->size = 0;
  297. }
  298. static void BN_STACK_finish(BN_STACK *st)
  299. {
  300. if(st->size) OPENSSL_free(st->indexes);
  301. }
  302. #ifndef OPENSSL_NO_DEPRECATED
  303. static void BN_STACK_reset(BN_STACK *st)
  304. {
  305. st->depth = 0;
  306. }
  307. #endif
  308. static int BN_STACK_push(BN_STACK *st, unsigned int idx)
  309. {
  310. if(st->depth == st->size)
  311. /* Need to expand */
  312. {
  313. unsigned int newsize = (st->size ?
  314. (st->size * 3 / 2) : BN_CTX_START_FRAMES);
  315. unsigned int *newitems = OPENSSL_malloc(newsize *
  316. sizeof(unsigned int));
  317. if(!newitems) return 0;
  318. if(st->depth)
  319. memcpy(newitems, st->indexes, st->depth *
  320. sizeof(unsigned int));
  321. if(st->size) OPENSSL_free(st->indexes);
  322. st->indexes = newitems;
  323. st->size = newsize;
  324. }
  325. st->indexes[(st->depth)++] = idx;
  326. return 1;
  327. }
  328. static unsigned int BN_STACK_pop(BN_STACK *st)
  329. {
  330. return st->indexes[--(st->depth)];
  331. }
  332. /***********/
  333. /* BN_POOL */
  334. /***********/
  335. static void BN_POOL_init(BN_POOL *p)
  336. {
  337. p->head = p->current = p->tail = NULL;
  338. p->used = p->size = 0;
  339. }
  340. static void BN_POOL_finish(BN_POOL *p)
  341. {
  342. while(p->head)
  343. {
  344. unsigned int loop = 0;
  345. BIGNUM *bn = p->head->vals;
  346. while(loop++ < BN_CTX_POOL_SIZE)
  347. {
  348. if(bn->d) BN_clear_free(bn);
  349. bn++;
  350. }
  351. p->current = p->head->next;
  352. OPENSSL_free(p->head);
  353. p->head = p->current;
  354. }
  355. }
  356. #ifndef OPENSSL_NO_DEPRECATED
  357. static void BN_POOL_reset(BN_POOL *p)
  358. {
  359. BN_POOL_ITEM *item = p->head;
  360. while(item)
  361. {
  362. unsigned int loop = 0;
  363. BIGNUM *bn = item->vals;
  364. while(loop++ < BN_CTX_POOL_SIZE)
  365. {
  366. if(bn->d) BN_clear(bn);
  367. bn++;
  368. }
  369. item = item->next;
  370. }
  371. p->current = p->head;
  372. p->used = 0;
  373. }
  374. #endif
  375. static BIGNUM *BN_POOL_get(BN_POOL *p)
  376. {
  377. if(p->used == p->size)
  378. {
  379. BIGNUM *bn;
  380. unsigned int loop = 0;
  381. BN_POOL_ITEM *item = OPENSSL_malloc(sizeof(BN_POOL_ITEM));
  382. if(!item) return NULL;
  383. /* Initialise the structure */
  384. bn = item->vals;
  385. while(loop++ < BN_CTX_POOL_SIZE)
  386. BN_init(bn++);
  387. item->prev = p->tail;
  388. item->next = NULL;
  389. /* Link it in */
  390. if(!p->head)
  391. p->head = p->current = p->tail = item;
  392. else
  393. {
  394. p->tail->next = item;
  395. p->tail = item;
  396. p->current = item;
  397. }
  398. p->size += BN_CTX_POOL_SIZE;
  399. p->used++;
  400. /* Return the first bignum from the new pool */
  401. return item->vals;
  402. }
  403. if(!p->used)
  404. p->current = p->head;
  405. else if((p->used % BN_CTX_POOL_SIZE) == 0)
  406. p->current = p->current->next;
  407. return p->current->vals + ((p->used++) % BN_CTX_POOL_SIZE);
  408. }
  409. static void BN_POOL_release(BN_POOL *p, unsigned int num)
  410. {
  411. unsigned int offset = (p->used - 1) % BN_CTX_POOL_SIZE;
  412. p->used -= num;
  413. while(num--)
  414. {
  415. bn_check_top(p->current->vals + offset);
  416. if(!offset)
  417. {
  418. offset = BN_CTX_POOL_SIZE - 1;
  419. p->current = p->current->prev;
  420. }
  421. else
  422. offset--;
  423. }
  424. }