Encode b == NULL or blen == 0 as zero.
[openssl.git] / crypto / asn1 / a_int.c
1 /* crypto/asn1/a_int.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58
59 #include <stdio.h>
60 #include "internal/cryptlib.h"
61 #include "internal/numbers.h"
62 #include <limits.h>
63 #include <openssl/asn1.h>
64 #include <openssl/bn.h>
65 #include "asn1_locl.h"
66
67 ASN1_INTEGER *ASN1_INTEGER_dup(const ASN1_INTEGER *x)
68 {
69     return ASN1_STRING_dup(x);
70 }
71
72 int ASN1_INTEGER_cmp(const ASN1_INTEGER *x, const ASN1_INTEGER *y)
73 {
74     int neg, ret;
75     /* Compare signs */
76     neg = x->type & V_ASN1_NEG;
77     if (neg != (y->type & V_ASN1_NEG)) {
78         if (neg)
79             return -1;
80         else
81             return 1;
82     }
83
84     ret = ASN1_STRING_cmp(x, y);
85
86     if (neg)
87         return -ret;
88     else
89         return ret;
90 }
91
92 /*-
93  * This converts a big endian buffer and sign into its content encoding.
94  * This is used for INTEGER and ENUMERATED types.
95  * The internal representation is an ASN1_STRING whose data is a big endian
96  * representation of the value, ignoring the sign. The sign is determined by
97  * the type: if type & V_ASN1_NEG is true it is negative, otherwise positive.
98  *
99  * Positive integers are no problem: they are almost the same as the DER
100  * encoding, except if the first byte is >= 0x80 we need to add a zero pad.
101  *
102  * Negative integers are a bit trickier...
103  * The DER representation of negative integers is in 2s complement form.
104  * The internal form is converted by complementing each octet and finally
105  * adding one to the result. This can be done less messily with a little trick.
106  * If the internal form has trailing zeroes then they will become FF by the
107  * complement and 0 by the add one (due to carry) so just copy as many trailing
108  * zeros to the destination as there are in the source. The carry will add one
109  * to the last none zero octet: so complement this octet and add one and finally
110  * complement any left over until you get to the start of the string.
111  *
112  * Padding is a little trickier too. If the first bytes is > 0x80 then we pad
113  * with 0xff. However if the first byte is 0x80 and one of the following bytes
114  * is non-zero we pad with 0xff. The reason for this distinction is that 0x80
115  * followed by optional zeros isn't padded.
116  */
117
118 static size_t i2c_ibuf(const unsigned char *b, size_t blen, int neg,
119                        unsigned char **pp)
120 {
121     int pad = 0;
122     size_t ret, i;
123     unsigned char *p, pb = 0;
124     const unsigned char *n;
125
126     if (b == NULL || blen == 0)
127         ret = 1;
128     else {
129         ret = blen;
130         i = b[0];
131         if (ret == 1 && i == 0)
132             neg = 0;
133         if (!neg && (i > 127)) {
134             pad = 1;
135             pb = 0;
136         } else if (neg) {
137             if (i > 128) {
138                 pad = 1;
139                 pb = 0xFF;
140             } else if (i == 128) {
141                 /*
142                  * Special case: if any other bytes non zero we pad:
143                  * otherwise we don't.
144                  */
145                 for (i = 1; i < blen; i++)
146                     if (b[i]) {
147                         pad = 1;
148                         pb = 0xFF;
149                         break;
150                     }
151             }
152         }
153         ret += pad;
154     }
155     if (pp == NULL)
156         return ret;
157     p = *pp;
158
159     if (pad)
160         *(p++) = pb;
161     if (b == NULL || blen == 0)
162         *p = 0;
163     else if (!neg)
164         memcpy(p, b, blen);
165     else {
166         /* Begin at the end of the encoding */
167         n = b + blen - 1;
168         p += blen - 1;
169         i = blen;
170         /* Copy zeros to destination as long as source is zero */
171         while (!*n && i > 1) {
172             *(p--) = 0;
173             n--;
174             i--;
175         }
176         /* Complement and increment next octet */
177         *(p--) = ((*(n--)) ^ 0xff) + 1;
178         i--;
179         /* Complement any octets left */
180         for (; i > 0; i--)
181             *(p--) = *(n--) ^ 0xff;
182     }
183
184     *pp += ret;
185     return ret;
186 }
187
188 /*
189  * convert content octets into a big endian buffer. Returns the length
190  * of buffer or 0 on error: for malformed INTEGER. If output bufer is
191  * NULL just return length.
192  */
193
194 static size_t c2i_ibuf(unsigned char *b, int *pneg,
195                        const unsigned char *p, size_t plen)
196 {
197     size_t i;
198     int neg, pad;
199     /* Zero content length is illegal */
200     if (plen == 0) {
201         ASN1err(ASN1_F_C2I_IBUF, ASN1_R_ILLEGAL_ZERO_CONTENT);
202         return 0;
203     }
204     neg = p[0] & 0x80;
205     if (pneg)
206         *pneg = neg;
207     /* Handle common case where length is 1 octet separately */
208     if (plen == 1) {
209         if (b) {
210             if (neg)
211                 b[0] = (p[0] ^ 0xFF) + 1;
212             else
213                 b[0] = p[0];
214         }
215         return 1;
216     }
217     if (p[0] == 0 || p[0] == 0xFF)
218         pad = 1;
219     else
220         pad = 0;
221     /* reject illegal padding: first two octets MSB can't match */
222     if (pad && (neg == (p[1] & 0x80))) {
223         ASN1err(ASN1_F_C2I_IBUF, ASN1_R_ILLEGAL_PADDING);
224         return 0;
225     }
226     /* If positive just copy across */
227     if (neg == 0) {
228         if (b)
229             memcpy(b, p + pad, plen - pad);
230         return plen - pad;
231     }
232
233     if (neg && pad) {
234         /* check is any following octets are non zero */
235         for (i = 1; i < plen; i++) {
236             if (p[i] != 0)
237                 break;
238         }
239         /* if all bytes are zero handle as special case */
240         if (i == plen) {
241             if (b) {
242                 b[0] = 1;
243                 memset(b + 1, 0, plen - 1);
244             }
245             return plen;
246         }
247     }
248
249     plen -= pad;
250     /* Must be negative: calculate twos complement */
251     if (b) {
252         const unsigned char *from = p + plen - 1 + pad;
253         unsigned char *to = b + plen - 1;
254         i = plen;
255         while (*from == 0 && i) {
256             *to-- = 0;
257             i--;
258             from--;
259         }
260         *to-- = (*from-- ^ 0xff) + 1;
261         OPENSSL_assert(i != 0);
262         i--;
263         for (; i > 0; i--)
264             *to-- = *from-- ^ 0xff;
265     }
266     return plen;
267 }
268
269 int i2c_ASN1_INTEGER(ASN1_INTEGER *a, unsigned char **pp)
270 {
271     return i2c_ibuf(a->data, a->length, a->type & V_ASN1_NEG, pp);
272 }
273
274 /* Convert big endian buffer into uint64_t, return 0 on error */
275 static int asn1_get_uint64(uint64_t *pr, const unsigned char *b, size_t blen)
276 {
277     size_t i;
278     if (blen > sizeof(*pr)) {
279         ASN1err(ASN1_F_ASN1_GET_UINT64, ASN1_R_TOO_LARGE);
280         return 0;
281     }
282     *pr = 0;
283     if (b == NULL)
284         return 0;
285     for (i = 0; i < blen; i++) {
286         *pr <<= 8;
287         *pr |= b[i];
288     }
289     return 1;
290 }
291
292 static size_t asn1_put_uint64(unsigned char *b, uint64_t r)
293 {
294     if (r >= 0x100) {
295         unsigned char *p;
296         uint64_t rtmp = r;
297         size_t i = 0;
298
299         /* Work out how many bytes we need */
300         while (rtmp) {
301             rtmp >>= 8;
302             i++;
303         }
304
305         /* Copy from end to beginning */
306         p = b + i - 1;
307
308         do {
309             *p-- = r & 0xFF;
310             r >>= 8;
311         } while (p >= b);
312
313         return i;
314     }
315
316     b[0] = (unsigned char)r;
317     return 1;
318
319 }
320
321 /*
322  * Absolute value of INT64_MIN: we can't just use -INT64_MIN as it produces
323  * overflow warnings.
324  */
325
326 #define ABS_INT64_MIN \
327     ((uint64_t)INT64_MAX + (uint64_t)(-(INT64_MIN + INT64_MAX)))
328
329 /* signed version of asn1_get_uint64 */
330 static int asn1_get_int64(int64_t *pr, const unsigned char *b, size_t blen,
331                           int neg)
332 {
333     uint64_t r;
334     if (asn1_get_uint64(&r, b, blen) == 0)
335         return 0;
336     if (neg) {
337         if (r > ABS_INT64_MIN) {
338             ASN1err(ASN1_F_ASN1_GET_INT64, ASN1_R_TOO_SMALL);
339             return 0;
340         }
341         *pr = (int64_t)-r;
342     } else {
343         if (r > INT64_MAX) {
344             ASN1err(ASN1_F_ASN1_GET_INT64, ASN1_R_TOO_LARGE);
345             return 0;
346         }
347         *pr = (int64_t)r;
348     }
349     return 1;
350 }
351
352 /* Convert ASN1 INTEGER content octets to ASN1_INTEGER structure */
353 ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **a, const unsigned char **pp,
354                                long len)
355 {
356     ASN1_INTEGER *ret = NULL;
357     size_t r;
358     int neg;
359
360     r = c2i_ibuf(NULL, NULL, *pp, len);
361
362     if (r == 0)
363         return NULL;
364
365     if ((a == NULL) || ((*a) == NULL)) {
366         ret = ASN1_INTEGER_new();
367         if (ret == NULL)
368             return NULL;
369         ret->type = V_ASN1_INTEGER;
370     } else
371         ret = *a;
372
373     if (ASN1_STRING_set(ret, NULL, r) == 0)
374         goto err;
375
376     c2i_ibuf(ret->data, &neg, *pp, len);
377
378     if (neg)
379         ret->type |= V_ASN1_NEG;
380
381     *pp += len;
382     if (a != NULL)
383         (*a) = ret;
384     return ret;
385  err:
386     ASN1err(ASN1_F_C2I_ASN1_INTEGER, ERR_R_MALLOC_FAILURE);
387     if ((a == NULL) || (*a != ret))
388         ASN1_INTEGER_free(ret);
389     return NULL;
390 }
391
392 static int asn1_string_get_int64(int64_t *pr, const ASN1_STRING *a, int itype)
393 {
394     if (a == NULL) {
395         ASN1err(ASN1_F_ASN1_STRING_GET_INT64, ERR_R_PASSED_NULL_PARAMETER);
396         return 0;
397     }
398     if ((a->type & ~V_ASN1_NEG) != itype) {
399         ASN1err(ASN1_F_ASN1_STRING_GET_INT64, ASN1_R_WRONG_INTEGER_TYPE);
400         return 0;
401     }
402     return asn1_get_int64(pr, a->data, a->length, a->type & V_ASN1_NEG);
403 }
404
405 static int asn1_string_set_int64(ASN1_STRING *a, int64_t r, int itype)
406 {
407     unsigned char tbuf[sizeof(r)];
408     size_t l;
409     a->type = itype;
410     if (r < 0) {
411         l = asn1_put_uint64(tbuf, -r);
412         a->type |= V_ASN1_NEG;
413     } else {
414         l = asn1_put_uint64(tbuf, r);
415         a->type &= ~V_ASN1_NEG;
416     }
417     if (l == 0)
418         return 0;
419     return ASN1_STRING_set(a, tbuf, l);
420 }
421
422 static int asn1_string_get_uint64(uint64_t *pr, const ASN1_STRING *a,
423                                   int itype)
424 {
425     if (a == NULL) {
426         ASN1err(ASN1_F_ASN1_STRING_GET_UINT64, ERR_R_PASSED_NULL_PARAMETER);
427         return 0;
428     }
429     if ((a->type & ~V_ASN1_NEG) != itype) {
430         ASN1err(ASN1_F_ASN1_STRING_GET_UINT64, ASN1_R_WRONG_INTEGER_TYPE);
431         return 0;
432     }
433     if (a->type & V_ASN1_NEG) {
434         ASN1err(ASN1_F_ASN1_STRING_GET_UINT64, ASN1_R_ILLEGAL_NEGATIVE_VALUE);
435         return 0;
436     }
437     return asn1_get_uint64(pr, a->data, a->length);
438 }
439
440 static int asn1_string_set_uint64(ASN1_STRING *a, uint64_t r, int itype)
441 {
442     unsigned char tbuf[sizeof(r)];
443     size_t l;
444     a->type = itype;
445     l = asn1_put_uint64(tbuf, r);
446     if (l == 0)
447         return 0;
448     return ASN1_STRING_set(a, tbuf, l);
449 }
450
451 /*
452  * This is a version of d2i_ASN1_INTEGER that ignores the sign bit of ASN1
453  * integers: some broken software can encode a positive INTEGER with its MSB
454  * set as negative (it doesn't add a padding zero).
455  */
456
457 ASN1_INTEGER *d2i_ASN1_UINTEGER(ASN1_INTEGER **a, const unsigned char **pp,
458                                 long length)
459 {
460     ASN1_INTEGER *ret = NULL;
461     const unsigned char *p;
462     unsigned char *s;
463     long len;
464     int inf, tag, xclass;
465     int i;
466
467     if ((a == NULL) || ((*a) == NULL)) {
468         if ((ret = ASN1_INTEGER_new()) == NULL)
469             return (NULL);
470         ret->type = V_ASN1_INTEGER;
471     } else
472         ret = (*a);
473
474     p = *pp;
475     inf = ASN1_get_object(&p, &len, &tag, &xclass, length);
476     if (inf & 0x80) {
477         i = ASN1_R_BAD_OBJECT_HEADER;
478         goto err;
479     }
480
481     if (tag != V_ASN1_INTEGER) {
482         i = ASN1_R_EXPECTING_AN_INTEGER;
483         goto err;
484     }
485
486     /*
487      * We must OPENSSL_malloc stuff, even for 0 bytes otherwise it signifies
488      * a missing NULL parameter.
489      */
490     s = OPENSSL_malloc((int)len + 1);
491     if (s == NULL) {
492         i = ERR_R_MALLOC_FAILURE;
493         goto err;
494     }
495     ret->type = V_ASN1_INTEGER;
496     if (len) {
497         if ((*p == 0) && (len != 1)) {
498             p++;
499             len--;
500         }
501         memcpy(s, p, (int)len);
502         p += len;
503     }
504
505     OPENSSL_free(ret->data);
506     ret->data = s;
507     ret->length = (int)len;
508     if (a != NULL)
509         (*a) = ret;
510     *pp = p;
511     return (ret);
512  err:
513     ASN1err(ASN1_F_D2I_ASN1_UINTEGER, i);
514     if ((a == NULL) || (*a != ret))
515         ASN1_INTEGER_free(ret);
516     return (NULL);
517 }
518
519 static ASN1_STRING *bn_to_asn1_string(const BIGNUM *bn, ASN1_STRING *ai,
520                                       int atype)
521 {
522     ASN1_INTEGER *ret;
523     int len;
524
525     if (ai == NULL) {
526         ret = ASN1_STRING_type_new(atype);
527     } else {
528         ret = ai;
529         ret->type = atype;
530     }
531
532     if (ret == NULL) {
533         ASN1err(ASN1_F_BN_TO_ASN1_STRING, ERR_R_NESTED_ASN1_ERROR);
534         goto err;
535     }
536
537     if (BN_is_negative(bn) && !BN_is_zero(bn))
538         ret->type |= V_ASN1_NEG_INTEGER;
539
540     len = BN_num_bytes(bn);
541
542     if (len == 0)
543         len = 1;
544
545     if (ASN1_STRING_set(ret, NULL, len) == 0) {
546         ASN1err(ASN1_F_BN_TO_ASN1_STRING, ERR_R_MALLOC_FAILURE);
547         goto err;
548     }
549
550     /* Correct zero case */
551     if (BN_is_zero(bn))
552         ret->data[0] = 0;
553     else
554         len = BN_bn2bin(bn, ret->data);
555     ret->length = len;
556     return ret;
557  err:
558     if (ret != ai)
559         ASN1_INTEGER_free(ret);
560     return (NULL);
561 }
562
563 static BIGNUM *asn1_string_to_bn(const ASN1_INTEGER *ai, BIGNUM *bn,
564                                  int itype)
565 {
566     BIGNUM *ret;
567
568     if ((ai->type & ~V_ASN1_NEG) != itype) {
569         ASN1err(ASN1_F_ASN1_STRING_TO_BN, ASN1_R_WRONG_INTEGER_TYPE);
570         return NULL;
571     }
572
573     ret = BN_bin2bn(ai->data, ai->length, bn);
574     if (ret == 0) {
575         ASN1err(ASN1_F_ASN1_STRING_TO_BN, ASN1_R_BN_LIB);
576         return NULL;
577     }
578     if (ai->type & V_ASN1_NEG)
579         BN_set_negative(ret, 1);
580     return ret;
581 }
582
583 int ASN1_INTEGER_get_int64(int64_t *pr, const ASN1_INTEGER *a)
584 {
585     return asn1_string_get_int64(pr, a, V_ASN1_INTEGER);
586 }
587
588 int ASN1_INTEGER_set_int64(ASN1_INTEGER *a, int64_t r)
589 {
590     return asn1_string_set_int64(a, r, V_ASN1_INTEGER);
591 }
592
593 int ASN1_INTEGER_get_uint64(uint64_t *pr, const ASN1_INTEGER *a)
594 {
595     return asn1_string_get_uint64(pr, a, V_ASN1_INTEGER);
596 }
597
598 int ASN1_INTEGER_set_uint64(ASN1_INTEGER *a, uint64_t r)
599 {
600     return asn1_string_set_uint64(a, r, V_ASN1_INTEGER);
601 }
602
603 int ASN1_INTEGER_set(ASN1_INTEGER *a, long v)
604 {
605     return ASN1_INTEGER_set_int64(a, v);
606 }
607
608 long ASN1_INTEGER_get(const ASN1_INTEGER *a)
609 {
610     int i;
611     int64_t r;
612     if (a == NULL)
613         return 0;
614     i = ASN1_INTEGER_get_int64(&r, a);
615     if (i == 0)
616         return -1;
617     if (r > LONG_MAX || r < LONG_MIN)
618         return -1;
619     return (long)r;
620 }
621
622 ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai)
623 {
624     return bn_to_asn1_string(bn, ai, V_ASN1_INTEGER);
625 }
626
627 BIGNUM *ASN1_INTEGER_to_BN(const ASN1_INTEGER *ai, BIGNUM *bn)
628 {
629     return asn1_string_to_bn(ai, bn, V_ASN1_INTEGER);
630 }
631
632 int ASN1_ENUMERATED_get_int64(int64_t *pr, const ASN1_ENUMERATED *a)
633 {
634     return asn1_string_get_int64(pr, a, V_ASN1_ENUMERATED);
635 }
636
637 int ASN1_ENUMERATED_set_int64(ASN1_ENUMERATED *a, int64_t r)
638 {
639     return asn1_string_set_int64(a, r, V_ASN1_ENUMERATED);
640 }
641
642 int ASN1_ENUMERATED_set(ASN1_ENUMERATED *a, long v)
643 {
644     return ASN1_ENUMERATED_set_int64(a, v);
645 }
646
647 long ASN1_ENUMERATED_get(ASN1_ENUMERATED *a)
648 {
649     int i;
650     int64_t r;
651     if (a == NULL)
652         return 0;
653     if ((a->type & ~V_ASN1_NEG) != V_ASN1_ENUMERATED)
654         return -1;
655     if (a->length > (int)sizeof(long))
656         return 0xffffffffL;
657     i = ASN1_ENUMERATED_get_int64(&r, a);
658     if (i == 0)
659         return -1;
660     if (r > LONG_MAX || r < LONG_MIN)
661         return -1;
662     return (long)r;
663 }
664
665 ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(const BIGNUM *bn, ASN1_ENUMERATED *ai)
666 {
667     return bn_to_asn1_string(bn, ai, V_ASN1_ENUMERATED);
668 }
669
670 BIGNUM *ASN1_ENUMERATED_to_BN(const ASN1_ENUMERATED *ai, BIGNUM *bn)
671 {
672     return asn1_string_to_bn(ai, bn, V_ASN1_ENUMERATED);
673 }