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
57 #include <openssl/bn.h>
58
59 #include <assert.h>
60 #include <ctype.h>
61 #include <limits.h>
62 #include <stdio.h>
63
64 #include <openssl/bio.h>
65 #include <openssl/bytestring.h>
66 #include <openssl/err.h>
67 #include <openssl/mem.h>
68
69 #include "../fipsmodule/bn/internal.h"
70
71
BN_bn2cbb_padded(CBB * out,size_t len,const BIGNUM * in)72 int BN_bn2cbb_padded(CBB *out, size_t len, const BIGNUM *in) {
73 uint8_t *ptr;
74 return CBB_add_space(out, &ptr, len) && BN_bn2bin_padded(ptr, len, in);
75 }
76
77 static const char hextable[] = "0123456789abcdef";
78
BN_bn2hex(const BIGNUM * bn)79 char *BN_bn2hex(const BIGNUM *bn) {
80 char *buf = OPENSSL_malloc(1 /* leading '-' */ + 1 /* zero is non-empty */ +
81 bn->top * BN_BYTES * 2 + 1 /* trailing NUL */);
82 if (buf == NULL) {
83 OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE);
84 return NULL;
85 }
86
87 char *p = buf;
88 if (bn->neg) {
89 *(p++) = '-';
90 }
91
92 if (BN_is_zero(bn)) {
93 *(p++) = '0';
94 }
95
96 int z = 0;
97 for (int i = bn->top - 1; i >= 0; i--) {
98 for (int j = BN_BITS2 - 8; j >= 0; j -= 8) {
99 // strip leading zeros
100 int v = ((int)(bn->d[i] >> (long)j)) & 0xff;
101 if (z || v != 0) {
102 *(p++) = hextable[v >> 4];
103 *(p++) = hextable[v & 0x0f];
104 z = 1;
105 }
106 }
107 }
108 *p = '\0';
109
110 return buf;
111 }
112
113 // decode_hex decodes |in_len| bytes of hex data from |in| and updates |bn|.
decode_hex(BIGNUM * bn,const char * in,int in_len)114 static int decode_hex(BIGNUM *bn, const char *in, int in_len) {
115 if (in_len > INT_MAX/4) {
116 OPENSSL_PUT_ERROR(BN, BN_R_BIGNUM_TOO_LONG);
117 return 0;
118 }
119 // |in_len| is the number of hex digits.
120 if (!bn_expand(bn, in_len * 4)) {
121 return 0;
122 }
123
124 int i = 0;
125 while (in_len > 0) {
126 // Decode one |BN_ULONG| at a time.
127 int todo = BN_BYTES * 2;
128 if (todo > in_len) {
129 todo = in_len;
130 }
131
132 BN_ULONG word = 0;
133 int j;
134 for (j = todo; j > 0; j--) {
135 char c = in[in_len - j];
136
137 BN_ULONG hex;
138 if (c >= '0' && c <= '9') {
139 hex = c - '0';
140 } else if (c >= 'a' && c <= 'f') {
141 hex = c - 'a' + 10;
142 } else if (c >= 'A' && c <= 'F') {
143 hex = c - 'A' + 10;
144 } else {
145 hex = 0;
146 // This shouldn't happen. The caller checks |isxdigit|.
147 assert(0);
148 }
149 word = (word << 4) | hex;
150 }
151
152 bn->d[i++] = word;
153 in_len -= todo;
154 }
155 assert(i <= bn->dmax);
156 bn->top = i;
157 return 1;
158 }
159
160 // decode_dec decodes |in_len| bytes of decimal data from |in| and updates |bn|.
decode_dec(BIGNUM * bn,const char * in,int in_len)161 static int decode_dec(BIGNUM *bn, const char *in, int in_len) {
162 int i, j;
163 BN_ULONG l = 0;
164
165 // Decode |BN_DEC_NUM| digits at a time.
166 j = BN_DEC_NUM - (in_len % BN_DEC_NUM);
167 if (j == BN_DEC_NUM) {
168 j = 0;
169 }
170 l = 0;
171 for (i = 0; i < in_len; i++) {
172 l *= 10;
173 l += in[i] - '0';
174 if (++j == BN_DEC_NUM) {
175 if (!BN_mul_word(bn, BN_DEC_CONV) ||
176 !BN_add_word(bn, l)) {
177 return 0;
178 }
179 l = 0;
180 j = 0;
181 }
182 }
183 return 1;
184 }
185
186 typedef int (*decode_func) (BIGNUM *bn, const char *in, int in_len);
187 typedef int (*char_test_func) (int c);
188
bn_x2bn(BIGNUM ** outp,const char * in,decode_func decode,char_test_func want_char)189 static int bn_x2bn(BIGNUM **outp, const char *in, decode_func decode, char_test_func want_char) {
190 BIGNUM *ret = NULL;
191 int neg = 0, i;
192 int num;
193
194 if (in == NULL || *in == 0) {
195 return 0;
196 }
197
198 if (*in == '-') {
199 neg = 1;
200 in++;
201 }
202
203 for (i = 0; want_char((unsigned char)in[i]) && i + neg < INT_MAX; i++) {}
204
205 num = i + neg;
206 if (outp == NULL) {
207 return num;
208 }
209
210 // in is the start of the hex digits, and it is 'i' long
211 if (*outp == NULL) {
212 ret = BN_new();
213 if (ret == NULL) {
214 return 0;
215 }
216 } else {
217 ret = *outp;
218 BN_zero(ret);
219 }
220
221 if (!decode(ret, in, i)) {
222 goto err;
223 }
224
225 bn_correct_top(ret);
226 if (!BN_is_zero(ret)) {
227 ret->neg = neg;
228 }
229
230 *outp = ret;
231 return num;
232
233 err:
234 if (*outp == NULL) {
235 BN_free(ret);
236 }
237
238 return 0;
239 }
240
BN_hex2bn(BIGNUM ** outp,const char * in)241 int BN_hex2bn(BIGNUM **outp, const char *in) {
242 return bn_x2bn(outp, in, decode_hex, isxdigit);
243 }
244
BN_bn2dec(const BIGNUM * a)245 char *BN_bn2dec(const BIGNUM *a) {
246 // It is easier to print strings little-endian, so we assemble it in reverse
247 // and fix at the end.
248 BIGNUM *copy = NULL;
249 CBB cbb;
250 if (!CBB_init(&cbb, 16) ||
251 !CBB_add_u8(&cbb, 0 /* trailing NUL */)) {
252 goto cbb_err;
253 }
254
255 if (BN_is_zero(a)) {
256 if (!CBB_add_u8(&cbb, '0')) {
257 goto cbb_err;
258 }
259 } else {
260 copy = BN_dup(a);
261 if (copy == NULL) {
262 goto err;
263 }
264
265 while (!BN_is_zero(copy)) {
266 BN_ULONG word = BN_div_word(copy, BN_DEC_CONV);
267 if (word == (BN_ULONG)-1) {
268 goto err;
269 }
270
271 const int add_leading_zeros = !BN_is_zero(copy);
272 for (int i = 0; i < BN_DEC_NUM && (add_leading_zeros || word != 0); i++) {
273 if (!CBB_add_u8(&cbb, '0' + word % 10)) {
274 goto cbb_err;
275 }
276 word /= 10;
277 }
278 assert(word == 0);
279 }
280 }
281
282 if (BN_is_negative(a) &&
283 !CBB_add_u8(&cbb, '-')) {
284 goto cbb_err;
285 }
286
287 uint8_t *data;
288 size_t len;
289 if (!CBB_finish(&cbb, &data, &len)) {
290 goto cbb_err;
291 }
292
293 // Reverse the buffer.
294 for (size_t i = 0; i < len/2; i++) {
295 uint8_t tmp = data[i];
296 data[i] = data[len - 1 - i];
297 data[len - 1 - i] = tmp;
298 }
299
300 BN_free(copy);
301 return (char *)data;
302
303 cbb_err:
304 OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE);
305 err:
306 BN_free(copy);
307 CBB_cleanup(&cbb);
308 return NULL;
309 }
310
BN_dec2bn(BIGNUM ** outp,const char * in)311 int BN_dec2bn(BIGNUM **outp, const char *in) {
312 return bn_x2bn(outp, in, decode_dec, isdigit);
313 }
314
BN_asc2bn(BIGNUM ** outp,const char * in)315 int BN_asc2bn(BIGNUM **outp, const char *in) {
316 const char *const orig_in = in;
317 if (*in == '-') {
318 in++;
319 }
320
321 if (in[0] == '0' && (in[1] == 'X' || in[1] == 'x')) {
322 if (!BN_hex2bn(outp, in+2)) {
323 return 0;
324 }
325 } else {
326 if (!BN_dec2bn(outp, in)) {
327 return 0;
328 }
329 }
330
331 if (*orig_in == '-' && !BN_is_zero(*outp)) {
332 (*outp)->neg = 1;
333 }
334
335 return 1;
336 }
337
BN_print(BIO * bp,const BIGNUM * a)338 int BN_print(BIO *bp, const BIGNUM *a) {
339 int i, j, v, z = 0;
340 int ret = 0;
341
342 if (a->neg && BIO_write(bp, "-", 1) != 1) {
343 goto end;
344 }
345
346 if (BN_is_zero(a) && BIO_write(bp, "0", 1) != 1) {
347 goto end;
348 }
349
350 for (i = a->top - 1; i >= 0; i--) {
351 for (j = BN_BITS2 - 4; j >= 0; j -= 4) {
352 // strip leading zeros
353 v = ((int)(a->d[i] >> (long)j)) & 0x0f;
354 if (z || v != 0) {
355 if (BIO_write(bp, &hextable[v], 1) != 1) {
356 goto end;
357 }
358 z = 1;
359 }
360 }
361 }
362 ret = 1;
363
364 end:
365 return ret;
366 }
367
BN_print_fp(FILE * fp,const BIGNUM * a)368 int BN_print_fp(FILE *fp, const BIGNUM *a) {
369 BIO *b;
370 int ret;
371
372 b = BIO_new(BIO_s_file());
373 if (b == NULL) {
374 return 0;
375 }
376 BIO_set_fp(b, fp, BIO_NOCLOSE);
377 ret = BN_print(b, a);
378 BIO_free(b);
379
380 return ret;
381 }
382
383
BN_bn2mpi(const BIGNUM * in,uint8_t * out)384 size_t BN_bn2mpi(const BIGNUM *in, uint8_t *out) {
385 const size_t bits = BN_num_bits(in);
386 const size_t bytes = (bits + 7) / 8;
387 // If the number of bits is a multiple of 8, i.e. if the MSB is set,
388 // prefix with a zero byte.
389 int extend = 0;
390 if (bytes != 0 && (bits & 0x07) == 0) {
391 extend = 1;
392 }
393
394 const size_t len = bytes + extend;
395 if (len < bytes ||
396 4 + len < len ||
397 (len & 0xffffffff) != len) {
398 // If we cannot represent the number then we emit zero as the interface
399 // doesn't allow an error to be signalled.
400 if (out) {
401 OPENSSL_memset(out, 0, 4);
402 }
403 return 4;
404 }
405
406 if (out == NULL) {
407 return 4 + len;
408 }
409
410 out[0] = len >> 24;
411 out[1] = len >> 16;
412 out[2] = len >> 8;
413 out[3] = len;
414 if (extend) {
415 out[4] = 0;
416 }
417 BN_bn2bin(in, out + 4 + extend);
418 if (in->neg && len > 0) {
419 out[4] |= 0x80;
420 }
421 return len + 4;
422 }
423
BN_mpi2bn(const uint8_t * in,size_t len,BIGNUM * out)424 BIGNUM *BN_mpi2bn(const uint8_t *in, size_t len, BIGNUM *out) {
425 if (len < 4) {
426 OPENSSL_PUT_ERROR(BN, BN_R_BAD_ENCODING);
427 return NULL;
428 }
429 const size_t in_len = ((size_t)in[0] << 24) |
430 ((size_t)in[1] << 16) |
431 ((size_t)in[2] << 8) |
432 ((size_t)in[3]);
433 if (in_len != len - 4) {
434 OPENSSL_PUT_ERROR(BN, BN_R_BAD_ENCODING);
435 return NULL;
436 }
437
438 int out_is_alloced = 0;
439 if (out == NULL) {
440 out = BN_new();
441 if (out == NULL) {
442 OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE);
443 return NULL;
444 }
445 out_is_alloced = 1;
446 }
447
448 if (in_len == 0) {
449 BN_zero(out);
450 return out;
451 }
452
453 in += 4;
454 if (BN_bin2bn(in, in_len, out) == NULL) {
455 if (out_is_alloced) {
456 BN_free(out);
457 }
458 return NULL;
459 }
460 out->neg = ((*in) & 0x80) != 0;
461 if (out->neg) {
462 BN_clear_bit(out, BN_num_bits(out) - 1);
463 }
464 return out;
465 }
466