You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

604 lines
15 KiB

  1. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  2. * All rights reserved.
  3. *
  4. * This package is an SSL implementation written
  5. * by Eric Young (eay@cryptsoft.com).
  6. * The implementation was written so as to conform with Netscapes SSL.
  7. *
  8. * This library is free for commercial and non-commercial use as long as
  9. * the following conditions are aheared to. The following conditions
  10. * apply to all code found in this distribution, be it the RC4, RSA,
  11. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  12. * included with this distribution is covered by the same copyright terms
  13. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  14. *
  15. * Copyright remains Eric Young's, and as such any Copyright notices in
  16. * the code are not to be removed.
  17. * If this package is used in a product, Eric Young should be given attribution
  18. * as the author of the parts of the library used.
  19. * This can be in the form of a textual message at program startup or
  20. * in documentation (online or textual) provided with the package.
  21. *
  22. * Redistribution and use in source and binary forms, with or without
  23. * modification, are permitted provided that the following conditions
  24. * are met:
  25. * 1. Redistributions of source code must retain the copyright
  26. * notice, this list of conditions and the following disclaimer.
  27. * 2. Redistributions in binary form must reproduce the above copyright
  28. * notice, this list of conditions and the following disclaimer in the
  29. * documentation and/or other materials provided with the distribution.
  30. * 3. All advertising materials mentioning features or use of this software
  31. * must display the following acknowledgement:
  32. * "This product includes cryptographic software written by
  33. * Eric Young (eay@cryptsoft.com)"
  34. * The word 'cryptographic' can be left out if the rouines from the library
  35. * being used are not cryptographic related :-).
  36. * 4. If you include any Windows specific code (or a derivative thereof) from
  37. * the apps directory (application code) you must include an acknowledgement:
  38. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  39. *
  40. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  41. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  42. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  43. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  44. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  45. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  46. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  47. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  48. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  49. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  50. * SUCH DAMAGE.
  51. *
  52. * The licence and distribution terms for any publically available version or
  53. * derivative of this code cannot be changed. i.e. this code cannot simply be
  54. * copied and put under another distribution licence
  55. * [including the GNU Public Licence.] */
  56. #include <openssl/bn.h>
  57. #include <assert.h>
  58. #include <ctype.h>
  59. #include <limits.h>
  60. #include <stdio.h>
  61. #include <string.h>
  62. #include <openssl/bio.h>
  63. #include <openssl/bytestring.h>
  64. #include <openssl/err.h>
  65. #include <openssl/mem.h>
  66. #include "internal.h"
  67. BIGNUM *BN_bin2bn(const uint8_t *in, size_t len, BIGNUM *ret) {
  68. size_t num_words;
  69. unsigned m;
  70. BN_ULONG word = 0;
  71. BIGNUM *bn = NULL;
  72. if (ret == NULL) {
  73. ret = bn = BN_new();
  74. }
  75. if (ret == NULL) {
  76. return NULL;
  77. }
  78. if (len == 0) {
  79. ret->top = 0;
  80. return ret;
  81. }
  82. num_words = ((len - 1) / BN_BYTES) + 1;
  83. m = (len - 1) % BN_BYTES;
  84. if (bn_wexpand(ret, num_words) == NULL) {
  85. if (bn) {
  86. BN_free(bn);
  87. }
  88. return NULL;
  89. }
  90. /* |bn_wexpand| must check bounds on |num_words| to write it into
  91. * |ret->dmax|. */
  92. assert(num_words <= INT_MAX);
  93. ret->top = (int)num_words;
  94. ret->neg = 0;
  95. while (len--) {
  96. word = (word << 8) | *(in++);
  97. if (m-- == 0) {
  98. ret->d[--num_words] = word;
  99. word = 0;
  100. m = BN_BYTES - 1;
  101. }
  102. }
  103. /* need to call this due to clear byte at top if avoiding having the top bit
  104. * set (-ve number) */
  105. bn_correct_top(ret);
  106. return ret;
  107. }
  108. size_t BN_bn2bin(const BIGNUM *in, uint8_t *out) {
  109. size_t n, i;
  110. BN_ULONG l;
  111. n = i = BN_num_bytes(in);
  112. while (i--) {
  113. l = in->d[i / BN_BYTES];
  114. *(out++) = (unsigned char)(l >> (8 * (i % BN_BYTES))) & 0xff;
  115. }
  116. return n;
  117. }
  118. /* constant_time_select_ulong returns |x| if |v| is 1 and |y| if |v| is 0. Its
  119. * behavior is undefined if |v| takes any other value. */
  120. static BN_ULONG constant_time_select_ulong(int v, BN_ULONG x, BN_ULONG y) {
  121. BN_ULONG mask = v;
  122. mask--;
  123. return (~mask & x) | (mask & y);
  124. }
  125. /* constant_time_le_size_t returns 1 if |x| <= |y| and 0 otherwise. |x| and |y|
  126. * must not have their MSBs set. */
  127. static int constant_time_le_size_t(size_t x, size_t y) {
  128. return ((x - y - 1) >> (sizeof(size_t) * 8 - 1)) & 1;
  129. }
  130. /* read_word_padded returns the |i|'th word of |in|, if it is not out of
  131. * bounds. Otherwise, it returns 0. It does so without branches on the size of
  132. * |in|, however it necessarily does not have the same memory access pattern. If
  133. * the access would be out of bounds, it reads the last word of |in|. |in| must
  134. * not be zero. */
  135. static BN_ULONG read_word_padded(const BIGNUM *in, size_t i) {
  136. /* Read |in->d[i]| if valid. Otherwise, read the last word. */
  137. BN_ULONG l = in->d[constant_time_select_ulong(
  138. constant_time_le_size_t(in->dmax, i), in->dmax - 1, i)];
  139. /* Clamp to zero if above |d->top|. */
  140. return constant_time_select_ulong(constant_time_le_size_t(in->top, i), 0, l);
  141. }
  142. int BN_bn2bin_padded(uint8_t *out, size_t len, const BIGNUM *in) {
  143. size_t i;
  144. BN_ULONG l;
  145. /* Special case for |in| = 0. Just branch as the probability is negligible. */
  146. if (BN_is_zero(in)) {
  147. memset(out, 0, len);
  148. return 1;
  149. }
  150. /* Check if the integer is too big. This case can exit early in non-constant
  151. * time. */
  152. if ((size_t)in->top > (len + (BN_BYTES - 1)) / BN_BYTES) {
  153. return 0;
  154. }
  155. if ((len % BN_BYTES) != 0) {
  156. l = read_word_padded(in, len / BN_BYTES);
  157. if (l >> (8 * (len % BN_BYTES)) != 0) {
  158. return 0;
  159. }
  160. }
  161. /* Write the bytes out one by one. Serialization is done without branching on
  162. * the bits of |in| or on |in->top|, but if the routine would otherwise read
  163. * out of bounds, the memory access pattern can't be fixed. However, for an
  164. * RSA key of size a multiple of the word size, the probability of BN_BYTES
  165. * leading zero octets is low.
  166. *
  167. * See Falko Stenzke, "Manger's Attack revisited", ICICS 2010. */
  168. i = len;
  169. while (i--) {
  170. l = read_word_padded(in, i / BN_BYTES);
  171. *(out++) = (uint8_t)(l >> (8 * (i % BN_BYTES))) & 0xff;
  172. }
  173. return 1;
  174. }
  175. int BN_bn2cbb_padded(CBB *out, size_t len, const BIGNUM *in) {
  176. uint8_t *ptr;
  177. return CBB_add_space(out, &ptr, len) && BN_bn2bin_padded(ptr, len, in);
  178. }
  179. static const char hextable[] = "0123456789abcdef";
  180. char *BN_bn2hex(const BIGNUM *bn) {
  181. int i, j, v, z = 0;
  182. char *buf;
  183. char *p;
  184. buf = (char *)OPENSSL_malloc(bn->top * BN_BYTES * 2 + 2);
  185. if (buf == NULL) {
  186. OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE);
  187. return NULL;
  188. }
  189. p = buf;
  190. if (bn->neg) {
  191. *(p++) = '-';
  192. }
  193. if (BN_is_zero(bn)) {
  194. *(p++) = '0';
  195. }
  196. for (i = bn->top - 1; i >= 0; i--) {
  197. for (j = BN_BITS2 - 8; j >= 0; j -= 8) {
  198. /* strip leading zeros */
  199. v = ((int)(bn->d[i] >> (long)j)) & 0xff;
  200. if (z || v != 0) {
  201. *(p++) = hextable[v >> 4];
  202. *(p++) = hextable[v & 0x0f];
  203. z = 1;
  204. }
  205. }
  206. }
  207. *p = '\0';
  208. return buf;
  209. }
  210. /* decode_hex decodes |in_len| bytes of hex data from |in| and updates |bn|. */
  211. static int decode_hex(BIGNUM *bn, const char *in, int in_len) {
  212. if (in_len > INT_MAX/4) {
  213. OPENSSL_PUT_ERROR(BN, BN_R_BIGNUM_TOO_LONG);
  214. return 0;
  215. }
  216. /* |in_len| is the number of hex digits. */
  217. if (bn_expand(bn, in_len * 4) == NULL) {
  218. return 0;
  219. }
  220. int i = 0;
  221. while (in_len > 0) {
  222. /* Decode one |BN_ULONG| at a time. */
  223. int todo = BN_BYTES * 2;
  224. if (todo > in_len) {
  225. todo = in_len;
  226. }
  227. BN_ULONG word = 0;
  228. int j;
  229. for (j = todo; j > 0; j--) {
  230. char c = in[in_len - j];
  231. BN_ULONG hex;
  232. if (c >= '0' && c <= '9') {
  233. hex = c - '0';
  234. } else if (c >= 'a' && c <= 'f') {
  235. hex = c - 'a' + 10;
  236. } else if (c >= 'A' && c <= 'F') {
  237. hex = c - 'A' + 10;
  238. } else {
  239. hex = 0;
  240. /* This shouldn't happen. The caller checks |isxdigit|. */
  241. assert(0);
  242. }
  243. word = (word << 4) | hex;
  244. }
  245. bn->d[i++] = word;
  246. in_len -= todo;
  247. }
  248. assert(i <= bn->dmax);
  249. bn->top = i;
  250. return 1;
  251. }
  252. /* decode_dec decodes |in_len| bytes of decimal data from |in| and updates |bn|. */
  253. static int decode_dec(BIGNUM *bn, const char *in, int in_len) {
  254. int i, j;
  255. BN_ULONG l = 0;
  256. /* Decode |BN_DEC_NUM| digits at a time. */
  257. j = BN_DEC_NUM - (in_len % BN_DEC_NUM);
  258. if (j == BN_DEC_NUM) {
  259. j = 0;
  260. }
  261. l = 0;
  262. for (i = 0; i < in_len; i++) {
  263. l *= 10;
  264. l += in[i] - '0';
  265. if (++j == BN_DEC_NUM) {
  266. if (!BN_mul_word(bn, BN_DEC_CONV) ||
  267. !BN_add_word(bn, l)) {
  268. return 0;
  269. }
  270. l = 0;
  271. j = 0;
  272. }
  273. }
  274. return 1;
  275. }
  276. typedef int (*decode_func) (BIGNUM *bn, const char *in, int in_len);
  277. typedef int (*char_test_func) (int c);
  278. static int bn_x2bn(BIGNUM **outp, const char *in, decode_func decode, char_test_func want_char) {
  279. BIGNUM *ret = NULL;
  280. int neg = 0, i;
  281. int num;
  282. if (in == NULL || *in == 0) {
  283. return 0;
  284. }
  285. if (*in == '-') {
  286. neg = 1;
  287. in++;
  288. }
  289. for (i = 0; want_char((unsigned char)in[i]) && i + neg < INT_MAX; i++) {}
  290. num = i + neg;
  291. if (outp == NULL) {
  292. return num;
  293. }
  294. /* in is the start of the hex digits, and it is 'i' long */
  295. if (*outp == NULL) {
  296. ret = BN_new();
  297. if (ret == NULL) {
  298. return 0;
  299. }
  300. } else {
  301. ret = *outp;
  302. BN_zero(ret);
  303. }
  304. if (!decode(ret, in, i)) {
  305. goto err;
  306. }
  307. bn_correct_top(ret);
  308. if (!BN_is_zero(ret)) {
  309. ret->neg = neg;
  310. }
  311. *outp = ret;
  312. return num;
  313. err:
  314. if (*outp == NULL) {
  315. BN_free(ret);
  316. }
  317. return 0;
  318. }
  319. int BN_hex2bn(BIGNUM **outp, const char *in) {
  320. return bn_x2bn(outp, in, decode_hex, isxdigit);
  321. }
  322. char *BN_bn2dec(const BIGNUM *a) {
  323. int i = 0, num, ok = 0;
  324. char *buf = NULL;
  325. char *p;
  326. BIGNUM *t = NULL;
  327. BN_ULONG *bn_data = NULL, *lp;
  328. /* get an upper bound for the length of the decimal integer
  329. * num <= (BN_num_bits(a) + 1) * log(2)
  330. * <= 3 * BN_num_bits(a) * 0.1001 + log(2) + 1 (rounding error)
  331. * <= BN_num_bits(a)/10 + BN_num_bits/1000 + 1 + 1
  332. */
  333. i = BN_num_bits(a) * 3;
  334. num = i / 10 + i / 1000 + 1 + 1;
  335. bn_data =
  336. (BN_ULONG *)OPENSSL_malloc((num / BN_DEC_NUM + 1) * sizeof(BN_ULONG));
  337. buf = (char *)OPENSSL_malloc(num + 3);
  338. if ((buf == NULL) || (bn_data == NULL)) {
  339. OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE);
  340. goto err;
  341. }
  342. t = BN_dup(a);
  343. if (t == NULL) {
  344. goto err;
  345. }
  346. #define BUF_REMAIN (num + 3 - (size_t)(p - buf))
  347. p = buf;
  348. lp = bn_data;
  349. if (BN_is_zero(t)) {
  350. *(p++) = '0';
  351. *(p++) = '\0';
  352. } else {
  353. if (BN_is_negative(t)) {
  354. *p++ = '-';
  355. }
  356. while (!BN_is_zero(t)) {
  357. *lp = BN_div_word(t, BN_DEC_CONV);
  358. lp++;
  359. }
  360. lp--;
  361. /* We now have a series of blocks, BN_DEC_NUM chars
  362. * in length, where the last one needs truncation.
  363. * The blocks need to be reversed in order. */
  364. BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT1, *lp);
  365. while (*p) {
  366. p++;
  367. }
  368. while (lp != bn_data) {
  369. lp--;
  370. BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT2, *lp);
  371. while (*p) {
  372. p++;
  373. }
  374. }
  375. }
  376. ok = 1;
  377. err:
  378. OPENSSL_free(bn_data);
  379. BN_free(t);
  380. if (!ok) {
  381. OPENSSL_free(buf);
  382. buf = NULL;
  383. }
  384. return buf;
  385. }
  386. int BN_dec2bn(BIGNUM **outp, const char *in) {
  387. return bn_x2bn(outp, in, decode_dec, isdigit);
  388. }
  389. int BN_asc2bn(BIGNUM **outp, const char *in) {
  390. const char *const orig_in = in;
  391. if (*in == '-') {
  392. in++;
  393. }
  394. if (in[0] == '0' && (in[1] == 'X' || in[1] == 'x')) {
  395. if (!BN_hex2bn(outp, in+2)) {
  396. return 0;
  397. }
  398. } else {
  399. if (!BN_dec2bn(outp, in)) {
  400. return 0;
  401. }
  402. }
  403. if (*orig_in == '-' && !BN_is_zero(*outp)) {
  404. (*outp)->neg = 1;
  405. }
  406. return 1;
  407. }
  408. int BN_print(BIO *bp, const BIGNUM *a) {
  409. int i, j, v, z = 0;
  410. int ret = 0;
  411. if (a->neg && BIO_write(bp, "-", 1) != 1) {
  412. goto end;
  413. }
  414. if (BN_is_zero(a) && BIO_write(bp, "0", 1) != 1) {
  415. goto end;
  416. }
  417. for (i = a->top - 1; i >= 0; i--) {
  418. for (j = BN_BITS2 - 4; j >= 0; j -= 4) {
  419. /* strip leading zeros */
  420. v = ((int)(a->d[i] >> (long)j)) & 0x0f;
  421. if (z || v != 0) {
  422. if (BIO_write(bp, &hextable[v], 1) != 1) {
  423. goto end;
  424. }
  425. z = 1;
  426. }
  427. }
  428. }
  429. ret = 1;
  430. end:
  431. return ret;
  432. }
  433. int BN_print_fp(FILE *fp, const BIGNUM *a) {
  434. BIO *b;
  435. int ret;
  436. b = BIO_new(BIO_s_file());
  437. if (b == NULL) {
  438. return 0;
  439. }
  440. BIO_set_fp(b, fp, BIO_NOCLOSE);
  441. ret = BN_print(b, a);
  442. BIO_free(b);
  443. return ret;
  444. }
  445. BN_ULONG BN_get_word(const BIGNUM *bn) {
  446. switch (bn->top) {
  447. case 0:
  448. return 0;
  449. case 1:
  450. return bn->d[0];
  451. default:
  452. return BN_MASK2;
  453. }
  454. }
  455. size_t BN_bn2mpi(const BIGNUM *in, uint8_t *out) {
  456. const size_t bits = BN_num_bits(in);
  457. const size_t bytes = (bits + 7) / 8;
  458. /* If the number of bits is a multiple of 8, i.e. if the MSB is set,
  459. * prefix with a zero byte. */
  460. int extend = 0;
  461. if (bytes != 0 && (bits & 0x07) == 0) {
  462. extend = 1;
  463. }
  464. const size_t len = bytes + extend;
  465. if (len < bytes ||
  466. 4 + len < len ||
  467. (len & 0xffffffff) != len) {
  468. /* If we cannot represent the number then we emit zero as the interface
  469. * doesn't allow an error to be signalled. */
  470. if (out) {
  471. memset(out, 0, 4);
  472. }
  473. return 4;
  474. }
  475. if (out == NULL) {
  476. return 4 + len;
  477. }
  478. out[0] = len >> 24;
  479. out[1] = len >> 16;
  480. out[2] = len >> 8;
  481. out[3] = len;
  482. if (extend) {
  483. out[4] = 0;
  484. }
  485. BN_bn2bin(in, out + 4 + extend);
  486. if (in->neg && len > 0) {
  487. out[4] |= 0x80;
  488. }
  489. return len + 4;
  490. }
  491. BIGNUM *BN_mpi2bn(const uint8_t *in, size_t len, BIGNUM *out) {
  492. if (len < 4) {
  493. OPENSSL_PUT_ERROR(BN, BN_R_BAD_ENCODING);
  494. return NULL;
  495. }
  496. const size_t in_len = ((size_t)in[0] << 24) |
  497. ((size_t)in[1] << 16) |
  498. ((size_t)in[2] << 8) |
  499. ((size_t)in[3]);
  500. if (in_len != len - 4) {
  501. OPENSSL_PUT_ERROR(BN, BN_R_BAD_ENCODING);
  502. return NULL;
  503. }
  504. if (out == NULL) {
  505. out = BN_new();
  506. }
  507. if (out == NULL) {
  508. OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE);
  509. return NULL;
  510. }
  511. if (in_len == 0) {
  512. BN_zero(out);
  513. return out;
  514. }
  515. in += 4;
  516. if (BN_bin2bn(in, in_len, out) == NULL) {
  517. return NULL;
  518. }
  519. out->neg = ((*in) & 0x80) != 0;
  520. if (out->neg) {
  521. BN_clear_bit(out, BN_num_bits(out) - 1);
  522. }
  523. return out;
  524. }