2
0

bn_ctx.c 13 KB

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