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 size_t BN_bn2bin(const BIGNUM *in, uint8_t *out) { 122 size_t n, i; 123 BN_ULONG l; 124 125 n = i = BN_num_bytes(in); 126 while (i--) { 127 l = in->d[i / BN_BYTES]; 128 *(out++) = (unsigned char)(l >> (8 * (i % BN_BYTES))) & 0xff; 129 } 130 return n; 131 } 132 133 /* constant_time_select_ulong returns |x| if |v| is 1 and |y| if |v| is 0. Its 134 * behavior is undefined if |v| takes any other value. */ 135 static BN_ULONG constant_time_select_ulong(int v, BN_ULONG x, BN_ULONG y) { 136 BN_ULONG mask = v; 137 mask--; 138 139 return (~mask & x) | (mask & y); 140 } 141 142 /* constant_time_le_size_t returns 1 if |x| <= |y| and 0 otherwise. |x| and |y| 143 * must not have their MSBs set. */ 144 static int constant_time_le_size_t(size_t x, size_t y) { 145 return ((x - y - 1) >> (sizeof(size_t) * 8 - 1)) & 1; 146 } 147 148 /* read_word_padded returns the |i|'th word of |in|, if it is not out of 149 * bounds. Otherwise, it returns 0. It does so without branches on the size of 150 * |in|, however it necessarily does not have the same memory access pattern. If 151 * the access would be out of bounds, it reads the last word of |in|. |in| must 152 * not be zero. */ 153 static BN_ULONG read_word_padded(const BIGNUM *in, size_t i) { 154 /* Read |in->d[i]| if valid. Otherwise, read the last word. */ 155 BN_ULONG l = in->d[constant_time_select_ulong( 156 constant_time_le_size_t(in->dmax, i), in->dmax - 1, i)]; 157 158 /* Clamp to zero if above |d->top|. */ 159 return constant_time_select_ulong(constant_time_le_size_t(in->top, i), 0, l); 160 } 161 162 int BN_bn2bin_padded(uint8_t *out, size_t len, const BIGNUM *in) { 163 size_t i; 164 BN_ULONG l; 165 166 /* Special case for |in| = 0. Just branch as the probability is negligible. */ 167 if (BN_is_zero(in)) { 168 memset(out, 0, len); 169 return 1; 170 } 171 172 /* Check if the integer is too big. This case can exit early in non-constant 173 * time. */ 174 if ((size_t)in->top > (len + (BN_BYTES - 1)) / BN_BYTES) { 175 return 0; 176 } 177 if ((len % BN_BYTES) != 0) { 178 l = read_word_padded(in, len / BN_BYTES); 179 if (l >> (8 * (len % BN_BYTES)) != 0) { 180 return 0; 181 } 182 } 183 184 /* Write the bytes out one by one. Serialization is done without branching on 185 * the bits of |in| or on |in->top|, but if the routine would otherwise read 186 * out of bounds, the memory access pattern can't be fixed. However, for an 187 * RSA key of size a multiple of the word size, the probability of BN_BYTES 188 * leading zero octets is low. 189 * 190 * See Falko Stenzke, "Manger's Attack revisited", ICICS 2010. */ 191 i = len; 192 while (i--) { 193 l = read_word_padded(in, i / BN_BYTES); 194 *(out++) = (uint8_t)(l >> (8 * (i % BN_BYTES))) & 0xff; 195 } 196 return 1; 197 } 198 199 int BN_bn2cbb_padded(CBB *out, size_t len, const BIGNUM *in) { 200 uint8_t *ptr; 201 return CBB_add_space(out, &ptr, len) && BN_bn2bin_padded(ptr, len, in); 202 } 203 204 static const char hextable[] = "0123456789abcdef"; 205 206 char *BN_bn2hex(const BIGNUM *bn) { 207 int i, j, v, z = 0; 208 char *buf; 209 char *p; 210 211 buf = (char *)OPENSSL_malloc(bn->top * BN_BYTES * 2 + 2); 212 if (buf == NULL) { 213 OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE); 214 return NULL; 215 } 216 217 p = buf; 218 if (bn->neg) { 219 *(p++) = '-'; 220 } 221 222 if (BN_is_zero(bn)) { 223 *(p++) = '0'; 224 } 225 226 for (i = bn->top - 1; i >= 0; i--) { 227 for (j = BN_BITS2 - 8; j >= 0; j -= 8) { 228 /* strip leading zeros */ 229 v = ((int)(bn->d[i] >> (long)j)) & 0xff; 230 if (z || v != 0) { 231 *(p++) = hextable[v >> 4]; 232 *(p++) = hextable[v & 0x0f]; 233 z = 1; 234 } 235 } 236 } 237 *p = '\0'; 238 239 return buf; 240 } 241 242 /* decode_hex decodes |in_len| bytes of hex data from |in| and updates |bn|. */ 243 static int decode_hex(BIGNUM *bn, const char *in, int in_len) { 244 if (in_len > INT_MAX/4) { 245 OPENSSL_PUT_ERROR(BN, BN_R_BIGNUM_TOO_LONG); 246 return 0; 247 } 248 /* |in_len| is the number of hex digits. */ 249 if (bn_expand(bn, in_len * 4) == NULL) { 250 return 0; 251 } 252 253 int i = 0; 254 while (in_len > 0) { 255 /* Decode one |BN_ULONG| at a time. */ 256 int todo = BN_BYTES * 2; 257 if (todo > in_len) { 258 todo = in_len; 259 } 260 261 BN_ULONG word = 0; 262 int j; 263 for (j = todo; j > 0; j--) { 264 char c = in[in_len - j]; 265 266 BN_ULONG hex; 267 if (c >= '0' && c <= '9') { 268 hex = c - '0'; 269 } else if (c >= 'a' && c <= 'f') { 270 hex = c - 'a' + 10; 271 } else if (c >= 'A' && c <= 'F') { 272 hex = c - 'A' + 10; 273 } else { 274 hex = 0; 275 /* This shouldn't happen. The caller checks |isxdigit|. */ 276 assert(0); 277 } 278 word = (word << 4) | hex; 279 } 280 281 bn->d[i++] = word; 282 in_len -= todo; 283 } 284 assert(i <= bn->dmax); 285 bn->top = i; 286 return 1; 287 } 288 289 /* decode_dec decodes |in_len| bytes of decimal data from |in| and updates |bn|. */ 290 static int decode_dec(BIGNUM *bn, const char *in, int in_len) { 291 int i, j; 292 BN_ULONG l = 0; 293 294 /* Decode |BN_DEC_NUM| digits at a time. */ 295 j = BN_DEC_NUM - (in_len % BN_DEC_NUM); 296 if (j == BN_DEC_NUM) { 297 j = 0; 298 } 299 l = 0; 300 for (i = 0; i < in_len; i++) { 301 l *= 10; 302 l += in[i] - '0'; 303 if (++j == BN_DEC_NUM) { 304 if (!BN_mul_word(bn, BN_DEC_CONV) || 305 !BN_add_word(bn, l)) { 306 return 0; 307 } 308 l = 0; 309 j = 0; 310 } 311 } 312 return 1; 313 } 314 315 typedef int (*decode_func) (BIGNUM *bn, const char *in, int in_len); 316 typedef int (*char_test_func) (int c); 317 318 static int bn_x2bn(BIGNUM **outp, const char *in, decode_func decode, char_test_func want_char) { 319 BIGNUM *ret = NULL; 320 int neg = 0, i; 321 int num; 322 323 if (in == NULL || *in == 0) { 324 return 0; 325 } 326 327 if (*in == '-') { 328 neg = 1; 329 in++; 330 } 331 332 for (i = 0; want_char((unsigned char)in[i]) && i + neg < INT_MAX; i++) {} 333 334 num = i + neg; 335 if (outp == NULL) { 336 return num; 337 } 338 339 /* in is the start of the hex digits, and it is 'i' long */ 340 if (*outp == NULL) { 341 ret = BN_new(); 342 if (ret == NULL) { 343 return 0; 344 } 345 } else { 346 ret = *outp; 347 BN_zero(ret); 348 } 349 350 if (!decode(ret, in, i)) { 351 goto err; 352 } 353 354 bn_correct_top(ret); 355 if (!BN_is_zero(ret)) { 356 ret->neg = neg; 357 } 358 359 *outp = ret; 360 return num; 361 362 err: 363 if (*outp == NULL) { 364 BN_free(ret); 365 } 366 367 return 0; 368 } 369 370 int BN_hex2bn(BIGNUM **outp, const char *in) { 371 return bn_x2bn(outp, in, decode_hex, isxdigit); 372 } 373 374 char *BN_bn2dec(const BIGNUM *a) { 375 int i = 0, num, ok = 0; 376 char *buf = NULL; 377 char *p; 378 BIGNUM *t = NULL; 379 BN_ULONG *bn_data = NULL, *lp; 380 381 /* get an upper bound for the length of the decimal integer 382 * num <= (BN_num_bits(a) + 1) * log(2) 383 * <= 3 * BN_num_bits(a) * 0.1001 + log(2) + 1 (rounding error) 384 * <= BN_num_bits(a)/10 + BN_num_bits/1000 + 1 + 1 385 */ 386 i = BN_num_bits(a) * 3; 387 num = i / 10 + i / 1000 + 1 + 1; 388 bn_data = 389 (BN_ULONG *)OPENSSL_malloc((num / BN_DEC_NUM + 1) * sizeof(BN_ULONG)); 390 buf = (char *)OPENSSL_malloc(num + 3); 391 if ((buf == NULL) || (bn_data == NULL)) { 392 OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE); 393 goto err; 394 } 395 t = BN_dup(a); 396 if (t == NULL) { 397 goto err; 398 } 399 400 #define BUF_REMAIN (num + 3 - (size_t)(p - buf)) 401 p = buf; 402 lp = bn_data; 403 if (BN_is_zero(t)) { 404 *(p++) = '0'; 405 *(p++) = '\0'; 406 } else { 407 if (BN_is_negative(t)) { 408 *p++ = '-'; 409 } 410 411 while (!BN_is_zero(t)) { 412 *lp = BN_div_word(t, BN_DEC_CONV); 413 lp++; 414 } 415 lp--; 416 /* We now have a series of blocks, BN_DEC_NUM chars 417 * in length, where the last one needs truncation. 418 * The blocks need to be reversed in order. */ 419 BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT1, *lp); 420 while (*p) { 421 p++; 422 } 423 while (lp != bn_data) { 424 lp--; 425 BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT2, *lp); 426 while (*p) { 427 p++; 428 } 429 } 430 } 431 ok = 1; 432 433 err: 434 OPENSSL_free(bn_data); 435 BN_free(t); 436 if (!ok) { 437 OPENSSL_free(buf); 438 buf = NULL; 439 } 440 441 return buf; 442 } 443 444 int BN_dec2bn(BIGNUM **outp, const char *in) { 445 return bn_x2bn(outp, in, decode_dec, isdigit); 446 } 447 448 int BN_asc2bn(BIGNUM **outp, const char *in) { 449 const char *const orig_in = in; 450 if (*in == '-') { 451 in++; 452 } 453 454 if (in[0] == '0' && (in[1] == 'X' || in[1] == 'x')) { 455 if (!BN_hex2bn(outp, in+2)) { 456 return 0; 457 } 458 } else { 459 if (!BN_dec2bn(outp, in)) { 460 return 0; 461 } 462 } 463 464 if (*orig_in == '-' && !BN_is_zero(*outp)) { 465 (*outp)->neg = 1; 466 } 467 468 return 1; 469 } 470 471 int BN_print(BIO *bp, const BIGNUM *a) { 472 int i, j, v, z = 0; 473 int ret = 0; 474 475 if (a->neg && BIO_write(bp, "-", 1) != 1) { 476 goto end; 477 } 478 479 if (BN_is_zero(a) && BIO_write(bp, "0", 1) != 1) { 480 goto end; 481 } 482 483 for (i = a->top - 1; i >= 0; i--) { 484 for (j = BN_BITS2 - 4; j >= 0; j -= 4) { 485 /* strip leading zeros */ 486 v = ((int)(a->d[i] >> (long)j)) & 0x0f; 487 if (z || v != 0) { 488 if (BIO_write(bp, &hextable[v], 1) != 1) { 489 goto end; 490 } 491 z = 1; 492 } 493 } 494 } 495 ret = 1; 496 497 end: 498 return ret; 499 } 500 501 int BN_print_fp(FILE *fp, const BIGNUM *a) { 502 BIO *b; 503 int ret; 504 505 b = BIO_new(BIO_s_file()); 506 if (b == NULL) { 507 return 0; 508 } 509 BIO_set_fp(b, fp, BIO_NOCLOSE); 510 ret = BN_print(b, a); 511 BIO_free(b); 512 513 return ret; 514 } 515 516 BN_ULONG BN_get_word(const BIGNUM *bn) { 517 switch (bn->top) { 518 case 0: 519 return 0; 520 case 1: 521 return bn->d[0]; 522 default: 523 return BN_MASK2; 524 } 525 } 526 527 size_t BN_bn2mpi(const BIGNUM *in, uint8_t *out) { 528 const size_t bits = BN_num_bits(in); 529 const size_t bytes = (bits + 7) / 8; 530 /* If the number of bits is a multiple of 8, i.e. if the MSB is set, 531 * prefix with a zero byte. */ 532 int extend = 0; 533 if (bytes != 0 && (bits & 0x07) == 0) { 534 extend = 1; 535 } 536 537 const size_t len = bytes + extend; 538 if (len < bytes || 539 4 + len < len || 540 (len & 0xffffffff) != len) { 541 /* If we cannot represent the number then we emit zero as the interface 542 * doesn't allow an error to be signalled. */ 543 if (out) { 544 memset(out, 0, 4); 545 } 546 return 4; 547 } 548 549 if (out == NULL) { 550 return 4 + len; 551 } 552 553 out[0] = len >> 24; 554 out[1] = len >> 16; 555 out[2] = len >> 8; 556 out[3] = len; 557 if (extend) { 558 out[4] = 0; 559 } 560 BN_bn2bin(in, out + 4 + extend); 561 if (in->neg && len > 0) { 562 out[4] |= 0x80; 563 } 564 return len + 4; 565 } 566 567 BIGNUM *BN_mpi2bn(const uint8_t *in, size_t len, BIGNUM *out) { 568 if (len < 4) { 569 OPENSSL_PUT_ERROR(BN, BN_R_BAD_ENCODING); 570 return NULL; 571 } 572 const size_t in_len = ((size_t)in[0] << 24) | 573 ((size_t)in[1] << 16) | 574 ((size_t)in[2] << 8) | 575 ((size_t)in[3]); 576 if (in_len != len - 4) { 577 OPENSSL_PUT_ERROR(BN, BN_R_BAD_ENCODING); 578 return NULL; 579 } 580 581 if (out == NULL) { 582 out = BN_new(); 583 } 584 if (out == NULL) { 585 OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE); 586 return NULL; 587 } 588 589 if (in_len == 0) { 590 BN_zero(out); 591 return out; 592 } 593 594 in += 4; 595 if (BN_bin2bn(in, in_len, out) == NULL) { 596 return NULL; 597 } 598 out->neg = ((*in) & 0x80) != 0; 599 if (out->neg) { 600 BN_clear_bit(out, BN_num_bits(out) - 1); 601 } 602 return out; 603 } 604