1 /* Copyright (C) 1995-1998 Eric Young (eay (at) cryptsoft.com) 2 * All rights reserved. 3 * 4 * This package is an SSL implementation written 5 * by Eric Young (eay (at) 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 (at) 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 (at) 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 (at) 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 57 #include <openssl/bn.h> 58 59 #include <assert.h> 60 #include <ctype.h> 61 #include <limits.h> 62 #include <stdio.h> 63 #include <string.h> 64 65 #include <openssl/bio.h> 66 #include <openssl/bytestring.h> 67 #include <openssl/err.h> 68 #include <openssl/mem.h> 69 70 #include "internal.h" 71 72 BIGNUM *BN_bin2bn(const uint8_t *in, size_t len, BIGNUM *ret) { 73 size_t num_words; 74 unsigned m; 75 BN_ULONG word = 0; 76 BIGNUM *bn = NULL; 77 78 if (ret == NULL) { 79 ret = bn = BN_new(); 80 } 81 82 if (ret == NULL) { 83 return NULL; 84 } 85 86 if (len == 0) { 87 ret->top = 0; 88 return ret; 89 } 90 91 num_words = ((len - 1) / BN_BYTES) + 1; 92 m = (len - 1) % BN_BYTES; 93 if (bn_wexpand(ret, num_words) == NULL) { 94 if (bn) { 95 BN_free(bn); 96 } 97 return NULL; 98 } 99 100 /* |bn_wexpand| must check bounds on |num_words| to write it into 101 * |ret->dmax|. */ 102 assert(num_words <= INT_MAX); 103 ret->top = (int)num_words; 104 ret->neg = 0; 105 106 while (len--) { 107 word = (word << 8) | *(in++); 108 if (m-- == 0) { 109 ret->d[--num_words] = word; 110 word = 0; 111 m = BN_BYTES - 1; 112 } 113 } 114 115 /* need to call this due to clear byte at top if avoiding having the top bit 116 * set (-ve number) */ 117 bn_correct_top(ret); 118 return ret; 119 } 120 121 BIGNUM *BN_le2bn(const uint8_t *in, size_t len, BIGNUM *ret) { 122 BIGNUM *bn = NULL; 123 if (ret == NULL) { 124 bn = BN_new(); 125 ret = bn; 126 } 127 128 if (ret == NULL) { 129 return NULL; 130 } 131 132 if (len == 0) { 133 ret->top = 0; 134 ret->neg = 0; 135 return ret; 136 } 137 138 /* Reserve enough space in |ret|. */ 139 size_t num_words = ((len - 1) / BN_BYTES) + 1; 140 if (!bn_wexpand(ret, num_words)) { 141 BN_free(bn); 142 return NULL; 143 } 144 ret->top = num_words; 145 146 /* Make sure the top bytes will be zeroed. */ 147 ret->d[num_words - 1] = 0; 148 149 /* We only support little-endian platforms, so we can simply memcpy the 150 * internal representation. */ 151 OPENSSL_memcpy(ret->d, in, len); 152 153 bn_correct_top(ret); 154 return ret; 155 } 156 157 size_t BN_bn2bin(const BIGNUM *in, uint8_t *out) { 158 size_t n, i; 159 BN_ULONG l; 160 161 n = i = BN_num_bytes(in); 162 while (i--) { 163 l = in->d[i / BN_BYTES]; 164 *(out++) = (unsigned char)(l >> (8 * (i % BN_BYTES))) & 0xff; 165 } 166 return n; 167 } 168 169 int BN_bn2le_padded(uint8_t *out, size_t len, const BIGNUM *in) { 170 /* If we don't have enough space, fail out. */ 171 size_t num_bytes = BN_num_bytes(in); 172 if (len < num_bytes) { 173 return 0; 174 } 175 176 /* We only support little-endian platforms, so we can simply memcpy into the 177 * internal representation. */ 178 OPENSSL_memcpy(out, in->d, num_bytes); 179 180 /* Pad out the rest of the buffer with zeroes. */ 181 OPENSSL_memset(out + num_bytes, 0, len - num_bytes); 182 183 return 1; 184 } 185 186 /* constant_time_select_ulong returns |x| if |v| is 1 and |y| if |v| is 0. Its 187 * behavior is undefined if |v| takes any other value. */ 188 static BN_ULONG constant_time_select_ulong(int v, BN_ULONG x, BN_ULONG y) { 189 BN_ULONG mask = v; 190 mask--; 191 192 return (~mask & x) | (mask & y); 193 } 194 195 /* constant_time_le_size_t returns 1 if |x| <= |y| and 0 otherwise. |x| and |y| 196 * must not have their MSBs set. */ 197 static int constant_time_le_size_t(size_t x, size_t y) { 198 return ((x - y - 1) >> (sizeof(size_t) * 8 - 1)) & 1; 199 } 200 201 /* read_word_padded returns the |i|'th word of |in|, if it is not out of 202 * bounds. Otherwise, it returns 0. It does so without branches on the size of 203 * |in|, however it necessarily does not have the same memory access pattern. If 204 * the access would be out of bounds, it reads the last word of |in|. |in| must 205 * not be zero. */ 206 static BN_ULONG read_word_padded(const BIGNUM *in, size_t i) { 207 /* Read |in->d[i]| if valid. Otherwise, read the last word. */ 208 BN_ULONG l = in->d[constant_time_select_ulong( 209 constant_time_le_size_t(in->dmax, i), in->dmax - 1, i)]; 210 211 /* Clamp to zero if above |d->top|. */ 212 return constant_time_select_ulong(constant_time_le_size_t(in->top, i), 0, l); 213 } 214 215 int BN_bn2bin_padded(uint8_t *out, size_t len, const BIGNUM *in) { 216 /* Special case for |in| = 0. Just branch as the probability is negligible. */ 217 if (BN_is_zero(in)) { 218 OPENSSL_memset(out, 0, len); 219 return 1; 220 } 221 222 /* Check if the integer is too big. This case can exit early in non-constant 223 * time. */ 224 if ((size_t)in->top > (len + (BN_BYTES - 1)) / BN_BYTES) { 225 return 0; 226 } 227 if ((len % BN_BYTES) != 0) { 228 BN_ULONG l = read_word_padded(in, len / BN_BYTES); 229 if (l >> (8 * (len % BN_BYTES)) != 0) { 230 return 0; 231 } 232 } 233 234 /* Write the bytes out one by one. Serialization is done without branching on 235 * the bits of |in| or on |in->top|, but if the routine would otherwise read 236 * out of bounds, the memory access pattern can't be fixed. However, for an 237 * RSA key of size a multiple of the word size, the probability of BN_BYTES 238 * leading zero octets is low. 239 * 240 * See Falko Stenzke, "Manger's Attack revisited", ICICS 2010. */ 241 size_t i = len; 242 while (i--) { 243 BN_ULONG l = read_word_padded(in, i / BN_BYTES); 244 *(out++) = (uint8_t)(l >> (8 * (i % BN_BYTES))) & 0xff; 245 } 246 return 1; 247 } 248 249 int BN_bn2cbb_padded(CBB *out, size_t len, const BIGNUM *in) { 250 uint8_t *ptr; 251 return CBB_add_space(out, &ptr, len) && BN_bn2bin_padded(ptr, len, in); 252 } 253 254 static const char hextable[] = "0123456789abcdef"; 255 256 char *BN_bn2hex(const BIGNUM *bn) { 257 char *buf = OPENSSL_malloc(1 /* leading '-' */ + 1 /* zero is non-empty */ + 258 bn->top * BN_BYTES * 2 + 1 /* trailing NUL */); 259 if (buf == NULL) { 260 OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE); 261 return NULL; 262 } 263 264 char *p = buf; 265 if (bn->neg) { 266 *(p++) = '-'; 267 } 268 269 if (BN_is_zero(bn)) { 270 *(p++) = '0'; 271 } 272 273 int z = 0; 274 for (int i = bn->top - 1; i >= 0; i--) { 275 for (int j = BN_BITS2 - 8; j >= 0; j -= 8) { 276 /* strip leading zeros */ 277 int v = ((int)(bn->d[i] >> (long)j)) & 0xff; 278 if (z || v != 0) { 279 *(p++) = hextable[v >> 4]; 280 *(p++) = hextable[v & 0x0f]; 281 z = 1; 282 } 283 } 284 } 285 *p = '\0'; 286 287 return buf; 288 } 289 290 /* decode_hex decodes |in_len| bytes of hex data from |in| and updates |bn|. */ 291 static int decode_hex(BIGNUM *bn, const char *in, int in_len) { 292 if (in_len > INT_MAX/4) { 293 OPENSSL_PUT_ERROR(BN, BN_R_BIGNUM_TOO_LONG); 294 return 0; 295 } 296 /* |in_len| is the number of hex digits. */ 297 if (bn_expand(bn, in_len * 4) == NULL) { 298 return 0; 299 } 300 301 int i = 0; 302 while (in_len > 0) { 303 /* Decode one |BN_ULONG| at a time. */ 304 int todo = BN_BYTES * 2; 305 if (todo > in_len) { 306 todo = in_len; 307 } 308 309 BN_ULONG word = 0; 310 int j; 311 for (j = todo; j > 0; j--) { 312 char c = in[in_len - j]; 313 314 BN_ULONG hex; 315 if (c >= '0' && c <= '9') { 316 hex = c - '0'; 317 } else if (c >= 'a' && c <= 'f') { 318 hex = c - 'a' + 10; 319 } else if (c >= 'A' && c <= 'F') { 320 hex = c - 'A' + 10; 321 } else { 322 hex = 0; 323 /* This shouldn't happen. The caller checks |isxdigit|. */ 324 assert(0); 325 } 326 word = (word << 4) | hex; 327 } 328 329 bn->d[i++] = word; 330 in_len -= todo; 331 } 332 assert(i <= bn->dmax); 333 bn->top = i; 334 return 1; 335 } 336 337 /* decode_dec decodes |in_len| bytes of decimal data from |in| and updates |bn|. */ 338 static int decode_dec(BIGNUM *bn, const char *in, int in_len) { 339 int i, j; 340 BN_ULONG l = 0; 341 342 /* Decode |BN_DEC_NUM| digits at a time. */ 343 j = BN_DEC_NUM - (in_len % BN_DEC_NUM); 344 if (j == BN_DEC_NUM) { 345 j = 0; 346 } 347 l = 0; 348 for (i = 0; i < in_len; i++) { 349 l *= 10; 350 l += in[i] - '0'; 351 if (++j == BN_DEC_NUM) { 352 if (!BN_mul_word(bn, BN_DEC_CONV) || 353 !BN_add_word(bn, l)) { 354 return 0; 355 } 356 l = 0; 357 j = 0; 358 } 359 } 360 return 1; 361 } 362 363 typedef int (*decode_func) (BIGNUM *bn, const char *in, int in_len); 364 typedef int (*char_test_func) (int c); 365 366 static int bn_x2bn(BIGNUM **outp, const char *in, decode_func decode, char_test_func want_char) { 367 BIGNUM *ret = NULL; 368 int neg = 0, i; 369 int num; 370 371 if (in == NULL || *in == 0) { 372 return 0; 373 } 374 375 if (*in == '-') { 376 neg = 1; 377 in++; 378 } 379 380 for (i = 0; want_char((unsigned char)in[i]) && i + neg < INT_MAX; i++) {} 381 382 num = i + neg; 383 if (outp == NULL) { 384 return num; 385 } 386 387 /* in is the start of the hex digits, and it is 'i' long */ 388 if (*outp == NULL) { 389 ret = BN_new(); 390 if (ret == NULL) { 391 return 0; 392 } 393 } else { 394 ret = *outp; 395 BN_zero(ret); 396 } 397 398 if (!decode(ret, in, i)) { 399 goto err; 400 } 401 402 bn_correct_top(ret); 403 if (!BN_is_zero(ret)) { 404 ret->neg = neg; 405 } 406 407 *outp = ret; 408 return num; 409 410 err: 411 if (*outp == NULL) { 412 BN_free(ret); 413 } 414 415 return 0; 416 } 417 418 int BN_hex2bn(BIGNUM **outp, const char *in) { 419 return bn_x2bn(outp, in, decode_hex, isxdigit); 420 } 421 422 char *BN_bn2dec(const BIGNUM *a) { 423 /* It is easier to print strings little-endian, so we assemble it in reverse 424 * and fix at the end. */ 425 BIGNUM *copy = NULL; 426 CBB cbb; 427 if (!CBB_init(&cbb, 16) || 428 !CBB_add_u8(&cbb, 0 /* trailing NUL */)) { 429 goto cbb_err; 430 } 431 432 if (BN_is_zero(a)) { 433 if (!CBB_add_u8(&cbb, '0')) { 434 goto cbb_err; 435 } 436 } else { 437 copy = BN_dup(a); 438 if (copy == NULL) { 439 goto err; 440 } 441 442 while (!BN_is_zero(copy)) { 443 BN_ULONG word = BN_div_word(copy, BN_DEC_CONV); 444 if (word == (BN_ULONG)-1) { 445 goto err; 446 } 447 448 const int add_leading_zeros = !BN_is_zero(copy); 449 for (int i = 0; i < BN_DEC_NUM && (add_leading_zeros || word != 0); i++) { 450 if (!CBB_add_u8(&cbb, '0' + word % 10)) { 451 goto cbb_err; 452 } 453 word /= 10; 454 } 455 assert(word == 0); 456 } 457 } 458 459 if (BN_is_negative(a) && 460 !CBB_add_u8(&cbb, '-')) { 461 goto cbb_err; 462 } 463 464 uint8_t *data; 465 size_t len; 466 if (!CBB_finish(&cbb, &data, &len)) { 467 goto cbb_err; 468 } 469 470 /* Reverse the buffer. */ 471 for (size_t i = 0; i < len/2; i++) { 472 uint8_t tmp = data[i]; 473 data[i] = data[len - 1 - i]; 474 data[len - 1 - i] = tmp; 475 } 476 477 BN_free(copy); 478 return (char *)data; 479 480 cbb_err: 481 OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE); 482 err: 483 BN_free(copy); 484 CBB_cleanup(&cbb); 485 return NULL; 486 } 487 488 int BN_dec2bn(BIGNUM **outp, const char *in) { 489 return bn_x2bn(outp, in, decode_dec, isdigit); 490 } 491 492 int BN_asc2bn(BIGNUM **outp, const char *in) { 493 const char *const orig_in = in; 494 if (*in == '-') { 495 in++; 496 } 497 498 if (in[0] == '0' && (in[1] == 'X' || in[1] == 'x')) { 499 if (!BN_hex2bn(outp, in+2)) { 500 return 0; 501 } 502 } else { 503 if (!BN_dec2bn(outp, in)) { 504 return 0; 505 } 506 } 507 508 if (*orig_in == '-' && !BN_is_zero(*outp)) { 509 (*outp)->neg = 1; 510 } 511 512 return 1; 513 } 514 515 int BN_print(BIO *bp, const BIGNUM *a) { 516 int i, j, v, z = 0; 517 int ret = 0; 518 519 if (a->neg && BIO_write(bp, "-", 1) != 1) { 520 goto end; 521 } 522 523 if (BN_is_zero(a) && BIO_write(bp, "0", 1) != 1) { 524 goto end; 525 } 526 527 for (i = a->top - 1; i >= 0; i--) { 528 for (j = BN_BITS2 - 4; j >= 0; j -= 4) { 529 /* strip leading zeros */ 530 v = ((int)(a->d[i] >> (long)j)) & 0x0f; 531 if (z || v != 0) { 532 if (BIO_write(bp, &hextable[v], 1) != 1) { 533 goto end; 534 } 535 z = 1; 536 } 537 } 538 } 539 ret = 1; 540 541 end: 542 return ret; 543 } 544 545 int BN_print_fp(FILE *fp, const BIGNUM *a) { 546 BIO *b; 547 int ret; 548 549 b = BIO_new(BIO_s_file()); 550 if (b == NULL) { 551 return 0; 552 } 553 BIO_set_fp(b, fp, BIO_NOCLOSE); 554 ret = BN_print(b, a); 555 BIO_free(b); 556 557 return ret; 558 } 559 560 BN_ULONG BN_get_word(const BIGNUM *bn) { 561 switch (bn->top) { 562 case 0: 563 return 0; 564 case 1: 565 return bn->d[0]; 566 default: 567 return BN_MASK2; 568 } 569 } 570 571 int BN_get_u64(const BIGNUM *bn, uint64_t *out) { 572 switch (bn->top) { 573 case 0: 574 *out = 0; 575 return 1; 576 case 1: 577 *out = bn->d[0]; 578 return 1; 579 #if defined(OPENSSL_32_BIT) 580 case 2: 581 *out = (uint64_t) bn->d[0] | (((uint64_t) bn->d[1]) << 32); 582 return 1; 583 #endif 584 default: 585 return 0; 586 } 587 } 588 589 size_t BN_bn2mpi(const BIGNUM *in, uint8_t *out) { 590 const size_t bits = BN_num_bits(in); 591 const size_t bytes = (bits + 7) / 8; 592 /* If the number of bits is a multiple of 8, i.e. if the MSB is set, 593 * prefix with a zero byte. */ 594 int extend = 0; 595 if (bytes != 0 && (bits & 0x07) == 0) { 596 extend = 1; 597 } 598 599 const size_t len = bytes + extend; 600 if (len < bytes || 601 4 + len < len || 602 (len & 0xffffffff) != len) { 603 /* If we cannot represent the number then we emit zero as the interface 604 * doesn't allow an error to be signalled. */ 605 if (out) { 606 OPENSSL_memset(out, 0, 4); 607 } 608 return 4; 609 } 610 611 if (out == NULL) { 612 return 4 + len; 613 } 614 615 out[0] = len >> 24; 616 out[1] = len >> 16; 617 out[2] = len >> 8; 618 out[3] = len; 619 if (extend) { 620 out[4] = 0; 621 } 622 BN_bn2bin(in, out + 4 + extend); 623 if (in->neg && len > 0) { 624 out[4] |= 0x80; 625 } 626 return len + 4; 627 } 628 629 BIGNUM *BN_mpi2bn(const uint8_t *in, size_t len, BIGNUM *out) { 630 if (len < 4) { 631 OPENSSL_PUT_ERROR(BN, BN_R_BAD_ENCODING); 632 return NULL; 633 } 634 const size_t in_len = ((size_t)in[0] << 24) | 635 ((size_t)in[1] << 16) | 636 ((size_t)in[2] << 8) | 637 ((size_t)in[3]); 638 if (in_len != len - 4) { 639 OPENSSL_PUT_ERROR(BN, BN_R_BAD_ENCODING); 640 return NULL; 641 } 642 643 int out_is_alloced = 0; 644 if (out == NULL) { 645 out = BN_new(); 646 if (out == NULL) { 647 OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE); 648 return NULL; 649 } 650 out_is_alloced = 1; 651 } 652 653 if (in_len == 0) { 654 BN_zero(out); 655 return out; 656 } 657 658 in += 4; 659 if (BN_bin2bn(in, in_len, out) == NULL) { 660 if (out_is_alloced) { 661 BN_free(out); 662 } 663 return NULL; 664 } 665 out->neg = ((*in) & 0x80) != 0; 666 if (out->neg) { 667 BN_clear_bit(out, BN_num_bits(out) - 1); 668 } 669 return out; 670 } 671