bn_ctx.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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 <assert.h>
  62. #include "internal/cryptlib.h"
  63. #include "bn_lcl.h"
  64. /*-
  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. /* The bignum values */
  86. BIGNUM vals[BN_CTX_POOL_SIZE];
  87. /* Linked-list admin */
  88. struct bignum_pool_item *prev, *next;
  89. } BN_POOL_ITEM;
  90. /* A linked-list of bignums grouped in bundles */
  91. typedef struct bignum_pool {
  92. /* Linked-list admin */
  93. BN_POOL_ITEM *head, *current, *tail;
  94. /* Stack depth and allocation size */
  95. unsigned used, size;
  96. } BN_POOL;
  97. static void BN_POOL_init(BN_POOL *);
  98. static void BN_POOL_finish(BN_POOL *);
  99. static BIGNUM *BN_POOL_get(BN_POOL *);
  100. static void BN_POOL_release(BN_POOL *, unsigned int);
  101. /************/
  102. /* BN_STACK */
  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. /* BN_CTX */
  117. /**********/
  118. /* The opaque BN_CTX type */
  119. struct bignum_ctx {
  120. /* The bignum bundles */
  121. BN_POOL pool;
  122. /* The "stack frames", if you will */
  123. BN_STACK stack;
  124. /* The number of bignums currently assigned */
  125. unsigned int used;
  126. /* Depth of stack overflow */
  127. int err_stack;
  128. /* Block "gets" until an "end" (compatibility behaviour) */
  129. int too_many;
  130. };
  131. /* Enable this to find BN_CTX bugs */
  132. #ifdef BN_CTX_DEBUG
  133. static const char *ctxdbg_cur = NULL;
  134. static void ctxdbg(BN_CTX *ctx)
  135. {
  136. unsigned int bnidx = 0, fpidx = 0;
  137. BN_POOL_ITEM *item = ctx->pool.head;
  138. BN_STACK *stack = &ctx->stack;
  139. fprintf(stderr, "(%16p): ", ctx);
  140. while (bnidx < ctx->used) {
  141. fprintf(stderr, "%03x ", item->vals[bnidx++ % BN_CTX_POOL_SIZE].dmax);
  142. if (!(bnidx % BN_CTX_POOL_SIZE))
  143. item = item->next;
  144. }
  145. fprintf(stderr, "\n");
  146. bnidx = 0;
  147. fprintf(stderr, " : ");
  148. while (fpidx < stack->depth) {
  149. while (bnidx++ < stack->indexes[fpidx])
  150. fprintf(stderr, " ");
  151. fprintf(stderr, "^^^ ");
  152. bnidx++;
  153. fpidx++;
  154. }
  155. fprintf(stderr, "\n");
  156. }
  157. # define CTXDBG_ENTRY(str, ctx) do { \
  158. ctxdbg_cur = (str); \
  159. fprintf(stderr,"Starting %s\n", ctxdbg_cur); \
  160. ctxdbg(ctx); \
  161. } while(0)
  162. # define CTXDBG_EXIT(ctx) do { \
  163. fprintf(stderr,"Ending %s\n", ctxdbg_cur); \
  164. ctxdbg(ctx); \
  165. } while(0)
  166. # define CTXDBG_RET(ctx,ret)
  167. #else
  168. # define CTXDBG_ENTRY(str, ctx)
  169. # define CTXDBG_EXIT(ctx)
  170. # define CTXDBG_RET(ctx,ret)
  171. #endif
  172. BN_CTX *BN_CTX_new(void)
  173. {
  174. BN_CTX *ret = OPENSSL_malloc(sizeof(*ret));
  175. if (!ret) {
  176. BNerr(BN_F_BN_CTX_NEW, ERR_R_MALLOC_FAILURE);
  177. return NULL;
  178. }
  179. /* Initialise the structure */
  180. BN_POOL_init(&ret->pool);
  181. BN_STACK_init(&ret->stack);
  182. ret->used = 0;
  183. ret->err_stack = 0;
  184. ret->too_many = 0;
  185. return ret;
  186. }
  187. void BN_CTX_free(BN_CTX *ctx)
  188. {
  189. if (ctx == NULL)
  190. return;
  191. #ifdef BN_CTX_DEBUG
  192. {
  193. BN_POOL_ITEM *pool = ctx->pool.head;
  194. fprintf(stderr, "BN_CTX_free, stack-size=%d, pool-bignums=%d\n",
  195. ctx->stack.size, ctx->pool.size);
  196. fprintf(stderr, "dmaxs: ");
  197. while (pool) {
  198. unsigned loop = 0;
  199. while (loop < BN_CTX_POOL_SIZE)
  200. fprintf(stderr, "%02x ", pool->vals[loop++].dmax);
  201. pool = pool->next;
  202. }
  203. fprintf(stderr, "\n");
  204. }
  205. #endif
  206. BN_STACK_finish(&ctx->stack);
  207. BN_POOL_finish(&ctx->pool);
  208. OPENSSL_free(ctx);
  209. }
  210. void BN_CTX_start(BN_CTX *ctx)
  211. {
  212. CTXDBG_ENTRY("BN_CTX_start", ctx);
  213. /* If we're already overflowing ... */
  214. if (ctx->err_stack || ctx->too_many)
  215. ctx->err_stack++;
  216. /* (Try to) get a new frame pointer */
  217. else if (!BN_STACK_push(&ctx->stack, ctx->used)) {
  218. BNerr(BN_F_BN_CTX_START, BN_R_TOO_MANY_TEMPORARY_VARIABLES);
  219. ctx->err_stack++;
  220. }
  221. CTXDBG_EXIT(ctx);
  222. }
  223. void BN_CTX_end(BN_CTX *ctx)
  224. {
  225. CTXDBG_ENTRY("BN_CTX_end", ctx);
  226. if (ctx->err_stack)
  227. ctx->err_stack--;
  228. else {
  229. unsigned int fp = BN_STACK_pop(&ctx->stack);
  230. /* Does this stack frame have anything to release? */
  231. if (fp < ctx->used)
  232. BN_POOL_release(&ctx->pool, ctx->used - fp);
  233. ctx->used = fp;
  234. /* Unjam "too_many" in case "get" had failed */
  235. ctx->too_many = 0;
  236. }
  237. CTXDBG_EXIT(ctx);
  238. }
  239. BIGNUM *BN_CTX_get(BN_CTX *ctx)
  240. {
  241. BIGNUM *ret;
  242. CTXDBG_ENTRY("BN_CTX_get", ctx);
  243. if (ctx->err_stack || ctx->too_many)
  244. return NULL;
  245. if ((ret = BN_POOL_get(&ctx->pool)) == NULL) {
  246. /*
  247. * Setting too_many prevents repeated "get" attempts from cluttering
  248. * the error stack.
  249. */
  250. ctx->too_many = 1;
  251. BNerr(BN_F_BN_CTX_GET, BN_R_TOO_MANY_TEMPORARY_VARIABLES);
  252. return NULL;
  253. }
  254. /* OK, make sure the returned bignum is "zero" */
  255. BN_zero(ret);
  256. ctx->used++;
  257. CTXDBG_RET(ctx, ret);
  258. return ret;
  259. }
  260. /************/
  261. /* BN_STACK */
  262. /************/
  263. static void BN_STACK_init(BN_STACK *st)
  264. {
  265. st->indexes = NULL;
  266. st->depth = st->size = 0;
  267. }
  268. static void BN_STACK_finish(BN_STACK *st)
  269. {
  270. if (st->size)
  271. OPENSSL_free(st->indexes);
  272. }
  273. static int BN_STACK_push(BN_STACK *st, unsigned int idx)
  274. {
  275. if (st->depth == st->size)
  276. /* Need to expand */
  277. {
  278. unsigned int newsize = (st->size ?
  279. (st->size * 3 / 2) : BN_CTX_START_FRAMES);
  280. unsigned int *newitems = OPENSSL_malloc(newsize *
  281. sizeof(unsigned int));
  282. if (!newitems)
  283. return 0;
  284. if (st->depth)
  285. memcpy(newitems, st->indexes, st->depth * sizeof(unsigned int));
  286. if (st->size)
  287. OPENSSL_free(st->indexes);
  288. st->indexes = newitems;
  289. st->size = newsize;
  290. }
  291. st->indexes[(st->depth)++] = idx;
  292. return 1;
  293. }
  294. static unsigned int BN_STACK_pop(BN_STACK *st)
  295. {
  296. return st->indexes[--(st->depth)];
  297. }
  298. /***********/
  299. /* BN_POOL */
  300. /***********/
  301. static void BN_POOL_init(BN_POOL *p)
  302. {
  303. p->head = p->current = p->tail = NULL;
  304. p->used = p->size = 0;
  305. }
  306. static void BN_POOL_finish(BN_POOL *p)
  307. {
  308. while (p->head) {
  309. unsigned int loop = 0;
  310. BIGNUM *bn = p->head->vals;
  311. while (loop++ < BN_CTX_POOL_SIZE) {
  312. if (bn->d)
  313. BN_clear_free(bn);
  314. bn++;
  315. }
  316. p->current = p->head->next;
  317. OPENSSL_free(p->head);
  318. p->head = p->current;
  319. }
  320. }
  321. static BIGNUM *BN_POOL_get(BN_POOL *p)
  322. {
  323. if (p->used == p->size) {
  324. BIGNUM *bn;
  325. unsigned int loop = 0;
  326. BN_POOL_ITEM *item = OPENSSL_malloc(sizeof(*item));
  327. if (!item)
  328. return NULL;
  329. /* Initialise the structure */
  330. bn = item->vals;
  331. while (loop++ < BN_CTX_POOL_SIZE)
  332. BN_init(bn++);
  333. item->prev = p->tail;
  334. item->next = NULL;
  335. /* Link it in */
  336. if (!p->head)
  337. p->head = p->current = p->tail = item;
  338. else {
  339. p->tail->next = item;
  340. p->tail = item;
  341. p->current = item;
  342. }
  343. p->size += BN_CTX_POOL_SIZE;
  344. p->used++;
  345. /* Return the first bignum from the new pool */
  346. return item->vals;
  347. }
  348. if (!p->used)
  349. p->current = p->head;
  350. else if ((p->used % BN_CTX_POOL_SIZE) == 0)
  351. p->current = p->current->next;
  352. return p->current->vals + ((p->used++) % BN_CTX_POOL_SIZE);
  353. }
  354. static void BN_POOL_release(BN_POOL *p, unsigned int num)
  355. {
  356. unsigned int offset = (p->used - 1) % BN_CTX_POOL_SIZE;
  357. p->used -= num;
  358. while (num--) {
  359. bn_check_top(p->current->vals + offset);
  360. if (!offset) {
  361. offset = BN_CTX_POOL_SIZE - 1;
  362. p->current = p->current->prev;
  363. } else
  364. offset--;
  365. }
  366. }