renamed asn1_copy_node2 to asn1_dup_node
[platform/upstream/libtasn1.git] / lib / coding.c
1 /*
2  * Copyright (C) 2002-2014 Free Software Foundation, Inc.
3  *
4  * This file is part of LIBTASN1.
5  *
6  * The LIBTASN1 library is free software; you can redistribute it
7  * and/or modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19  * 02110-1301, USA
20  */
21
22
23 /*****************************************************/
24 /* File: coding.c                                    */
25 /* Description: Functions to create a DER coding of  */
26 /*   an ASN1 type.                                   */
27 /*****************************************************/
28
29 #include <int.h>
30 #include "parser_aux.h"
31 #include <gstr.h>
32 #include "element.h"
33 #include "minmax.h"
34 #include <structure.h>
35
36 #define MAX_TAG_LEN 16
37
38 /******************************************************/
39 /* Function : _asn1_error_description_value_not_found */
40 /* Description: creates the ErrorDescription string   */
41 /* for the ASN1_VALUE_NOT_FOUND error.                */
42 /* Parameters:                                        */
43 /*   node: node of the tree where the value is NULL.  */
44 /*   ErrorDescription: string returned.               */
45 /* Return:                                            */
46 /******************************************************/
47 static void
48 _asn1_error_description_value_not_found (asn1_node node,
49                                          char *ErrorDescription)
50 {
51
52   if (ErrorDescription == NULL)
53     return;
54
55   Estrcpy (ErrorDescription, ":: value of element '");
56   _asn1_hierarchical_name (node, ErrorDescription + strlen (ErrorDescription),
57                            ASN1_MAX_ERROR_DESCRIPTION_SIZE - 40);
58   Estrcat (ErrorDescription, "' not found");
59
60 }
61
62 /**
63  * asn1_length_der:
64  * @len: value to convert.
65  * @der: buffer to hold the returned encoding (may be %NULL).
66  * @der_len: number of meaningful bytes of ANS (der[0]..der[der_len-1]).
67  *
68  * Creates the DER encoding of the provided length value.
69  * The @der buffer must have enough room for the output. The maximum
70  * length this function will encode is %ASN1_MAX_LENGTH_SIZE.
71  *
72  * To know the size of the DER encoding use a %NULL value for @der.
73  **/
74 void
75 asn1_length_der (unsigned long int len, unsigned char *der, int *der_len)
76 {
77   int k;
78   unsigned char temp[ASN1_MAX_LENGTH_SIZE];
79 #if SIZEOF_UNSIGNED_LONG_INT > 8
80   len &= 0xFFFFFFFFFFFFFFFF;
81 #endif
82
83   if (len < 128)
84     {
85       /* short form */
86       if (der != NULL)
87         der[0] = (unsigned char) len;
88       *der_len = 1;
89     }
90   else
91     {
92       /* Long form */
93       k = 0;
94       while (len)
95         {
96           temp[k++] = len & 0xFF;
97           len = len >> 8;
98         }
99       *der_len = k + 1;
100       if (der != NULL)
101         {
102           der[0] = ((unsigned char) k & 0x7F) + 128;
103           while (k--)
104             der[*der_len - 1 - k] = temp[k];
105         }
106     }
107 }
108
109 /******************************************************/
110 /* Function : _asn1_tag_der                           */
111 /* Description: creates the DER coding for the CLASS  */
112 /* and TAG parameters.                                */
113 /* It is limited by the ASN1_MAX_TAG_SIZE variable    */
114 /* Parameters:                                        */
115 /*   class: value to convert.                         */
116 /*   tag_value: value to convert.                     */
117 /*   ans: string returned.                            */
118 /*   ans_len: number of meaningful bytes of ANS       */
119 /*            (ans[0]..ans[ans_len-1]).               */
120 /* Return:                                            */
121 /******************************************************/
122 static void
123 _asn1_tag_der (unsigned char class, unsigned int tag_value,
124                unsigned char *ans, int *ans_len)
125 {
126   int k;
127   unsigned char temp[ASN1_MAX_TAG_SIZE];
128
129   if (tag_value < 31)
130     {
131       /* short form */
132       ans[0] = (class & 0xE0) + ((unsigned char) (tag_value & 0x1F));
133       *ans_len = 1;
134     }
135   else
136     {
137       /* Long form */
138       ans[0] = (class & 0xE0) + 31;
139       k = 0;
140       while (tag_value != 0)
141         {
142           temp[k++] = tag_value & 0x7F;
143           tag_value >>= 7;
144
145           if (k > ASN1_MAX_TAG_SIZE - 1)
146             break;              /* will not encode larger tags */
147         }
148       *ans_len = k + 1;
149       while (k--)
150         ans[*ans_len - 1 - k] = temp[k] + 128;
151       ans[*ans_len - 1] -= 128;
152     }
153 }
154
155 /**
156  * asn1_octet_der:
157  * @str: the input data.
158  * @str_len: STR length (str[0]..str[*str_len-1]).
159  * @der: encoded string returned.
160  * @der_len: number of meaningful bytes of DER (der[0]..der[der_len-1]).
161  *
162  * Creates a length-value DER encoding for the input data.
163  * The DER encoding of the input data will be placed in the @der variable.
164  *
165  * Note that the OCTET STRING tag is not included in the output.
166  *
167  * This function does not return any value because it is expected
168  * that @der_len will contain enough bytes to store the string
169  * plus the DER encoding. The DER encoding size can be obtained using
170  * asn1_length_der().
171  **/
172 void
173 asn1_octet_der (const unsigned char *str, int str_len,
174                 unsigned char *der, int *der_len)
175 {
176   int len_len;
177
178   if (der == NULL || str_len < 0)
179     return;
180
181   asn1_length_der (str_len, der, &len_len);
182   memcpy (der + len_len, str, str_len);
183   *der_len = str_len + len_len;
184 }
185
186
187 /**
188  * asn1_encode_simple_der:
189  * @etype: The type of the string to be encoded (ASN1_ETYPE_)
190  * @str: the string data.
191  * @str_len: the string length
192  * @tl: the encoded tag and length
193  * @tl_len: the bytes of the @tl field
194  *
195  * Creates the DER encoding for various simple ASN.1 types like strings etc.
196  * It stores the tag and length in @tl, which should have space for at least
197  * %ASN1_MAX_TL_SIZE bytes. Initially @tl_len should contain the size of @tl.
198  *
199  * The complete DER encoding should consist of the value in @tl appended
200  * with the provided @str.
201  *
202  * Returns: %ASN1_SUCCESS if successful or an error value.
203  **/
204 int
205 asn1_encode_simple_der (unsigned int etype, const unsigned char *str,
206                         unsigned int str_len, unsigned char *tl,
207                         unsigned int *tl_len)
208 {
209   int tag_len, len_len;
210   unsigned tlen;
211   unsigned char der_tag[ASN1_MAX_TAG_SIZE];
212   unsigned char der_length[ASN1_MAX_LENGTH_SIZE];
213   unsigned char *p;
214
215   if (str == NULL)
216     return ASN1_VALUE_NOT_VALID;
217
218   if (ETYPE_OK (etype) == 0)
219     return ASN1_VALUE_NOT_VALID;
220
221   /* doesn't handle constructed classes */
222   if (ETYPE_CLASS (etype) != ASN1_CLASS_UNIVERSAL)
223     return ASN1_VALUE_NOT_VALID;
224
225   _asn1_tag_der (ETYPE_CLASS (etype), ETYPE_TAG (etype), der_tag, &tag_len);
226
227   asn1_length_der (str_len, der_length, &len_len);
228
229   if (tag_len <= 0 || len_len <= 0)
230     return ASN1_VALUE_NOT_VALID;
231
232   tlen = tag_len + len_len;
233
234   if (*tl_len < tlen)
235     return ASN1_MEM_ERROR;
236
237   p = tl;
238   memcpy (p, der_tag, tag_len);
239   p += tag_len;
240   memcpy (p, der_length, len_len);
241
242   *tl_len = tlen;
243
244   return ASN1_SUCCESS;
245 }
246
247 /******************************************************/
248 /* Function : _asn1_time_der                          */
249 /* Description: creates the DER coding for a TIME     */
250 /* type (length included).                            */
251 /* Parameters:                                        */
252 /*   str: TIME null-terminated string.                */
253 /*   der: string returned.                            */
254 /*   der_len: number of meaningful bytes of DER       */
255 /*            (der[0]..der[ans_len-1]). Initially it  */
256 /*            if must store the lenght of DER.        */
257 /* Return:                                            */
258 /*   ASN1_MEM_ERROR when DER isn't big enough         */
259 /*   ASN1_SUCCESS otherwise                           */
260 /******************************************************/
261 static int
262 _asn1_time_der (unsigned char *str, int str_len, unsigned char *der,
263                 int *der_len)
264 {
265   int len_len;
266   int max_len;
267
268   max_len = *der_len;
269
270   asn1_length_der (str_len, (max_len > 0) ? der : NULL, &len_len);
271
272   if ((len_len + str_len) <= max_len)
273     memcpy (der + len_len, str, str_len);
274   *der_len = len_len + str_len;
275
276   if ((*der_len) > max_len)
277     return ASN1_MEM_ERROR;
278
279   return ASN1_SUCCESS;
280 }
281
282
283 /*
284 void
285 _asn1_get_utctime_der(unsigned char *der,int *der_len,unsigned char *str)
286 {
287   int len_len,str_len;
288   char temp[20];
289
290   if(str==NULL) return;
291   str_len=asn1_get_length_der(der,*der_len,&len_len);
292   if (str_len<0) return;
293   memcpy(temp,der+len_len,str_len);
294   *der_len=str_len+len_len;
295   switch(str_len){
296   case 11:
297     temp[10]=0;
298     strcat(temp,"00+0000");
299     break;
300   case 13:
301     temp[12]=0;
302     strcat(temp,"+0000");
303     break;
304   case 15:
305     temp[15]=0;
306     memmove(temp+12,temp+10,6);
307     temp[10]=temp[11]='0';
308     break;
309   case 17:
310     temp[17]=0;
311     break;
312   default:
313     return;
314   }
315   strcpy(str,temp);
316 }
317 */
318
319 /******************************************************/
320 /* Function : _asn1_objectid_der                      */
321 /* Description: creates the DER coding for an         */
322 /* OBJECT IDENTIFIER  type (length included).         */
323 /* Parameters:                                        */
324 /*   str: OBJECT IDENTIFIER null-terminated string.   */
325 /*   der: string returned.                            */
326 /*   der_len: number of meaningful bytes of DER       */
327 /*            (der[0]..der[ans_len-1]). Initially it  */
328 /*            must store the length of DER.           */
329 /* Return:                                            */
330 /*   ASN1_MEM_ERROR when DER isn't big enough         */
331 /*   ASN1_SUCCESS if succesful                        */
332 /*   or an error value.                               */
333 /******************************************************/
334 static int
335 _asn1_objectid_der (unsigned char *str, unsigned char *der, int *der_len)
336 {
337   int len_len, counter, k, first, max_len;
338   char *temp, *n_end, *n_start;
339   unsigned char bit7;
340   unsigned long val, val1 = 0;
341   int str_len = _asn1_strlen (str);
342
343   max_len = *der_len;
344
345   temp = malloc (str_len + 2);
346   if (temp == NULL)
347     return ASN1_MEM_ALLOC_ERROR;
348
349   memcpy (temp, str, str_len);
350   temp[str_len] = '.';
351   temp[str_len + 1] = 0;
352
353   counter = 0;
354   n_start = temp;
355   while ((n_end = strchr (n_start, '.')))
356     {
357       *n_end = 0;
358       val = strtoul (n_start, NULL, 10);
359       counter++;
360
361       if (counter == 1)
362         val1 = val;
363       else if (counter == 2)
364         {
365           if (max_len > 0)
366             der[0] = 40 * val1 + val;
367           *der_len = 1;
368         }
369       else
370         {
371           first = 0;
372           for (k = 4; k >= 0; k--)
373             {
374               bit7 = (val >> (k * 7)) & 0x7F;
375               if (bit7 || first || !k)
376                 {
377                   if (k)
378                     bit7 |= 0x80;
379                   if (max_len > (*der_len))
380                     der[*der_len] = bit7;
381                   (*der_len)++;
382                   first = 1;
383                 }
384             }
385
386         }
387       n_start = n_end + 1;
388     }
389
390   asn1_length_der (*der_len, NULL, &len_len);
391   if (max_len >= (*der_len + len_len))
392     {
393       memmove (der + len_len, der, *der_len);
394       asn1_length_der (*der_len, der, &len_len);
395     }
396   *der_len += len_len;
397
398   free (temp);
399
400   if (max_len < (*der_len))
401     return ASN1_MEM_ERROR;
402
403   return ASN1_SUCCESS;
404 }
405
406
407 static const unsigned char bit_mask[] =
408   { 0xFF, 0xFE, 0xFC, 0xF8, 0xF0, 0xE0, 0xC0, 0x80 };
409
410 /**
411  * asn1_bit_der:
412  * @str: BIT string.
413  * @bit_len: number of meaningful bits in STR.
414  * @der: string returned.
415  * @der_len: number of meaningful bytes of DER
416  *   (der[0]..der[ans_len-1]).
417  *
418  * Creates a length-value DER encoding for the input data
419  * as it would have been for a BIT STRING.
420  * The DER encoded data will be copied in @der.
421  *
422  * Note that the BIT STRING tag is not included in the output.
423  *
424  * This function does not return any value because it is expected
425  * that @der_len will contain enough bytes to store the string
426  * plus the DER encoding. The DER encoding size can be obtained using
427  * asn1_length_der().
428  **/
429 void
430 asn1_bit_der (const unsigned char *str, int bit_len,
431               unsigned char *der, int *der_len)
432 {
433   int len_len, len_byte, len_pad;
434
435   if (der == NULL)
436     return;
437
438   len_byte = bit_len >> 3;
439   len_pad = 8 - (bit_len & 7);
440   if (len_pad == 8)
441     len_pad = 0;
442   else
443     len_byte++;
444   asn1_length_der (len_byte + 1, der, &len_len);
445   der[len_len] = len_pad;
446   memcpy (der + len_len + 1, str, len_byte);
447   der[len_len + len_byte] &= bit_mask[len_pad];
448   *der_len = len_byte + len_len + 1;
449 }
450
451
452 /******************************************************/
453 /* Function : _asn1_complete_explicit_tag             */
454 /* Description: add the length coding to the EXPLICIT */
455 /* tags.                                              */
456 /* Parameters:                                        */
457 /*   node: pointer to the tree element.               */
458 /*   der: string with the DER coding of the whole tree*/
459 /*   counter: number of meaningful bytes of DER       */
460 /*            (der[0]..der[*counter-1]).              */
461 /*   max_len: size of der vector                      */
462 /* Return:                                            */
463 /*   ASN1_MEM_ERROR if der vector isn't big enough,   */
464 /*   otherwise ASN1_SUCCESS.                          */
465 /******************************************************/
466 static int
467 _asn1_complete_explicit_tag (asn1_node node, unsigned char *der,
468                              int *counter, int *max_len)
469 {
470   asn1_node p;
471   int is_tag_implicit, len2, len3;
472   unsigned char temp[SIZEOF_UNSIGNED_INT];
473
474   is_tag_implicit = 0;
475
476   if (node->type & CONST_TAG)
477     {
478       p = node->down;
479       if (p == NULL)
480         return ASN1_DER_ERROR;
481       /* When there are nested tags we must complete them reverse to
482          the order they were created. This is because completing a tag
483          modifies all data within it, including the incomplete tags
484          which store buffer positions -- simon@josefsson.org 2002-09-06
485        */
486       while (p->right)
487         p = p->right;
488       while (p && p != node->down->left)
489         {
490           if (type_field (p->type) == ASN1_ETYPE_TAG)
491             {
492               if (p->type & CONST_EXPLICIT)
493                 {
494                   len2 = strtol (p->name, NULL, 10);
495                   _asn1_set_name (p, NULL);
496
497                   asn1_length_der (*counter - len2, temp, &len3);
498                   if (len3 <= (*max_len))
499                     {
500                       memmove (der + len2 + len3, der + len2,
501                                *counter - len2);
502                       memcpy (der + len2, temp, len3);
503                     }
504                   *max_len -= len3;
505                   *counter += len3;
506                   is_tag_implicit = 0;
507                 }
508               else
509                 {               /* CONST_IMPLICIT */
510                   if (!is_tag_implicit)
511                     {
512                       is_tag_implicit = 1;
513                     }
514                 }
515             }
516           p = p->left;
517         }
518     }
519
520   if (*max_len < 0)
521     return ASN1_MEM_ERROR;
522
523   return ASN1_SUCCESS;
524 }
525
526 const tag_and_class_st _asn1_tags[] = {
527   [ASN1_ETYPE_GENERALSTRING] =
528     {ASN1_TAG_GENERALSTRING, ASN1_CLASS_UNIVERSAL, "type:GENERALSTRING"},
529   [ASN1_ETYPE_NUMERIC_STRING] =
530     {ASN1_TAG_NUMERIC_STRING, ASN1_CLASS_UNIVERSAL, "type:NUMERIC_STR"},
531   [ASN1_ETYPE_IA5_STRING] =
532     {ASN1_TAG_IA5_STRING, ASN1_CLASS_UNIVERSAL, "type:IA5_STR"},
533   [ASN1_ETYPE_TELETEX_STRING] =
534     {ASN1_TAG_TELETEX_STRING, ASN1_CLASS_UNIVERSAL, "type:TELETEX_STR"},
535   [ASN1_ETYPE_PRINTABLE_STRING] =
536     {ASN1_TAG_PRINTABLE_STRING, ASN1_CLASS_UNIVERSAL, "type:PRINTABLE_STR"},
537   [ASN1_ETYPE_UNIVERSAL_STRING] =
538     {ASN1_TAG_UNIVERSAL_STRING, ASN1_CLASS_UNIVERSAL, "type:UNIVERSAL_STR"},
539   [ASN1_ETYPE_BMP_STRING] =
540     {ASN1_TAG_BMP_STRING, ASN1_CLASS_UNIVERSAL, "type:BMP_STR"},
541   [ASN1_ETYPE_UTF8_STRING] =
542     {ASN1_TAG_UTF8_STRING, ASN1_CLASS_UNIVERSAL, "type:UTF8_STR"},
543   [ASN1_ETYPE_VISIBLE_STRING] =
544     {ASN1_TAG_VISIBLE_STRING, ASN1_CLASS_UNIVERSAL, "type:VISIBLE_STR"},
545   [ASN1_ETYPE_OCTET_STRING] =
546     {ASN1_TAG_OCTET_STRING, ASN1_CLASS_UNIVERSAL, "type:OCT_STR"},
547   [ASN1_ETYPE_BIT_STRING] =
548     {ASN1_TAG_BIT_STRING, ASN1_CLASS_UNIVERSAL, "type:BIT_STR"},
549   [ASN1_ETYPE_OBJECT_ID] =
550     {ASN1_TAG_OBJECT_ID, ASN1_CLASS_UNIVERSAL, "type:OBJ_ID"},
551   [ASN1_ETYPE_NULL] = {ASN1_TAG_NULL, ASN1_CLASS_UNIVERSAL, "type:NULL"},
552   [ASN1_ETYPE_BOOLEAN] =
553     {ASN1_TAG_BOOLEAN, ASN1_CLASS_UNIVERSAL, "type:BOOLEAN"},
554   [ASN1_ETYPE_INTEGER] =
555     {ASN1_TAG_INTEGER, ASN1_CLASS_UNIVERSAL, "type:INTEGER"},
556   [ASN1_ETYPE_ENUMERATED] =
557     {ASN1_TAG_ENUMERATED, ASN1_CLASS_UNIVERSAL, "type:ENUMERATED"},
558   [ASN1_ETYPE_SEQUENCE] =
559     {ASN1_TAG_SEQUENCE, ASN1_CLASS_UNIVERSAL | ASN1_CLASS_STRUCTURED,
560      "type:SEQUENCE"},
561   [ASN1_ETYPE_SEQUENCE_OF] =
562     {ASN1_TAG_SEQUENCE, ASN1_CLASS_UNIVERSAL | ASN1_CLASS_STRUCTURED,
563      "type:SEQ_OF"},
564   [ASN1_ETYPE_SET] =
565     {ASN1_TAG_SET, ASN1_CLASS_UNIVERSAL | ASN1_CLASS_STRUCTURED, "type:SET"},
566   [ASN1_ETYPE_SET_OF] =
567     {ASN1_TAG_SET, ASN1_CLASS_UNIVERSAL | ASN1_CLASS_STRUCTURED,
568      "type:SET_OF"},
569   [ASN1_ETYPE_GENERALIZED_TIME] =
570     {ASN1_TAG_GENERALIZEDTime, ASN1_CLASS_UNIVERSAL, "type:GENERALIZED_TIME"},
571   [ASN1_ETYPE_UTC_TIME] =
572     {ASN1_TAG_UTCTime, ASN1_CLASS_UNIVERSAL, "type:UTC_TIME"},
573 };
574
575 unsigned int _asn1_tags_size = sizeof (_asn1_tags) / sizeof (_asn1_tags[0]);
576
577 /******************************************************/
578 /* Function : _asn1_insert_tag_der                    */
579 /* Description: creates the DER coding of tags of one */
580 /* NODE.                                              */
581 /* Parameters:                                        */
582 /*   node: pointer to the tree element.               */
583 /*   der: string returned                             */
584 /*   counter: number of meaningful bytes of DER       */
585 /*            (counter[0]..der[*counter-1]).          */
586 /*   max_len: size of der vector                      */
587 /* Return:                                            */
588 /*   ASN1_GENERIC_ERROR if the type is unknown,       */
589 /*   ASN1_MEM_ERROR if der vector isn't big enough,   */
590 /*   otherwise ASN1_SUCCESS.                          */
591 /******************************************************/
592 static int
593 _asn1_insert_tag_der (asn1_node node, unsigned char *der, int *counter,
594                       int *max_len)
595 {
596   asn1_node p;
597   int tag_len, is_tag_implicit;
598   unsigned char class, class_implicit = 0, temp[MAX(SIZEOF_UNSIGNED_INT * 3 + 1, LTOSTR_MAX_SIZE)];
599   unsigned long tag_implicit = 0;
600   unsigned char tag_der[MAX_TAG_LEN];
601
602   is_tag_implicit = 0;
603
604   if (node->type & CONST_TAG)
605     {
606       p = node->down;
607       while (p)
608         {
609           if (type_field (p->type) == ASN1_ETYPE_TAG)
610             {
611               if (p->type & CONST_APPLICATION)
612                 class = ASN1_CLASS_APPLICATION;
613               else if (p->type & CONST_UNIVERSAL)
614                 class = ASN1_CLASS_UNIVERSAL;
615               else if (p->type & CONST_PRIVATE)
616                 class = ASN1_CLASS_PRIVATE;
617               else
618                 class = ASN1_CLASS_CONTEXT_SPECIFIC;
619
620               if (p->type & CONST_EXPLICIT)
621                 {
622                   if (is_tag_implicit)
623                     _asn1_tag_der (class_implicit, tag_implicit, tag_der,
624                                    &tag_len);
625                   else
626                     _asn1_tag_der (class | ASN1_CLASS_STRUCTURED,
627                                    _asn1_strtoul (p->value, NULL, 10),
628                                    tag_der, &tag_len);
629
630                   *max_len -= tag_len;
631                   if (*max_len >= 0)
632                     memcpy (der + *counter, tag_der, tag_len);
633                   *counter += tag_len;
634
635                   _asn1_ltostr (*counter, (char *) temp);
636                   _asn1_set_name (p, (const char *) temp);
637
638                   is_tag_implicit = 0;
639                 }
640               else
641                 {               /* CONST_IMPLICIT */
642                   if (!is_tag_implicit)
643                     {
644                       if ((type_field (node->type) == ASN1_ETYPE_SEQUENCE) ||
645                           (type_field (node->type) == ASN1_ETYPE_SEQUENCE_OF)
646                           || (type_field (node->type) == ASN1_ETYPE_SET)
647                           || (type_field (node->type) == ASN1_ETYPE_SET_OF))
648                         class |= ASN1_CLASS_STRUCTURED;
649                       class_implicit = class;
650                       tag_implicit = _asn1_strtoul (p->value, NULL, 10);
651                       is_tag_implicit = 1;
652                     }
653                 }
654             }
655           p = p->right;
656         }
657     }
658
659   if (is_tag_implicit)
660     {
661       _asn1_tag_der (class_implicit, tag_implicit, tag_der, &tag_len);
662     }
663   else
664     {
665       unsigned type = type_field (node->type);
666       switch (type)
667         {
668         CASE_HANDLED_ETYPES:
669           _asn1_tag_der (_asn1_tags[type].class, _asn1_tags[type].tag,
670                          tag_der, &tag_len);
671           break;
672         case ASN1_ETYPE_TAG:
673         case ASN1_ETYPE_CHOICE:
674         case ASN1_ETYPE_ANY:
675           tag_len = 0;
676           break;
677         default:
678           return ASN1_GENERIC_ERROR;
679         }
680     }
681
682   *max_len -= tag_len;
683   if (*max_len >= 0)
684     memcpy (der + *counter, tag_der, tag_len);
685   *counter += tag_len;
686
687   if (*max_len < 0)
688     return ASN1_MEM_ERROR;
689
690   return ASN1_SUCCESS;
691 }
692
693 /******************************************************/
694 /* Function : _asn1_ordering_set                      */
695 /* Description: puts the elements of a SET type in    */
696 /* the correct order according to DER rules.          */
697 /* Parameters:                                        */
698 /*   der: string with the DER coding.                 */
699 /*   node: pointer to the SET element.                */
700 /* Return:                                            */
701 /*    ASN1_SUCCESS if successful                      */
702 /*    or an error value.                              */
703 /******************************************************/
704 static int
705 _asn1_ordering_set (unsigned char *der, int der_len, asn1_node node)
706 {
707   struct vet
708   {
709     int end;
710     unsigned long value;
711     struct vet *next, *prev;
712   };
713
714   int counter, len, len2;
715   struct vet *first, *last, *p_vet, *p2_vet;
716   asn1_node p;
717   unsigned char class, *temp;
718   unsigned long tag, t;
719   int err;
720
721   counter = 0;
722
723   if (type_field (node->type) != ASN1_ETYPE_SET)
724     return ASN1_VALUE_NOT_VALID;
725
726   p = node->down;
727   while (p && ((type_field (p->type) == ASN1_ETYPE_TAG) ||
728          (type_field (p->type) == ASN1_ETYPE_SIZE)))
729     p = p->right;
730
731   if ((p == NULL) || (p->right == NULL))
732     return ASN1_SUCCESS;
733
734   first = last = NULL;
735   while (p)
736     {
737       p_vet = malloc (sizeof (struct vet));
738       if (p_vet == NULL)
739         {
740           err = ASN1_MEM_ALLOC_ERROR;
741           goto error;
742         }
743
744       p_vet->next = NULL;
745       p_vet->prev = last;
746       if (first == NULL)
747         first = p_vet;
748       else
749         last->next = p_vet;
750       last = p_vet;
751
752       /* tag value calculation */
753       err = asn1_get_tag_der (der + counter, der_len - counter, &class, &len2,
754                               &tag);
755       if (err != ASN1_SUCCESS)
756         goto error;
757
758       t = class << 24;
759       p_vet->value = t | tag;
760       counter += len2;
761
762       /* extraction and length */
763       len2 = asn1_get_length_der (der + counter, der_len - counter, &len);
764       if (len2 < 0)
765         {
766           err = ASN1_DER_ERROR;
767           goto error;
768         }
769       counter += len + len2;
770
771       p_vet->end = counter;
772       p = p->right;
773     }
774
775   p_vet = first;
776
777   while (p_vet)
778     {
779       p2_vet = p_vet->next;
780       counter = 0;
781       while (p2_vet)
782         {
783           if (p_vet->value > p2_vet->value)
784             {
785               /* change position */
786               temp = malloc (p_vet->end - counter);
787               if (temp == NULL)
788                 {
789                   err = ASN1_MEM_ALLOC_ERROR;
790                   goto error;
791                 }
792
793               memcpy (temp, der + counter, p_vet->end - counter);
794               memcpy (der + counter, der + p_vet->end,
795                       p2_vet->end - p_vet->end);
796               memcpy (der + counter + p2_vet->end - p_vet->end, temp,
797                       p_vet->end - counter);
798               free (temp);
799
800               tag = p_vet->value;
801               p_vet->value = p2_vet->value;
802               p2_vet->value = tag;
803
804               p_vet->end = counter + (p2_vet->end - p_vet->end);
805             }
806           counter = p_vet->end;
807
808           p2_vet = p2_vet->next;
809           p_vet = p_vet->next;
810         }
811
812       if (p_vet != first)
813         p_vet->prev->next = NULL;
814       else
815         first = NULL;
816       free (p_vet);
817       p_vet = first;
818     }
819   return ASN1_SUCCESS;
820
821 error:
822   while (first != NULL)
823     {
824       p_vet = first;
825       first = first->next;
826       free(p_vet);
827     }
828   return err;
829 }
830
831 /******************************************************/
832 /* Function : _asn1_ordering_set_of                   */
833 /* Description: puts the elements of a SET OF type in */
834 /* the correct order according to DER rules.          */
835 /* Parameters:                                        */
836 /*   der: string with the DER coding.                 */
837 /*   node: pointer to the SET OF element.             */
838 /* Return:                                            */
839 /*    ASN1_SUCCESS if successful                      */
840 /*    or an error value.                              */
841 /******************************************************/
842 static int
843 _asn1_ordering_set_of (unsigned char *der, int der_len, asn1_node node)
844 {
845   struct vet
846   {
847     int end;
848     struct vet *next, *prev;
849   };
850
851   int counter, len, len2, change;
852   struct vet *first, *last, *p_vet, *p2_vet;
853   asn1_node p;
854   unsigned char *temp, class;
855   unsigned long k, length;
856   int err;
857
858   counter = 0;
859
860   if (type_field (node->type) != ASN1_ETYPE_SET_OF)
861     return ASN1_VALUE_NOT_VALID;
862
863   p = node->down;
864   while (p && ((type_field (p->type) == ASN1_ETYPE_TAG) ||
865          (type_field (p->type) == ASN1_ETYPE_SIZE)))
866     p = p->right;
867   if (p == NULL)
868     return ASN1_VALUE_NOT_VALID;
869   p = p->right;
870
871   if ((p == NULL) || (p->right == NULL))
872     return ASN1_SUCCESS;
873
874   first = last = NULL;
875   while (p)
876     {
877       p_vet = malloc (sizeof (struct vet));
878       if (p_vet == NULL)
879         {
880           err = ASN1_MEM_ALLOC_ERROR;
881           goto error;
882         }
883
884       p_vet->next = NULL;
885       p_vet->prev = last;
886       if (first == NULL)
887         first = p_vet;
888       else
889         last->next = p_vet;
890       last = p_vet;
891
892       /* extraction of tag and length */
893       if (der_len - counter > 0)
894         {
895
896           err = asn1_get_tag_der (der + counter, der_len - counter, &class,
897                                   &len, NULL);
898           if (err != ASN1_SUCCESS)
899             goto error;
900           counter += len;
901
902           len2 = asn1_get_length_der (der + counter, der_len - counter, &len);
903           if (len2 < 0)
904             {
905               err = ASN1_DER_ERROR;
906               goto error;
907             }
908           counter += len + len2;
909         }
910       else
911         {
912           err = ASN1_DER_ERROR;
913           goto error;
914         }
915
916       p_vet->end = counter;
917       p = p->right;
918     }
919
920   p_vet = first;
921
922   while (p_vet)
923     {
924       p2_vet = p_vet->next;
925       counter = 0;
926       while (p2_vet)
927         {
928           length = MIN(p_vet->end - counter, p2_vet->end - p_vet->end);
929           change = -1;
930           for (k = 0; k < length; k++)
931             if (der[counter + k] > der[p_vet->end + k])
932               {
933                 change = 1;
934                 break;
935               }
936             else if (der[counter + k] < der[p_vet->end + k])
937               {
938                 change = 0;
939                 break;
940               }
941
942           if ((change == -1)
943               && ((p_vet->end - counter) > (p2_vet->end - p_vet->end)))
944             change = 1;
945
946           if (change == 1)
947             {
948               /* change position */
949               temp = malloc (p_vet->end - counter);
950               if (temp == NULL)
951                 {
952                   err = ASN1_MEM_ALLOC_ERROR;
953                   goto error;
954                 }
955
956               memcpy (temp, der + counter, (p_vet->end) - counter);
957               memcpy (der + counter, der + (p_vet->end),
958                       (p2_vet->end) - (p_vet->end));
959               memcpy (der + counter + (p2_vet->end) - (p_vet->end), temp,
960                       (p_vet->end) - counter);
961               free (temp);
962
963               p_vet->end = counter + (p2_vet->end - p_vet->end);
964             }
965           counter = p_vet->end;
966
967           p2_vet = p2_vet->next;
968           p_vet = p_vet->next;
969         }
970
971       if (p_vet != first)
972         p_vet->prev->next = NULL;
973       else
974         first = NULL;
975       free (p_vet);
976       p_vet = first;
977     }
978   return ASN1_SUCCESS;
979
980 error:
981   while (first != NULL)
982     {
983       p_vet = first;
984       first = first->next;
985       free(p_vet);
986     }
987   return err;
988 }
989
990 /**
991  * asn1_der_coding:
992  * @element: pointer to an ASN1 element
993  * @name: the name of the structure you want to encode (it must be
994  *   inside *POINTER).
995  * @ider: vector that will contain the DER encoding. DER must be a
996  *   pointer to memory cells already allocated.
997  * @len: number of bytes of *@ider: @ider[0]..@ider[len-1], Initialy
998  *   holds the sizeof of der vector.
999  * @ErrorDescription: return the error description or an empty
1000  *   string if success.
1001  *
1002  * Creates the DER encoding for the NAME structure (inside *POINTER
1003  * structure).
1004  *
1005  * Returns: %ASN1_SUCCESS if DER encoding OK, %ASN1_ELEMENT_NOT_FOUND
1006  *   if @name is not a valid element, %ASN1_VALUE_NOT_FOUND if there
1007  *   is an element without a value, %ASN1_MEM_ERROR if the @ider
1008  *   vector isn't big enough and in this case @len will contain the
1009  *   length needed.
1010  **/
1011 int
1012 asn1_der_coding (asn1_node element, const char *name, void *ider, int *len,
1013                  char *ErrorDescription)
1014 {
1015   asn1_node node, p, p2;
1016   unsigned char temp[MAX(LTOSTR_MAX_SIZE, SIZEOF_UNSIGNED_LONG_INT * 3 + 1)];
1017   int counter, counter_old, len2, len3, move, max_len, max_len_old;
1018   int err;
1019   unsigned char *der = ider;
1020
1021   node = asn1_find_node (element, name);
1022   if (node == NULL)
1023     return ASN1_ELEMENT_NOT_FOUND;
1024
1025   /* Node is now a locally allocated variable.
1026    * That is because in some point we modify the
1027    * structure, and I don't know why! --nmav
1028    */
1029   node = _asn1_copy_structure3 (node);
1030   if (node == NULL)
1031     return ASN1_ELEMENT_NOT_FOUND;
1032
1033   max_len = *len;
1034
1035   counter = 0;
1036   move = DOWN;
1037   p = node;
1038   while (1)
1039     {
1040
1041       counter_old = counter;
1042       max_len_old = max_len;
1043       if (move != UP)
1044         {
1045           err = _asn1_insert_tag_der (p, der, &counter, &max_len);
1046           if (err != ASN1_SUCCESS && err != ASN1_MEM_ERROR)
1047             goto error;
1048         }
1049       switch (type_field (p->type))
1050         {
1051         case ASN1_ETYPE_NULL:
1052           max_len--;
1053           if (max_len >= 0)
1054             der[counter] = 0;
1055           counter++;
1056           move = RIGHT;
1057           break;
1058         case ASN1_ETYPE_BOOLEAN:
1059           if ((p->type & CONST_DEFAULT) && (p->value == NULL))
1060             {
1061               counter = counter_old;
1062               max_len = max_len_old;
1063             }
1064           else
1065             {
1066               if (p->value == NULL)
1067                 {
1068                   _asn1_error_description_value_not_found (p,
1069                                                            ErrorDescription);
1070                   err = ASN1_VALUE_NOT_FOUND;
1071                   goto error;
1072                 }
1073               max_len -= 2;
1074               if (max_len >= 0)
1075                 {
1076                   der[counter++] = 1;
1077                   if (p->value[0] == 'F')
1078                     der[counter++] = 0;
1079                   else
1080                     der[counter++] = 0xFF;
1081                 }
1082               else
1083                 counter += 2;
1084             }
1085           move = RIGHT;
1086           break;
1087         case ASN1_ETYPE_INTEGER:
1088         case ASN1_ETYPE_ENUMERATED:
1089           if ((p->type & CONST_DEFAULT) && (p->value == NULL))
1090             {
1091               counter = counter_old;
1092               max_len = max_len_old;
1093             }
1094           else
1095             {
1096               if (p->value == NULL)
1097                 {
1098                   _asn1_error_description_value_not_found (p,
1099                                                            ErrorDescription);
1100                   err = ASN1_VALUE_NOT_FOUND;
1101                   goto error;
1102                 }
1103               len2 = asn1_get_length_der (p->value, p->value_len, &len3);
1104               if (len2 < 0)
1105                 {
1106                   err = ASN1_DER_ERROR;
1107                   goto error;
1108                 }
1109               max_len -= len2 + len3;
1110               if (max_len >= 0)
1111                 memcpy (der + counter, p->value, len3 + len2);
1112               counter += len3 + len2;
1113             }
1114           move = RIGHT;
1115           break;
1116         case ASN1_ETYPE_OBJECT_ID:
1117           if ((p->type & CONST_DEFAULT) && (p->value == NULL))
1118             {
1119               counter = counter_old;
1120               max_len = max_len_old;
1121             }
1122           else
1123             {
1124               if (p->value == NULL)
1125                 {
1126                   _asn1_error_description_value_not_found (p,
1127                                                            ErrorDescription);
1128                   err = ASN1_VALUE_NOT_FOUND;
1129                   goto error;
1130                 }
1131               len2 = max_len;
1132               err = _asn1_objectid_der (p->value, der + counter, &len2);
1133               if (err != ASN1_SUCCESS && err != ASN1_MEM_ERROR)
1134                 goto error;
1135
1136               max_len -= len2;
1137               counter += len2;
1138             }
1139           move = RIGHT;
1140           break;
1141         case ASN1_ETYPE_GENERALIZED_TIME:
1142         case ASN1_ETYPE_UTC_TIME:
1143           if (p->value == NULL)
1144             {
1145               _asn1_error_description_value_not_found (p, ErrorDescription);
1146               err = ASN1_VALUE_NOT_FOUND;
1147               goto error;
1148             }
1149           len2 = max_len;
1150           err = _asn1_time_der (p->value, p->value_len, der + counter, &len2);
1151           if (err != ASN1_SUCCESS && err != ASN1_MEM_ERROR)
1152             goto error;
1153
1154           max_len -= len2;
1155           counter += len2;
1156           move = RIGHT;
1157           break;
1158         case ASN1_ETYPE_OCTET_STRING:
1159         case ASN1_ETYPE_GENERALSTRING:
1160         case ASN1_ETYPE_NUMERIC_STRING:
1161         case ASN1_ETYPE_IA5_STRING:
1162         case ASN1_ETYPE_TELETEX_STRING:
1163         case ASN1_ETYPE_PRINTABLE_STRING:
1164         case ASN1_ETYPE_UNIVERSAL_STRING:
1165         case ASN1_ETYPE_BMP_STRING:
1166         case ASN1_ETYPE_UTF8_STRING:
1167         case ASN1_ETYPE_VISIBLE_STRING:
1168         case ASN1_ETYPE_BIT_STRING:
1169           if (p->value == NULL)
1170             {
1171               _asn1_error_description_value_not_found (p, ErrorDescription);
1172               err = ASN1_VALUE_NOT_FOUND;
1173               goto error;
1174             }
1175           len2 = asn1_get_length_der (p->value, p->value_len, &len3);
1176           if (len2 < 0)
1177             {
1178               err = ASN1_DER_ERROR;
1179               goto error;
1180             }
1181           max_len -= len2 + len3;
1182           if (max_len >= 0)
1183             memcpy (der + counter, p->value, len3 + len2);
1184           counter += len3 + len2;
1185           move = RIGHT;
1186           break;
1187         case ASN1_ETYPE_SEQUENCE:
1188         case ASN1_ETYPE_SET:
1189           if (move != UP)
1190             {
1191               p->tmp_ival = counter;
1192               if (p->down == NULL)
1193                 {
1194                   move = UP;
1195                   continue;
1196                 }
1197               else
1198                 {
1199                   p2 = p->down;
1200                   while (p2 && (type_field (p2->type) == ASN1_ETYPE_TAG))
1201                     p2 = p2->right;
1202                   if (p2)
1203                     {
1204                       p = p2;
1205                       move = RIGHT;
1206                       continue;
1207                     }
1208                   move = UP;
1209                   continue;
1210                 }
1211             }
1212           else
1213             {                   /* move==UP */
1214               len2 = p->tmp_ival;
1215               p->tmp_ival = 0;
1216               if ((type_field (p->type) == ASN1_ETYPE_SET) && (max_len >= 0))
1217                 {
1218                   err = _asn1_ordering_set (der + len2, counter - len2, p);
1219                   if (err != ASN1_SUCCESS)
1220                     goto error;
1221                 }
1222               asn1_length_der (counter - len2, temp, &len3);
1223               max_len -= len3;
1224               if (max_len >= 0)
1225                 {
1226                   memmove (der + len2 + len3, der + len2, counter - len2);
1227                   memcpy (der + len2, temp, len3);
1228                 }
1229               counter += len3;
1230               move = RIGHT;
1231             }
1232           break;
1233         case ASN1_ETYPE_SEQUENCE_OF:
1234         case ASN1_ETYPE_SET_OF:
1235           if (move != UP)
1236             {
1237               p->tmp_ival = counter;
1238               p = p->down;
1239               while ((type_field (p->type) == ASN1_ETYPE_TAG)
1240                      || (type_field (p->type) == ASN1_ETYPE_SIZE))
1241                 p = p->right;
1242               if (p->right)
1243                 {
1244                   p = p->right;
1245                   move = RIGHT;
1246                   continue;
1247                 }
1248               else
1249                 p = _asn1_get_up (p);
1250               move = UP;
1251             }
1252           if (move == UP)
1253             {
1254               len2 = p->tmp_ival;
1255               p->tmp_ival = 0;
1256               if ((type_field (p->type) == ASN1_ETYPE_SET_OF)
1257                   && (counter - len2 > 0) && (max_len >= 0))
1258                 {
1259                   err = _asn1_ordering_set_of (der + len2, counter - len2, p);
1260                   if (err != ASN1_SUCCESS)
1261                     goto error;
1262                 }
1263               asn1_length_der (counter - len2, temp, &len3);
1264               max_len -= len3;
1265               if (max_len >= 0)
1266                 {
1267                   memmove (der + len2 + len3, der + len2, counter - len2);
1268                   memcpy (der + len2, temp, len3);
1269                 }
1270               counter += len3;
1271               move = RIGHT;
1272             }
1273           break;
1274         case ASN1_ETYPE_ANY:
1275           if (p->value == NULL)
1276             {
1277               _asn1_error_description_value_not_found (p, ErrorDescription);
1278               err = ASN1_VALUE_NOT_FOUND;
1279               goto error;
1280             }
1281           len2 = asn1_get_length_der (p->value, p->value_len, &len3);
1282           if (len2 < 0)
1283             {
1284               err = ASN1_DER_ERROR;
1285               goto error;
1286             }
1287           max_len -= len2;
1288           if (max_len >= 0)
1289             memcpy (der + counter, p->value + len3, len2);
1290           counter += len2;
1291           move = RIGHT;
1292           break;
1293         default:
1294           move = (move == UP) ? RIGHT : DOWN;
1295           break;
1296         }
1297
1298       if ((move != DOWN) && (counter != counter_old))
1299         {
1300           err = _asn1_complete_explicit_tag (p, der, &counter, &max_len);
1301           if (err != ASN1_SUCCESS && err != ASN1_MEM_ERROR)
1302             goto error;
1303         }
1304
1305       if (p == node && move != DOWN)
1306         break;
1307
1308       if (move == DOWN)
1309         {
1310           if (p->down)
1311             p = p->down;
1312           else
1313             move = RIGHT;
1314         }
1315       if (move == RIGHT)
1316         {
1317           if (p->right)
1318             p = p->right;
1319           else
1320             move = UP;
1321         }
1322       if (move == UP)
1323         p = _asn1_get_up (p);
1324     }
1325
1326   *len = counter;
1327
1328   if (max_len < 0)
1329     {
1330       err = ASN1_MEM_ERROR;
1331       goto error;
1332     }
1333
1334   err = ASN1_SUCCESS;
1335
1336 error:
1337   asn1_delete_structure (&node);
1338   return err;
1339 }