asn1/a_int.c: clean up asn1_get_int64.
[openssl.git] / crypto / asn1 / a_int.c
1 /*
2  * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include "internal/cryptlib.h"
12 #include "internal/numbers.h"
13 #include <limits.h>
14 #include <openssl/asn1.h>
15 #include <openssl/bn.h>
16 #include "asn1_locl.h"
17
18 ASN1_INTEGER *ASN1_INTEGER_dup(const ASN1_INTEGER *x)
19 {
20     return ASN1_STRING_dup(x);
21 }
22
23 int ASN1_INTEGER_cmp(const ASN1_INTEGER *x, const ASN1_INTEGER *y)
24 {
25     int neg, ret;
26     /* Compare signs */
27     neg = x->type & V_ASN1_NEG;
28     if (neg != (y->type & V_ASN1_NEG)) {
29         if (neg)
30             return -1;
31         else
32             return 1;
33     }
34
35     ret = ASN1_STRING_cmp(x, y);
36
37     if (neg)
38         return -ret;
39     else
40         return ret;
41 }
42
43 /*-
44  * This converts a big endian buffer and sign into its content encoding.
45  * This is used for INTEGER and ENUMERATED types.
46  * The internal representation is an ASN1_STRING whose data is a big endian
47  * representation of the value, ignoring the sign. The sign is determined by
48  * the type: if type & V_ASN1_NEG is true it is negative, otherwise positive.
49  *
50  * Positive integers are no problem: they are almost the same as the DER
51  * encoding, except if the first byte is >= 0x80 we need to add a zero pad.
52  *
53  * Negative integers are a bit trickier...
54  * The DER representation of negative integers is in 2s complement form.
55  * The internal form is converted by complementing each octet and finally
56  * adding one to the result. This can be done less messily with a little trick.
57  * If the internal form has trailing zeroes then they will become FF by the
58  * complement and 0 by the add one (due to carry) so just copy as many trailing
59  * zeros to the destination as there are in the source. The carry will add one
60  * to the last none zero octet: so complement this octet and add one and finally
61  * complement any left over until you get to the start of the string.
62  *
63  * Padding is a little trickier too. If the first bytes is > 0x80 then we pad
64  * with 0xff. However if the first byte is 0x80 and one of the following bytes
65  * is non-zero we pad with 0xff. The reason for this distinction is that 0x80
66  * followed by optional zeros isn't padded.
67  */
68
69 /*
70  * If |pad| is zero, the operation is effectively reduced to memcpy,
71  * and if |pad| is 0xff, then it performs two's complement, ~dst + 1.
72  * Note that in latter case sequence of zeros yields itself, and so
73  * does 0x80 followed by any number of zeros. These properties are
74  * used elsewhere below...
75  */
76 static void twos_complement(unsigned char *dst, const unsigned char *src,
77                             size_t len, unsigned char pad)
78 {
79     unsigned int carry = pad & 1;
80
81     /* Begin at the end of the encoding */
82     dst += len;
83     src += len;
84     /* two's complement value: ~value + 1 */
85     while (len-- != 0) {
86         *(--dst) = (unsigned char)(carry += *(--src) ^ pad);
87         carry >>= 8;
88     }
89 }
90
91 static size_t i2c_ibuf(const unsigned char *b, size_t blen, int neg,
92                        unsigned char **pp)
93 {
94     unsigned int pad = 0;
95     size_t ret, i;
96     unsigned char *p, pb = 0;
97
98     if (b != NULL && blen) {
99         ret = blen;
100         i = b[0];
101         if (!neg && (i > 127)) {
102             pad = 1;
103             pb = 0;
104         } else if (neg) {
105             pb = 0xFF;
106             if (i > 128) {
107                 pad = 1;
108             } else if (i == 128) {
109                 /*
110                  * Special case [of minimal negative for given length]:
111                  * if any other bytes non zero we pad, otherwise we don't.
112                  */
113                 for (pad = 0, i = 1; i < blen; i++)
114                     pad |= b[i];
115                 pb = pad != 0 ? 0xffU : 0;
116                 pad = pb & 1;
117             }
118         }
119         ret += pad;
120     } else {
121         ret = 1;
122         blen = 0;   /* reduce '(b == NULL || blen == 0)' to '(blen == 0)' */
123     }
124
125     if (pp == NULL || (p = *pp) == NULL)
126         return ret;
127
128     /*
129      * This magically handles all corner cases, such as '(b == NULL ||
130      * blen == 0)', non-negative value, "negative" zero, 0x80 followed
131      * by any number of zeros...
132      */
133     *p = pb;
134     p += pad;       /* yes, p[0] can be written twice, but it's little
135                      * price to pay for eliminated branches */
136     twos_complement(p, b, blen, pb);
137
138     *pp += ret;
139     return ret;
140 }
141
142 /*
143  * convert content octets into a big endian buffer. Returns the length
144  * of buffer or 0 on error: for malformed INTEGER. If output buffer is
145  * NULL just return length.
146  */
147
148 static size_t c2i_ibuf(unsigned char *b, int *pneg,
149                        const unsigned char *p, size_t plen)
150 {
151     int neg, pad;
152     /* Zero content length is illegal */
153     if (plen == 0) {
154         ASN1err(ASN1_F_C2I_IBUF, ASN1_R_ILLEGAL_ZERO_CONTENT);
155         return 0;
156     }
157     neg = p[0] & 0x80;
158     if (pneg)
159         *pneg = neg;
160     /* Handle common case where length is 1 octet separately */
161     if (plen == 1) {
162         if (b != NULL) {
163             if (neg)
164                 b[0] = (p[0] ^ 0xFF) + 1;
165             else
166                 b[0] = p[0];
167         }
168         return 1;
169     }
170     if (p[0] == 0 || p[0] == 0xFF)
171         pad = 1;
172     else
173         pad = 0;
174     /* reject illegal padding: first two octets MSB can't match */
175     if (pad && (neg == (p[1] & 0x80))) {
176         ASN1err(ASN1_F_C2I_IBUF, ASN1_R_ILLEGAL_PADDING);
177         return 0;
178     }
179
180     /* skip over pad */
181     p += pad;
182     plen -= pad;
183
184     if (b != NULL)
185         twos_complement(b, p, plen, neg ? 0xffU : 0);
186
187     return plen;
188 }
189
190 int i2c_ASN1_INTEGER(ASN1_INTEGER *a, unsigned char **pp)
191 {
192     return i2c_ibuf(a->data, a->length, a->type & V_ASN1_NEG, pp);
193 }
194
195 /* Convert big endian buffer into uint64_t, return 0 on error */
196 static int asn1_get_uint64(uint64_t *pr, const unsigned char *b, size_t blen)
197 {
198     size_t i;
199     uint64_t r;
200
201     if (blen > sizeof(*pr)) {
202         ASN1err(ASN1_F_ASN1_GET_UINT64, ASN1_R_TOO_LARGE);
203         return 0;
204     }
205     if (b == NULL)
206         return 0;
207     for (r = 0, i = 0; i < blen; i++) {
208         r <<= 8;
209         r |= b[i];
210     }
211     *pr = r;
212     return 1;
213 }
214
215 /*
216  * Write uint64_t to big endian buffer and return offset to first
217  * written octet. In other words it returns offset in range from 0
218  * to 7, with 0 denoting 8 written octets and 7 - one.
219  */
220 static size_t asn1_put_uint64(unsigned char b[sizeof(uint64_t)], uint64_t r)
221 {
222     size_t off = sizeof(uint64_t);
223
224     do {
225         b[--off] = (unsigned char)r;
226     } while (r >>= 8);
227
228     return off;
229 }
230
231 /*
232  * Absolute value of INT64_MIN: we can't just use -INT64_MIN as gcc produces
233  * overflow warnings.
234  */
235 #define ABS_INT64_MIN ((uint64_t)INT64_MAX + (-(INT64_MIN + INT64_MAX)))
236
237 /* signed version of asn1_get_uint64 */
238 static int asn1_get_int64(int64_t *pr, const unsigned char *b, size_t blen,
239                           int neg)
240 {
241     uint64_t r;
242     if (asn1_get_uint64(&r, b, blen) == 0)
243         return 0;
244     if (neg) {
245         if (r <= INT64_MAX) {
246             /* Most significant bit is guaranteed to be clear, negation
247              * is guaranteed to be meaningful in platform-neutral sense. */
248             *pr = -(int64_t)r;
249         } else if (r == ABS_INT64_MIN) {
250             /* This never happens if INT64_MAX == ABS_INT64_MIN, e.g.
251              * on ones'-complement system. */
252             *pr = (int64_t)(0 - r);
253         } else {
254             ASN1err(ASN1_F_ASN1_GET_INT64, ASN1_R_TOO_SMALL);
255             return 0;
256         }
257     } else {
258         if (r <= INT64_MAX) {
259             *pr = (int64_t)r;
260         } else {
261             ASN1err(ASN1_F_ASN1_GET_INT64, ASN1_R_TOO_LARGE);
262             return 0;
263         }
264     }
265     return 1;
266 }
267
268 /* Convert ASN1 INTEGER content octets to ASN1_INTEGER structure */
269 ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **a, const unsigned char **pp,
270                                long len)
271 {
272     ASN1_INTEGER *ret = NULL;
273     size_t r;
274     int neg;
275
276     r = c2i_ibuf(NULL, NULL, *pp, len);
277
278     if (r == 0)
279         return NULL;
280
281     if ((a == NULL) || ((*a) == NULL)) {
282         ret = ASN1_INTEGER_new();
283         if (ret == NULL)
284             return NULL;
285         ret->type = V_ASN1_INTEGER;
286     } else
287         ret = *a;
288
289     if (ASN1_STRING_set(ret, NULL, r) == 0)
290         goto err;
291
292     c2i_ibuf(ret->data, &neg, *pp, len);
293
294     if (neg)
295         ret->type |= V_ASN1_NEG;
296
297     *pp += len;
298     if (a != NULL)
299         (*a) = ret;
300     return ret;
301  err:
302     ASN1err(ASN1_F_C2I_ASN1_INTEGER, ERR_R_MALLOC_FAILURE);
303     if ((a == NULL) || (*a != ret))
304         ASN1_INTEGER_free(ret);
305     return NULL;
306 }
307
308 static int asn1_string_get_int64(int64_t *pr, const ASN1_STRING *a, int itype)
309 {
310     if (a == NULL) {
311         ASN1err(ASN1_F_ASN1_STRING_GET_INT64, ERR_R_PASSED_NULL_PARAMETER);
312         return 0;
313     }
314     if ((a->type & ~V_ASN1_NEG) != itype) {
315         ASN1err(ASN1_F_ASN1_STRING_GET_INT64, ASN1_R_WRONG_INTEGER_TYPE);
316         return 0;
317     }
318     return asn1_get_int64(pr, a->data, a->length, a->type & V_ASN1_NEG);
319 }
320
321 static int asn1_string_set_int64(ASN1_STRING *a, int64_t r, int itype)
322 {
323     unsigned char tbuf[sizeof(r)];
324     size_t off;
325
326     a->type = itype;
327     if (r < 0) {
328         /* Most obvious '-r' triggers undefined behaviour for most
329          * common INT64_MIN. Even though below '0 - (uint64_t)r' can
330          * appear two's-complement centric, it does produce correct/
331          * expected result even on one's-complement. This is because
332          * cast to unsigned has to change bit pattern... */
333         off = asn1_put_uint64(tbuf, 0 - (uint64_t)r);
334         a->type |= V_ASN1_NEG;
335     } else {
336         off = asn1_put_uint64(tbuf, r);
337         a->type &= ~V_ASN1_NEG;
338     }
339     return ASN1_STRING_set(a, tbuf + off, sizeof(tbuf) - off);
340 }
341
342 static int asn1_string_get_uint64(uint64_t *pr, const ASN1_STRING *a,
343                                   int itype)
344 {
345     if (a == NULL) {
346         ASN1err(ASN1_F_ASN1_STRING_GET_UINT64, ERR_R_PASSED_NULL_PARAMETER);
347         return 0;
348     }
349     if ((a->type & ~V_ASN1_NEG) != itype) {
350         ASN1err(ASN1_F_ASN1_STRING_GET_UINT64, ASN1_R_WRONG_INTEGER_TYPE);
351         return 0;
352     }
353     if (a->type & V_ASN1_NEG) {
354         ASN1err(ASN1_F_ASN1_STRING_GET_UINT64, ASN1_R_ILLEGAL_NEGATIVE_VALUE);
355         return 0;
356     }
357     return asn1_get_uint64(pr, a->data, a->length);
358 }
359
360 static int asn1_string_set_uint64(ASN1_STRING *a, uint64_t r, int itype)
361 {
362     unsigned char tbuf[sizeof(r)];
363     size_t off;
364
365     a->type = itype;
366     off = asn1_put_uint64(tbuf, r);
367     return ASN1_STRING_set(a, tbuf + off, sizeof(tbuf) - off);
368 }
369
370 /*
371  * This is a version of d2i_ASN1_INTEGER that ignores the sign bit of ASN1
372  * integers: some broken software can encode a positive INTEGER with its MSB
373  * set as negative (it doesn't add a padding zero).
374  */
375
376 ASN1_INTEGER *d2i_ASN1_UINTEGER(ASN1_INTEGER **a, const unsigned char **pp,
377                                 long length)
378 {
379     ASN1_INTEGER *ret = NULL;
380     const unsigned char *p;
381     unsigned char *s;
382     long len;
383     int inf, tag, xclass;
384     int i;
385
386     if ((a == NULL) || ((*a) == NULL)) {
387         if ((ret = ASN1_INTEGER_new()) == NULL)
388             return (NULL);
389         ret->type = V_ASN1_INTEGER;
390     } else
391         ret = (*a);
392
393     p = *pp;
394     inf = ASN1_get_object(&p, &len, &tag, &xclass, length);
395     if (inf & 0x80) {
396         i = ASN1_R_BAD_OBJECT_HEADER;
397         goto err;
398     }
399
400     if (tag != V_ASN1_INTEGER) {
401         i = ASN1_R_EXPECTING_AN_INTEGER;
402         goto err;
403     }
404
405     /*
406      * We must OPENSSL_malloc stuff, even for 0 bytes otherwise it signifies
407      * a missing NULL parameter.
408      */
409     s = OPENSSL_malloc((int)len + 1);
410     if (s == NULL) {
411         i = ERR_R_MALLOC_FAILURE;
412         goto err;
413     }
414     ret->type = V_ASN1_INTEGER;
415     if (len) {
416         if ((*p == 0) && (len != 1)) {
417             p++;
418             len--;
419         }
420         memcpy(s, p, (int)len);
421         p += len;
422     }
423
424     OPENSSL_free(ret->data);
425     ret->data = s;
426     ret->length = (int)len;
427     if (a != NULL)
428         (*a) = ret;
429     *pp = p;
430     return (ret);
431  err:
432     ASN1err(ASN1_F_D2I_ASN1_UINTEGER, i);
433     if ((a == NULL) || (*a != ret))
434         ASN1_INTEGER_free(ret);
435     return (NULL);
436 }
437
438 static ASN1_STRING *bn_to_asn1_string(const BIGNUM *bn, ASN1_STRING *ai,
439                                       int atype)
440 {
441     ASN1_INTEGER *ret;
442     int len;
443
444     if (ai == NULL) {
445         ret = ASN1_STRING_type_new(atype);
446     } else {
447         ret = ai;
448         ret->type = atype;
449     }
450
451     if (ret == NULL) {
452         ASN1err(ASN1_F_BN_TO_ASN1_STRING, ERR_R_NESTED_ASN1_ERROR);
453         goto err;
454     }
455
456     if (BN_is_negative(bn) && !BN_is_zero(bn))
457         ret->type |= V_ASN1_NEG_INTEGER;
458
459     len = BN_num_bytes(bn);
460
461     if (len == 0)
462         len = 1;
463
464     if (ASN1_STRING_set(ret, NULL, len) == 0) {
465         ASN1err(ASN1_F_BN_TO_ASN1_STRING, ERR_R_MALLOC_FAILURE);
466         goto err;
467     }
468
469     /* Correct zero case */
470     if (BN_is_zero(bn))
471         ret->data[0] = 0;
472     else
473         len = BN_bn2bin(bn, ret->data);
474     ret->length = len;
475     return ret;
476  err:
477     if (ret != ai)
478         ASN1_INTEGER_free(ret);
479     return (NULL);
480 }
481
482 static BIGNUM *asn1_string_to_bn(const ASN1_INTEGER *ai, BIGNUM *bn,
483                                  int itype)
484 {
485     BIGNUM *ret;
486
487     if ((ai->type & ~V_ASN1_NEG) != itype) {
488         ASN1err(ASN1_F_ASN1_STRING_TO_BN, ASN1_R_WRONG_INTEGER_TYPE);
489         return NULL;
490     }
491
492     ret = BN_bin2bn(ai->data, ai->length, bn);
493     if (ret == NULL) {
494         ASN1err(ASN1_F_ASN1_STRING_TO_BN, ASN1_R_BN_LIB);
495         return NULL;
496     }
497     if (ai->type & V_ASN1_NEG)
498         BN_set_negative(ret, 1);
499     return ret;
500 }
501
502 int ASN1_INTEGER_get_int64(int64_t *pr, const ASN1_INTEGER *a)
503 {
504     return asn1_string_get_int64(pr, a, V_ASN1_INTEGER);
505 }
506
507 int ASN1_INTEGER_set_int64(ASN1_INTEGER *a, int64_t r)
508 {
509     return asn1_string_set_int64(a, r, V_ASN1_INTEGER);
510 }
511
512 int ASN1_INTEGER_get_uint64(uint64_t *pr, const ASN1_INTEGER *a)
513 {
514     return asn1_string_get_uint64(pr, a, V_ASN1_INTEGER);
515 }
516
517 int ASN1_INTEGER_set_uint64(ASN1_INTEGER *a, uint64_t r)
518 {
519     return asn1_string_set_uint64(a, r, V_ASN1_INTEGER);
520 }
521
522 int ASN1_INTEGER_set(ASN1_INTEGER *a, long v)
523 {
524     return ASN1_INTEGER_set_int64(a, v);
525 }
526
527 long ASN1_INTEGER_get(const ASN1_INTEGER *a)
528 {
529     int i;
530     int64_t r;
531     if (a == NULL)
532         return 0;
533     i = ASN1_INTEGER_get_int64(&r, a);
534     if (i == 0)
535         return -1;
536     if (r > LONG_MAX || r < LONG_MIN)
537         return -1;
538     return (long)r;
539 }
540
541 ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai)
542 {
543     return bn_to_asn1_string(bn, ai, V_ASN1_INTEGER);
544 }
545
546 BIGNUM *ASN1_INTEGER_to_BN(const ASN1_INTEGER *ai, BIGNUM *bn)
547 {
548     return asn1_string_to_bn(ai, bn, V_ASN1_INTEGER);
549 }
550
551 int ASN1_ENUMERATED_get_int64(int64_t *pr, const ASN1_ENUMERATED *a)
552 {
553     return asn1_string_get_int64(pr, a, V_ASN1_ENUMERATED);
554 }
555
556 int ASN1_ENUMERATED_set_int64(ASN1_ENUMERATED *a, int64_t r)
557 {
558     return asn1_string_set_int64(a, r, V_ASN1_ENUMERATED);
559 }
560
561 int ASN1_ENUMERATED_set(ASN1_ENUMERATED *a, long v)
562 {
563     return ASN1_ENUMERATED_set_int64(a, v);
564 }
565
566 long ASN1_ENUMERATED_get(const ASN1_ENUMERATED *a)
567 {
568     int i;
569     int64_t r;
570     if (a == NULL)
571         return 0;
572     if ((a->type & ~V_ASN1_NEG) != V_ASN1_ENUMERATED)
573         return -1;
574     if (a->length > (int)sizeof(long))
575         return 0xffffffffL;
576     i = ASN1_ENUMERATED_get_int64(&r, a);
577     if (i == 0)
578         return -1;
579     if (r > LONG_MAX || r < LONG_MIN)
580         return -1;
581     return (long)r;
582 }
583
584 ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(const BIGNUM *bn, ASN1_ENUMERATED *ai)
585 {
586     return bn_to_asn1_string(bn, ai, V_ASN1_ENUMERATED);
587 }
588
589 BIGNUM *ASN1_ENUMERATED_to_BN(const ASN1_ENUMERATED *ai, BIGNUM *bn)
590 {
591     return asn1_string_to_bn(ai, bn, V_ASN1_ENUMERATED);
592 }
593
594 /* Internal functions used by x_int64.c */
595 int c2i_uint64_int(uint64_t *ret, int *neg, const unsigned char **pp, long len)
596 {
597     unsigned char buf[sizeof(uint64_t)];
598     size_t buflen;
599
600     buflen = c2i_ibuf(NULL, NULL, *pp, len);
601     if (buflen == 0)
602         return 0;
603     if (buflen > sizeof(uint64_t)) {
604         ASN1err(ASN1_F_C2I_UINT64_INT, ASN1_R_TOO_LARGE);
605         return 0;
606     }
607     (void)c2i_ibuf(buf, neg, *pp, len);
608     return asn1_get_uint64(ret, buf, buflen);
609 }
610
611 int i2c_uint64_int(unsigned char *p, uint64_t r, int neg)
612 {
613     unsigned char buf[sizeof(uint64_t)];
614     size_t off;
615
616     off = asn1_put_uint64(buf, r);
617     return i2c_ibuf(buf + off, sizeof(buf) - off, neg, &p);
618 }
619