asn1/a_int.c: simplify asn1_put_uint64.
[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     *pr = 0;
206     if (b == NULL)
207         return 0;
208     for (r = 0, i = 0; i < blen; i++) {
209         r <<= 8;
210         r |= b[i];
211     }
212     *pr = r;
213     return 1;
214 }
215
216 /*
217  * Write uint64_t to big endian buffer and return offset to first
218  * written octet. In other words it returns offset in range from 0
219  * to 7, with 0 denoting 8 written octets and 7 - one.
220  */
221 static size_t asn1_put_uint64(unsigned char b[sizeof(uint64_t)], uint64_t r)
222 {
223     size_t off = sizeof(uint64_t);
224
225     do {
226         b[--off] = (unsigned char)r;
227     } while (r >>= 8);
228
229     return off;
230 }
231
232 /*
233  * Absolute value of INT64_MIN: we can't just use -INT64_MIN as it produces
234  * overflow warnings.
235  */
236
237 #define ABS_INT64_MIN \
238     ((uint64_t)INT64_MAX + (uint64_t)(-(INT64_MIN + INT64_MAX)))
239
240 /* signed version of asn1_get_uint64 */
241 static int asn1_get_int64(int64_t *pr, const unsigned char *b, size_t blen,
242                           int neg)
243 {
244     uint64_t r;
245     if (asn1_get_uint64(&r, b, blen) == 0)
246         return 0;
247     if (neg) {
248         if (r > ABS_INT64_MIN) {
249             ASN1err(ASN1_F_ASN1_GET_INT64, ASN1_R_TOO_SMALL);
250             return 0;
251         }
252         *pr = 0 - (uint64_t)r;
253     } else {
254         if (r > INT64_MAX) {
255             ASN1err(ASN1_F_ASN1_GET_INT64, ASN1_R_TOO_LARGE);
256             return 0;
257         }
258         *pr = (int64_t)r;
259     }
260     return 1;
261 }
262
263 /* Convert ASN1 INTEGER content octets to ASN1_INTEGER structure */
264 ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **a, const unsigned char **pp,
265                                long len)
266 {
267     ASN1_INTEGER *ret = NULL;
268     size_t r;
269     int neg;
270
271     r = c2i_ibuf(NULL, NULL, *pp, len);
272
273     if (r == 0)
274         return NULL;
275
276     if ((a == NULL) || ((*a) == NULL)) {
277         ret = ASN1_INTEGER_new();
278         if (ret == NULL)
279             return NULL;
280         ret->type = V_ASN1_INTEGER;
281     } else
282         ret = *a;
283
284     if (ASN1_STRING_set(ret, NULL, r) == 0)
285         goto err;
286
287     c2i_ibuf(ret->data, &neg, *pp, len);
288
289     if (neg)
290         ret->type |= V_ASN1_NEG;
291
292     *pp += len;
293     if (a != NULL)
294         (*a) = ret;
295     return ret;
296  err:
297     ASN1err(ASN1_F_C2I_ASN1_INTEGER, ERR_R_MALLOC_FAILURE);
298     if ((a == NULL) || (*a != ret))
299         ASN1_INTEGER_free(ret);
300     return NULL;
301 }
302
303 static int asn1_string_get_int64(int64_t *pr, const ASN1_STRING *a, int itype)
304 {
305     if (a == NULL) {
306         ASN1err(ASN1_F_ASN1_STRING_GET_INT64, ERR_R_PASSED_NULL_PARAMETER);
307         return 0;
308     }
309     if ((a->type & ~V_ASN1_NEG) != itype) {
310         ASN1err(ASN1_F_ASN1_STRING_GET_INT64, ASN1_R_WRONG_INTEGER_TYPE);
311         return 0;
312     }
313     return asn1_get_int64(pr, a->data, a->length, a->type & V_ASN1_NEG);
314 }
315
316 static int asn1_string_set_int64(ASN1_STRING *a, int64_t r, int itype)
317 {
318     unsigned char tbuf[sizeof(r)];
319     size_t off;
320
321     a->type = itype;
322     if (r < 0) {
323         off = asn1_put_uint64(tbuf, -r);
324         a->type |= V_ASN1_NEG;
325     } else {
326         off = asn1_put_uint64(tbuf, r);
327         a->type &= ~V_ASN1_NEG;
328     }
329     return ASN1_STRING_set(a, tbuf + off, sizeof(tbuf) - off);
330 }
331
332 static int asn1_string_get_uint64(uint64_t *pr, const ASN1_STRING *a,
333                                   int itype)
334 {
335     if (a == NULL) {
336         ASN1err(ASN1_F_ASN1_STRING_GET_UINT64, ERR_R_PASSED_NULL_PARAMETER);
337         return 0;
338     }
339     if ((a->type & ~V_ASN1_NEG) != itype) {
340         ASN1err(ASN1_F_ASN1_STRING_GET_UINT64, ASN1_R_WRONG_INTEGER_TYPE);
341         return 0;
342     }
343     if (a->type & V_ASN1_NEG) {
344         ASN1err(ASN1_F_ASN1_STRING_GET_UINT64, ASN1_R_ILLEGAL_NEGATIVE_VALUE);
345         return 0;
346     }
347     return asn1_get_uint64(pr, a->data, a->length);
348 }
349
350 static int asn1_string_set_uint64(ASN1_STRING *a, uint64_t r, int itype)
351 {
352     unsigned char tbuf[sizeof(r)];
353     size_t off;
354
355     a->type = itype;
356     off = asn1_put_uint64(tbuf, r);
357     return ASN1_STRING_set(a, tbuf + off, sizeof(tbuf) - off);
358 }
359
360 /*
361  * This is a version of d2i_ASN1_INTEGER that ignores the sign bit of ASN1
362  * integers: some broken software can encode a positive INTEGER with its MSB
363  * set as negative (it doesn't add a padding zero).
364  */
365
366 ASN1_INTEGER *d2i_ASN1_UINTEGER(ASN1_INTEGER **a, const unsigned char **pp,
367                                 long length)
368 {
369     ASN1_INTEGER *ret = NULL;
370     const unsigned char *p;
371     unsigned char *s;
372     long len;
373     int inf, tag, xclass;
374     int i;
375
376     if ((a == NULL) || ((*a) == NULL)) {
377         if ((ret = ASN1_INTEGER_new()) == NULL)
378             return (NULL);
379         ret->type = V_ASN1_INTEGER;
380     } else
381         ret = (*a);
382
383     p = *pp;
384     inf = ASN1_get_object(&p, &len, &tag, &xclass, length);
385     if (inf & 0x80) {
386         i = ASN1_R_BAD_OBJECT_HEADER;
387         goto err;
388     }
389
390     if (tag != V_ASN1_INTEGER) {
391         i = ASN1_R_EXPECTING_AN_INTEGER;
392         goto err;
393     }
394
395     /*
396      * We must OPENSSL_malloc stuff, even for 0 bytes otherwise it signifies
397      * a missing NULL parameter.
398      */
399     s = OPENSSL_malloc((int)len + 1);
400     if (s == NULL) {
401         i = ERR_R_MALLOC_FAILURE;
402         goto err;
403     }
404     ret->type = V_ASN1_INTEGER;
405     if (len) {
406         if ((*p == 0) && (len != 1)) {
407             p++;
408             len--;
409         }
410         memcpy(s, p, (int)len);
411         p += len;
412     }
413
414     OPENSSL_free(ret->data);
415     ret->data = s;
416     ret->length = (int)len;
417     if (a != NULL)
418         (*a) = ret;
419     *pp = p;
420     return (ret);
421  err:
422     ASN1err(ASN1_F_D2I_ASN1_UINTEGER, i);
423     if ((a == NULL) || (*a != ret))
424         ASN1_INTEGER_free(ret);
425     return (NULL);
426 }
427
428 static ASN1_STRING *bn_to_asn1_string(const BIGNUM *bn, ASN1_STRING *ai,
429                                       int atype)
430 {
431     ASN1_INTEGER *ret;
432     int len;
433
434     if (ai == NULL) {
435         ret = ASN1_STRING_type_new(atype);
436     } else {
437         ret = ai;
438         ret->type = atype;
439     }
440
441     if (ret == NULL) {
442         ASN1err(ASN1_F_BN_TO_ASN1_STRING, ERR_R_NESTED_ASN1_ERROR);
443         goto err;
444     }
445
446     if (BN_is_negative(bn) && !BN_is_zero(bn))
447         ret->type |= V_ASN1_NEG_INTEGER;
448
449     len = BN_num_bytes(bn);
450
451     if (len == 0)
452         len = 1;
453
454     if (ASN1_STRING_set(ret, NULL, len) == 0) {
455         ASN1err(ASN1_F_BN_TO_ASN1_STRING, ERR_R_MALLOC_FAILURE);
456         goto err;
457     }
458
459     /* Correct zero case */
460     if (BN_is_zero(bn))
461         ret->data[0] = 0;
462     else
463         len = BN_bn2bin(bn, ret->data);
464     ret->length = len;
465     return ret;
466  err:
467     if (ret != ai)
468         ASN1_INTEGER_free(ret);
469     return (NULL);
470 }
471
472 static BIGNUM *asn1_string_to_bn(const ASN1_INTEGER *ai, BIGNUM *bn,
473                                  int itype)
474 {
475     BIGNUM *ret;
476
477     if ((ai->type & ~V_ASN1_NEG) != itype) {
478         ASN1err(ASN1_F_ASN1_STRING_TO_BN, ASN1_R_WRONG_INTEGER_TYPE);
479         return NULL;
480     }
481
482     ret = BN_bin2bn(ai->data, ai->length, bn);
483     if (ret == NULL) {
484         ASN1err(ASN1_F_ASN1_STRING_TO_BN, ASN1_R_BN_LIB);
485         return NULL;
486     }
487     if (ai->type & V_ASN1_NEG)
488         BN_set_negative(ret, 1);
489     return ret;
490 }
491
492 int ASN1_INTEGER_get_int64(int64_t *pr, const ASN1_INTEGER *a)
493 {
494     return asn1_string_get_int64(pr, a, V_ASN1_INTEGER);
495 }
496
497 int ASN1_INTEGER_set_int64(ASN1_INTEGER *a, int64_t r)
498 {
499     return asn1_string_set_int64(a, r, V_ASN1_INTEGER);
500 }
501
502 int ASN1_INTEGER_get_uint64(uint64_t *pr, const ASN1_INTEGER *a)
503 {
504     return asn1_string_get_uint64(pr, a, V_ASN1_INTEGER);
505 }
506
507 int ASN1_INTEGER_set_uint64(ASN1_INTEGER *a, uint64_t r)
508 {
509     return asn1_string_set_uint64(a, r, V_ASN1_INTEGER);
510 }
511
512 int ASN1_INTEGER_set(ASN1_INTEGER *a, long v)
513 {
514     return ASN1_INTEGER_set_int64(a, v);
515 }
516
517 long ASN1_INTEGER_get(const ASN1_INTEGER *a)
518 {
519     int i;
520     int64_t r;
521     if (a == NULL)
522         return 0;
523     i = ASN1_INTEGER_get_int64(&r, a);
524     if (i == 0)
525         return -1;
526     if (r > LONG_MAX || r < LONG_MIN)
527         return -1;
528     return (long)r;
529 }
530
531 ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai)
532 {
533     return bn_to_asn1_string(bn, ai, V_ASN1_INTEGER);
534 }
535
536 BIGNUM *ASN1_INTEGER_to_BN(const ASN1_INTEGER *ai, BIGNUM *bn)
537 {
538     return asn1_string_to_bn(ai, bn, V_ASN1_INTEGER);
539 }
540
541 int ASN1_ENUMERATED_get_int64(int64_t *pr, const ASN1_ENUMERATED *a)
542 {
543     return asn1_string_get_int64(pr, a, V_ASN1_ENUMERATED);
544 }
545
546 int ASN1_ENUMERATED_set_int64(ASN1_ENUMERATED *a, int64_t r)
547 {
548     return asn1_string_set_int64(a, r, V_ASN1_ENUMERATED);
549 }
550
551 int ASN1_ENUMERATED_set(ASN1_ENUMERATED *a, long v)
552 {
553     return ASN1_ENUMERATED_set_int64(a, v);
554 }
555
556 long ASN1_ENUMERATED_get(const ASN1_ENUMERATED *a)
557 {
558     int i;
559     int64_t r;
560     if (a == NULL)
561         return 0;
562     if ((a->type & ~V_ASN1_NEG) != V_ASN1_ENUMERATED)
563         return -1;
564     if (a->length > (int)sizeof(long))
565         return 0xffffffffL;
566     i = ASN1_ENUMERATED_get_int64(&r, a);
567     if (i == 0)
568         return -1;
569     if (r > LONG_MAX || r < LONG_MIN)
570         return -1;
571     return (long)r;
572 }
573
574 ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(const BIGNUM *bn, ASN1_ENUMERATED *ai)
575 {
576     return bn_to_asn1_string(bn, ai, V_ASN1_ENUMERATED);
577 }
578
579 BIGNUM *ASN1_ENUMERATED_to_BN(const ASN1_ENUMERATED *ai, BIGNUM *bn)
580 {
581     return asn1_string_to_bn(ai, bn, V_ASN1_ENUMERATED);
582 }
583
584 /* Internal functions used by x_int64.c */
585 int c2i_uint64_int(uint64_t *ret, int *neg, const unsigned char **pp, long len)
586 {
587     unsigned char buf[sizeof(uint64_t)];
588     size_t buflen;
589
590     buflen = c2i_ibuf(NULL, NULL, *pp, len);
591     if (buflen == 0)
592         return 0;
593     if (buflen > sizeof(uint64_t)) {
594         ASN1err(ASN1_F_C2I_UINT64_INT, ASN1_R_TOO_LARGE);
595         return 0;
596     }
597     (void)c2i_ibuf(buf, neg, *pp, len);
598     return asn1_get_uint64(ret, buf, buflen);
599 }
600
601 int i2c_uint64_int(unsigned char *p, uint64_t r, int neg)
602 {
603     unsigned char buf[sizeof(uint64_t)];
604     size_t off;
605
606     off = asn1_put_uint64(buf, r);
607     return i2c_ibuf(buf + off, sizeof(buf) - off, neg, &p);
608 }
609