bn_ctx.c 12 KB

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