"Fossies" - the Fresh Open Source Software Archive

Member "libksba-1.5.0/src/cms.c" (28 May 2020, 103813 Bytes) of package /linux/privat/libksba-1.5.0.tar.bz2:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "cms.c" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 1.4.0_vs_1.5.0.

    1 /* cms.c - cryptographic message syntax main functions
    2  * Copyright (C) 2001, 2003, 2004, 2008, 2012, 2020 g10 Code GmbH
    3  *
    4  * This file is part of KSBA.
    5  *
    6  * KSBA is free software; you can redistribute it and/or modify
    7  * it under the terms of either
    8  *
    9  *   - the GNU Lesser General Public License as published by the Free
   10  *     Software Foundation; either version 3 of the License, or (at
   11  *     your option) any later version.
   12  *
   13  * or
   14  *
   15  *   - the GNU General Public License as published by the Free
   16  *     Software Foundation; either version 2 of the License, or (at
   17  *     your option) any later version.
   18  *
   19  * or both in parallel, as here.
   20  *
   21  * KSBA is distributed in the hope that it will be useful, but WITHOUT
   22  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
   23  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
   24  * License for more details.
   25  *
   26  * You should have received a copies of the GNU General Public License
   27  * and the GNU Lesser General Public License along with this program;
   28  * if not, see <http://www.gnu.org/licenses/>.
   29  */
   30 
   31 /* References:
   32  * RFC-5652 := Cryptographic Message Syntax (CMS) (aka STD0070)
   33  * SPHINX   := CMS profile developed by the German BSI.
   34  *             (see also https://lwn.net/2001/1011/a/german-smime.php3)
   35  * PKCS#7   := Original specification of CMS
   36  */
   37 
   38 #include <config.h>
   39 #include <stdio.h>
   40 #include <stdlib.h>
   41 #include <string.h>
   42 #include <assert.h>
   43 #include <errno.h>
   44 
   45 #include "util.h"
   46 
   47 #include "cms.h"
   48 #include "convert.h"
   49 #include "keyinfo.h"
   50 #include "der-encoder.h"
   51 #include "ber-help.h"
   52 #include "sexp-parse.h"
   53 #include "cert.h"
   54 #include "der-builder.h"
   55 
   56 
   57 static gpg_error_t ct_parse_data (ksba_cms_t cms);
   58 static gpg_error_t ct_parse_signed_data (ksba_cms_t cms);
   59 static gpg_error_t ct_parse_enveloped_data (ksba_cms_t cms);
   60 static gpg_error_t ct_parse_digested_data (ksba_cms_t cms);
   61 static gpg_error_t ct_parse_encrypted_data (ksba_cms_t cms);
   62 static gpg_error_t ct_build_data (ksba_cms_t cms);
   63 static gpg_error_t ct_build_signed_data (ksba_cms_t cms);
   64 static gpg_error_t ct_build_enveloped_data (ksba_cms_t cms);
   65 static gpg_error_t ct_build_digested_data (ksba_cms_t cms);
   66 static gpg_error_t ct_build_encrypted_data (ksba_cms_t cms);
   67 
   68 static struct {
   69   const char *oid;
   70   ksba_content_type_t ct;
   71   gpg_error_t (*parse_handler)(ksba_cms_t);
   72   gpg_error_t (*build_handler)(ksba_cms_t);
   73 } content_handlers[] = {
   74   {  "1.2.840.113549.1.7.1", KSBA_CT_DATA,
   75      ct_parse_data   , ct_build_data                  },
   76   {  "1.2.840.113549.1.7.2", KSBA_CT_SIGNED_DATA,
   77      ct_parse_signed_data   , ct_build_signed_data    },
   78   {  "1.2.840.113549.1.7.3", KSBA_CT_ENVELOPED_DATA,
   79      ct_parse_enveloped_data, ct_build_enveloped_data },
   80   {  "1.2.840.113549.1.7.5", KSBA_CT_DIGESTED_DATA,
   81      ct_parse_digested_data , ct_build_digested_data  },
   82   {  "1.2.840.113549.1.7.6", KSBA_CT_ENCRYPTED_DATA,
   83      ct_parse_encrypted_data, ct_build_encrypted_data },
   84   {  "1.2.840.113549.1.9.16.1.2", KSBA_CT_AUTH_DATA   },
   85   {  "1.3.6.1.4.1.311.2.1.4", KSBA_CT_SPC_IND_DATA_CTX,
   86      ct_parse_data   , ct_build_data                  },
   87   {  "1.3.6.1.4.1.11591.2.3.1", KSBA_CT_OPENPGP_KEYBLOCK,
   88      ct_parse_data   , ct_build_data                  },
   89   { NULL }
   90 };
   91 
   92 static const char oidstr_contentType[] = "1.2.840.113549.1.9.3";
   93 /*static char oid_contentType[9] = "\x2A\x86\x48\x86\xF7\x0D\x01\x09\x03";*/
   94 
   95 static const char oidstr_messageDigest[] = "1.2.840.113549.1.9.4";
   96 static const char oid_messageDigest[9] ="\x2A\x86\x48\x86\xF7\x0D\x01\x09\x04";
   97 
   98 static const char oidstr_signingTime[] = "1.2.840.113549.1.9.5";
   99 static const char oid_signingTime[9] = "\x2A\x86\x48\x86\xF7\x0D\x01\x09\x05";
  100 
  101 static const char oidstr_smimeCapabilities[] = "1.2.840.113549.1.9.15";
  102 
  103 
  104 
  105 #if 0 /* Set to 1 to use this debug helper.  */
  106 static void
  107 log_sexp (const char *text, ksba_const_sexp_t p)
  108 {
  109   int level = 0;
  110 
  111   gpgrt_log_debug ("%s: ", text);
  112   if (!p)
  113     gpgrt_log_printf ("[none]");
  114   else
  115     {
  116       for (;;)
  117         {
  118           if (*p == '(')
  119             {
  120               gpgrt_log_printf ("%c", *p);
  121               p++;
  122               level++;
  123             }
  124           else if (*p == ')')
  125             {
  126               gpgrt_log_printf ("%c", *p);
  127               p++;
  128               if (--level <= 0 )
  129                 return;
  130             }
  131           else if (!digitp (p))
  132             {
  133               gpgrt_log_printf ("[invalid s-exp]");
  134               return;
  135             }
  136           else
  137             {
  138               char *endp;
  139               const unsigned char *s;
  140               unsigned long len, n;
  141 
  142               len = strtoul (p, &endp, 10);
  143               p = endp;
  144               if (*p != ':')
  145                 {
  146                   gpgrt_log_printf ("[invalid s-exp]");
  147                   return;
  148                 }
  149               p++;
  150               for (s=p,n=0; n < len; n++, s++)
  151                 if ( !((*s >= 'a' && *s <= 'z')
  152                        || (*s >= 'A' && *s <= 'Z')
  153                        || (*s >= '0' && *s <= '9')
  154                        || *s == '-' || *s == '.'))
  155                   break;
  156               if (n < len)
  157                 {
  158                   gpgrt_log_printf ("#");
  159                   for (n=0; n < len; n++, p++)
  160                     gpgrt_log_printf ("%02X", *p);
  161                   gpgrt_log_printf ("#");
  162                 }
  163               else
  164                 {
  165                   for (n=0; n < len; n++, p++)
  166                     gpgrt_log_printf ("%c", *p);
  167                 }
  168             }
  169         }
  170     }
  171   gpgrt_log_printf ("\n");
  172 }
  173 #endif /* debug helper */
  174 
  175 
  176 /* Helper for read_and_hash_cont().  */
  177 static gpg_error_t
  178 read_hash_block (ksba_cms_t cms, unsigned long nleft)
  179 {
  180   gpg_error_t err;
  181   char buffer[4096];
  182   size_t n, nread;
  183 
  184   while (nleft)
  185     {
  186       n = nleft < sizeof (buffer)? nleft : sizeof (buffer);
  187       err = ksba_reader_read (cms->reader, buffer, n, &nread);
  188       if (err)
  189         return err;
  190       nleft -= nread;
  191       if (cms->hash_fnc)
  192         cms->hash_fnc (cms->hash_fnc_arg, buffer, nread);
  193       if (cms->writer)
  194         err = ksba_writer_write (cms->writer, buffer, nread);
  195       if (err)
  196         return err;
  197     }
  198   return 0;
  199 }
  200 
  201 
  202 /* Copy all the bytes from the reader to the writer and hash them if a
  203    a hash function has been set.  The writer may be NULL to just do
  204    the hashing */
  205 static gpg_error_t
  206 read_and_hash_cont (ksba_cms_t cms)
  207 {
  208   gpg_error_t err = 0;
  209   unsigned long nleft;
  210   struct tag_info ti;
  211 
  212   if (cms->inner_cont_ndef)
  213     {
  214       for (;;)
  215         {
  216           err = _ksba_ber_read_tl (cms->reader, &ti);
  217           if (err)
  218             return err;
  219 
  220           if (ti.class == CLASS_UNIVERSAL && ti.tag == TYPE_OCTET_STRING
  221               && !ti.is_constructed)
  222             { /* next chunk */
  223               nleft = ti.length;
  224               err = read_hash_block (cms, nleft);
  225               if (err)
  226                 return err;
  227             }
  228           else if (ti.class == CLASS_UNIVERSAL && ti.tag == TYPE_OCTET_STRING
  229                    && ti.is_constructed)
  230             { /* next chunk is constructed */
  231               for (;;)
  232                 {
  233                   err = _ksba_ber_read_tl (cms->reader, &ti);
  234                   if (err)
  235                     return err;
  236                   if (ti.class == CLASS_UNIVERSAL
  237                       && ti.tag == TYPE_OCTET_STRING
  238                       && !ti.is_constructed)
  239                     {
  240                       nleft = ti.length;
  241                       err = read_hash_block (cms, nleft);
  242                       if (err)
  243                         return err;
  244                     }
  245                   else if (ti.class == CLASS_UNIVERSAL && !ti.tag
  246                            && !ti.is_constructed)
  247                     break; /* ready with this chunk */
  248                   else
  249                     return gpg_error (GPG_ERR_ENCODING_PROBLEM);
  250                 }
  251             }
  252           else if (ti.class == CLASS_UNIVERSAL && !ti.tag
  253                    && !ti.is_constructed)
  254             return 0; /* ready */
  255           else
  256             return gpg_error (GPG_ERR_ENCODING_PROBLEM);
  257         }
  258     }
  259   else
  260     {
  261       /* This is basically the same as above but we allow for
  262          arbitrary types.  Not sure whether it is really needed but
  263          right in the beginning of gnupg 1.9 we had at least one
  264          message with didn't used octet strings.  Not ethat we don't
  265          do proper NLEFT checking but well why should we validate
  266          these things?  Well, it might be nice to have such a feature
  267          but then we should write a more general mechanism to do
  268          that.  */
  269       nleft = cms->inner_cont_len;
  270       /* First read the octet string but allow all types here */
  271       err = _ksba_ber_read_tl (cms->reader, &ti);
  272       if (err)
  273         return err;
  274       if (nleft < ti.nhdr)
  275         return gpg_error (GPG_ERR_ENCODING_PROBLEM);
  276       nleft -= ti.nhdr;
  277 
  278       if (ti.class == CLASS_UNIVERSAL && ti.tag == TYPE_OCTET_STRING
  279           && ti.is_constructed)
  280         { /* Next chunk is constructed */
  281           for (;;)
  282             {
  283               err = _ksba_ber_read_tl (cms->reader, &ti);
  284               if (err)
  285                 return err;
  286               if (ti.class == CLASS_UNIVERSAL
  287                   && ti.tag == TYPE_OCTET_STRING
  288                   && !ti.is_constructed)
  289                 {
  290                   nleft = ti.length;
  291                   err = read_hash_block (cms, nleft);
  292                   if (err)
  293                     return err;
  294                 }
  295               else if (ti.class == CLASS_UNIVERSAL && !ti.tag
  296                        && !ti.is_constructed)
  297                 break; /* Ready with this chunk */
  298               else
  299                 return gpg_error (GPG_ERR_ENCODING_PROBLEM);
  300             }
  301         }
  302       else if (ti.class == CLASS_UNIVERSAL && !ti.tag
  303                && !ti.is_constructed)
  304         return 0; /* ready */
  305       else
  306         {
  307           err = read_hash_block (cms, nleft);
  308           if (err)
  309             return err;
  310         }
  311     }
  312   return 0;
  313 }
  314 
  315 
  316 
  317 /* Copy all the encrypted bytes from the reader to the writer.
  318    Handles indefinite length encoding */
  319 static gpg_error_t
  320 read_encrypted_cont (ksba_cms_t cms)
  321 {
  322   gpg_error_t err = 0;
  323   unsigned long nleft;
  324   char buffer[4096];
  325   size_t n, nread;
  326 
  327   if (cms->inner_cont_ndef)
  328     {
  329       struct tag_info ti;
  330 
  331       /* fixme: this ist mostly a duplicate of the code in
  332          read_and_hash_cont(). */
  333       for (;;)
  334         {
  335           err = _ksba_ber_read_tl (cms->reader, &ti);
  336           if (err)
  337             return err;
  338 
  339           if (ti.class == CLASS_UNIVERSAL && ti.tag == TYPE_OCTET_STRING
  340               && !ti.is_constructed)
  341             { /* next chunk */
  342               nleft = ti.length;
  343               while (nleft)
  344                 {
  345                   n = nleft < sizeof (buffer)? nleft : sizeof (buffer);
  346                   err = ksba_reader_read (cms->reader, buffer, n, &nread);
  347                   if (err)
  348                     return err;
  349                   nleft -= nread;
  350                   err = ksba_writer_write (cms->writer, buffer, nread);
  351                   if (err)
  352                     return err;
  353                 }
  354             }
  355           else if (ti.class == CLASS_UNIVERSAL && ti.tag == TYPE_OCTET_STRING
  356                    && ti.is_constructed)
  357             { /* next chunk is constructed */
  358               for (;;)
  359                 {
  360                   err = _ksba_ber_read_tl (cms->reader, &ti);
  361                   if (err)
  362                     return err;
  363                   if (ti.class == CLASS_UNIVERSAL
  364                       && ti.tag == TYPE_OCTET_STRING
  365                       && !ti.is_constructed)
  366                     {
  367                       nleft = ti.length;
  368                       while (nleft)
  369                         {
  370                           n = nleft < sizeof (buffer)? nleft : sizeof (buffer);
  371                           err = ksba_reader_read (cms->reader, buffer, n, &nread);
  372                           if (err)
  373                             return err;
  374                           nleft -= nread;
  375                           if (cms->writer)
  376                             err = ksba_writer_write (cms->writer, buffer, nread);
  377                           if (err)
  378                             return err;
  379                         }
  380                     }
  381                   else if (ti.class == CLASS_UNIVERSAL && !ti.tag
  382                            && !ti.is_constructed)
  383                     break; /* ready with this chunk */
  384                   else
  385                     return gpg_error (GPG_ERR_ENCODING_PROBLEM);
  386                 }
  387             }
  388           else if (ti.class == CLASS_UNIVERSAL && !ti.tag
  389                    && !ti.is_constructed)
  390             return 0; /* ready */
  391           else
  392             return gpg_error (GPG_ERR_ENCODING_PROBLEM);
  393         }
  394     }
  395   else
  396     {
  397       nleft = cms->inner_cont_len;
  398       while (nleft)
  399         {
  400           n = nleft < sizeof (buffer)? nleft : sizeof (buffer);
  401           err = ksba_reader_read (cms->reader, buffer, n, &nread);
  402           if (err)
  403             return err;
  404           nleft -= nread;
  405           err = ksba_writer_write (cms->writer, buffer, nread);
  406           if (err)
  407             return err;
  408         }
  409     }
  410   return 0;
  411 }
  412 
  413 /* copy data from reader to writer.  Assume that it is an octet string
  414    and insert undefinite length headers where needed */
  415 static gpg_error_t
  416 write_encrypted_cont (ksba_cms_t cms)
  417 {
  418   gpg_error_t err = 0;
  419   char buffer[4096];
  420   size_t nread;
  421 
  422   /* we do it the simple way: the parts are made up from the chunks we
  423      got from the read function.
  424 
  425      Fixme: We should write the tag here, and write a definite length
  426      header if everything fits into our local buffer.  Actually pretty
  427      simple to do, but I am too lazy right now. */
  428   while (!(err = ksba_reader_read (cms->reader, buffer,
  429                                    sizeof buffer, &nread)) )
  430     {
  431       err = _ksba_ber_write_tl (cms->writer, TYPE_OCTET_STRING,
  432                                 CLASS_UNIVERSAL, 0, nread);
  433       if (!err)
  434         err = ksba_writer_write (cms->writer, buffer, nread);
  435     }
  436   if (gpg_err_code (err) == GPG_ERR_EOF) /* write the end tag */
  437       err = _ksba_ber_write_tl (cms->writer, 0, 0, 0, 0);
  438 
  439   return err;
  440 }
  441 
  442 
  443 /* Figure out whether the data read from READER is a CMS object and
  444    return its content type.  This function does only peek at the
  445    READER and tries to identify the type with best effort.  Because of
  446    the ubiquity of the stupid and insecure pkcs#12 format, the
  447    function will also identify those files and return KSBA_CT_PKCS12;
  448    there is and will be no other pkcs#12 support in this library. */
  449 ksba_content_type_t
  450 ksba_cms_identify (ksba_reader_t reader)
  451 {
  452   struct tag_info ti;
  453   unsigned char buffer[24];
  454   const unsigned char*p;
  455   size_t n, count;
  456   char *oid;
  457   int i;
  458   int maybe_p12 = 0;
  459 
  460   if (!reader)
  461     return KSBA_CT_NONE; /* oops */
  462 
  463   /* This is a common example of a CMS object - it is obvious that we
  464      only need to read a few bytes to get to the OID:
  465   30 82 0B 59 06 09 2A 86 48 86 F7 0D 01 07 02 A0 82 0B 4A 30 82 0B 46 02
  466   ----------- ++++++++++++++++++++++++++++++++
  467   SEQUENCE    OID (signedData)
  468   (2 byte len)
  469 
  470      For a pkcs12 message we have this:
  471 
  472   30 82 08 59 02 01 03 30 82 08 1F 06 09 2A 86 48 86 F7 0D 01 07 01 A0 82
  473   ----------- ++++++++ ----------- ++++++++++++++++++++++++++++++++
  474   SEQUENCE    INTEGER  SEQUENCE    OID (data)
  475 
  476     This we need to read at least 22 bytes, we add 2 bytes to cope with
  477     length headers store with 4 bytes.
  478   */
  479 
  480   for (count = sizeof buffer; count; count -= n)
  481     {
  482       if (ksba_reader_read (reader, buffer+sizeof (buffer)-count, count, &n))
  483         return KSBA_CT_NONE; /* too short */
  484     }
  485   n = sizeof buffer;
  486   if (ksba_reader_unread (reader, buffer, n))
  487     return KSBA_CT_NONE; /* oops */
  488 
  489   p = buffer;
  490   if (_ksba_ber_parse_tl (&p, &n, &ti))
  491     return KSBA_CT_NONE;
  492   if ( !(ti.class == CLASS_UNIVERSAL && ti.tag == TYPE_SEQUENCE
  493          && ti.is_constructed) )
  494     return KSBA_CT_NONE;
  495   if (_ksba_ber_parse_tl (&p, &n, &ti))
  496     return KSBA_CT_NONE;
  497   if ( ti.class == CLASS_UNIVERSAL && ti.tag == TYPE_INTEGER
  498        && !ti.is_constructed && ti.length == 1 && n && *p == 3)
  499     {
  500       maybe_p12 = 1;
  501       p++;
  502       n--;
  503       if (_ksba_ber_parse_tl (&p, &n, &ti))
  504         return KSBA_CT_NONE;
  505       if ( !(ti.class == CLASS_UNIVERSAL && ti.tag == TYPE_SEQUENCE
  506              && ti.is_constructed) )
  507         return KSBA_CT_NONE;
  508       if (_ksba_ber_parse_tl (&p, &n, &ti))
  509         return KSBA_CT_NONE;
  510     }
  511   if ( !(ti.class == CLASS_UNIVERSAL && ti.tag == TYPE_OBJECT_ID
  512          && !ti.is_constructed && ti.length) || ti.length > n)
  513     return KSBA_CT_NONE;
  514   oid = ksba_oid_to_str (p, ti.length);
  515   if (!oid)
  516     return KSBA_CT_NONE; /* out of core */
  517   for (i=0; content_handlers[i].oid; i++)
  518     {
  519       if (!strcmp (content_handlers[i].oid, oid))
  520         break;
  521     }
  522   ksba_free(oid);
  523   if (!content_handlers[i].oid)
  524     return KSBA_CT_NONE; /* unknown */
  525   if (maybe_p12 && (content_handlers[i].ct == KSBA_CT_DATA
  526                     || content_handlers[i].ct == KSBA_CT_SIGNED_DATA))
  527       return KSBA_CT_PKCS12;
  528   return content_handlers[i].ct;
  529 }
  530 
  531 
  532 
  533 /**
  534  * ksba_cms_new:
  535  *
  536  * Create a new and empty CMS object
  537  *
  538  * Return value: A CMS object or an error code.
  539  **/
  540 gpg_error_t
  541 ksba_cms_new (ksba_cms_t *r_cms)
  542 {
  543   *r_cms = xtrycalloc (1, sizeof **r_cms);
  544   if (!*r_cms)
  545     return gpg_error_from_errno (errno);
  546   return 0;
  547 }
  548 
  549 /* Release a list of value trees. */
  550 static void
  551 release_value_tree (struct value_tree_s *tree)
  552 {
  553   while (tree)
  554     {
  555       struct value_tree_s *tmp = tree->next;
  556       _ksba_asn_release_nodes (tree->root);
  557       xfree (tree->image);
  558       xfree (tree);
  559       tree = tmp;
  560     }
  561 }
  562 
  563 /**
  564  * ksba_cms_release:
  565  * @cms: A CMS object
  566  *
  567  * Release a CMS object.
  568  **/
  569 void
  570 ksba_cms_release (ksba_cms_t cms)
  571 {
  572   if (!cms)
  573     return;
  574   xfree (cms->content.oid);
  575   while (cms->digest_algos)
  576     {
  577       struct oidlist_s *ol = cms->digest_algos->next;
  578       xfree (cms->digest_algos->oid);
  579       xfree (cms->digest_algos);
  580       cms->digest_algos = ol;
  581     }
  582   while (cms->cert_list)
  583     {
  584       struct certlist_s *cl = cms->cert_list->next;
  585       ksba_cert_release (cms->cert_list->cert);
  586       xfree (cms->cert_list->enc_val.algo);
  587       xfree (cms->cert_list->enc_val.value);
  588       xfree (cms->cert_list->enc_val.ecdh.e);
  589       xfree (cms->cert_list->enc_val.ecdh.wrap_algo);
  590       xfree (cms->cert_list->enc_val.ecdh.encr_algo);
  591       xfree (cms->cert_list);
  592       cms->cert_list = cl;
  593     }
  594   while (cms->cert_info_list)
  595     {
  596       struct certlist_s *cl = cms->cert_info_list->next;
  597       ksba_cert_release (cms->cert_info_list->cert);
  598       xfree (cms->cert_info_list->enc_val.algo);
  599       xfree (cms->cert_info_list->enc_val.value);
  600       xfree (cms->cert_info_list);
  601       cms->cert_info_list = cl;
  602     }
  603   xfree (cms->inner_cont_oid);
  604   xfree (cms->encr_algo_oid);
  605   xfree (cms->encr_iv);
  606   xfree (cms->data.digest);
  607   while (cms->signer_info)
  608     {
  609       struct signer_info_s *tmp = cms->signer_info->next;
  610       _ksba_asn_release_nodes (cms->signer_info->root);
  611       xfree (cms->signer_info->image);
  612       xfree (cms->signer_info->cache.digest_algo);
  613       xfree (cms->signer_info);
  614       cms->signer_info = tmp;
  615     }
  616   release_value_tree (cms->recp_info);
  617   while (cms->sig_val)
  618     {
  619       struct sig_val_s *tmp = cms->sig_val->next;
  620       xfree (cms->sig_val->algo);
  621       xfree (cms->sig_val->value);
  622       xfree (cms->sig_val->ecc.r);
  623       xfree (cms->sig_val);
  624       cms->sig_val = tmp;
  625     }
  626   while (cms->capability_list)
  627     {
  628       struct oidparmlist_s *tmp = cms->capability_list->next;
  629       xfree (cms->capability_list->oid);
  630       xfree (cms->capability_list);
  631       cms->capability_list = tmp;
  632     }
  633 
  634   xfree (cms);
  635 }
  636 
  637 
  638 gpg_error_t
  639 ksba_cms_set_reader_writer (ksba_cms_t cms, ksba_reader_t r, ksba_writer_t w)
  640 {
  641   if (!cms || !(r || w))
  642     return gpg_error (GPG_ERR_INV_VALUE);
  643   if ((r && cms->reader) || (w && cms->writer) )
  644     return gpg_error (GPG_ERR_CONFLICT); /* already set */
  645 
  646   cms->reader = r;
  647   cms->writer = w;
  648   return 0;
  649 }
  650 
  651 
  652 
  653 gpg_error_t
  654 ksba_cms_parse (ksba_cms_t cms, ksba_stop_reason_t *r_stopreason)
  655 {
  656   gpg_error_t err;
  657   int i;
  658 
  659   if (!cms || !r_stopreason)
  660     return gpg_error (GPG_ERR_INV_VALUE);
  661 
  662   *r_stopreason = KSBA_SR_RUNNING;
  663   if (!cms->stop_reason)
  664     { /* Initial state: start parsing */
  665       err = _ksba_cms_parse_content_info (cms);
  666       if (err)
  667         return err;
  668       for (i=0; content_handlers[i].oid; i++)
  669         {
  670           if (!strcmp (content_handlers[i].oid, cms->content.oid))
  671             break;
  672         }
  673       if (!content_handlers[i].oid)
  674         return gpg_error (GPG_ERR_UNKNOWN_CMS_OBJ);
  675       if (!content_handlers[i].parse_handler)
  676         return gpg_error (GPG_ERR_UNSUPPORTED_CMS_OBJ);
  677       cms->content.ct      = content_handlers[i].ct;
  678       cms->content.handler = content_handlers[i].parse_handler;
  679       cms->stop_reason = KSBA_SR_GOT_CONTENT;
  680     }
  681   else if (cms->content.handler)
  682     {
  683       err = cms->content.handler (cms);
  684       if (err)
  685         return err;
  686     }
  687   else
  688     return gpg_error (GPG_ERR_UNSUPPORTED_CMS_OBJ);
  689 
  690   *r_stopreason = cms->stop_reason;
  691   return 0;
  692 }
  693 
  694 gpg_error_t
  695 ksba_cms_build (ksba_cms_t cms, ksba_stop_reason_t *r_stopreason)
  696 {
  697   gpg_error_t err;
  698 
  699   if (!cms || !r_stopreason)
  700     return gpg_error (GPG_ERR_INV_VALUE);
  701 
  702   *r_stopreason = KSBA_SR_RUNNING;
  703   if (!cms->stop_reason)
  704     { /* Initial state: check that the content handler is known */
  705       if (!cms->writer)
  706         return gpg_error (GPG_ERR_MISSING_ACTION);
  707       if (!cms->content.handler)
  708         return gpg_error (GPG_ERR_MISSING_ACTION);
  709       if (!cms->inner_cont_oid)
  710         return gpg_error (GPG_ERR_MISSING_ACTION);
  711       cms->stop_reason = KSBA_SR_GOT_CONTENT;
  712     }
  713   else if (cms->content.handler)
  714     {
  715       err = cms->content.handler (cms);
  716       if (err)
  717         return err;
  718     }
  719   else
  720     return gpg_error (GPG_ERR_UNSUPPORTED_CMS_OBJ);
  721 
  722   *r_stopreason = cms->stop_reason;
  723   return 0;
  724 }
  725 
  726 
  727 
  728 
  729 /* Return the content type.  A WHAT of 0 returns the real content type
  730    whereas a 1 returns the inner content type.
  731 */
  732 ksba_content_type_t
  733 ksba_cms_get_content_type (ksba_cms_t cms, int what)
  734 {
  735   int i;
  736 
  737   if (!cms)
  738     return 0;
  739   if (!what)
  740     return cms->content.ct;
  741 
  742   if (what == 1 && cms->inner_cont_oid)
  743     {
  744       for (i=0; content_handlers[i].oid; i++)
  745         {
  746           if (!strcmp (content_handlers[i].oid, cms->inner_cont_oid))
  747             return content_handlers[i].ct;
  748         }
  749     }
  750   return 0;
  751 }
  752 
  753 
  754 /* Return the object ID of the current cms.  This is a constant string
  755    valid as long as the context is valid and no new parse is
  756    started. */
  757 const char *
  758 ksba_cms_get_content_oid (ksba_cms_t cms, int what)
  759 {
  760   if (!cms)
  761     return NULL;
  762   if (!what)
  763     return cms->content.oid;
  764   if (what == 1)
  765     return cms->inner_cont_oid;
  766   if (what == 2)
  767     return cms->encr_algo_oid;
  768   return NULL;
  769 }
  770 
  771 
  772 /* Copy the initialization vector into iv and its len into ivlen.
  773    The caller should provide a suitable large buffer */
  774 gpg_error_t
  775 ksba_cms_get_content_enc_iv (ksba_cms_t cms, void *iv,
  776                              size_t maxivlen, size_t *ivlen)
  777 {
  778   if (!cms || !iv || !ivlen)
  779     return gpg_error (GPG_ERR_INV_VALUE);
  780   if (!cms->encr_ivlen)
  781     return gpg_error (GPG_ERR_NO_DATA);
  782   if (cms->encr_ivlen > maxivlen)
  783     return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
  784   memcpy (iv, cms->encr_iv, cms->encr_ivlen);
  785   *ivlen = cms->encr_ivlen;
  786   return 0;
  787 }
  788 
  789 
  790 /**
  791  * ksba_cert_get_digest_algo_list:
  792  * @cert: Initialized certificate object
  793  * @idx: enumerator
  794  *
  795  * Figure out the the digest algorithm used for the signature and
  796  * return its OID.  Note that the algos returned are just hints on
  797  * what to hash.
  798  *
  799  * Return value: NULL for no more algorithms or a string valid as long
  800  * as the the cms object is valid.
  801  **/
  802 const char *
  803 ksba_cms_get_digest_algo_list (ksba_cms_t cms, int idx)
  804 {
  805   struct oidlist_s *ol;
  806 
  807   if (!cms)
  808     return NULL;
  809 
  810   for (ol=cms->digest_algos; ol && idx; ol = ol->next, idx-- )
  811     ;
  812   if (!ol)
  813     return NULL;
  814   return ol->oid;
  815 }
  816 
  817 
  818 /**
  819  * ksba_cms_get_issuer_serial:
  820  * @cms: CMS object
  821  * @idx: index number
  822  * @r_issuer: returns the issuer
  823  * @r_serial: returns the serial number
  824  *
  825  * This functions returns the issuer and serial number either from the
  826  * sid or the rid elements of a CMS object.
  827  *
  828  * Return value: 0 on success or an error code.  An error code of -1
  829  * is returned to indicate that there is no issuer with that idx,
  830  * GPG_ERR_No_Data is returned to indicate that there is no issuer at
  831  * all.
  832  **/
  833 gpg_error_t
  834 ksba_cms_get_issuer_serial (ksba_cms_t cms, int idx,
  835                             char **r_issuer, ksba_sexp_t *r_serial)
  836 {
  837   gpg_error_t err;
  838   const char *issuer_path, *serial_path;
  839   AsnNode root;
  840   const unsigned char *image;
  841   AsnNode n;
  842 
  843   if (!cms)
  844     return gpg_error (GPG_ERR_INV_VALUE);
  845   if (idx < 0)
  846     return gpg_error (GPG_ERR_INV_INDEX);
  847 
  848   if (cms->signer_info)
  849     {
  850       struct signer_info_s *si;
  851 
  852       for (si=cms->signer_info; si && idx; si = si->next, idx-- )
  853         ;
  854       if (!si)
  855         return -1;
  856 
  857       root = si->root;
  858       image = si->image;
  859     }
  860   else if (cms->recp_info)
  861     {
  862       struct value_tree_s *tmp;
  863 
  864       for (tmp=cms->recp_info; tmp && idx; tmp=tmp->next, idx-- )
  865         ;
  866       if (!tmp)
  867         return -1;
  868       root = tmp->root;
  869       image = tmp->image;
  870     }
  871   else
  872     return gpg_error (GPG_ERR_NO_DATA);
  873 
  874 
  875   if (cms->signer_info)
  876     {
  877       issuer_path = "SignerInfo.sid.issuerAndSerialNumber.issuer";
  878       serial_path = "SignerInfo.sid.issuerAndSerialNumber.serialNumber";
  879     }
  880   else if (cms->recp_info)
  881     {
  882       /* Find the choice to use.  */
  883       n = _ksba_asn_find_node (root, "RecipientInfo.+");
  884       if (!n || !n->name)
  885         return gpg_error (GPG_ERR_NO_VALUE);
  886 
  887       if (!strcmp (n->name, "ktri"))
  888         {
  889           issuer_path = "ktri.rid.issuerAndSerialNumber.issuer";
  890           serial_path = "ktri.rid.issuerAndSerialNumber.serialNumber";
  891         }
  892       else if (!strcmp (n->name, "kari"))
  893         {
  894           issuer_path = ("kari..recipientEncryptedKeys"
  895                          "..rid.issuerAndSerialNumber.issuer");
  896           serial_path = ("kari..recipientEncryptedKeys"
  897                          "..rid.issuerAndSerialNumber.serialNumber");
  898         }
  899       else if (!strcmp (n->name, "kekri"))
  900         return gpg_error (GPG_ERR_UNSUPPORTED_CMS_OBJ);
  901       else
  902         return gpg_error (GPG_ERR_INV_CMS_OBJ);
  903       root = n;
  904     }
  905 
  906   if (r_issuer)
  907     {
  908       n = _ksba_asn_find_node (root, issuer_path);
  909       if (!n || !n->down)
  910         return gpg_error (GPG_ERR_NO_VALUE);
  911       n = n->down; /* dereference the choice node */
  912 
  913       if (n->off == -1)
  914         {
  915 /*            fputs ("get_issuer problem at node:\n", stderr); */
  916 /*            _ksba_asn_node_dump_all (n, stderr); */
  917           return gpg_error (GPG_ERR_GENERAL);
  918         }
  919       err = _ksba_dn_to_str (image, n, r_issuer);
  920       if (err)
  921         return err;
  922     }
  923 
  924   if (r_serial)
  925     {
  926       char numbuf[22];
  927       int numbuflen;
  928       unsigned char *p;
  929 
  930       /* fixme: we do not release the r_issuer stuff on error */
  931       n = _ksba_asn_find_node (root, serial_path);
  932       if (!n)
  933         return gpg_error (GPG_ERR_NO_VALUE);
  934 
  935       if (n->off == -1)
  936         {
  937 /*            fputs ("get_serial problem at node:\n", stderr); */
  938 /*            _ksba_asn_node_dump_all (n, stderr); */
  939           return gpg_error (GPG_ERR_GENERAL);
  940         }
  941 
  942       sprintf (numbuf,"(%u:", (unsigned int)n->len);
  943       numbuflen = strlen (numbuf);
  944       p = xtrymalloc (numbuflen + n->len + 2);
  945       if (!p)
  946         return gpg_error (GPG_ERR_ENOMEM);
  947       strcpy (p, numbuf);
  948       memcpy (p+numbuflen, image + n->off + n->nhdr, n->len);
  949       p[numbuflen + n->len] = ')';
  950       p[numbuflen + n->len + 1] = 0;
  951       *r_serial = p;
  952     }
  953 
  954   return 0;
  955 }
  956 
  957 
  958 
  959 /**
  960  * ksba_cms_get_digest_algo:
  961  * @cms: CMS object
  962  * @idx: index of signer
  963  *
  964  * Figure out the the digest algorithm used by the signer @idx return
  965  * its OID.  This is the algorithm acually used to calculate the
  966  * signature.
  967  *
  968  * Return value: NULL for no such signer or a constn string valid as
  969  * long as the CMS object lives.
  970  **/
  971 const char *
  972 ksba_cms_get_digest_algo (ksba_cms_t cms, int idx)
  973 {
  974   AsnNode n;
  975   char *algo;
  976   struct signer_info_s *si;
  977 
  978   if (!cms)
  979     return NULL;
  980   if (!cms->signer_info)
  981     return NULL;
  982   if (idx < 0)
  983     return NULL;
  984 
  985   for (si=cms->signer_info; si && idx; si = si->next, idx-- )
  986     ;
  987   if (!si)
  988     return NULL;
  989 
  990   if (si->cache.digest_algo)
  991     return si->cache.digest_algo;
  992 
  993   n = _ksba_asn_find_node (si->root, "SignerInfo.digestAlgorithm.algorithm");
  994   algo = _ksba_oid_node_to_str (si->image, n);
  995   if (algo)
  996     {
  997       si->cache.digest_algo = algo;
  998     }
  999   return algo;
 1000 }
 1001 
 1002 
 1003 /**
 1004  * ksba_cms_get_cert:
 1005  * @cms: CMS object
 1006  * @idx: enumerator
 1007  *
 1008  * Get the certificate out of a CMS.  The caller should use this in a
 1009  * loop to get all certificates.  The returned certificate is a
 1010  * shallow copy of the original one; the caller must still use
 1011  * ksba_cert_release() to free it.
 1012  *
 1013  * Return value: A Certificate object or NULL for end of list or error
 1014  **/
 1015 ksba_cert_t
 1016 ksba_cms_get_cert (ksba_cms_t cms, int idx)
 1017 {
 1018   struct certlist_s *cl;
 1019 
 1020   if (!cms || idx < 0)
 1021     return NULL;
 1022 
 1023   for (cl=cms->cert_list; cl && idx; cl = cl->next, idx--)
 1024     ;
 1025   if (!cl)
 1026     return NULL;
 1027   ksba_cert_ref (cl->cert);
 1028   return cl->cert;
 1029 }
 1030 
 1031 
 1032 /*
 1033    Return the extension attribute messageDigest
 1034 */
 1035 gpg_error_t
 1036 ksba_cms_get_message_digest (ksba_cms_t cms, int idx,
 1037                              char **r_digest, size_t *r_digest_len)
 1038 {
 1039   AsnNode nsiginfo, n;
 1040   struct signer_info_s *si;
 1041 
 1042   if (!cms || !r_digest || !r_digest_len)
 1043     return gpg_error (GPG_ERR_INV_VALUE);
 1044   if (!cms->signer_info)
 1045     return gpg_error (GPG_ERR_NO_DATA);
 1046   if (idx < 0)
 1047     return gpg_error (GPG_ERR_INV_INDEX);
 1048 
 1049   for (si=cms->signer_info; si && idx; si = si->next, idx-- )
 1050     ;
 1051   if (!si)
 1052     return -1;
 1053 
 1054 
 1055   *r_digest = NULL;
 1056   *r_digest_len = 0;
 1057   nsiginfo = _ksba_asn_find_node (si->root, "SignerInfo.signedAttrs");
 1058   if (!nsiginfo)
 1059     return gpg_error (GPG_ERR_BUG);
 1060 
 1061   n = _ksba_asn_find_type_value (si->image, nsiginfo, 0,
 1062                                  oid_messageDigest, DIM(oid_messageDigest));
 1063   if (!n)
 1064     return 0; /* this is okay, because the element is optional */
 1065 
 1066   /* check that there is only one */
 1067   if (_ksba_asn_find_type_value (si->image, nsiginfo, 1,
 1068                                  oid_messageDigest, DIM(oid_messageDigest)))
 1069     return gpg_error (GPG_ERR_DUP_VALUE);
 1070 
 1071   /* the value is is a SET OF OCTECT STRING but the set must have
 1072      excactly one OCTECT STRING.  (rfc2630 11.2) */
 1073   if ( !(n->type == TYPE_SET_OF && n->down
 1074          && n->down->type == TYPE_OCTET_STRING && !n->down->right))
 1075     return gpg_error (GPG_ERR_INV_CMS_OBJ);
 1076   n = n->down;
 1077   if (n->off == -1)
 1078     return gpg_error (GPG_ERR_BUG);
 1079 
 1080   *r_digest_len = n->len;
 1081   *r_digest = xtrymalloc (n->len);
 1082   if (!*r_digest)
 1083     return gpg_error (GPG_ERR_ENOMEM);
 1084   memcpy (*r_digest, si->image + n->off + n->nhdr, n->len);
 1085   return 0;
 1086 }
 1087 
 1088 
 1089 /* Return the extension attribute signing time, which may be empty for no
 1090    signing time available. */
 1091 gpg_error_t
 1092 ksba_cms_get_signing_time (ksba_cms_t cms, int idx, ksba_isotime_t r_sigtime)
 1093 {
 1094   AsnNode nsiginfo, n;
 1095   struct signer_info_s *si;
 1096 
 1097   if (!cms)
 1098     return gpg_error (GPG_ERR_INV_VALUE);
 1099   *r_sigtime = 0;
 1100   if (!cms->signer_info)
 1101     return gpg_error (GPG_ERR_NO_DATA);
 1102   if (idx < 0)
 1103     return gpg_error (GPG_ERR_INV_INDEX);
 1104 
 1105   for (si=cms->signer_info; si && idx; si = si->next, idx-- )
 1106     ;
 1107   if (!si)
 1108     return -1;
 1109 
 1110   *r_sigtime = 0;
 1111   nsiginfo = _ksba_asn_find_node (si->root, "SignerInfo.signedAttrs");
 1112   if (!nsiginfo)
 1113     return 0; /* This is okay because signedAttribs are optional. */
 1114 
 1115   n = _ksba_asn_find_type_value (si->image, nsiginfo, 0,
 1116                                  oid_signingTime, DIM(oid_signingTime));
 1117   if (!n)
 1118     return 0; /* This is okay because signing time is optional. */
 1119 
 1120   /* check that there is only one */
 1121   if (_ksba_asn_find_type_value (si->image, nsiginfo, 1,
 1122                                  oid_signingTime, DIM(oid_signingTime)))
 1123     return gpg_error (GPG_ERR_DUP_VALUE);
 1124 
 1125   /* the value is is a SET OF CHOICE but the set must have
 1126      excactly one CHOICE of generalized or utctime.  (rfc2630 11.3) */
 1127   if ( !(n->type == TYPE_SET_OF && n->down
 1128          && (n->down->type == TYPE_GENERALIZED_TIME
 1129              || n->down->type == TYPE_UTC_TIME)
 1130          && !n->down->right))
 1131     return gpg_error (GPG_ERR_INV_CMS_OBJ);
 1132   n = n->down;
 1133   if (n->off == -1)
 1134     return gpg_error (GPG_ERR_BUG);
 1135 
 1136   return _ksba_asntime_to_iso (si->image + n->off + n->nhdr, n->len,
 1137                                n->type == TYPE_UTC_TIME, r_sigtime);
 1138 }
 1139 
 1140 
 1141 /* Return a list of OIDs stored as signed attributes for the signature
 1142    number IDX.  All the values (OIDs) for the the requested OID REQOID
 1143    are returned delimited by a linefeed.  Caller must free that
 1144    list. -1 is returned when IDX is larger than the number of
 1145    signatures, GPG_ERR_No_Data is returned when there is no such
 1146    attribute for the given signer. */
 1147 gpg_error_t
 1148 ksba_cms_get_sigattr_oids (ksba_cms_t cms, int idx,
 1149                            const char *reqoid, char **r_value)
 1150 {
 1151   gpg_error_t err;
 1152   AsnNode nsiginfo, n;
 1153   struct signer_info_s *si;
 1154   unsigned char *reqoidbuf;
 1155   size_t reqoidlen;
 1156   char *retstr = NULL;
 1157   int i;
 1158 
 1159   if (!cms || !r_value)
 1160     return gpg_error (GPG_ERR_INV_VALUE);
 1161   if (!cms->signer_info)
 1162     return gpg_error (GPG_ERR_NO_DATA);
 1163   if (idx < 0)
 1164     return gpg_error (GPG_ERR_INV_INDEX);
 1165   *r_value = NULL;
 1166 
 1167   for (si=cms->signer_info; si && idx; si = si->next, idx-- )
 1168     ;
 1169   if (!si)
 1170     return -1; /* no more signers */
 1171 
 1172   nsiginfo = _ksba_asn_find_node (si->root, "SignerInfo.signedAttrs");
 1173   if (!nsiginfo)
 1174     return -1; /* this is okay, because signedAttribs are optional */
 1175 
 1176   err = ksba_oid_from_str (reqoid, &reqoidbuf, &reqoidlen);
 1177   if(err)
 1178     return err;
 1179 
 1180   for (i=0; (n = _ksba_asn_find_type_value (si->image, nsiginfo,
 1181                                             i, reqoidbuf, reqoidlen)); i++)
 1182     {
 1183       char *line, *p;
 1184 
 1185       /* the value is is a SET OF OBJECT ID but the set must have
 1186          excactly one OBJECT ID.  (rfc2630 11.1) */
 1187       if ( !(n->type == TYPE_SET_OF && n->down
 1188              && n->down->type == TYPE_OBJECT_ID && !n->down->right))
 1189         {
 1190           xfree (reqoidbuf);
 1191           xfree (retstr);
 1192           return gpg_error (GPG_ERR_INV_CMS_OBJ);
 1193         }
 1194       n = n->down;
 1195       if (n->off == -1)
 1196         {
 1197           xfree (reqoidbuf);
 1198           xfree (retstr);
 1199           return gpg_error (GPG_ERR_BUG);
 1200         }
 1201 
 1202       p = _ksba_oid_node_to_str (si->image, n);
 1203       if (!p)
 1204         {
 1205           xfree (reqoidbuf);
 1206           xfree (retstr);
 1207           return gpg_error (GPG_ERR_INV_CMS_OBJ);
 1208         }
 1209 
 1210       if (!retstr)
 1211         line = retstr = xtrymalloc (strlen (p) + 2);
 1212       else
 1213         {
 1214           char *tmp = xtryrealloc (retstr,
 1215                                    strlen (retstr) + 1 + strlen (p) + 2);
 1216           if (!tmp)
 1217             line = NULL;
 1218           else
 1219             {
 1220               retstr = tmp;
 1221               line = stpcpy (retstr + strlen (retstr), "\n");
 1222             }
 1223         }
 1224       if (!line)
 1225         {
 1226           xfree (reqoidbuf);
 1227           xfree (retstr);
 1228           xfree (p);
 1229           return gpg_error (GPG_ERR_ENOMEM);
 1230         }
 1231       strcpy (line, p);
 1232       xfree (p);
 1233     }
 1234   xfree (reqoidbuf);
 1235   if (!n && !i)
 1236     return -1; /* no such attribute */
 1237   *r_value = retstr;
 1238   return 0;
 1239 }
 1240 
 1241 
 1242 /**
 1243  * ksba_cms_get_sig_val:
 1244  * @cms: CMS object
 1245  * @idx: index of signer
 1246  *
 1247  * Return the actual signature of signer @idx in a format suitable to
 1248  * be used as input to Libgcrypt's verification function.  The caller
 1249  * must free the returned string.
 1250  *
 1251  * Return value: NULL or a string with a S-Exp.
 1252  **/
 1253 ksba_sexp_t
 1254 ksba_cms_get_sig_val (ksba_cms_t cms, int idx)
 1255 {
 1256   AsnNode n, n2;
 1257   gpg_error_t err;
 1258   ksba_sexp_t string;
 1259   struct signer_info_s *si;
 1260 
 1261   if (!cms)
 1262     return NULL;
 1263   if (!cms->signer_info)
 1264     return NULL;
 1265   if (idx < 0)
 1266     return NULL;
 1267 
 1268   for (si=cms->signer_info; si && idx; si = si->next, idx-- )
 1269     ;
 1270   if (!si)
 1271     return NULL;
 1272 
 1273   n = _ksba_asn_find_node (si->root, "SignerInfo.signatureAlgorithm");
 1274   if (!n)
 1275       return NULL;
 1276   if (n->off == -1)
 1277     {
 1278 /*        fputs ("ksba_cms_get_sig_val problem at node:\n", stderr); */
 1279 /*        _ksba_asn_node_dump_all (n, stderr); */
 1280       return NULL;
 1281     }
 1282 
 1283   n2 = n->right; /* point to the actual value */
 1284   err = _ksba_sigval_to_sexp (si->image + n->off,
 1285                               n->nhdr + n->len
 1286                               + ((!n2||n2->off == -1)? 0:(n2->nhdr+n2->len)),
 1287                               &string);
 1288   if (err)
 1289       return NULL;
 1290 
 1291   return string;
 1292 }
 1293 
 1294 
 1295 /* Helper to dump a S-expression. */
 1296 #if 0
 1297 static void
 1298 dbg_print_sexp (ksba_const_sexp_t p)
 1299 {
 1300   int level = 0;
 1301 
 1302   if (!p)
 1303     fputs ("[none]", stdout);
 1304   else
 1305     {
 1306       for (;;)
 1307         {
 1308           if (*p == '(')
 1309             {
 1310               putchar (*p);
 1311               p++;
 1312               level++;
 1313             }
 1314           else if (*p == ')')
 1315             {
 1316               putchar (*p);
 1317               p++;
 1318               if (--level <= 0 )
 1319                 {
 1320                   putchar ('\n');
 1321                   return;
 1322                 }
 1323             }
 1324           else if (!digitp (p))
 1325             {
 1326               fputs ("[invalid s-exp]\n", stdout);
 1327               return;
 1328             }
 1329           else
 1330             {
 1331               const unsigned char *s;
 1332               char *endp;
 1333               unsigned long len, n;
 1334 
 1335               len = strtoul (p, &endp, 10);
 1336               p = endp;
 1337               if (*p != ':')
 1338                 {
 1339                   fputs ("[invalid s-exp]\n", stdout);
 1340                   return;
 1341                 }
 1342               p++;
 1343               for (s=p,n=0; n < len; n++, s++)
 1344                 if ( !((*s >= 'a' && *s <= 'z')
 1345                        || (*s >= 'A' && *s <= 'Z')
 1346                        || (*s >= '0' && *s <= '9')
 1347                        || *s == '-' || *s == '.'))
 1348                   break;
 1349               if (n < len)
 1350                 {
 1351                   putchar('#');
 1352                   for (n=0; n < len; n++, p++)
 1353                     printf ("%02X", *p);
 1354                   putchar('#');
 1355                 }
 1356               else
 1357                 {
 1358                   for (n=0; n < len; n++, p++)
 1359                     putchar (*p);
 1360                 }
 1361             }
 1362         }
 1363     }
 1364   putchar ('\n');
 1365 }
 1366 #endif /* 0 */
 1367 
 1368 
 1369 
 1370 /**
 1371  * ksba_cms_get_enc_val:
 1372  * @cms: CMS object
 1373  * @idx: index of recipient info
 1374  *
 1375  * Return the encrypted value (the session key) of recipient @idx in a
 1376  * format suitable to be used as input to Libgcrypt's decryption
 1377  * function.  The caller must free the returned string.
 1378  *
 1379  * Return value: NULL or a string with a S-Exp.
 1380  **/
 1381 ksba_sexp_t
 1382 ksba_cms_get_enc_val (ksba_cms_t cms, int idx)
 1383 {
 1384   AsnNode root, n, n2;
 1385   gpg_error_t err;
 1386   ksba_sexp_t string;
 1387   struct value_tree_s *vt;
 1388   char *keyencralgo = NULL; /* Key encryption algo.  */
 1389   char *parm = NULL;        /* Helper to get the parms of kencralgo.  */
 1390   size_t parmlen;
 1391   char *keywrapalgo = NULL; /* Key wrap algo.  */
 1392   struct tag_info ti;
 1393   const unsigned char *der;
 1394   size_t derlen;
 1395 
 1396   if (!cms)
 1397     return NULL;
 1398   if (!cms->recp_info)
 1399     return NULL;
 1400   if (idx < 0)
 1401     return NULL;
 1402 
 1403   for (vt=cms->recp_info; vt && idx; vt=vt->next, idx--)
 1404     ;
 1405   if (!vt)
 1406     return NULL; /* No value at this IDX */
 1407 
 1408   /* Find the choice to use.  */
 1409   root = _ksba_asn_find_node (vt->root, "RecipientInfo.+");
 1410   if (!root || !root->name)
 1411     return NULL;
 1412 
 1413   if (!strcmp (root->name, "ktri"))
 1414     {
 1415       n = _ksba_asn_find_node (root, "ktri.keyEncryptionAlgorithm");
 1416       if (!n || n->off == -1)
 1417         return NULL;
 1418       n2 = n->right; /* point to the actual value */
 1419       err = _ksba_encval_to_sexp
 1420         (vt->image + n->off,
 1421          n->nhdr + n->len + ((!n2||n2->off == -1)? 0:(n2->nhdr+n2->len)),
 1422          &string);
 1423     }
 1424   else if (!strcmp (root->name, "kari"))
 1425     {
 1426       /* _ksba_asn_node_dump_all (root, stderr); */
 1427 
 1428       /* Get the encrypted key.  Result is in (DER,DERLEN)  */
 1429       n = _ksba_asn_find_node (root, ("kari..recipientEncryptedKeys"
 1430                                       "..encryptedKey"));
 1431       if (!n || n->off == -1)
 1432         {
 1433           err = gpg_error (GPG_ERR_INV_KEYINFO);
 1434           goto leave;
 1435         }
 1436 
 1437       der = vt->image + n->off;
 1438       derlen = n->nhdr + n->len;
 1439       err = parse_octet_string (&der, &derlen, &ti);
 1440       if (err)
 1441         goto leave;
 1442       derlen = ti.length;
 1443       /* gpgrt_log_printhex (der, derlen, "%s: encryptedKey", __func__); */
 1444 
 1445       /* Get the KEK algos.  */
 1446       n = _ksba_asn_find_node (root, "kari..keyEncryptionAlgorithm");
 1447       if (!n || n->off == -1)
 1448         {
 1449           err = gpg_error (GPG_ERR_INV_KEYINFO);
 1450           goto leave;
 1451         }
 1452       err = _ksba_parse_algorithm_identifier2 (vt->image + n->off,
 1453                                                n->nhdr + n->len, NULL,
 1454                                                &keyencralgo, &parm, &parmlen);
 1455       if (err)
 1456         goto leave;
 1457       if (!parm)
 1458         {
 1459           err = gpg_error (GPG_ERR_INV_KEYINFO);
 1460           goto leave;
 1461         }
 1462       err = _ksba_parse_algorithm_identifier (parm, parmlen,NULL, &keywrapalgo);
 1463       if (err)
 1464         goto leave;
 1465 
 1466       /* gpgrt_log_debug ("%s: keyencralgo='%s'\n", __func__, keyencralgo); */
 1467       /* gpgrt_log_debug ("%s: keywrapalgo='%s'\n", __func__, keywrapalgo); */
 1468 
 1469       /* Get the ephemeral public key.  */
 1470       n = _ksba_asn_find_node (root, "kari..originator..originatorKey");
 1471       if (!n || n->off == -1)
 1472         {
 1473           err = gpg_error (GPG_ERR_INV_KEYINFO);
 1474           goto leave;
 1475         }
 1476       err = _ksba_encval_kari_to_sexp (vt->image + n->off, n->nhdr + n->len,
 1477                                        keyencralgo, keywrapalgo, der, derlen,
 1478                                        &string);
 1479       if (err)
 1480         goto leave;
 1481 
 1482       /* gpgrt_log_debug ("%s: encryptedKey:\n", __func__); */
 1483       /* dbg_print_sexp (string); */
 1484     }
 1485   else if (!strcmp (n->name, "kekri"))
 1486     return NULL; /*GPG_ERR_UNSUPPORTED_CMS_OBJ*/
 1487   else
 1488     return NULL; /*GPG_ERR_INV_CMS_OBJ*/
 1489 
 1490  leave:
 1491   xfree (keyencralgo);
 1492   xfree (keywrapalgo);
 1493   xfree (parm);
 1494   if (err)
 1495     {
 1496       /* gpgrt_log_debug ("%s: error: %s\n", __func__, gpg_strerror (err)); */
 1497       return NULL;
 1498     }
 1499 
 1500   return string;
 1501 }
 1502 
 1503 
 1504 
 1505 
 1506 
 1507 /* Provide a hash function so that we are able to hash the data */
 1508 void
 1509 ksba_cms_set_hash_function (ksba_cms_t cms,
 1510                             void (*hash_fnc)(void *, const void *, size_t),
 1511                             void *hash_fnc_arg)
 1512 {
 1513   if (cms)
 1514     {
 1515       cms->hash_fnc = hash_fnc;
 1516       cms->hash_fnc_arg = hash_fnc_arg;
 1517     }
 1518 }
 1519 
 1520 
 1521 /* hash the signed attributes of the given signer */
 1522 gpg_error_t
 1523 ksba_cms_hash_signed_attrs (ksba_cms_t cms, int idx)
 1524 {
 1525   AsnNode n;
 1526   struct signer_info_s *si;
 1527 
 1528   if (!cms)
 1529     return gpg_error (GPG_ERR_INV_VALUE);
 1530   if (!cms->hash_fnc)
 1531     return gpg_error (GPG_ERR_MISSING_ACTION);
 1532   if (idx < 0)
 1533     return -1;
 1534 
 1535   for (si=cms->signer_info; si && idx; si = si->next, idx-- )
 1536     ;
 1537   if (!si)
 1538     return -1;
 1539 
 1540   n = _ksba_asn_find_node (si->root, "SignerInfo.signedAttrs");
 1541   if (!n || n->off == -1)
 1542     return gpg_error (GPG_ERR_NO_VALUE);
 1543 
 1544   /* We don't hash the implicit tag [0] but a SET tag */
 1545   cms->hash_fnc (cms->hash_fnc_arg, "\x31", 1);
 1546   cms->hash_fnc (cms->hash_fnc_arg,
 1547                  si->image + n->off + 1, n->nhdr + n->len - 1);
 1548 
 1549   return 0;
 1550 }
 1551 
 1552 
 1553 /*
 1554   Code to create CMS structures
 1555 */
 1556 
 1557 
 1558 /**
 1559  * ksba_cms_set_content_type:
 1560  * @cms: A CMS object
 1561  * @what: 0 for content type, 1 for inner content type
 1562  * @type: Type constant
 1563  *
 1564  * Set the content type used for build operations.  This should be the
 1565  * first operation before starting to create a CMS message.
 1566  *
 1567  * Return value: 0 on success or an error code
 1568  **/
 1569 gpg_error_t
 1570 ksba_cms_set_content_type (ksba_cms_t cms, int what, ksba_content_type_t type)
 1571 {
 1572   int i;
 1573   char *oid;
 1574 
 1575   if (!cms || what < 0 || what > 1 )
 1576     return gpg_error (GPG_ERR_INV_VALUE);
 1577 
 1578   for (i=0; content_handlers[i].oid; i++)
 1579     {
 1580       if (content_handlers[i].ct == type)
 1581         break;
 1582     }
 1583   if (!content_handlers[i].oid)
 1584     return gpg_error (GPG_ERR_UNKNOWN_CMS_OBJ);
 1585   if (!content_handlers[i].build_handler)
 1586     return gpg_error (GPG_ERR_UNSUPPORTED_CMS_OBJ);
 1587   oid = xtrystrdup (content_handlers[i].oid);
 1588   if (!oid)
 1589     return gpg_error (GPG_ERR_ENOMEM);
 1590 
 1591   if (!what)
 1592     {
 1593       cms->content.oid     = oid;
 1594       cms->content.ct      = content_handlers[i].ct;
 1595       cms->content.handler = content_handlers[i].build_handler;
 1596     }
 1597   else
 1598     {
 1599       cms->inner_cont_oid = oid;
 1600     }
 1601 
 1602   return 0;
 1603 }
 1604 
 1605 
 1606 /**
 1607  * ksba_cms_add_digest_algo:
 1608  * @cms:  A CMS object
 1609  * @oid: A stringified object OID describing the hash algorithm
 1610  *
 1611  * Set the algorithm to be used for creating the hash. Note, that we
 1612  * currently can't do a per-signer hash.
 1613  *
 1614  * Return value: 0 on success or an error code
 1615  **/
 1616 gpg_error_t
 1617 ksba_cms_add_digest_algo (ksba_cms_t cms, const char *oid)
 1618 {
 1619   struct oidlist_s *ol;
 1620 
 1621   if (!cms || !oid)
 1622     return gpg_error (GPG_ERR_INV_VALUE);
 1623 
 1624   ol = xtrymalloc (sizeof *ol);
 1625   if (!ol)
 1626     return gpg_error (GPG_ERR_ENOMEM);
 1627 
 1628   ol->oid = xtrystrdup (oid);
 1629   if (!ol->oid)
 1630     {
 1631       xfree (ol);
 1632       return gpg_error (GPG_ERR_ENOMEM);
 1633     }
 1634   ol->next = cms->digest_algos;
 1635   cms->digest_algos = ol;
 1636   return 0;
 1637 }
 1638 
 1639 
 1640 /**
 1641  * ksba_cms_add_signer:
 1642  * @cms: A CMS object
 1643  * @cert: A certificate used to describe the signer.
 1644  *
 1645  * This functions starts assembly of a new signed data content or adds
 1646  * another signer to the list of signers.
 1647  *
 1648  * Return value: 0 on success or an error code.
 1649  **/
 1650 gpg_error_t
 1651 ksba_cms_add_signer (ksba_cms_t cms, ksba_cert_t cert)
 1652 {
 1653   struct certlist_s *cl, *cl2;
 1654 
 1655   if (!cms)
 1656     return gpg_error (GPG_ERR_INV_VALUE);
 1657 
 1658   cl = xtrycalloc (1,sizeof *cl);
 1659   if (!cl)
 1660       return gpg_error (GPG_ERR_ENOMEM);
 1661 
 1662   ksba_cert_ref (cert);
 1663   cl->cert = cert;
 1664   if (!cms->cert_list)
 1665     cms->cert_list = cl;
 1666   else
 1667     {
 1668       for (cl2=cms->cert_list; cl2->next; cl2 = cl2->next)
 1669         ;
 1670       cl2->next = cl;
 1671     }
 1672   return 0;
 1673 }
 1674 
 1675 /**
 1676  * ksba_cms_add_cert:
 1677  * @cms: A CMS object
 1678  * @cert: A certificate to be send along with the signed data.
 1679  *
 1680  * This functions adds a certificate to the list of certificates send
 1681  * along with the signed data.  Using this is optional but it is very
 1682  * common to include at least the certificate of the signer it self.
 1683  *
 1684  * Return value: 0 on success or an error code.
 1685  **/
 1686 gpg_error_t
 1687 ksba_cms_add_cert (ksba_cms_t cms, ksba_cert_t cert)
 1688 {
 1689   struct certlist_s *cl;
 1690 
 1691   if (!cms || !cert)
 1692     return gpg_error (GPG_ERR_INV_VALUE);
 1693 
 1694   /* first check whether this is a duplicate. */
 1695   for (cl = cms->cert_info_list; cl; cl = cl->next)
 1696     {
 1697       if (!_ksba_cert_cmp (cert, cl->cert))
 1698         return 0; /* duplicate */
 1699     }
 1700 
 1701   /* Okay, add it. */
 1702   cl = xtrycalloc (1,sizeof *cl);
 1703   if (!cl)
 1704       return gpg_error (GPG_ERR_ENOMEM);
 1705 
 1706   ksba_cert_ref (cert);
 1707   cl->cert = cert;
 1708   cl->next = cms->cert_info_list;
 1709   cms->cert_info_list = cl;
 1710   return 0;
 1711 }
 1712 
 1713 
 1714 /* Add an S/MIME capability as an extended attribute to the message.
 1715    This function is to be called for each capability in turn. The
 1716    first capability added will receive the highest priority.  CMS is
 1717    the context, OID the object identifier of the capability and if DER
 1718    is not NULL it is used as the DER-encoded parameters of the
 1719    capability; the length of that DER object is given in DERLEN.
 1720    DERLEN should be 0 if DER is NULL.
 1721 
 1722    The function returns 0 on success or an error code.
 1723 */
 1724 gpg_error_t
 1725 ksba_cms_add_smime_capability (ksba_cms_t cms, const char *oid,
 1726                                const unsigned char *der, size_t derlen)
 1727 {
 1728   gpg_error_t err;
 1729   struct oidparmlist_s *opl, *opl2;
 1730 
 1731   if (!cms || !oid)
 1732     return gpg_error (GPG_ERR_INV_VALUE);
 1733 
 1734   if (!der)
 1735     derlen = 0;
 1736 
 1737   opl = xtrymalloc (sizeof *opl + derlen - 1);
 1738   if (!opl)
 1739     return gpg_error_from_errno (errno);
 1740   opl->next = NULL;
 1741   opl->oid = xtrystrdup (oid);
 1742   if (!opl->oid)
 1743     {
 1744       err = gpg_error_from_errno (errno);
 1745       xfree (opl);
 1746       return err;
 1747     }
 1748   opl->parmlen = derlen;
 1749   if (der)
 1750     memcpy (opl->parm, der, derlen);
 1751 
 1752   /* Append it to maintain the desired order. */
 1753   if (!cms->capability_list)
 1754     cms->capability_list = opl;
 1755   else
 1756     {
 1757       for (opl2=cms->capability_list; opl2->next; opl2 = opl2->next)
 1758         ;
 1759       opl2->next = opl;
 1760     }
 1761 
 1762   return 0;
 1763 }
 1764 
 1765 
 1766 
 1767 /**
 1768  * ksba_cms_set_message_digest:
 1769  * @cms: A CMS object
 1770  * @idx: The index of the signer
 1771  * @digest: a message digest
 1772  * @digest_len: the length of the message digest
 1773  *
 1774  * Set a message digest into the signedAttributes of the signer with
 1775  * the index IDX.  The index of a signer is determined by the sequence
 1776  * of ksba_cms_add_signer() calls; the first signer has the index 0.
 1777  * This function is to be used when the hash value of the data has
 1778  * been calculated and before the create function requests the sign
 1779  * operation.
 1780  *
 1781  * Return value: 0 on success or an error code
 1782  **/
 1783 gpg_error_t
 1784 ksba_cms_set_message_digest (ksba_cms_t cms, int idx,
 1785                              const unsigned char *digest, size_t digest_len)
 1786 {
 1787   struct certlist_s *cl;
 1788 
 1789   if (!cms || !digest)
 1790     return gpg_error (GPG_ERR_INV_VALUE);
 1791   if (!digest_len || digest_len > DIM(cl->msg_digest))
 1792     return gpg_error (GPG_ERR_INV_VALUE);
 1793   if (idx < 0)
 1794     return gpg_error (GPG_ERR_INV_INDEX);
 1795 
 1796   for (cl=cms->cert_list; cl && idx; cl = cl->next, idx--)
 1797     ;
 1798   if (!cl)
 1799     return gpg_error (GPG_ERR_INV_INDEX); /* no certificate to store it */
 1800   cl->msg_digest_len = digest_len;
 1801   memcpy (cl->msg_digest, digest, digest_len);
 1802   return 0;
 1803 }
 1804 
 1805 /**
 1806  * ksba_cms_set_signing_time:
 1807  * @cms: A CMS object
 1808  * @idx: The index of the signer
 1809  * @sigtime: a time or an empty value to use the current time
 1810  *
 1811  * Set a signing time into the signedAttributes of the signer with
 1812  * the index IDX.  The index of a signer is determined by the sequence
 1813  * of ksba_cms_add_signer() calls; the first signer has the index 0.
 1814  *
 1815  * Return value: 0 on success or an error code
 1816  **/
 1817 gpg_error_t
 1818 ksba_cms_set_signing_time (ksba_cms_t cms, int idx, const ksba_isotime_t sigtime)
 1819 {
 1820   struct certlist_s *cl;
 1821 
 1822   if (!cms)
 1823     return gpg_error (GPG_ERR_INV_VALUE);
 1824   if (idx < 0)
 1825     return gpg_error (GPG_ERR_INV_INDEX);
 1826 
 1827   for (cl=cms->cert_list; cl && idx; cl = cl->next, idx--)
 1828     ;
 1829   if (!cl)
 1830     return gpg_error (GPG_ERR_INV_INDEX); /* no certificate to store it */
 1831 
 1832   /* Fixme: We might want to check the validity of the passed time
 1833      string. */
 1834   if (!*sigtime)
 1835     _ksba_current_time (cl->signing_time);
 1836   else
 1837     _ksba_copy_time (cl->signing_time, sigtime);
 1838   return 0;
 1839 }
 1840 
 1841 
 1842 /* Set the signature value as a canonical encoded s-expression.
 1843  *
 1844  * r_sig  = (sig-val
 1845  *        (<algo>
 1846  *      (<param_name1> <mpi>)
 1847  *      ...
 1848  *      (<param_namen> <mpi>)
 1849  *        ))
 1850  *
 1851  * <algo> must be given as a stringified OID or the special string
 1852  * "rsa".  For ECC <algo> must either be "ecdsa" or the OID matching the used
 1853  * hash algorithm; the expected parameters are "r" and "s".
 1854  *
 1855  * Note that IDX is only used for consistency checks.
 1856  */
 1857 gpg_error_t
 1858 ksba_cms_set_sig_val (ksba_cms_t cms, int idx, ksba_const_sexp_t sigval)
 1859 {
 1860   gpg_error_t err;
 1861   unsigned long n, namelen;
 1862   struct sig_val_s *sv, **sv_tail;
 1863   const unsigned char *s, *endp, *name;
 1864   int ecc;  /* True for ECC algos.  */
 1865   int i;
 1866 
 1867   if (!cms)
 1868     return gpg_error (GPG_ERR_INV_VALUE);
 1869   if (idx < 0)
 1870     return gpg_error (GPG_ERR_INV_INDEX); /* only one signer for now */
 1871 
 1872   /* log_sexp ("sigval:", sigval); */
 1873   s = sigval;
 1874   if (*s != '(')
 1875     return gpg_error (GPG_ERR_INV_SEXP);
 1876   s++;
 1877 
 1878   for (i=0, sv_tail=&cms->sig_val; *sv_tail; sv_tail=&(*sv_tail)->next, i++)
 1879     ;
 1880   if (i != idx)
 1881     return gpg_error (GPG_ERR_INV_INDEX);
 1882 
 1883   if (!(n = snext (&s)))
 1884     return gpg_error (GPG_ERR_INV_SEXP);
 1885   if (!smatch (&s, 7, "sig-val"))
 1886     return gpg_error (GPG_ERR_UNKNOWN_SEXP);
 1887   if (*s != '(')
 1888     return gpg_error (digitp (s)? GPG_ERR_UNKNOWN_SEXP : GPG_ERR_INV_SEXP);
 1889   s++;
 1890 
 1891   /* Break out the algorithm ID. */
 1892   if (!(n = snext (&s)))
 1893     return gpg_error (GPG_ERR_INV_SEXP);
 1894 
 1895   sv = xtrycalloc (1, sizeof *sv);
 1896   if (!sv)
 1897     return gpg_error (GPG_ERR_ENOMEM);
 1898 
 1899   if (n==3 && s[0] == 'r' && s[1] == 's' && s[2] == 'a')
 1900     {
 1901       sv->algo = xtrystrdup ("1.2.840.113549.1.1.1"); /* rsa */
 1902       if (!sv->algo)
 1903         {
 1904           xfree (sv);
 1905           return gpg_error (GPG_ERR_ENOMEM);
 1906         }
 1907     }
 1908   else if (n==5 && !memcmp (s, "ecdsa", 5))
 1909     {
 1910       /* Use a placeholder for later fixup.  */
 1911       sv->algo = xtrystrdup ("ecdsa");
 1912       if (!sv->algo)
 1913         {
 1914           xfree (sv);
 1915           return gpg_error (GPG_ERR_ENOMEM);
 1916         }
 1917     }
 1918   else
 1919     {
 1920       sv->algo = xtrymalloc (n+1);
 1921       if (!sv->algo)
 1922         {
 1923           xfree (sv);
 1924           return gpg_error (GPG_ERR_ENOMEM);
 1925         }
 1926       memcpy (sv->algo, s, n);
 1927       sv->algo[n] = 0;
 1928     }
 1929   s += n;
 1930 
 1931   ecc = (!strcmp (sv->algo, "ecdsa")                  /* placeholder */
 1932          || !strcmp (sv->algo, "1.2.840.10045.4.3.2") /* ecdsa-with-SHA256 */
 1933          || !strcmp (sv->algo, "1.2.840.10045.4.3.3") /* ecdsa-with-SHA384 */
 1934          || !strcmp (sv->algo, "1.2.840.10045.4.3.4") /* ecdsa-with-SHA512 */
 1935          );
 1936 
 1937   xfree (sv->value); sv->value = NULL;
 1938   xfree (sv->ecc.r); sv->ecc.r = NULL;
 1939 
 1940   while (*s == '(')
 1941     {
 1942       s++;
 1943       n = strtoul (s, (char**)&endp, 10);
 1944       s = endp;
 1945       if (!n || *s != ':')
 1946         {
 1947           err = gpg_error (GPG_ERR_INV_SEXP);
 1948           goto leave;
 1949         }
 1950       s++;
 1951       name = s;
 1952       namelen = n;
 1953       s += n;
 1954 
 1955       if (!digitp(s))
 1956         {
 1957           err = gpg_error (GPG_ERR_UNKNOWN_SEXP); /* or invalid sexp */
 1958           goto leave;
 1959         }
 1960       n = strtoul (s, (char**)&endp, 10);
 1961       s = endp;
 1962       if (!n || *s != ':')
 1963         {
 1964           err = gpg_error (GPG_ERR_INV_SEXP);
 1965           goto leave;
 1966         }
 1967       s++;
 1968 
 1969       if (namelen == 1 && *name == 's')
 1970         {
 1971           /* Store the "main" parameter into value. */
 1972           xfree (sv->value);
 1973           sv->value = xtrymalloc (n);
 1974           if (!sv->value)
 1975             {
 1976               err = gpg_error_from_syserror ();
 1977               goto leave;
 1978             }
 1979           memcpy (sv->value, s, n);
 1980           sv->valuelen = n;
 1981         }
 1982       else if (ecc && namelen == 1 && *name == 'r')
 1983         {
 1984           xfree (sv->ecc.r);
 1985           sv->ecc.r = xtrymalloc (n);
 1986           if (!sv->ecc.r)
 1987             {
 1988               err = gpg_error_from_syserror ();
 1989               goto leave;
 1990             }
 1991           memcpy (sv->ecc.r, s, n);
 1992           sv->ecc.rlen = n;
 1993         }
 1994       /* (We ignore all other parameter of the (key value) form.)  */
 1995 
 1996       s += n;
 1997       if ( *s != ')')
 1998         {
 1999           err = gpg_error (GPG_ERR_UNKNOWN_SEXP); /* or invalid sexp */
 2000           goto leave;
 2001         }
 2002       s++;
 2003     }
 2004 
 2005   /* Expect two closing parenthesis.  */
 2006   if (*s != ')')
 2007     {
 2008       err = gpg_error (digitp (s)? GPG_ERR_UNKNOWN_SEXP : GPG_ERR_INV_SEXP);
 2009       goto leave;
 2010     }
 2011   s++;
 2012   if ( *s != ')')
 2013     {
 2014       err = gpg_error (GPG_ERR_INV_SEXP);
 2015       goto leave;
 2016     }
 2017 
 2018   /* Check that we have all required data.  */
 2019   if (!sv->value)
 2020     {
 2021       err = gpg_error (GPG_ERR_INV_SEXP);
 2022       goto leave;
 2023     }
 2024   if (ecc && (!sv->ecc.r || !sv->ecc.rlen))
 2025     {
 2026       err = gpg_error (GPG_ERR_INV_SEXP);
 2027       goto leave;
 2028     }
 2029 
 2030   *sv_tail = sv;
 2031   return 0; /* Success.  */
 2032 
 2033  leave:  /* Note: This is an error-only label.  */
 2034   xfree (sv->value);
 2035   xfree (sv->algo);
 2036   xfree (sv->ecc.r);
 2037   xfree (sv);
 2038   return err;
 2039 }
 2040 
 2041 
 2042 /* Set the content encryption algorithm to OID and optionally set the
 2043    initialization vector to IV */
 2044 gpg_error_t
 2045 ksba_cms_set_content_enc_algo (ksba_cms_t cms,
 2046                                const char *oid,
 2047                                const void *iv, size_t ivlen)
 2048 {
 2049   if (!cms || !oid)
 2050     return gpg_error (GPG_ERR_INV_VALUE);
 2051 
 2052   xfree (cms->encr_iv);
 2053   cms->encr_iv = NULL;
 2054   cms->encr_ivlen = 0;
 2055 
 2056   cms->encr_algo_oid = xtrystrdup (oid);
 2057   if (!cms->encr_algo_oid)
 2058     return gpg_error (GPG_ERR_ENOMEM);
 2059 
 2060   if (iv)
 2061     {
 2062       cms->encr_iv = xtrymalloc (ivlen);
 2063       if (!cms->encr_iv)
 2064         return gpg_error (GPG_ERR_ENOMEM);
 2065       memcpy (cms->encr_iv, iv, ivlen);
 2066       cms->encr_ivlen = ivlen;
 2067     }
 2068   return 0;
 2069 }
 2070 
 2071 
 2072 /*
 2073  * encval is expected to be a canonical encoded  S-Exp of this form:
 2074  *  (enc-val
 2075  *  (<algo>
 2076  *     (<param_name1> <mpi>)
 2077  *      ...
 2078  *         (<param_namen> <mpi>)
 2079  *         (encr-algo <oid>)
 2080  *         (wrap-algo <oid>)
 2081  *  ))
 2082  *
 2083  * Note the <algo> must be given as a stringified OID or the special
 2084  * string "rsa".  For RSA there is just one parameter named "a";
 2085  * encr-algo and wrap-algo are also not used.  For ECC <algo> must be
 2086  * "ecdh", the parameter "s" gives the encrypted key, "e" specified
 2087  * the ephemeral public key, and wrap-algo algo and encr-algo are the
 2088  * stringified OIDs for the ECDH algorithm parameters.  */
 2089 gpg_error_t
 2090 ksba_cms_set_enc_val (ksba_cms_t cms, int idx, ksba_const_sexp_t encval)
 2091 {
 2092   /*FIXME: This shares most code with ...set_sig_val */
 2093   struct certlist_s *cl;
 2094   const char *s, *endp, *name;
 2095   unsigned long n, namelen;
 2096   int ecdh = 0;   /* We expect ECC parameters.  */
 2097 
 2098   if (!cms)
 2099     return gpg_error (GPG_ERR_INV_VALUE);
 2100   if (idx < 0)
 2101     return gpg_error (GPG_ERR_INV_INDEX);
 2102   for (cl=cms->cert_list; cl && idx; cl = cl->next, idx--)
 2103     ;
 2104   if (!cl)
 2105     return gpg_error (GPG_ERR_INV_INDEX); /* No cert to store the value.  */
 2106 
 2107   /* log_sexp ("encval", encval); */
 2108   s = encval;
 2109   if (*s != '(')
 2110     return gpg_error (GPG_ERR_INV_SEXP);
 2111   s++;
 2112 
 2113   n = strtoul (s, (char**)&endp, 10);
 2114   s = endp;
 2115   if (!n || *s!=':')
 2116     return gpg_error (GPG_ERR_INV_SEXP); /* we don't allow empty lengths */
 2117   s++;
 2118   if (n != 7 || memcmp (s, "enc-val", 7))
 2119     return gpg_error (GPG_ERR_UNKNOWN_SEXP);
 2120   s += 7;
 2121   if (*s != '(')
 2122     return gpg_error (digitp (s)? GPG_ERR_UNKNOWN_SEXP : GPG_ERR_INV_SEXP);
 2123   s++;
 2124 
 2125   /* break out the algorithm ID */
 2126   n = strtoul (s, (char**)&endp, 10);
 2127   s = endp;
 2128   if (!n || *s != ':')
 2129     return gpg_error (GPG_ERR_INV_SEXP); /* we don't allow empty lengths */
 2130   s++;
 2131   xfree (cl->enc_val.algo);
 2132   if (n==3 && !memcmp (s, "rsa", 3))
 2133     { /* kludge to allow "rsa" to be passed as algorithm name */
 2134       cl->enc_val.algo = xtrystrdup ("1.2.840.113549.1.1.1");
 2135       if (!cl->enc_val.algo)
 2136         return gpg_error (GPG_ERR_ENOMEM);
 2137     }
 2138   else if (n==4 && !memcmp (s, "ecdh", 4))
 2139     {
 2140       cl->enc_val.algo = xtrystrdup ("1.2.840.10045.2.1"); /* ecPublicKey */
 2141       if (!cl->enc_val.algo)
 2142         return gpg_error (GPG_ERR_ENOMEM);
 2143     }
 2144   else
 2145     {
 2146       cl->enc_val.algo = xtrymalloc (n+1);
 2147       if (!cl->enc_val.algo)
 2148         return gpg_error (GPG_ERR_ENOMEM);
 2149       memcpy (cl->enc_val.algo, s, n);
 2150       cl->enc_val.algo[n] = 0;
 2151     }
 2152   s += n;
 2153 
 2154   ecdh = !strcmp (cl->enc_val.algo, "1.2.840.10045.2.1");
 2155 
 2156   xfree (cl->enc_val.value);  cl->enc_val.value = NULL;
 2157   xfree (cl->enc_val.ecdh.e); cl->enc_val.ecdh.e = NULL;
 2158   xfree (cl->enc_val.ecdh.encr_algo); cl->enc_val.ecdh.encr_algo = NULL;
 2159   xfree (cl->enc_val.ecdh.wrap_algo); cl->enc_val.ecdh.wrap_algo = NULL;
 2160 
 2161   while (*s == '(')
 2162     {
 2163       s++;
 2164       n = strtoul (s, (char**)&endp, 10);
 2165       s = endp;
 2166       if (!n || *s != ':')
 2167         return gpg_error (GPG_ERR_INV_SEXP);
 2168       s++;
 2169       name = s;
 2170       namelen = n;
 2171       s += n;
 2172 
 2173       if (!digitp(s))
 2174         return gpg_error (GPG_ERR_UNKNOWN_SEXP); /* or invalid sexp */
 2175       n = strtoul (s, (char**)&endp, 10);
 2176       s = endp;
 2177       if (!n || *s != ':')
 2178         return gpg_error (GPG_ERR_INV_SEXP);
 2179       s++;
 2180 
 2181       if (namelen == 1 && ((!ecdh && *name == 'a') || (ecdh && *name == 's')))
 2182         {
 2183           /* Store the "main" parameter into value. */
 2184           xfree (cl->enc_val.value);
 2185           cl->enc_val.value = xtrymalloc (n);
 2186           if (!cl->enc_val.value)
 2187             return gpg_error (GPG_ERR_ENOMEM);
 2188           memcpy (cl->enc_val.value, s, n);
 2189           cl->enc_val.valuelen = n;
 2190         }
 2191       else if (!ecdh)
 2192         ; /* Ignore all other parameters for RSA.  */
 2193       else if (namelen == 1 && *name == 'e')
 2194         {
 2195           xfree (cl->enc_val.ecdh.e);
 2196           cl->enc_val.ecdh.e = xtrymalloc (n);
 2197           if (!cl->enc_val.ecdh.e)
 2198             return gpg_error (GPG_ERR_ENOMEM);
 2199           memcpy (cl->enc_val.ecdh.e, s, n);
 2200           cl->enc_val.ecdh.elen = n;
 2201         }
 2202       else if (namelen == 9 && !memcmp (name, "encr-algo", 9))
 2203         {
 2204           xfree (cl->enc_val.ecdh.encr_algo);
 2205           cl->enc_val.ecdh.encr_algo = xtrymalloc (n+1);
 2206           if (!cl->enc_val.ecdh.encr_algo)
 2207             return gpg_error (GPG_ERR_ENOMEM);
 2208           memcpy (cl->enc_val.ecdh.encr_algo, s, n);
 2209           cl->enc_val.ecdh.encr_algo[n] = 0;
 2210         }
 2211       else if (namelen == 9 && !memcmp (name, "wrap-algo", 9))
 2212         {
 2213           xfree (cl->enc_val.ecdh.wrap_algo);
 2214           cl->enc_val.ecdh.wrap_algo = xtrymalloc (n+1);
 2215           if (!cl->enc_val.ecdh.wrap_algo)
 2216             return gpg_error (GPG_ERR_ENOMEM);
 2217           memcpy (cl->enc_val.ecdh.wrap_algo, s, n);
 2218           cl->enc_val.ecdh.wrap_algo[n] = 0;
 2219         }
 2220       /* (We ignore all other parameter of the (key value) form.)  */
 2221 
 2222       s += n;
 2223       if ( *s != ')')
 2224         return gpg_error (GPG_ERR_UNKNOWN_SEXP); /* or invalid sexp */
 2225       s++;
 2226     }
 2227   /* Expect two closing parenthesis.  */
 2228   if (*s != ')')
 2229     return gpg_error (digitp (s)? GPG_ERR_UNKNOWN_SEXP : GPG_ERR_INV_SEXP);
 2230   s++;
 2231   if ( *s != ')')
 2232     return gpg_error (GPG_ERR_INV_SEXP);
 2233 
 2234   /* Check that we have all required data.  */
 2235   if (!cl->enc_val.value)
 2236     return gpg_error (GPG_ERR_INV_SEXP);
 2237   if (ecdh && (!cl->enc_val.ecdh.e
 2238                || !cl->enc_val.ecdh.elen
 2239                || !cl->enc_val.ecdh.encr_algo
 2240                || !cl->enc_val.ecdh.wrap_algo))
 2241     return gpg_error (GPG_ERR_INV_SEXP);
 2242 
 2243 
 2244   return 0;
 2245 }
 2246 
 2247 
 2248 
 2249 
 2250 /**
 2251  * ksba_cms_add_recipient:
 2252  * @cms: A CMS object
 2253  * @cert: A certificate used to describe the recipient.
 2254  *
 2255  * This functions starts assembly of a new enveloped data content or adds
 2256  * another recipient to the list of recipients.
 2257  *
 2258  * Note: after successful completion of this function ownership of
 2259  * @cert is transferred to @cms.
 2260  *
 2261  * Return value: 0 on success or an error code.
 2262  **/
 2263 gpg_error_t
 2264 ksba_cms_add_recipient (ksba_cms_t cms, ksba_cert_t cert)
 2265 {
 2266   /* for now we use the same structure */
 2267   return ksba_cms_add_signer (cms, cert);
 2268 }
 2269 
 2270 
 2271 
 2272 
 2273 /*
 2274    Content handler for parsing messages
 2275 */
 2276 
 2277 static gpg_error_t
 2278 ct_parse_data (ksba_cms_t cms)
 2279 {
 2280   (void)cms;
 2281   return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
 2282 }
 2283 
 2284 
 2285 static gpg_error_t
 2286 ct_parse_signed_data (ksba_cms_t cms)
 2287 {
 2288   enum {
 2289     sSTART,
 2290     sGOT_HASH,
 2291     sIN_DATA,
 2292     sERROR
 2293   } state = sERROR;
 2294   ksba_stop_reason_t stop_reason = cms->stop_reason;
 2295   gpg_error_t err = 0;
 2296 
 2297   cms->stop_reason = KSBA_SR_RUNNING;
 2298 
 2299   /* Calculate state from last reason and do some checks */
 2300   if (stop_reason == KSBA_SR_GOT_CONTENT)
 2301     {
 2302       state = sSTART;
 2303     }
 2304   else if (stop_reason == KSBA_SR_NEED_HASH)
 2305     {
 2306       state = sGOT_HASH;
 2307     }
 2308   else if (stop_reason == KSBA_SR_BEGIN_DATA)
 2309     {
 2310       if (!cms->hash_fnc)
 2311         err = gpg_error (GPG_ERR_MISSING_ACTION);
 2312       else
 2313         state = sIN_DATA;
 2314     }
 2315   else if (stop_reason == KSBA_SR_END_DATA)
 2316     {
 2317       state = sGOT_HASH;
 2318     }
 2319   else if (stop_reason == KSBA_SR_RUNNING)
 2320     err = gpg_error (GPG_ERR_INV_STATE);
 2321   else if (stop_reason)
 2322     err = gpg_error (GPG_ERR_BUG);
 2323 
 2324   if (err)
 2325     return err;
 2326 
 2327   /* Do the action */
 2328   if (state == sSTART)
 2329     err = _ksba_cms_parse_signed_data_part_1 (cms);
 2330   else if (state == sGOT_HASH)
 2331     err = _ksba_cms_parse_signed_data_part_2 (cms);
 2332   else if (state == sIN_DATA)
 2333     err = read_and_hash_cont (cms);
 2334   else
 2335     err = gpg_error (GPG_ERR_INV_STATE);
 2336 
 2337   if (err)
 2338     return err;
 2339 
 2340   /* Calculate new stop reason */
 2341   if (state == sSTART)
 2342     {
 2343       if (cms->detached_data && !cms->data.digest)
 2344         { /* We use this stop reason to inform the caller about a
 2345              detached signatures.  Actually there is no need for him
 2346              to hash the data now, he can do this also later. */
 2347           stop_reason = KSBA_SR_NEED_HASH;
 2348         }
 2349       else
 2350         { /* The user must now provide a hash function so that we can
 2351              hash the data in the next round */
 2352           stop_reason = KSBA_SR_BEGIN_DATA;
 2353         }
 2354     }
 2355   else if (state == sIN_DATA)
 2356     stop_reason = KSBA_SR_END_DATA;
 2357   else if (state ==sGOT_HASH)
 2358     stop_reason = KSBA_SR_READY;
 2359 
 2360   cms->stop_reason = stop_reason;
 2361   return 0;
 2362 }
 2363 
 2364 
 2365 static gpg_error_t
 2366 ct_parse_enveloped_data (ksba_cms_t cms)
 2367 {
 2368   enum {
 2369     sSTART,
 2370     sREST,
 2371     sINDATA,
 2372     sERROR
 2373   } state = sERROR;
 2374   ksba_stop_reason_t stop_reason = cms->stop_reason;
 2375   gpg_error_t err = 0;
 2376 
 2377   cms->stop_reason = KSBA_SR_RUNNING;
 2378 
 2379   /* Calculate state from last reason and do some checks */
 2380   if (stop_reason == KSBA_SR_GOT_CONTENT)
 2381     {
 2382       state = sSTART;
 2383     }
 2384   else if (stop_reason == KSBA_SR_DETACHED_DATA)
 2385     {
 2386       state = sREST;
 2387     }
 2388   else if (stop_reason == KSBA_SR_BEGIN_DATA)
 2389     {
 2390       state = sINDATA;
 2391     }
 2392   else if (stop_reason == KSBA_SR_END_DATA)
 2393     {
 2394       state = sREST;
 2395     }
 2396   else if (stop_reason == KSBA_SR_RUNNING)
 2397     err = gpg_error (GPG_ERR_INV_STATE);
 2398   else if (stop_reason)
 2399     err = gpg_error (GPG_ERR_BUG);
 2400 
 2401   if (err)
 2402     return err;
 2403 
 2404   /* Do the action */
 2405   if (state == sSTART)
 2406     err = _ksba_cms_parse_enveloped_data_part_1 (cms);
 2407   else if (state == sREST)
 2408     err = _ksba_cms_parse_enveloped_data_part_2 (cms);
 2409   else if (state == sINDATA)
 2410     err = read_encrypted_cont (cms);
 2411   else
 2412     err = gpg_error (GPG_ERR_INV_STATE);
 2413 
 2414   if (err)
 2415     return err;
 2416 
 2417   /* Calculate new stop reason */
 2418   if (state == sSTART)
 2419     {
 2420       stop_reason = cms->detached_data? KSBA_SR_DETACHED_DATA
 2421                                       : KSBA_SR_BEGIN_DATA;
 2422     }
 2423   else if (state == sINDATA)
 2424     stop_reason = KSBA_SR_END_DATA;
 2425   else if (state ==sREST)
 2426     stop_reason = KSBA_SR_READY;
 2427 
 2428   cms->stop_reason = stop_reason;
 2429   return 0;
 2430 }
 2431 
 2432 
 2433 static gpg_error_t
 2434 ct_parse_digested_data (ksba_cms_t cms)
 2435 {
 2436   (void)cms;
 2437   return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
 2438 }
 2439 
 2440 
 2441 static gpg_error_t
 2442 ct_parse_encrypted_data (ksba_cms_t cms)
 2443 {
 2444   (void)cms;
 2445   return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
 2446 }
 2447 
 2448 
 2449 
 2450 /*
 2451    Content handlers for building messages
 2452 */
 2453 
 2454 static gpg_error_t
 2455 ct_build_data (ksba_cms_t cms)
 2456 {
 2457   (void)cms;
 2458   return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
 2459 }
 2460 
 2461 
 2462 
 2463 /* Write everything up to the encapsulated data content type. */
 2464 static gpg_error_t
 2465 build_signed_data_header (ksba_cms_t cms)
 2466 {
 2467   gpg_error_t err;
 2468   unsigned char *buf;
 2469   const char *s;
 2470   size_t len;
 2471   int i;
 2472 
 2473   /* Write the outer contentInfo. */
 2474   err = _ksba_ber_write_tl (cms->writer, TYPE_SEQUENCE, CLASS_UNIVERSAL, 1, 0);
 2475   if (err)
 2476     return err;
 2477   err = ksba_oid_from_str (cms->content.oid, &buf, &len);
 2478   if (err)
 2479     return err;
 2480   err = _ksba_ber_write_tl (cms->writer,
 2481                             TYPE_OBJECT_ID, CLASS_UNIVERSAL, 0, len);
 2482   if (!err)
 2483     err = ksba_writer_write (cms->writer, buf, len);
 2484   xfree (buf);
 2485   if (err)
 2486     return err;
 2487 
 2488   err = _ksba_ber_write_tl (cms->writer, 0, CLASS_CONTEXT, 1, 0);
 2489   if (err)
 2490     return err;
 2491 
 2492   /* The SEQUENCE */
 2493   err = _ksba_ber_write_tl (cms->writer, TYPE_SEQUENCE, CLASS_UNIVERSAL, 1, 0);
 2494   if (err)
 2495     return err;
 2496 
 2497   /* figure out the CMSVersion to be used */
 2498   if (0 /* fixme: have_attribute_certificates
 2499            || encapsulated_content != data
 2500            || any_signer_info_is_version_3*/ )
 2501     s = "\x03";
 2502   else
 2503     s = "\x01";
 2504   err = _ksba_ber_write_tl (cms->writer, TYPE_INTEGER, CLASS_UNIVERSAL, 0, 1);
 2505   if (err)
 2506     return err;
 2507   err = ksba_writer_write (cms->writer, s, 1);
 2508   if (err)
 2509     return err;
 2510 
 2511   /* SET OF DigestAlgorithmIdentifier */
 2512   {
 2513     unsigned char *value;
 2514     size_t valuelen;
 2515     ksba_writer_t tmpwrt;
 2516 
 2517     err = ksba_writer_new (&tmpwrt);
 2518     if (err)
 2519       return err;
 2520     err = ksba_writer_set_mem (tmpwrt, 512);
 2521     if (err)
 2522       {
 2523         ksba_writer_release (tmpwrt);
 2524         return err;
 2525       }
 2526 
 2527     for (i=0; (s = ksba_cms_get_digest_algo_list (cms, i)); i++)
 2528       {
 2529         int j;
 2530         const char *s2;
 2531 
 2532         /* (make sure not to write duplicates) */
 2533         for (j=0; j < i && (s2=ksba_cms_get_digest_algo_list (cms, j)); j++)
 2534           {
 2535             if (!strcmp (s, s2))
 2536               break;
 2537           }
 2538         if (j == i)
 2539           {
 2540             err = _ksba_der_write_algorithm_identifier (tmpwrt, s, NULL, 0);
 2541             if (err)
 2542               {
 2543                 ksba_writer_release (tmpwrt);
 2544                 return err;
 2545               }
 2546           }
 2547       }
 2548 
 2549     value = ksba_writer_snatch_mem (tmpwrt, &valuelen);
 2550     ksba_writer_release (tmpwrt);
 2551     if (!value)
 2552       {
 2553         err = gpg_error (GPG_ERR_ENOMEM);
 2554         return err;
 2555       }
 2556     err = _ksba_ber_write_tl (cms->writer, TYPE_SET, CLASS_UNIVERSAL,
 2557                               1, valuelen);
 2558     if (!err)
 2559       err = ksba_writer_write (cms->writer, value, valuelen);
 2560     xfree (value);
 2561     if (err)
 2562       return err;
 2563   }
 2564 
 2565 
 2566 
 2567   /* Write the (inner) encapsulatedContentInfo */
 2568   /* if we have a detached signature we don't need to use undefinite
 2569      length here - but it doesn't matter either */
 2570   err = _ksba_ber_write_tl (cms->writer, TYPE_SEQUENCE, CLASS_UNIVERSAL, 1, 0);
 2571   if (err)
 2572     return err;
 2573   err = ksba_oid_from_str (cms->inner_cont_oid, &buf, &len);
 2574   if (err)
 2575     return err;
 2576   err = _ksba_ber_write_tl (cms->writer,
 2577                             TYPE_OBJECT_ID, CLASS_UNIVERSAL, 0, len);
 2578   if (!err)
 2579     err = ksba_writer_write (cms->writer, buf, len);
 2580   xfree (buf);
 2581   if (err)
 2582     return err;
 2583 
 2584   if ( !cms->detached_data)
 2585     { /* write the tag */
 2586       err = _ksba_ber_write_tl (cms->writer, 0, CLASS_CONTEXT, 1, 0);
 2587       if (err)
 2588         return err;
 2589     }
 2590 
 2591   return err;
 2592 }
 2593 
 2594 /* Set the issuer/serial from the cert to the node.
 2595    mode 0: sid
 2596    mode 1: rid
 2597  */
 2598 static gpg_error_t
 2599 set_issuer_serial (AsnNode info, ksba_cert_t cert, int mode)
 2600 {
 2601   gpg_error_t err;
 2602   AsnNode dst, src;
 2603 
 2604   if (!info || !cert)
 2605     return gpg_error (GPG_ERR_INV_VALUE);
 2606 
 2607   src = _ksba_asn_find_node (cert->root,
 2608                              "Certificate.tbsCertificate.serialNumber");
 2609   dst = _ksba_asn_find_node (info,
 2610                              mode?
 2611                              "rid.issuerAndSerialNumber.serialNumber":
 2612                              "sid.issuerAndSerialNumber.serialNumber");
 2613   err = _ksba_der_copy_tree (dst, src, cert->image);
 2614   if (err)
 2615     return err;
 2616 
 2617   src = _ksba_asn_find_node (cert->root,
 2618                              "Certificate.tbsCertificate.issuer");
 2619   dst = _ksba_asn_find_node (info,
 2620                              mode?
 2621                              "rid.issuerAndSerialNumber.issuer":
 2622                              "sid.issuerAndSerialNumber.issuer");
 2623   err = _ksba_der_copy_tree (dst, src, cert->image);
 2624   if (err)
 2625     return err;
 2626 
 2627   return 0;
 2628 }
 2629 
 2630 
 2631 /* Store the sequence of capabilities at NODE */
 2632 static gpg_error_t
 2633 store_smime_capability_sequence (AsnNode node,
 2634                                  struct oidparmlist_s *capabilities)
 2635 {
 2636   gpg_error_t err;
 2637   struct oidparmlist_s *cap, *cap2;
 2638   unsigned char *value;
 2639   size_t valuelen;
 2640   ksba_writer_t tmpwrt;
 2641 
 2642   err = ksba_writer_new (&tmpwrt);
 2643   if (err)
 2644     return err;
 2645   err = ksba_writer_set_mem (tmpwrt, 512);
 2646   if (err)
 2647     {
 2648       ksba_writer_release (tmpwrt);
 2649       return err;
 2650     }
 2651 
 2652   for (cap=capabilities; cap; cap = cap->next)
 2653     {
 2654       /* (avoid writing duplicates) */
 2655       for (cap2=capabilities; cap2 != cap; cap2 = cap2->next)
 2656         {
 2657           if (!strcmp (cap->oid, cap2->oid)
 2658               && cap->parmlen && cap->parmlen == cap2->parmlen
 2659               && !memcmp (cap->parm, cap2->parm, cap->parmlen))
 2660             break; /* Duplicate found. */
 2661         }
 2662       if (cap2 == cap)
 2663         {
 2664           /* RFC3851 requires that a missing parameter must not be
 2665              encoded as NULL.  This is in contrast to all other usages
 2666              of the algorithm identifier where ist is allowed and in
 2667              some profiles (e.g. tmttv2) even explicitly suggested to
 2668              use NULL.  */
 2669           err = _ksba_der_write_algorithm_identifier
 2670                  (tmpwrt, cap->oid,
 2671                   cap->parmlen?cap->parm:(const void*)"", cap->parmlen);
 2672           if (err)
 2673             {
 2674               ksba_writer_release (tmpwrt);
 2675               return err;
 2676             }
 2677         }
 2678     }
 2679 
 2680   value = ksba_writer_snatch_mem (tmpwrt, &valuelen);
 2681   if (!value)
 2682     err = gpg_error (GPG_ERR_ENOMEM);
 2683   if (!err)
 2684     err = _ksba_der_store_sequence (node, value, valuelen);
 2685   xfree (value);
 2686   ksba_writer_release (tmpwrt);
 2687   return err;
 2688 }
 2689 
 2690 
 2691 /* An object used to construct the signed attributes. */
 2692 struct attrarray_s {
 2693   AsnNode root;
 2694   unsigned char *image;
 2695   size_t imagelen;
 2696 };
 2697 
 2698 
 2699 /* Thank you ASN.1 committee for allowing us to employ a sort to make
 2700    that DER encoding even more complicate. */
 2701 static int
 2702 compare_attrarray (const void *a_v, const void *b_v)
 2703 {
 2704   const struct attrarray_s *a = a_v;
 2705   const struct attrarray_s *b = b_v;
 2706   const unsigned char *ap, *bp;
 2707   size_t an, bn;
 2708 
 2709   ap = a->image;
 2710   an = a->imagelen;
 2711   bp = b->image;
 2712   bn = b->imagelen;
 2713   for (; an && bn; an--, bn--, ap++, bp++ )
 2714     if (*ap != *bp)
 2715       return *ap - *bp;
 2716 
 2717   return (an == bn)? 0 : (an > bn)? 1 : -1;
 2718 }
 2719 
 2720 
 2721 
 2722 
 2723 /* Write the END of data NULL tag and everything we can write before
 2724    the user can calculate the signature */
 2725 static gpg_error_t
 2726 build_signed_data_attributes (ksba_cms_t cms)
 2727 {
 2728   gpg_error_t err;
 2729   int signer;
 2730   ksba_asn_tree_t cms_tree = NULL;
 2731   struct certlist_s *certlist;
 2732   struct oidlist_s *digestlist;
 2733   struct signer_info_s *si, **si_tail;
 2734   AsnNode root = NULL;
 2735   struct attrarray_s attrarray[4];
 2736   int attridx = 0;
 2737   int i;
 2738 
 2739   memset (attrarray, 0, sizeof (attrarray));
 2740 
 2741   /* Write the End tag */
 2742   err = _ksba_ber_write_tl (cms->writer, 0, 0, 0, 0);
 2743   if (err)
 2744     return err;
 2745 
 2746   if (cms->signer_info)
 2747     return gpg_error (GPG_ERR_CONFLICT); /* This list must be empty at
 2748                                             this point. */
 2749 
 2750   /* Write optional certificates */
 2751   if (cms->cert_info_list)
 2752     {
 2753       unsigned long totallen = 0;
 2754       const unsigned char *der;
 2755       size_t n;
 2756 
 2757       for (certlist = cms->cert_info_list; certlist; certlist = certlist->next)
 2758         {
 2759           if (!ksba_cert_get_image (certlist->cert, &n))
 2760             return gpg_error (GPG_ERR_GENERAL); /* User passed an
 2761                                                    unitialized cert */
 2762           totallen += n;
 2763         }
 2764 
 2765       err = _ksba_ber_write_tl (cms->writer, 0, CLASS_CONTEXT, 1, totallen);
 2766       if (err)
 2767         return err;
 2768 
 2769       for (certlist = cms->cert_info_list; certlist; certlist = certlist->next)
 2770         {
 2771           if (!(der=ksba_cert_get_image (certlist->cert, &n)))
 2772             return gpg_error (GPG_ERR_BUG);
 2773           err = ksba_writer_write (cms->writer, der, n);
 2774           if (err )
 2775             return err;
 2776         }
 2777     }
 2778 
 2779   /* If we ever support it, here is the right place to do it:
 2780      Write the optional CRLs */
 2781 
 2782   /* Now we have to prepare the signer info.  For now we will just build the
 2783      signedAttributes, so that the user can do the signature calculation */
 2784   err = ksba_asn_create_tree ("cms", &cms_tree);
 2785   if (err)
 2786     return err;
 2787 
 2788   certlist = cms->cert_list;
 2789   if (!certlist)
 2790     {
 2791       err = gpg_error (GPG_ERR_MISSING_VALUE); /* oops */
 2792       goto leave;
 2793     }
 2794   digestlist = cms->digest_algos;
 2795   if (!digestlist)
 2796     {
 2797       err = gpg_error (GPG_ERR_MISSING_VALUE); /* oops */
 2798       goto leave;
 2799     }
 2800 
 2801   si_tail = &cms->signer_info;
 2802   for (signer=0; certlist;
 2803        signer++, certlist = certlist->next, digestlist = digestlist->next)
 2804     {
 2805       AsnNode attr;
 2806       AsnNode n;
 2807       unsigned char *image;
 2808       size_t imagelen;
 2809 
 2810       for (i = 0; i < attridx; i++)
 2811         {
 2812           _ksba_asn_release_nodes (attrarray[i].root);
 2813           xfree (attrarray[i].image);
 2814         }
 2815       attridx = 0;
 2816       memset (attrarray, 0, sizeof (attrarray));
 2817 
 2818       if (!digestlist)
 2819         {
 2820       err = gpg_error (GPG_ERR_MISSING_VALUE); /* oops */
 2821       goto leave;
 2822     }
 2823 
 2824       if (!certlist->cert || !digestlist->oid)
 2825     {
 2826       err = gpg_error (GPG_ERR_BUG);
 2827       goto leave;
 2828     }
 2829 
 2830       /* Include the pretty important message digest. */
 2831       attr = _ksba_asn_expand_tree (cms_tree->parse_tree,
 2832                                     "CryptographicMessageSyntax.Attribute");
 2833       if (!attr)
 2834         {
 2835       err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 2836       goto leave;
 2837     }
 2838       n = _ksba_asn_find_node (attr, "Attribute.attrType");
 2839       if (!n)
 2840         {
 2841       err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 2842       goto leave;
 2843     }
 2844       err = _ksba_der_store_oid (n, oidstr_messageDigest);
 2845       if (err)
 2846         goto leave;
 2847       n = _ksba_asn_find_node (attr, "Attribute.attrValues");
 2848       if (!n || !n->down)
 2849         return gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 2850       n = n->down; /* fixme: ugly hack */
 2851       assert (certlist && certlist->msg_digest_len);
 2852       err = _ksba_der_store_octet_string (n, certlist->msg_digest,
 2853                                           certlist->msg_digest_len);
 2854       if (err)
 2855         goto leave;
 2856       err = _ksba_der_encode_tree (attr, &image, &imagelen);
 2857       if (err)
 2858         goto leave;
 2859       attrarray[attridx].root = attr;
 2860       attrarray[attridx].image = image;
 2861       attrarray[attridx].imagelen = imagelen;
 2862       attridx++;
 2863 
 2864       /* Include the content-type attribute. */
 2865       attr = _ksba_asn_expand_tree (cms_tree->parse_tree,
 2866                                     "CryptographicMessageSyntax.Attribute");
 2867       if (!attr)
 2868         {
 2869       err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 2870       goto leave;
 2871     }
 2872       n = _ksba_asn_find_node (attr, "Attribute.attrType");
 2873       if (!n)
 2874         {
 2875       err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 2876       goto leave;
 2877     }
 2878       err = _ksba_der_store_oid (n, oidstr_contentType);
 2879       if (err)
 2880     goto leave;
 2881       n = _ksba_asn_find_node (attr, "Attribute.attrValues");
 2882       if (!n || !n->down)
 2883         {
 2884       err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 2885       goto leave;
 2886     }
 2887       n = n->down; /* fixme: ugly hack */
 2888       err = _ksba_der_store_oid (n, cms->inner_cont_oid);
 2889       if (err)
 2890         goto leave;
 2891       err = _ksba_der_encode_tree (attr, &image, &imagelen);
 2892       if (err)
 2893         goto leave;
 2894       attrarray[attridx].root = attr;
 2895       attrarray[attridx].image = image;
 2896       attrarray[attridx].imagelen = imagelen;
 2897       attridx++;
 2898 
 2899       /* Include the signing time */
 2900       if (*certlist->signing_time)
 2901         {
 2902           attr = _ksba_asn_expand_tree (cms_tree->parse_tree,
 2903                                      "CryptographicMessageSyntax.Attribute");
 2904           if (!attr)
 2905             {
 2906           err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 2907           goto leave;
 2908         }
 2909           n = _ksba_asn_find_node (attr, "Attribute.attrType");
 2910           if (!n)
 2911             {
 2912           err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 2913           goto leave;
 2914         }
 2915           err = _ksba_der_store_oid (n, oidstr_signingTime);
 2916           if (err)
 2917             goto leave;
 2918           n = _ksba_asn_find_node (attr, "Attribute.attrValues");
 2919           if (!n || !n->down)
 2920             {
 2921           err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 2922           goto leave;
 2923         }
 2924           n = n->down; /* fixme: ugly hack */
 2925           err = _ksba_der_store_time (n, certlist->signing_time);
 2926           if (err)
 2927             goto leave;
 2928           err = _ksba_der_encode_tree (attr, &image, &imagelen);
 2929           if (err)
 2930             goto leave;
 2931           /* We will use the attributes again - so save them */
 2932           attrarray[attridx].root = attr;
 2933           attrarray[attridx].image = image;
 2934           attrarray[attridx].imagelen = imagelen;
 2935           attridx++;
 2936         }
 2937 
 2938       /* Include the S/MIME capabilities with the first signer. */
 2939       if (cms->capability_list && !signer)
 2940         {
 2941           attr = _ksba_asn_expand_tree (cms_tree->parse_tree,
 2942                                     "CryptographicMessageSyntax.Attribute");
 2943           if (!attr)
 2944             {
 2945           err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 2946           goto leave;
 2947         }
 2948           n = _ksba_asn_find_node (attr, "Attribute.attrType");
 2949           if (!n)
 2950             {
 2951           err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 2952           goto leave;
 2953         }
 2954           err = _ksba_der_store_oid (n, oidstr_smimeCapabilities);
 2955           if (err)
 2956             goto leave;
 2957           n = _ksba_asn_find_node (attr, "Attribute.attrValues");
 2958           if (!n || !n->down)
 2959             {
 2960           err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 2961           goto leave;
 2962         }
 2963           n = n->down; /* fixme: ugly hack */
 2964           err = store_smime_capability_sequence (n, cms->capability_list);
 2965           if (err)
 2966             goto leave;
 2967           err = _ksba_der_encode_tree (attr, &image, &imagelen);
 2968           if (err)
 2969             goto leave;
 2970           attrarray[attridx].root = attr;
 2971           attrarray[attridx].image = image;
 2972           attrarray[attridx].imagelen = imagelen;
 2973           attridx++;
 2974         }
 2975 
 2976       /* Arggh.  That silly ASN.1 DER encoding rules: We need to sort
 2977          the SET values. */
 2978       qsort (attrarray, attridx, sizeof (struct attrarray_s),
 2979              compare_attrarray);
 2980 
 2981       /* Now copy them to an SignerInfo tree.  This tree is not
 2982          complete but suitable for ksba_cms_hash_signed_attributes() */
 2983       root = _ksba_asn_expand_tree (cms_tree->parse_tree,
 2984                                     "CryptographicMessageSyntax.SignerInfo");
 2985       n = _ksba_asn_find_node (root, "SignerInfo.signedAttrs");
 2986       if (!n || !n->down)
 2987         {
 2988       err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 2989       goto leave;
 2990     }
 2991       /* This is another ugly hack to move to the element we want */
 2992       for (n = n->down->down; n && n->type != TYPE_SEQUENCE; n = n->right)
 2993         ;
 2994       if (!n)
 2995         {
 2996       err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 2997       goto leave;
 2998     }
 2999 
 3000       assert (attridx <= DIM (attrarray));
 3001       for (i=0; i < attridx; i++)
 3002         {
 3003           if (i)
 3004             {
 3005               if ( !(n=_ksba_asn_insert_copy (n)))
 3006                 {
 3007           err = gpg_error (GPG_ERR_ENOMEM);
 3008           goto leave;
 3009         }
 3010             }
 3011           err = _ksba_der_copy_tree (n, attrarray[i].root, attrarray[i].image);
 3012           if (err)
 3013             goto leave;
 3014       _ksba_asn_release_nodes (attrarray[i].root);
 3015       free (attrarray[i].image);
 3016       attrarray[i].root = NULL;
 3017       attrarray[i].image = NULL;
 3018         }
 3019 
 3020       err = _ksba_der_encode_tree (root, &image, NULL);
 3021       if (err)
 3022         goto leave;
 3023 
 3024       si = xtrycalloc (1, sizeof *si);
 3025       if (!si)
 3026         return gpg_error (GPG_ERR_ENOMEM);
 3027       si->root = root;
 3028       root = NULL;
 3029       si->image = image;
 3030       /* Hmmm, we don't set the length of the image. */
 3031       *si_tail = si;
 3032       si_tail = &si->next;
 3033     }
 3034 
 3035  leave:
 3036   _ksba_asn_release_nodes (root);
 3037   ksba_asn_tree_release (cms_tree);
 3038   for (i = 0; i < attridx; i++)
 3039     {
 3040       _ksba_asn_release_nodes (attrarray[i].root);
 3041       xfree (attrarray[i].image);
 3042     }
 3043 
 3044   return err;
 3045 }
 3046 
 3047 
 3048 
 3049 
 3050 /* The user has calculated the signatures and we can therefore write
 3051    everything left over to do. */
 3052 static gpg_error_t
 3053 build_signed_data_rest (ksba_cms_t cms)
 3054 {
 3055   gpg_error_t err;
 3056   int signer;
 3057   ksba_asn_tree_t cms_tree = NULL;
 3058   struct certlist_s *certlist;
 3059   struct oidlist_s *digestlist;
 3060   struct signer_info_s *si;
 3061   struct sig_val_s *sv;
 3062   ksba_writer_t tmpwrt = NULL;
 3063   AsnNode root = NULL;
 3064   ksba_der_t dbld = NULL;
 3065 
 3066   /* Now we can really write the signer info */
 3067   err = ksba_asn_create_tree ("cms", &cms_tree);
 3068   if (err)
 3069     return err;
 3070 
 3071   certlist = cms->cert_list;
 3072   if (!certlist)
 3073     {
 3074       err = gpg_error (GPG_ERR_MISSING_VALUE); /* oops */
 3075       return err;
 3076     }
 3077 
 3078   /* To construct the set we use a temporary writer object. */
 3079   err = ksba_writer_new (&tmpwrt);
 3080   if (err)
 3081     goto leave;
 3082   err = ksba_writer_set_mem (tmpwrt, 2048);
 3083   if (err)
 3084     goto leave;
 3085 
 3086   digestlist = cms->digest_algos;
 3087   si = cms->signer_info;
 3088   sv = cms->sig_val;
 3089 
 3090   for (signer=0; certlist;
 3091        signer++,
 3092          certlist = certlist->next,
 3093          digestlist = digestlist->next,
 3094          si = si->next,
 3095          sv = sv->next)
 3096     {
 3097       AsnNode n, n2;
 3098       unsigned char *image;
 3099       size_t imagelen;
 3100       const char *oid;
 3101 
 3102       if (!digestlist || !si || !sv)
 3103         {
 3104       err = gpg_error (GPG_ERR_MISSING_VALUE); /* oops */
 3105       goto leave;
 3106     }
 3107       if (!certlist->cert || !digestlist->oid)
 3108         {
 3109       err = gpg_error (GPG_ERR_BUG);
 3110       goto leave;
 3111     }
 3112 
 3113       root = _ksba_asn_expand_tree (cms_tree->parse_tree,
 3114                                     "CryptographicMessageSyntax.SignerInfo");
 3115 
 3116       /* We store a version of 1 because we use the issuerAndSerialNumber */
 3117       n = _ksba_asn_find_node (root, "SignerInfo.version");
 3118       if (!n)
 3119     {
 3120       err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 3121       goto leave;
 3122     }
 3123       err = _ksba_der_store_integer (n, "\x00\x00\x00\x01\x01");
 3124       if (err)
 3125         goto leave;
 3126 
 3127       /* Store the sid */
 3128       n = _ksba_asn_find_node (root, "SignerInfo.sid");
 3129       if (!n)
 3130         {
 3131       err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 3132       goto leave;
 3133     }
 3134 
 3135       err = set_issuer_serial (n, certlist->cert, 0);
 3136       if (err)
 3137         goto leave;
 3138 
 3139       /* store the digestAlgorithm */
 3140       n = _ksba_asn_find_node (root, "SignerInfo.digestAlgorithm.algorithm");
 3141       if (!n)
 3142     {
 3143       err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 3144       goto leave;
 3145     }
 3146       err = _ksba_der_store_oid (n, digestlist->oid);
 3147       if (err)
 3148         goto leave;
 3149       n = _ksba_asn_find_node (root, "SignerInfo.digestAlgorithm.parameters");
 3150       if (!n)
 3151         {
 3152       err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 3153       goto leave;
 3154     }
 3155       err = _ksba_der_store_null (n);
 3156       if (err)
 3157         goto leave;
 3158 
 3159       /* and the signed attributes */
 3160       n = _ksba_asn_find_node (root, "SignerInfo.signedAttrs");
 3161       if (!n || !n->down)
 3162         {
 3163       err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 3164       goto leave;
 3165     }
 3166       assert (si->root);
 3167       assert (si->image);
 3168       n2 = _ksba_asn_find_node (si->root, "SignerInfo.signedAttrs");
 3169       if (!n2 || !n2->down)
 3170         {
 3171       err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 3172       goto leave;
 3173     }
 3174       err = _ksba_der_copy_tree (n, n2, si->image);
 3175       if (err)
 3176         goto leave;
 3177       image = NULL;
 3178 
 3179       /* store the signatureAlgorithm */
 3180       n = _ksba_asn_find_node (root,
 3181                    "SignerInfo.signatureAlgorithm.algorithm");
 3182       if (!n)
 3183         {
 3184       err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 3185       goto leave;
 3186     }
 3187       if (!sv->algo)
 3188         {
 3189       err = gpg_error (GPG_ERR_MISSING_VALUE);
 3190       goto leave;
 3191     }
 3192 
 3193       if (!strcmp (sv->algo, "ecdsa"))
 3194         {
 3195           /* Look at the digest algorithm and replace accordingly.  */
 3196           if (!strcmp (digestlist->oid, "2.16.840.1.101.3.4.2.1"))
 3197             oid = "1.2.840.10045.4.3.2";  /* ecdsa-with-SHA256 */
 3198           else if (!strcmp (digestlist->oid, "2.16.840.1.101.3.4.2.2"))
 3199             oid = "1.2.840.10045.4.3.3";  /* ecdsa-with-SHA384 */
 3200           else if (!strcmp (digestlist->oid, "2.16.840.1.101.3.4.2.3"))
 3201             oid = "1.2.840.10045.4.3.4";  /* ecdsa-with-SHA512 */
 3202           else
 3203             {
 3204               err = gpg_error (GPG_ERR_DIGEST_ALGO);
 3205               goto leave;
 3206             }
 3207         }
 3208       else
 3209         oid = sv->algo;
 3210 
 3211       err = _ksba_der_store_oid (n, oid);
 3212       if (err)
 3213     goto leave;
 3214       n = _ksba_asn_find_node (root,
 3215                    "SignerInfo.signatureAlgorithm.parameters");
 3216       if (!n)
 3217         {
 3218       err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 3219       goto leave;
 3220     }
 3221       err = _ksba_der_store_null (n);
 3222       if (err)
 3223     goto leave;
 3224 
 3225       /* store the signature  */
 3226       if (!sv->value)
 3227         {
 3228       err = gpg_error (GPG_ERR_MISSING_VALUE);
 3229       goto leave;
 3230     }
 3231       n = _ksba_asn_find_node (root, "SignerInfo.signature");
 3232       if (!n)
 3233     {
 3234       err = gpg_error (GPG_ERR_ELEMENT_NOT_FOUND);
 3235       goto leave;
 3236     }
 3237 
 3238       if (sv->ecc.r)  /* ECDSA */
 3239         {
 3240           unsigned char *tmpder;
 3241           size_t tmpderlen;
 3242 
 3243           _ksba_der_release (dbld);
 3244           dbld = _ksba_der_builder_new (0);
 3245           if (!dbld)
 3246             {
 3247               err = gpg_error_from_syserror ();
 3248               goto leave;
 3249             }
 3250           _ksba_der_add_tag (dbld, 0, TYPE_SEQUENCE);
 3251           _ksba_der_add_int (dbld, sv->ecc.r, sv->ecc.rlen, 1);
 3252           _ksba_der_add_int (dbld, sv->value, sv->valuelen, 1);
 3253           _ksba_der_add_end (dbld);
 3254 
 3255           err = _ksba_der_builder_get (dbld, &tmpder, &tmpderlen);
 3256           if (err)
 3257             goto leave;
 3258           err = _ksba_der_store_octet_string (n, tmpder, tmpderlen);
 3259           xfree (tmpder);
 3260           if (err)
 3261             goto leave;
 3262         }
 3263       else  /* RSA */
 3264         {
 3265           err = _ksba_der_store_octet_string (n, sv->value, sv->valuelen);
 3266           if (err)
 3267             goto leave;
 3268         }
 3269 
 3270       /* Make the DER encoding and write it out. */
 3271       err = _ksba_der_encode_tree (root, &image, &imagelen);
 3272       if (err)
 3273     goto leave;
 3274 
 3275       err = ksba_writer_write (tmpwrt, image, imagelen);
 3276       xfree (image);
 3277       if (err)
 3278     goto leave;
 3279     }
 3280 
 3281   /* Write out the SET filled with all signer infos */
 3282   {
 3283     unsigned char *value;
 3284     size_t valuelen;
 3285 
 3286     value = ksba_writer_snatch_mem (tmpwrt, &valuelen);
 3287     if (!value)
 3288       {
 3289         err = gpg_error (GPG_ERR_ENOMEM);
 3290     goto leave;
 3291       }
 3292     err = _ksba_ber_write_tl (cms->writer, TYPE_SET, CLASS_UNIVERSAL,
 3293                               1, valuelen);
 3294     if (!err)
 3295       err = ksba_writer_write (cms->writer, value, valuelen);
 3296     xfree (value);
 3297     if (err)
 3298       goto leave;
 3299   }
 3300 
 3301   /* Write 3 end tags */
 3302   err = _ksba_ber_write_tl (cms->writer, 0, 0, 0, 0);
 3303   if (!err)
 3304     err = _ksba_ber_write_tl (cms->writer, 0, 0, 0, 0);
 3305   if (!err)
 3306     err = _ksba_ber_write_tl (cms->writer, 0, 0, 0, 0);
 3307 
 3308  leave:
 3309   ksba_asn_tree_release (cms_tree);
 3310   _ksba_asn_release_nodes (root);
 3311   ksba_writer_release (tmpwrt);
 3312   _ksba_der_release (dbld);
 3313   return err;
 3314 }
 3315 
 3316 
 3317 
 3318 
 3319 static gpg_error_t
 3320 ct_build_signed_data (ksba_cms_t cms)
 3321 {
 3322   enum {
 3323     sSTART,
 3324     sDATAREADY,
 3325     sGOTSIG,
 3326     sERROR
 3327   } state = sERROR;
 3328   ksba_stop_reason_t stop_reason;
 3329   gpg_error_t err = 0;
 3330 
 3331   stop_reason = cms->stop_reason;
 3332   cms->stop_reason = KSBA_SR_RUNNING;
 3333 
 3334   /* Calculate state from last reason and do some checks */
 3335   if (stop_reason == KSBA_SR_GOT_CONTENT)
 3336     {
 3337       state = sSTART;
 3338     }
 3339   else if (stop_reason == KSBA_SR_BEGIN_DATA)
 3340     {
 3341       /* fixme: check that the message digest has been set */
 3342       state = sDATAREADY;
 3343     }
 3344   else if (stop_reason == KSBA_SR_END_DATA)
 3345     state = sDATAREADY;
 3346   else if (stop_reason == KSBA_SR_NEED_SIG)
 3347     {
 3348       if (!cms->sig_val)
 3349         err = gpg_error (GPG_ERR_MISSING_ACTION); /* No ksba_cms_set_sig_val () called */
 3350       state = sGOTSIG;
 3351     }
 3352   else if (stop_reason == KSBA_SR_RUNNING)
 3353     err = gpg_error (GPG_ERR_INV_STATE);
 3354   else if (stop_reason)
 3355     err = gpg_error (GPG_ERR_BUG);
 3356 
 3357   if (err)
 3358     return err;
 3359 
 3360   /* Do the action */
 3361   if (state == sSTART)
 3362     {
 3363       /* figure out whether a detached signature is requested */
 3364       if (cms->cert_list && cms->cert_list->msg_digest_len)
 3365         cms->detached_data = 1;
 3366       else
 3367         cms->detached_data = 0;
 3368       /* and start encoding */
 3369       err = build_signed_data_header (cms);
 3370     }
 3371   else if (state == sDATAREADY)
 3372     {
 3373       if (!cms->detached_data)
 3374         err = _ksba_ber_write_tl (cms->writer, 0, 0, 0, 0);
 3375       if (!err)
 3376         err = build_signed_data_attributes (cms);
 3377     }
 3378   else if (state == sGOTSIG)
 3379     err = build_signed_data_rest (cms);
 3380   else
 3381     err = gpg_error (GPG_ERR_INV_STATE);
 3382 
 3383   if (err)
 3384     return err;
 3385 
 3386   /* Calculate new stop reason */
 3387   if (state == sSTART)
 3388     {
 3389       /* user should write the data and calculate the hash or do
 3390          nothing in case of END_DATA */
 3391       stop_reason = cms->detached_data? KSBA_SR_END_DATA
 3392                                       : KSBA_SR_BEGIN_DATA;
 3393     }
 3394   else if (state == sDATAREADY)
 3395     stop_reason = KSBA_SR_NEED_SIG;
 3396   else if (state == sGOTSIG)
 3397     stop_reason = KSBA_SR_READY;
 3398 
 3399   cms->stop_reason = stop_reason;
 3400   return 0;
 3401 }
 3402 
 3403 
 3404 /* write everything up to the encryptedContentInfo including the tag */
 3405 static gpg_error_t
 3406 build_enveloped_data_header (ksba_cms_t cms)
 3407 {
 3408   gpg_error_t err;
 3409   int recpno;
 3410   struct certlist_s *certlist;
 3411   unsigned char *buf;
 3412   const char *s;
 3413   size_t len;
 3414   ksba_der_t dbld = NULL;
 3415   int any_ecdh = 0;
 3416 
 3417   /* See whether we have any ECDH recipients.  */
 3418   for (certlist = cms->cert_list; certlist; certlist = certlist->next)
 3419     if (certlist->enc_val.ecdh.e)
 3420       {
 3421         any_ecdh = 1;
 3422         break;
 3423       }
 3424 
 3425   /* Write the outer contentInfo */
 3426   /* fixme: code is shared with signed_data_header */
 3427   err = _ksba_ber_write_tl (cms->writer, TYPE_SEQUENCE, CLASS_UNIVERSAL, 1, 0);
 3428   if (err)
 3429     return err;
 3430   err = ksba_oid_from_str (cms->content.oid, &buf, &len);
 3431   if (err)
 3432     return err;
 3433   err = _ksba_ber_write_tl (cms->writer,
 3434                             TYPE_OBJECT_ID, CLASS_UNIVERSAL, 0, len);
 3435   if (!err)
 3436     err = ksba_writer_write (cms->writer, buf, len);
 3437   xfree (buf);
 3438   if (err)
 3439     return err;
 3440 
 3441   err = _ksba_ber_write_tl (cms->writer, 0, CLASS_CONTEXT, 1, 0);
 3442   if (err)
 3443     return err;
 3444 
 3445   /* The SEQUENCE */
 3446   err = _ksba_ber_write_tl (cms->writer, TYPE_SEQUENCE, CLASS_UNIVERSAL, 1, 0);
 3447   if (err)
 3448     return err;
 3449 
 3450   /* figure out the CMSVersion to be used (from rfc2630):
 3451      version is the syntax version number.  If originatorInfo is
 3452      present, then version shall be 2.  If any of the RecipientInfo
 3453      structures included have a version other than 0, then the version
 3454      shall be 2.  If unprotectedAttrs is present, then version shall
 3455      be 2.  If originatorInfo is absent, all of the RecipientInfo
 3456      structures are version 0, and unprotectedAttrs is absent, then
 3457      version shall be 0.
 3458 
 3459      For SPHINX the version number must be 0.
 3460   */
 3461 
 3462 
 3463   s = any_ecdh? "\x02" :"\x00";
 3464   err = _ksba_ber_write_tl (cms->writer, TYPE_INTEGER, CLASS_UNIVERSAL, 0, 1);
 3465   if (err)
 3466     return err;
 3467   err = ksba_writer_write (cms->writer, s, 1);
 3468   if (err)
 3469     return err;
 3470 
 3471   /* Note: originatorInfo is not yet implemented and must not be used
 3472      for SPHINX */
 3473 
 3474   certlist = cms->cert_list;
 3475   if (!certlist)
 3476     {
 3477       err = gpg_error (GPG_ERR_MISSING_VALUE); /* oops */
 3478       goto leave;
 3479     }
 3480 
 3481 
 3482   dbld = _ksba_der_builder_new (0);
 3483   if (!dbld)
 3484     {
 3485       err = gpg_error_from_syserror ();
 3486       goto leave;
 3487     }
 3488 
 3489   _ksba_der_add_tag (dbld, 0, TYPE_SET);
 3490   for (recpno=0; certlist; recpno++, certlist = certlist->next)
 3491     {
 3492       const unsigned char *der;
 3493       size_t derlen;
 3494 
 3495       if (!certlist->cert)
 3496         {
 3497           err = gpg_error (GPG_ERR_BUG);
 3498           goto leave;
 3499         }
 3500 
 3501       if (!certlist->enc_val.ecdh.e)  /* RSA (ktri) */
 3502         {
 3503           _ksba_der_add_tag (dbld, 0, TYPE_SEQUENCE);
 3504           /* We store a version of 0 because we are only allowed to
 3505            * use the issuerAndSerialNumber for SPHINX */
 3506           _ksba_der_add_ptr (dbld, 0, TYPE_INTEGER, "", 1);
 3507           /* rid.issuerAndSerialNumber */
 3508           _ksba_der_add_tag (dbld, 0, TYPE_SEQUENCE);
 3509           /* rid.issuerAndSerialNumber.issuer */
 3510           err = _ksba_cert_get_issuer_dn_ptr (certlist->cert, &der, &derlen);
 3511           if (err)
 3512             goto leave;
 3513           _ksba_der_add_der (dbld, der, derlen);
 3514           /* rid.issuerAndSerialNumber.serialNumber */
 3515           err = _ksba_cert_get_serial_ptr (certlist->cert, &der, &derlen);
 3516           if (err)
 3517             goto leave;
 3518           _ksba_der_add_der (dbld, der, derlen);
 3519           _ksba_der_add_end (dbld);
 3520 
 3521           /* Store the keyEncryptionAlgorithm */
 3522           _ksba_der_add_tag (dbld, 0, TYPE_SEQUENCE);
 3523           if (!certlist->enc_val.algo || !certlist->enc_val.value)
 3524             {
 3525               err = gpg_error (GPG_ERR_MISSING_VALUE);
 3526               goto leave;
 3527             }
 3528           _ksba_der_add_oid (dbld, certlist->enc_val.algo);
 3529           /* Now store NULL for the optional parameters.  From Peter
 3530            * Gutmann's X.509 style guide:
 3531            *
 3532            *   Another pitfall to be aware of is that algorithms which
 3533            *   have no parameters have this specified as a NULL value
 3534            *   rather than omitting the parameters field entirely.  The
 3535            *   reason for this is that when the 1988 syntax for
 3536            *   AlgorithmIdentifier was translated into the 1997 syntax,
 3537            *   the OPTIONAL associated with the AlgorithmIdentifier
 3538            *   parameters got lost.  Later it was recovered via a defect
 3539            *   report, but by then everyone thought that algorithm
 3540            *   parameters were mandatory.  Because of this the algorithm
 3541            *   parameters should be specified as NULL, regardless of what
 3542            *   you read elsewhere.
 3543            *
 3544            *        The trouble is that things *never* get better, they just
 3545            *        stay the same, only more so
 3546            *            -- Terry Pratchett, "Eric"
 3547            *
 3548            * Although this is about signing, we always do it.  Versions of
 3549            * Libksba before 1.0.6 had a bug writing out the NULL tag here,
 3550            * thus in reality we used to be correct according to the
 3551            * standards despite we didn't intended so.
 3552            */
 3553           _ksba_der_add_ptr (dbld, 0, TYPE_NULL, NULL, 0);
 3554           _ksba_der_add_end (dbld);
 3555 
 3556           /* Store the encryptedKey  */
 3557           if (!certlist->enc_val.value)
 3558             {
 3559               err = gpg_error (GPG_ERR_MISSING_VALUE);
 3560               goto leave;
 3561             }
 3562           _ksba_der_add_ptr (dbld, 0, TYPE_OCTET_STRING,
 3563                              certlist->enc_val.value,
 3564                              certlist->enc_val.valuelen);
 3565 
 3566         }
 3567       else /* ECDH */
 3568         {
 3569           _ksba_der_add_tag (dbld, CLASS_CONTEXT, 1); /* kari */
 3570           _ksba_der_add_ptr (dbld, 0, TYPE_INTEGER, "\x03", 1);
 3571 
 3572           _ksba_der_add_tag (dbld, CLASS_CONTEXT, 0); /* originator */
 3573           _ksba_der_add_tag (dbld, CLASS_CONTEXT, 1); /* originatorKey */
 3574           _ksba_der_add_tag (dbld, 0, TYPE_SEQUENCE); /* algorithm */
 3575           _ksba_der_add_oid (dbld, certlist->enc_val.algo);
 3576           _ksba_der_add_end (dbld);
 3577           _ksba_der_add_bts (dbld, certlist->enc_val.ecdh.e,
 3578                              certlist->enc_val.ecdh.elen, 0);
 3579           _ksba_der_add_end (dbld); /* end originatorKey */
 3580           _ksba_der_add_end (dbld); /* end originator */
 3581 
 3582           _ksba_der_add_tag (dbld, 0, TYPE_SEQUENCE); /* keyEncrAlgo */
 3583           _ksba_der_add_oid (dbld, certlist->enc_val.ecdh.encr_algo);
 3584           _ksba_der_add_tag (dbld, 0, TYPE_SEQUENCE);
 3585           _ksba_der_add_oid (dbld, certlist->enc_val.ecdh.wrap_algo);
 3586           _ksba_der_add_end (dbld);
 3587           _ksba_der_add_end (dbld); /* end keyEncrAlgo */
 3588           _ksba_der_add_tag (dbld, 0, TYPE_SEQUENCE); /* recpEncrKeys */
 3589           _ksba_der_add_tag (dbld, 0, TYPE_SEQUENCE); /* recpEncrKey */
 3590 
 3591           /* rid.issuerAndSerialNumber */
 3592           _ksba_der_add_tag (dbld, 0, TYPE_SEQUENCE);
 3593           err = _ksba_cert_get_issuer_dn_ptr (certlist->cert, &der, &derlen);
 3594           if (err)
 3595             goto leave;
 3596           _ksba_der_add_der (dbld, der, derlen);
 3597           err = _ksba_cert_get_serial_ptr (certlist->cert, &der, &derlen);
 3598           if (err)
 3599             goto leave;
 3600           _ksba_der_add_der (dbld, der, derlen);
 3601           _ksba_der_add_end (dbld);
 3602 
 3603           /* encryptedKey  */
 3604           if (!certlist->enc_val.value)
 3605             {
 3606               err = gpg_error (GPG_ERR_MISSING_VALUE);
 3607               goto leave;
 3608             }
 3609           _ksba_der_add_ptr (dbld, 0, TYPE_OCTET_STRING,
 3610                              certlist->enc_val.value,
 3611                              certlist->enc_val.valuelen);
 3612 
 3613           _ksba_der_add_end (dbld); /* end recpEncrKey */
 3614           _ksba_der_add_end (dbld); /* end recpEncrKeys */
 3615        }
 3616 
 3617       _ksba_der_add_end (dbld); /* End SEQUENCE (ktri or kari) */
 3618     }
 3619   _ksba_der_add_end (dbld);  /* End SET */
 3620 
 3621   /* Write out the SET filled with all recipient infos */
 3622   {
 3623     unsigned char *image;
 3624     size_t imagelen;
 3625 
 3626     err = _ksba_der_builder_get (dbld, &image, &imagelen);
 3627     if (err)
 3628       goto leave;
 3629     err = ksba_writer_write (cms->writer, image, imagelen);
 3630     xfree (image);
 3631     if (err)
 3632       goto leave;
 3633   }
 3634 
 3635   /* Write the (inner) encryptedContentInfo */
 3636   err = _ksba_ber_write_tl (cms->writer, TYPE_SEQUENCE, CLASS_UNIVERSAL, 1, 0);
 3637   if (err)
 3638     return err;
 3639   err = ksba_oid_from_str (cms->inner_cont_oid, &buf, &len);
 3640   if (err)
 3641     return err;
 3642   err = _ksba_ber_write_tl (cms->writer,
 3643                             TYPE_OBJECT_ID, CLASS_UNIVERSAL, 0, len);
 3644   if (!err)
 3645     err = ksba_writer_write (cms->writer, buf, len);
 3646   xfree (buf);
 3647   if (err)
 3648     return err;
 3649 
 3650   /* and the encryptionAlgorithm */
 3651   err = _ksba_der_write_algorithm_identifier (cms->writer,
 3652                                               cms->encr_algo_oid,
 3653                                               cms->encr_iv,
 3654                                               cms->encr_ivlen);
 3655   if (err)
 3656     return err;
 3657 
 3658   /* write the tag for the encrypted data, it is an implicit octect
 3659      string in constructed form and indefinite length */
 3660   err = _ksba_ber_write_tl (cms->writer, 0, CLASS_CONTEXT, 1, 0);
 3661   if (err)
 3662     return err;
 3663 
 3664   /* Now the encrypted data should be written */
 3665 
 3666  leave:
 3667   _ksba_der_release (dbld);
 3668   return err;
 3669 }
 3670 
 3671 
 3672 static gpg_error_t
 3673 ct_build_enveloped_data (ksba_cms_t cms)
 3674 {
 3675   enum {
 3676     sSTART,
 3677     sINDATA,
 3678     sREST,
 3679     sERROR
 3680   } state = sERROR;
 3681   ksba_stop_reason_t stop_reason;
 3682   gpg_error_t err = 0;
 3683 
 3684   stop_reason = cms->stop_reason;
 3685   cms->stop_reason = KSBA_SR_RUNNING;
 3686 
 3687   /* Calculate state from last reason and do some checks */
 3688   if (stop_reason == KSBA_SR_GOT_CONTENT)
 3689     state = sSTART;
 3690   else if (stop_reason == KSBA_SR_BEGIN_DATA)
 3691     state = sINDATA;
 3692   else if (stop_reason == KSBA_SR_END_DATA)
 3693     state = sREST;
 3694   else if (stop_reason == KSBA_SR_RUNNING)
 3695     err = gpg_error (GPG_ERR_INV_STATE);
 3696   else if (stop_reason)
 3697     err = gpg_error (GPG_ERR_BUG);
 3698 
 3699   if (err)
 3700     return err;
 3701 
 3702   /* Do the action */
 3703   if (state == sSTART)
 3704     err = build_enveloped_data_header (cms);
 3705   else if (state == sINDATA)
 3706     err = write_encrypted_cont (cms);
 3707   else if (state == sREST)
 3708     {
 3709       /* SPHINX does not allow for unprotectedAttributes */
 3710 
 3711       /* Write 5 end tags */
 3712       err = _ksba_ber_write_tl (cms->writer, 0, 0, 0, 0);
 3713       if (!err)
 3714         err = _ksba_ber_write_tl (cms->writer, 0, 0, 0, 0);
 3715       if (!err)
 3716         err = _ksba_ber_write_tl (cms->writer, 0, 0, 0, 0);
 3717       if (!err)
 3718         err = _ksba_ber_write_tl (cms->writer, 0, 0, 0, 0);
 3719     }
 3720   else
 3721     err = gpg_error (GPG_ERR_INV_STATE);
 3722 
 3723   if (err)
 3724     return err;
 3725 
 3726   /* Calculate new stop reason */
 3727   if (state == sSTART)
 3728     { /* user should now write the encrypted data */
 3729       stop_reason = KSBA_SR_BEGIN_DATA;
 3730     }
 3731   else if (state == sINDATA)
 3732     { /* tell the user that we wrote everything */
 3733       stop_reason = KSBA_SR_END_DATA;
 3734     }
 3735   else if (state == sREST)
 3736     {
 3737       stop_reason = KSBA_SR_READY;
 3738     }
 3739 
 3740   cms->stop_reason = stop_reason;
 3741   return 0;
 3742 }
 3743 
 3744 
 3745 static gpg_error_t
 3746 ct_build_digested_data (ksba_cms_t cms)
 3747 {
 3748   (void)cms;
 3749   return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
 3750 }
 3751 
 3752 
 3753 static gpg_error_t
 3754 ct_build_encrypted_data (ksba_cms_t cms)
 3755 {
 3756   (void)cms;
 3757   return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
 3758 }