Don't write out a bad OID
[openssl.git] / crypto / asn1 / tasn_enc.c
1 /*
2  * Copyright 2000-2016 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 <stddef.h>
11 #include <string.h>
12 #include "internal/cryptlib.h"
13 #include <openssl/asn1.h>
14 #include <openssl/asn1t.h>
15 #include <openssl/objects.h>
16 #include "internal/asn1_int.h"
17 #include "asn1_locl.h"
18
19 static int asn1_i2d_ex_primitive(ASN1_VALUE **pval, unsigned char **out,
20                                  const ASN1_ITEM *it, int tag, int aclass);
21 static int asn1_set_seq_out(STACK_OF(ASN1_VALUE) *sk, unsigned char **out,
22                             int skcontlen, const ASN1_ITEM *item,
23                             int do_sort, int iclass);
24 static int asn1_template_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
25                                 const ASN1_TEMPLATE *tt, int tag, int aclass);
26 static int asn1_item_flags_i2d(ASN1_VALUE *val, unsigned char **out,
27                                const ASN1_ITEM *it, int flags);
28 static int asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cout, int *putype,
29                        const ASN1_ITEM *it);
30
31 /*
32  * Top level i2d equivalents: the 'ndef' variant instructs the encoder to use
33  * indefinite length constructed encoding, where appropriate
34  */
35
36 int ASN1_item_ndef_i2d(ASN1_VALUE *val, unsigned char **out,
37                        const ASN1_ITEM *it)
38 {
39     return asn1_item_flags_i2d(val, out, it, ASN1_TFLG_NDEF);
40 }
41
42 int ASN1_item_i2d(ASN1_VALUE *val, unsigned char **out, const ASN1_ITEM *it)
43 {
44     return asn1_item_flags_i2d(val, out, it, 0);
45 }
46
47 /*
48  * Encode an ASN1 item, this is use by the standard 'i2d' function. 'out'
49  * points to a buffer to output the data to. The new i2d has one additional
50  * feature. If the output buffer is NULL (i.e. *out == NULL) then a buffer is
51  * allocated and populated with the encoding.
52  */
53
54 static int asn1_item_flags_i2d(ASN1_VALUE *val, unsigned char **out,
55                                const ASN1_ITEM *it, int flags)
56 {
57     if (out && !*out) {
58         unsigned char *p, *buf;
59         int len;
60         len = ASN1_item_ex_i2d(&val, NULL, it, -1, flags);
61         if (len <= 0)
62             return len;
63         buf = OPENSSL_malloc(len);
64         if (buf == NULL)
65             return -1;
66         p = buf;
67         ASN1_item_ex_i2d(&val, &p, it, -1, flags);
68         *out = buf;
69         return len;
70     }
71
72     return ASN1_item_ex_i2d(&val, out, it, -1, flags);
73 }
74
75 /*
76  * Encode an item, taking care of IMPLICIT tagging (if any). This function
77  * performs the normal item handling: it can be used in external types.
78  */
79
80 int ASN1_item_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
81                      const ASN1_ITEM *it, int tag, int aclass)
82 {
83     const ASN1_TEMPLATE *tt = NULL;
84     int i, seqcontlen, seqlen, ndef = 1;
85     const ASN1_EXTERN_FUNCS *ef;
86     const ASN1_AUX *aux = it->funcs;
87     ASN1_aux_cb *asn1_cb = 0;
88
89     if ((it->itype != ASN1_ITYPE_PRIMITIVE) && !*pval)
90         return 0;
91
92     if (aux && aux->asn1_cb)
93         asn1_cb = aux->asn1_cb;
94
95     switch (it->itype) {
96
97     case ASN1_ITYPE_PRIMITIVE:
98         if (it->templates)
99             return asn1_template_ex_i2d(pval, out, it->templates,
100                                         tag, aclass);
101         return asn1_i2d_ex_primitive(pval, out, it, tag, aclass);
102
103     case ASN1_ITYPE_MSTRING:
104         return asn1_i2d_ex_primitive(pval, out, it, -1, aclass);
105
106     case ASN1_ITYPE_CHOICE:
107         if (asn1_cb && !asn1_cb(ASN1_OP_I2D_PRE, pval, it, NULL))
108             return 0;
109         i = asn1_get_choice_selector(pval, it);
110         if ((i >= 0) && (i < it->tcount)) {
111             ASN1_VALUE **pchval;
112             const ASN1_TEMPLATE *chtt;
113             chtt = it->templates + i;
114             pchval = asn1_get_field_ptr(pval, chtt);
115             return asn1_template_ex_i2d(pchval, out, chtt, -1, aclass);
116         }
117         /* Fixme: error condition if selector out of range */
118         if (asn1_cb && !asn1_cb(ASN1_OP_I2D_POST, pval, it, NULL))
119             return 0;
120         break;
121
122     case ASN1_ITYPE_EXTERN:
123         /* If new style i2d it does all the work */
124         ef = it->funcs;
125         return ef->asn1_ex_i2d(pval, out, it, tag, aclass);
126
127     case ASN1_ITYPE_NDEF_SEQUENCE:
128         /* Use indefinite length constructed if requested */
129         if (aclass & ASN1_TFLG_NDEF)
130             ndef = 2;
131         /* fall through */
132
133     case ASN1_ITYPE_SEQUENCE:
134         i = asn1_enc_restore(&seqcontlen, out, pval, it);
135         /* An error occurred */
136         if (i < 0)
137             return 0;
138         /* We have a valid cached encoding... */
139         if (i > 0)
140             return seqcontlen;
141         /* Otherwise carry on */
142         seqcontlen = 0;
143         /* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */
144         if (tag == -1) {
145             tag = V_ASN1_SEQUENCE;
146             /* Retain any other flags in aclass */
147             aclass = (aclass & ~ASN1_TFLG_TAG_CLASS)
148                 | V_ASN1_UNIVERSAL;
149         }
150         if (asn1_cb && !asn1_cb(ASN1_OP_I2D_PRE, pval, it, NULL))
151             return 0;
152         /* First work out sequence content length */
153         for (i = 0, tt = it->templates; i < it->tcount; tt++, i++) {
154             const ASN1_TEMPLATE *seqtt;
155             ASN1_VALUE **pseqval;
156             int tmplen;
157             seqtt = asn1_do_adb(pval, tt, 1);
158             if (!seqtt)
159                 return 0;
160             pseqval = asn1_get_field_ptr(pval, seqtt);
161             tmplen = asn1_template_ex_i2d(pseqval, NULL, seqtt, -1, aclass);
162             if (tmplen == -1 || (tmplen > INT_MAX - seqcontlen))
163                 return -1;
164             seqcontlen += tmplen;
165         }
166
167         seqlen = ASN1_object_size(ndef, seqcontlen, tag);
168         if (!out || seqlen == -1)
169             return seqlen;
170         /* Output SEQUENCE header */
171         ASN1_put_object(out, ndef, seqcontlen, tag, aclass);
172         for (i = 0, tt = it->templates; i < it->tcount; tt++, i++) {
173             const ASN1_TEMPLATE *seqtt;
174             ASN1_VALUE **pseqval;
175             seqtt = asn1_do_adb(pval, tt, 1);
176             if (!seqtt)
177                 return 0;
178             pseqval = asn1_get_field_ptr(pval, seqtt);
179             /* FIXME: check for errors in enhanced version */
180             asn1_template_ex_i2d(pseqval, out, seqtt, -1, aclass);
181         }
182         if (ndef == 2)
183             ASN1_put_eoc(out);
184         if (asn1_cb && !asn1_cb(ASN1_OP_I2D_POST, pval, it, NULL))
185             return 0;
186         return seqlen;
187
188     default:
189         return 0;
190
191     }
192     return 0;
193 }
194
195 static int asn1_template_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
196                                 const ASN1_TEMPLATE *tt, int tag, int iclass)
197 {
198     int i, ret, flags, ttag, tclass, ndef;
199     ASN1_VALUE *tval;
200     flags = tt->flags;
201
202     /*
203      * If field is embedded then val needs fixing so it is a pointer to
204      * a pointer to a field.
205      */
206     if (flags & ASN1_TFLG_EMBED) {
207         tval = (ASN1_VALUE *)pval;
208         pval = &tval;
209     }
210     /*
211      * Work out tag and class to use: tagging may come either from the
212      * template or the arguments, not both because this would create
213      * ambiguity. Additionally the iclass argument may contain some
214      * additional flags which should be noted and passed down to other
215      * levels.
216      */
217     if (flags & ASN1_TFLG_TAG_MASK) {
218         /* Error if argument and template tagging */
219         if (tag != -1)
220             /* FIXME: error code here */
221             return -1;
222         /* Get tagging from template */
223         ttag = tt->tag;
224         tclass = flags & ASN1_TFLG_TAG_CLASS;
225     } else if (tag != -1) {
226         /* No template tagging, get from arguments */
227         ttag = tag;
228         tclass = iclass & ASN1_TFLG_TAG_CLASS;
229     } else {
230         ttag = -1;
231         tclass = 0;
232     }
233     /*
234      * Remove any class mask from iflag.
235      */
236     iclass &= ~ASN1_TFLG_TAG_CLASS;
237
238     /*
239      * At this point 'ttag' contains the outer tag to use, 'tclass' is the
240      * class and iclass is any flags passed to this function.
241      */
242
243     /* if template and arguments require ndef, use it */
244     if ((flags & ASN1_TFLG_NDEF) && (iclass & ASN1_TFLG_NDEF))
245         ndef = 2;
246     else
247         ndef = 1;
248
249     if (flags & ASN1_TFLG_SK_MASK) {
250         /* SET OF, SEQUENCE OF */
251         STACK_OF(ASN1_VALUE) *sk = (STACK_OF(ASN1_VALUE) *)*pval;
252         int isset, sktag, skaclass;
253         int skcontlen, sklen;
254         ASN1_VALUE *skitem;
255
256         if (!*pval)
257             return 0;
258
259         if (flags & ASN1_TFLG_SET_OF) {
260             isset = 1;
261             /* 2 means we reorder */
262             if (flags & ASN1_TFLG_SEQUENCE_OF)
263                 isset = 2;
264         } else
265             isset = 0;
266
267         /*
268          * Work out inner tag value: if EXPLICIT or no tagging use underlying
269          * type.
270          */
271         if ((ttag != -1) && !(flags & ASN1_TFLG_EXPTAG)) {
272             sktag = ttag;
273             skaclass = tclass;
274         } else {
275             skaclass = V_ASN1_UNIVERSAL;
276             if (isset)
277                 sktag = V_ASN1_SET;
278             else
279                 sktag = V_ASN1_SEQUENCE;
280         }
281
282         /* Determine total length of items */
283         skcontlen = 0;
284         for (i = 0; i < sk_ASN1_VALUE_num(sk); i++) {
285             int tmplen;
286             skitem = sk_ASN1_VALUE_value(sk, i);
287             tmplen = ASN1_item_ex_i2d(&skitem, NULL, ASN1_ITEM_ptr(tt->item),
288                                       -1, iclass);
289             if (tmplen == -1 || (skcontlen > INT_MAX - tmplen))
290                 return -1;
291             skcontlen += tmplen;
292         }
293         sklen = ASN1_object_size(ndef, skcontlen, sktag);
294         if (sklen == -1)
295             return -1;
296         /* If EXPLICIT need length of surrounding tag */
297         if (flags & ASN1_TFLG_EXPTAG)
298             ret = ASN1_object_size(ndef, sklen, ttag);
299         else
300             ret = sklen;
301
302         if (!out || ret == -1)
303             return ret;
304
305         /* Now encode this lot... */
306         /* EXPLICIT tag */
307         if (flags & ASN1_TFLG_EXPTAG)
308             ASN1_put_object(out, ndef, sklen, ttag, tclass);
309         /* SET or SEQUENCE and IMPLICIT tag */
310         ASN1_put_object(out, ndef, skcontlen, sktag, skaclass);
311         /* And the stuff itself */
312         asn1_set_seq_out(sk, out, skcontlen, ASN1_ITEM_ptr(tt->item),
313                          isset, iclass);
314         if (ndef == 2) {
315             ASN1_put_eoc(out);
316             if (flags & ASN1_TFLG_EXPTAG)
317                 ASN1_put_eoc(out);
318         }
319
320         return ret;
321     }
322
323     if (flags & ASN1_TFLG_EXPTAG) {
324         /* EXPLICIT tagging */
325         /* Find length of tagged item */
326         i = ASN1_item_ex_i2d(pval, NULL, ASN1_ITEM_ptr(tt->item), -1, iclass);
327         if (!i)
328             return 0;
329         /* Find length of EXPLICIT tag */
330         ret = ASN1_object_size(ndef, i, ttag);
331         if (out && ret != -1) {
332             /* Output tag and item */
333             ASN1_put_object(out, ndef, i, ttag, tclass);
334             ASN1_item_ex_i2d(pval, out, ASN1_ITEM_ptr(tt->item), -1, iclass);
335             if (ndef == 2)
336                 ASN1_put_eoc(out);
337         }
338         return ret;
339     }
340
341     /* Either normal or IMPLICIT tagging: combine class and flags */
342     return ASN1_item_ex_i2d(pval, out, ASN1_ITEM_ptr(tt->item),
343                             ttag, tclass | iclass);
344
345 }
346
347 /* Temporary structure used to hold DER encoding of items for SET OF */
348
349 typedef struct {
350     unsigned char *data;
351     int length;
352     ASN1_VALUE *field;
353 } DER_ENC;
354
355 static int der_cmp(const void *a, const void *b)
356 {
357     const DER_ENC *d1 = a, *d2 = b;
358     int cmplen, i;
359     cmplen = (d1->length < d2->length) ? d1->length : d2->length;
360     i = memcmp(d1->data, d2->data, cmplen);
361     if (i)
362         return i;
363     return d1->length - d2->length;
364 }
365
366 /* Output the content octets of SET OF or SEQUENCE OF */
367
368 static int asn1_set_seq_out(STACK_OF(ASN1_VALUE) *sk, unsigned char **out,
369                             int skcontlen, const ASN1_ITEM *item,
370                             int do_sort, int iclass)
371 {
372     int i;
373     ASN1_VALUE *skitem;
374     unsigned char *tmpdat = NULL, *p = NULL;
375     DER_ENC *derlst = NULL, *tder;
376     if (do_sort) {
377         /* Don't need to sort less than 2 items */
378         if (sk_ASN1_VALUE_num(sk) < 2)
379             do_sort = 0;
380         else {
381             derlst = OPENSSL_malloc(sk_ASN1_VALUE_num(sk)
382                                     * sizeof(*derlst));
383             if (derlst == NULL)
384                 return 0;
385             tmpdat = OPENSSL_malloc(skcontlen);
386             if (tmpdat == NULL) {
387                 OPENSSL_free(derlst);
388                 return 0;
389             }
390         }
391     }
392     /* If not sorting just output each item */
393     if (!do_sort) {
394         for (i = 0; i < sk_ASN1_VALUE_num(sk); i++) {
395             skitem = sk_ASN1_VALUE_value(sk, i);
396             ASN1_item_ex_i2d(&skitem, out, item, -1, iclass);
397         }
398         return 1;
399     }
400     p = tmpdat;
401
402     /* Doing sort: build up a list of each member's DER encoding */
403     for (i = 0, tder = derlst; i < sk_ASN1_VALUE_num(sk); i++, tder++) {
404         skitem = sk_ASN1_VALUE_value(sk, i);
405         tder->data = p;
406         tder->length = ASN1_item_ex_i2d(&skitem, &p, item, -1, iclass);
407         tder->field = skitem;
408     }
409
410     /* Now sort them */
411     qsort(derlst, sk_ASN1_VALUE_num(sk), sizeof(*derlst), der_cmp);
412     /* Output sorted DER encoding */
413     p = *out;
414     for (i = 0, tder = derlst; i < sk_ASN1_VALUE_num(sk); i++, tder++) {
415         memcpy(p, tder->data, tder->length);
416         p += tder->length;
417     }
418     *out = p;
419     /* If do_sort is 2 then reorder the STACK */
420     if (do_sort == 2) {
421         for (i = 0, tder = derlst; i < sk_ASN1_VALUE_num(sk); i++, tder++)
422             (void)sk_ASN1_VALUE_set(sk, i, tder->field);
423     }
424     OPENSSL_free(derlst);
425     OPENSSL_free(tmpdat);
426     return 1;
427 }
428
429 static int asn1_i2d_ex_primitive(ASN1_VALUE **pval, unsigned char **out,
430                                  const ASN1_ITEM *it, int tag, int aclass)
431 {
432     int len;
433     int utype;
434     int usetag;
435     int ndef = 0;
436
437     utype = it->utype;
438
439     /*
440      * Get length of content octets and maybe find out the underlying type.
441      */
442
443     len = asn1_ex_i2c(pval, NULL, &utype, it);
444
445     /*
446      * If SEQUENCE, SET or OTHER then header is included in pseudo content
447      * octets so don't include tag+length. We need to check here because the
448      * call to asn1_ex_i2c() could change utype.
449      */
450     if ((utype == V_ASN1_SEQUENCE) || (utype == V_ASN1_SET) ||
451         (utype == V_ASN1_OTHER))
452         usetag = 0;
453     else
454         usetag = 1;
455
456     /* -1 means omit type */
457
458     if (len == -1)
459         return 0;
460
461     /* -2 return is special meaning use ndef */
462     if (len == -2) {
463         ndef = 2;
464         len = 0;
465     }
466
467     /* If not implicitly tagged get tag from underlying type */
468     if (tag == -1)
469         tag = utype;
470
471     /* Output tag+length followed by content octets */
472     if (out) {
473         if (usetag)
474             ASN1_put_object(out, ndef, len, tag, aclass);
475         asn1_ex_i2c(pval, *out, &utype, it);
476         if (ndef)
477             ASN1_put_eoc(out);
478         else
479             *out += len;
480     }
481
482     if (usetag)
483         return ASN1_object_size(ndef, len, tag);
484     return len;
485 }
486
487 /* Produce content octets from a structure */
488
489 static int asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cout, int *putype,
490                        const ASN1_ITEM *it)
491 {
492     ASN1_BOOLEAN *tbool = NULL;
493     ASN1_STRING *strtmp;
494     ASN1_OBJECT *otmp;
495     int utype;
496     const unsigned char *cont;
497     unsigned char c;
498     int len;
499     const ASN1_PRIMITIVE_FUNCS *pf;
500     pf = it->funcs;
501     if (pf && pf->prim_i2c)
502         return pf->prim_i2c(pval, cout, putype, it);
503
504     /* Should type be omitted? */
505     if ((it->itype != ASN1_ITYPE_PRIMITIVE)
506         || (it->utype != V_ASN1_BOOLEAN)) {
507         if (!*pval)
508             return -1;
509     }
510
511     if (it->itype == ASN1_ITYPE_MSTRING) {
512         /* If MSTRING type set the underlying type */
513         strtmp = (ASN1_STRING *)*pval;
514         utype = strtmp->type;
515         *putype = utype;
516     } else if (it->utype == V_ASN1_ANY) {
517         /* If ANY set type and pointer to value */
518         ASN1_TYPE *typ;
519         typ = (ASN1_TYPE *)*pval;
520         utype = typ->type;
521         *putype = utype;
522         pval = &typ->value.asn1_value;
523     } else
524         utype = *putype;
525
526     switch (utype) {
527     case V_ASN1_OBJECT:
528         otmp = (ASN1_OBJECT *)*pval;
529         cont = otmp->data;
530         len = otmp->length;
531         if (cont == NULL || len == 0)
532             return -1;
533         break;
534
535     case V_ASN1_NULL:
536         cont = NULL;
537         len = 0;
538         break;
539
540     case V_ASN1_BOOLEAN:
541         tbool = (ASN1_BOOLEAN *)pval;
542         if (*tbool == -1)
543             return -1;
544         if (it->utype != V_ASN1_ANY) {
545             /*
546              * Default handling if value == size field then omit
547              */
548             if (*tbool && (it->size > 0))
549                 return -1;
550             if (!*tbool && !it->size)
551                 return -1;
552         }
553         c = (unsigned char)*tbool;
554         cont = &c;
555         len = 1;
556         break;
557
558     case V_ASN1_BIT_STRING:
559         return i2c_ASN1_BIT_STRING((ASN1_BIT_STRING *)*pval,
560                                    cout ? &cout : NULL);
561
562     case V_ASN1_INTEGER:
563     case V_ASN1_ENUMERATED:
564         /*
565          * These are all have the same content format as ASN1_INTEGER
566          */
567         return i2c_ASN1_INTEGER((ASN1_INTEGER *)*pval, cout ? &cout : NULL);
568
569     case V_ASN1_OCTET_STRING:
570     case V_ASN1_NUMERICSTRING:
571     case V_ASN1_PRINTABLESTRING:
572     case V_ASN1_T61STRING:
573     case V_ASN1_VIDEOTEXSTRING:
574     case V_ASN1_IA5STRING:
575     case V_ASN1_UTCTIME:
576     case V_ASN1_GENERALIZEDTIME:
577     case V_ASN1_GRAPHICSTRING:
578     case V_ASN1_VISIBLESTRING:
579     case V_ASN1_GENERALSTRING:
580     case V_ASN1_UNIVERSALSTRING:
581     case V_ASN1_BMPSTRING:
582     case V_ASN1_UTF8STRING:
583     case V_ASN1_SEQUENCE:
584     case V_ASN1_SET:
585     default:
586         /* All based on ASN1_STRING and handled the same */
587         strtmp = (ASN1_STRING *)*pval;
588         /* Special handling for NDEF */
589         if ((it->size == ASN1_TFLG_NDEF)
590             && (strtmp->flags & ASN1_STRING_FLAG_NDEF)) {
591             if (cout) {
592                 strtmp->data = cout;
593                 strtmp->length = 0;
594             }
595             /* Special return code */
596             return -2;
597         }
598         cont = strtmp->data;
599         len = strtmp->length;
600
601         break;
602
603     }
604     if (cout && len)
605         memcpy(cout, cont, len);
606     return len;
607 }