Imported Upstream version 2.3.0
[platform/upstream/gpg2.git] / sm / decrypt.c
1 /* decrypt.c - Decrypt a message
2  * Copyright (C) 2001, 2003, 2010 Free Software Foundation, Inc.
3  * Copyright (C) 2001-2019 Werner Koch
4  * Copyright (C) 2015-2020 g10 Code GmbH
5  *
6  * This file is part of GnuPG.
7  *
8  * GnuPG is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * GnuPG is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, see <https://www.gnu.org/licenses/>.
20  * SPDX-License-Identifier: GPL-3.0-or-later
21  */
22
23 #include <config.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <errno.h>
28 #include <unistd.h>
29 #include <time.h>
30
31 #include "gpgsm.h"
32 #include <gcrypt.h>
33 #include <ksba.h>
34
35 #include "keydb.h"
36 #include "../common/i18n.h"
37 #include "../common/tlv.h"
38 #include "../common/compliance.h"
39
40 struct decrypt_filter_parm_s
41 {
42   int algo;
43   int mode;
44   int blklen;
45   gcry_cipher_hd_t hd;
46   char iv[16];
47   size_t ivlen;
48   int any_data;  /* did we push anything through the filter at all? */
49   unsigned char lastblock[16];  /* to strip the padding we have to
50                                    keep this one */
51   char helpblock[16];  /* needed because there is no block buffering in
52                           libgcrypt (yet) */
53   int  helpblocklen;
54 };
55
56
57 /* Return the hash algorithm's algo id from its name given in the
58  * non-null termnated string in (buffer,buflen).  Returns 0 on failure
59  * or if the algo is not known.  */
60 static char *
61 string_from_gcry_buffer (gcry_buffer_t *buffer)
62 {
63   char *string;
64
65   string = xtrymalloc (buffer->len + 1);
66   if (!string)
67     return NULL;
68   memcpy (string, buffer->data, buffer->len);
69   string[buffer->len] = 0;
70   return string;
71 }
72
73
74 /* Helper to construct and hash the
75  *  ECC-CMS-SharedInfo ::= SEQUENCE {
76  *      keyInfo         AlgorithmIdentifier,
77  *      entityUInfo [0] EXPLICIT OCTET STRING OPTIONAL,
78  *      suppPubInfo [2] EXPLICIT OCTET STRING  }
79  * as described in RFC-5753, 7.2.  */
80 static gpg_error_t
81 hash_ecc_cms_shared_info (gcry_md_hd_t hash_hd, const char *wrap_algo_str,
82                           unsigned int keylen,
83                           const void *ukm, unsigned int ukmlen)
84 {
85   gpg_error_t err;
86   void *p;
87   unsigned char *oid;
88   size_t n, oidlen, toidlen, tkeyinfo, tukmlen, tsupppubinfo;
89   unsigned char keylenbuf[6];
90   membuf_t mb = MEMBUF_ZERO;
91
92   err = ksba_oid_from_str (wrap_algo_str, &oid, &oidlen);
93   if (err)
94     return err;
95   toidlen = get_tlv_length (CLASS_UNIVERSAL, TAG_OBJECT_ID, 0, oidlen);
96   tkeyinfo = get_tlv_length (CLASS_UNIVERSAL, TAG_SEQUENCE, 1, toidlen);
97
98   tukmlen = ukm? get_tlv_length (CLASS_CONTEXT, 0, 1, ukmlen) : 0;
99
100   keylen *= 8;
101   keylenbuf[0] = TAG_OCTET_STRING;
102   keylenbuf[1] = 4;
103   keylenbuf[2] = (keylen >> 24);
104   keylenbuf[3] = (keylen >> 16);
105   keylenbuf[4] = (keylen >> 8);
106   keylenbuf[5] = keylen;
107
108   tsupppubinfo = get_tlv_length (CLASS_CONTEXT, 2, 1, sizeof keylenbuf);
109
110   put_tlv_to_membuf (&mb, CLASS_UNIVERSAL, TAG_SEQUENCE, 1,
111                      tkeyinfo + tukmlen + tsupppubinfo);
112   put_tlv_to_membuf (&mb, CLASS_UNIVERSAL, TAG_SEQUENCE, 1,
113                      toidlen);
114   put_tlv_to_membuf (&mb, CLASS_UNIVERSAL, TAG_OBJECT_ID, 0, oidlen);
115   put_membuf (&mb, oid, oidlen);
116   ksba_free (oid);
117
118   if (ukm)
119     {
120       put_tlv_to_membuf (&mb, CLASS_CONTEXT, 0, 1, ukmlen);
121       put_membuf (&mb, ukm, ukmlen);
122     }
123
124   put_tlv_to_membuf (&mb, CLASS_CONTEXT, 2, 1, sizeof keylenbuf);
125   put_membuf (&mb, keylenbuf, sizeof keylenbuf);
126
127   p = get_membuf (&mb, &n);
128   if (!p)
129     return gpg_error_from_syserror ();
130
131   gcry_md_write (hash_hd, p, n);
132   xfree (p);
133   return 0;
134 }
135
136
137
138 /* Derive a KEK (key wrapping key) using (SECRET,SECRETLEN), an
139  * optional (UKM,ULMLEN), the wrap algorithm WRAP_ALGO_STR in decimal
140  * dotted form, and the hash algorithm HASH_ALGO.  On success a key of
141  * length KEYLEN is stored at KEY.  */
142 gpg_error_t
143 ecdh_derive_kek (unsigned char *key, unsigned int keylen,
144                  int hash_algo, const char *wrap_algo_str,
145                  const void *secret, unsigned int secretlen,
146                  const void *ukm, unsigned int ukmlen)
147 {
148   gpg_error_t err = 0;
149   unsigned int hashlen;
150   gcry_md_hd_t hash_hd;
151   unsigned char counter;
152   unsigned int n, ncopy;
153
154   hashlen = gcry_md_get_algo_dlen (hash_algo);
155   if (!hashlen)
156     return gpg_error (GPG_ERR_INV_ARG);
157
158   err = gcry_md_open (&hash_hd, hash_algo, 0);
159   if (err)
160     return err;
161
162   /* According to SEC1 3.6.1 we should check that
163    *   SECRETLEN + UKMLEN + 4 < maxhashlen
164    * However, we have no practical limit on the hash length and thus
165    * there is no point in checking this.  The second check that
166    *   KEYLEN < hashlen*(2^32-1)
167    * is obviously also not needed.
168    */
169   for (n=0, counter=1; n < keylen; counter++)
170     {
171       if (counter > 1)
172         gcry_md_reset (hash_hd);
173       gcry_md_write (hash_hd, secret, secretlen);
174       gcry_md_write (hash_hd, "\x00\x00\x00", 3);  /* MSBs of counter */
175       gcry_md_write (hash_hd, &counter, 1);
176       err = hash_ecc_cms_shared_info (hash_hd, wrap_algo_str, keylen,
177                                       ukm, ukmlen);
178       if (err)
179         break;
180       gcry_md_final (hash_hd);
181       if (n + hashlen > keylen)
182         ncopy = keylen - n;
183       else
184         ncopy = hashlen;
185       memcpy (key+n, gcry_md_read (hash_hd, 0), ncopy);
186       n += ncopy;
187     }
188
189   gcry_md_close (hash_hd);
190   return err;
191 }
192
193
194 /* This function will modify SECRET.  NBITS is the size of the curve
195  * which which we took from the certificate.  */
196 static gpg_error_t
197 ecdh_decrypt (unsigned char *secret, size_t secretlen,
198               unsigned int nbits, gcry_sexp_t enc_val,
199               unsigned char **r_result, unsigned int *r_resultlen)
200 {
201   gpg_error_t err;
202   gcry_buffer_t ioarray[4] = { {0}, {0}, {0}, {0} };
203   char *encr_algo_str = NULL;
204   char *wrap_algo_str = NULL;
205   int hash_algo, cipher_algo;
206   const unsigned char *ukm;  /* Alias for ioarray[2].  */
207   unsigned int ukmlen;
208   const unsigned char *data;  /* Alias for ioarray[3].  */
209   unsigned int datalen;
210   unsigned int keylen;
211   unsigned char key[32];
212   gcry_cipher_hd_t cipher_hd = NULL;
213   unsigned char *result = NULL;
214   unsigned int resultlen;
215
216   *r_resultlen = 0;
217   *r_result = NULL;
218
219   /* Extract X from SECRET; this is the actual secret.  Unless a
220    * smartcard diretcly returns X, it must be in the format of:
221    *
222    *   04 || X || Y
223    *   40 || X
224    *   41 || X
225    */
226   if (secretlen < 2)
227     return gpg_error (GPG_ERR_BAD_DATA);
228   if (secretlen == (nbits+7)/8)
229     ; /* Matches curve length - this is already the X coordinate.  */
230   else if (*secret == 0x04)
231     {
232       secretlen--;
233       memmove (secret, secret+1, secretlen);
234       if ((secretlen & 1))
235         return gpg_error (GPG_ERR_BAD_DATA);
236       secretlen /= 2;
237     }
238   else if (*secret == 0x40 || *secret == 0x41)
239     {
240       secretlen--;
241       memmove (secret, secret+1, secretlen);
242     }
243   else
244     return gpg_error (GPG_ERR_BAD_DATA);
245   if (!secretlen)
246     return gpg_error (GPG_ERR_BAD_DATA);
247
248   if (DBG_CRYPTO)
249     log_printhex (secret, secretlen, "ECDH X ..:");
250
251   /* We have now the shared secret bytes in (SECRET,SECRETLEN).  Now
252    * we will compute the KEK using a value dervied from the secret
253    * bytes. */
254   err = gcry_sexp_extract_param (enc_val, "enc-val",
255                                  "&'encr-algo''wrap-algo''ukm'?s",
256                                  ioarray+0, ioarray+1,
257                                  ioarray+2, ioarray+3, NULL);
258   if (err)
259     {
260       log_error ("extracting ECDH parameter failed: %s\n", gpg_strerror (err));
261       goto leave;
262     }
263   encr_algo_str = string_from_gcry_buffer (ioarray);
264   if (!encr_algo_str)
265     {
266       err = gpg_error_from_syserror ();
267       goto leave;
268     }
269   wrap_algo_str = string_from_gcry_buffer (ioarray+1);
270   if (!wrap_algo_str)
271     {
272       err = gpg_error_from_syserror ();
273       goto leave;
274     }
275   ukm = ioarray[2].data;
276   ukmlen = ioarray[2].len;
277   data = ioarray[3].data;
278   datalen = ioarray[3].len;
279
280   /* Check parameters.  */
281   if (DBG_CRYPTO)
282     {
283       log_debug ("encr_algo: %s\n", encr_algo_str);
284       log_debug ("wrap_algo: %s\n", wrap_algo_str);
285       log_printhex (ukm, ukmlen, "ukm .....:");
286       log_printhex (data, datalen, "data ....:");
287     }
288
289   if (!strcmp (encr_algo_str, "1.3.132.1.11.1"))
290     {
291       /* dhSinglePass-stdDH-sha256kdf-scheme */
292       hash_algo = GCRY_MD_SHA256;
293     }
294   else if (!strcmp (encr_algo_str, "1.3.132.1.11.2"))
295     {
296       /* dhSinglePass-stdDH-sha384kdf-scheme */
297       hash_algo = GCRY_MD_SHA384;
298     }
299   else if (!strcmp (encr_algo_str, "1.3.132.1.11.3"))
300     {
301       /* dhSinglePass-stdDH-sha512kdf-scheme */
302       hash_algo = GCRY_MD_SHA512;
303     }
304   else if (!strcmp (encr_algo_str, "1.3.133.16.840.63.0.2"))
305     {
306       /* dhSinglePass-stdDH-sha1kdf-scheme */
307       hash_algo = GCRY_MD_SHA1;
308     }
309   else
310     {
311       err = gpg_error (GPG_ERR_PUBKEY_ALGO);
312       goto leave;
313     }
314
315   if (!strcmp (wrap_algo_str, "2.16.840.1.101.3.4.1.5"))
316     {
317       cipher_algo = GCRY_CIPHER_AES128;
318       keylen = 16;
319     }
320   else if (!strcmp (wrap_algo_str, "2.16.840.1.101.3.4.1.25"))
321     {
322       cipher_algo = GCRY_CIPHER_AES192;
323       keylen = 24;
324     }
325   else if (!strcmp (wrap_algo_str, "2.16.840.1.101.3.4.1.45"))
326     {
327       cipher_algo = GCRY_CIPHER_AES256;
328       keylen = 32;
329     }
330   else
331     {
332       err = gpg_error (GPG_ERR_PUBKEY_ALGO);
333       goto leave;
334     }
335
336   err = ecdh_derive_kek (key, keylen, hash_algo, wrap_algo_str,
337                          secret, secretlen, ukm, ukmlen);
338   if (err)
339     goto leave;
340
341   if (DBG_CRYPTO)
342     log_printhex (key, keylen, "KEK .....:");
343
344   /* Unwrap the key.  */
345   if ((datalen % 8) || datalen < 16)
346     {
347       log_error ("can't use a shared secret of %u bytes for ecdh\n", datalen);
348       err = gpg_error (GPG_ERR_BAD_DATA);
349       goto leave;
350     }
351
352   resultlen = datalen - 8;
353   result = xtrymalloc_secure (resultlen);
354   if (!result)
355     {
356       err = gpg_error_from_syserror ();
357       goto leave;
358     }
359
360   err = gcry_cipher_open (&cipher_hd, cipher_algo, GCRY_CIPHER_MODE_AESWRAP, 0);
361   if (err)
362     {
363       log_error ("ecdh failed to initialize AESWRAP: %s\n", gpg_strerror (err));
364       goto leave;
365     }
366
367   err = gcry_cipher_setkey (cipher_hd, key, keylen);
368   wipememory (key, sizeof key);
369   if (err)
370     {
371       log_error ("ecdh failed in gcry_cipher_setkey: %s\n", gpg_strerror (err));
372       goto leave;
373     }
374
375   err = gcry_cipher_decrypt (cipher_hd, result, resultlen, data, datalen);
376   if (err)
377     {
378       log_error ("ecdh failed in gcry_cipher_decrypt: %s\n",gpg_strerror (err));
379       goto leave;
380     }
381
382   *r_resultlen = resultlen;
383   *r_result = result;
384   result = NULL;
385
386  leave:
387   if (result)
388     {
389       wipememory (result, resultlen);
390       xfree (result);
391     }
392   gcry_cipher_close (cipher_hd);
393   xfree (encr_algo_str);
394   xfree (wrap_algo_str);
395   xfree (ioarray[0].data);
396   xfree (ioarray[1].data);
397   xfree (ioarray[2].data);
398   xfree (ioarray[3].data);
399   return err;
400 }
401
402
403
404 /* Decrypt the session key and fill in the parm structure.  The
405    algo and the IV is expected to be already in PARM. */
406 static int
407 prepare_decryption (ctrl_t ctrl, const char *hexkeygrip,
408                     int pk_algo, unsigned int nbits, const char *desc,
409                     ksba_const_sexp_t enc_val,
410                     struct decrypt_filter_parm_s *parm)
411 {
412   char *seskey = NULL;
413   size_t n, seskeylen;
414   int rc;
415
416   if (DBG_CRYPTO)
417     log_printcanon ("decrypting:", enc_val, 0);
418   rc = gpgsm_agent_pkdecrypt (ctrl, hexkeygrip, desc, enc_val,
419                               &seskey, &seskeylen);
420   if (rc)
421     {
422       log_error ("error decrypting session key: %s\n", gpg_strerror (rc));
423       goto leave;
424     }
425
426   if (DBG_CRYPTO)
427     log_printhex (seskey, seskeylen, "DEK frame:");
428
429   n=0;
430   if (pk_algo == GCRY_PK_ECC)
431     {
432       gcry_sexp_t s_enc_val;
433       unsigned char *decrypted;
434       unsigned int decryptedlen;
435
436       rc = gcry_sexp_sscan (&s_enc_val, NULL, enc_val,
437                             gcry_sexp_canon_len (enc_val, 0, NULL, NULL));
438       if (rc)
439         goto leave;
440
441       rc = ecdh_decrypt (seskey, seskeylen, nbits, s_enc_val,
442                          &decrypted, &decryptedlen);
443       gcry_sexp_release (s_enc_val);
444       if (rc)
445         goto leave;
446       xfree (seskey);
447       seskey = decrypted;
448       seskeylen = decryptedlen;
449
450     }
451   else if (seskeylen == 32 || seskeylen == 24 || seskeylen == 16)
452     {
453       /* Smells like an AES-128, 3-DES, or AES-256 key.  This might
454        * happen because a SC has already done the unpacking.  A better
455        * solution would be to test for this only after we triggered
456        * the GPG_ERR_INV_SESSION_KEY. */
457     }
458   else
459     {
460       if (n + 7 > seskeylen )
461         {
462           rc = gpg_error (GPG_ERR_INV_SESSION_KEY);
463           goto leave;
464         }
465
466       /* FIXME: Actually the leading zero is required but due to the way
467          we encode the output in libgcrypt as an MPI we are not able to
468          encode that leading zero.  However, when using a Smartcard we are
469          doing it the right way and therefore we have to skip the zero.  This
470          should be fixed in gpg-agent of course. */
471       if (!seskey[n])
472         n++;
473
474       if (seskey[n] != 2 )  /* Wrong block type version. */
475         {
476           rc = gpg_error (GPG_ERR_INV_SESSION_KEY);
477           goto leave;
478         }
479
480       for (n++; n < seskeylen && seskey[n]; n++) /* Skip the random bytes. */
481         ;
482       n++; /* and the zero byte */
483       if (n >= seskeylen )
484         {
485           rc = gpg_error (GPG_ERR_INV_SESSION_KEY);
486           goto leave;
487         }
488     }
489
490   if (DBG_CRYPTO)
491     log_printhex (seskey+n, seskeylen-n, "CEK .....:");
492
493   if (opt.verbose)
494     log_info (_("%s.%s encrypted data\n"),
495               gcry_cipher_algo_name (parm->algo),
496               cipher_mode_to_string (parm->mode));
497
498   rc = gcry_cipher_open (&parm->hd, parm->algo, parm->mode, 0);
499   if (rc)
500     {
501       log_error ("error creating decryptor: %s\n", gpg_strerror (rc));
502       goto leave;
503     }
504
505   rc = gcry_cipher_setkey (parm->hd, seskey+n, seskeylen-n);
506   if (gpg_err_code (rc) == GPG_ERR_WEAK_KEY)
507     {
508       log_info (_("WARNING: message was encrypted with "
509                   "a weak key in the symmetric cipher.\n"));
510       rc = 0;
511     }
512   if (rc)
513     {
514       log_error("key setup failed: %s\n", gpg_strerror(rc) );
515       goto leave;
516     }
517
518   gcry_cipher_setiv (parm->hd, parm->iv, parm->ivlen);
519
520  leave:
521   xfree (seskey);
522   return rc;
523 }
524
525
526 /* This function is called by the KSBA writer just before the actual
527    write is done.  The function must take INLEN bytes from INBUF,
528    decrypt it and store it inoutbuf which has a maximum size of
529    maxoutlen.  The valid bytes in outbuf should be return in outlen.
530    Due to different buffer sizes or different length of input and
531    output, it may happen that fewer bytes are processed or fewer bytes
532    are written. */
533 static gpg_error_t
534 decrypt_filter (void *arg,
535                 const void *inbuf, size_t inlen, size_t *inused,
536                 void *outbuf, size_t maxoutlen, size_t *outlen)
537 {
538   struct decrypt_filter_parm_s *parm = arg;
539   int blklen = parm->blklen;
540   size_t orig_inlen = inlen;
541
542   /* fixme: Should we issue an error when we have not seen one full block? */
543   if (!inlen)
544     return gpg_error (GPG_ERR_BUG);
545
546   if (maxoutlen < 2*parm->blklen)
547     return gpg_error (GPG_ERR_BUG);
548   /* Make some space because we will later need an extra block at the end.  */
549   maxoutlen -= blklen;
550
551   if (parm->helpblocklen)
552     {
553       int i, j;
554
555       for (i=parm->helpblocklen,j=0; i < blklen && j < inlen; i++, j++)
556         parm->helpblock[i] = ((const char*)inbuf)[j];
557       inlen -= j;
558       if (blklen > maxoutlen)
559         return gpg_error (GPG_ERR_BUG);
560       if (i < blklen)
561         {
562           parm->helpblocklen = i;
563           *outlen = 0;
564         }
565       else
566         {
567           parm->helpblocklen = 0;
568           if (parm->any_data)
569             {
570               memcpy (outbuf, parm->lastblock, blklen);
571               *outlen =blklen;
572             }
573           else
574             *outlen = 0;
575           gcry_cipher_decrypt (parm->hd, parm->lastblock, blklen,
576                                parm->helpblock, blklen);
577           parm->any_data = 1;
578         }
579       *inused = orig_inlen - inlen;
580       return 0;
581     }
582
583
584   if (inlen > maxoutlen)
585     inlen = maxoutlen;
586   if (inlen % blklen)
587     { /* store the remainder away */
588       parm->helpblocklen = inlen%blklen;
589       inlen = inlen/blklen*blklen;
590       memcpy (parm->helpblock, (const char*)inbuf+inlen, parm->helpblocklen);
591     }
592
593   *inused = inlen + parm->helpblocklen;
594   if (inlen)
595     {
596       log_assert (inlen >= blklen);
597       if (parm->any_data)
598         {
599           gcry_cipher_decrypt (parm->hd, (char*)outbuf+blklen, inlen,
600                                inbuf, inlen);
601           memcpy (outbuf, parm->lastblock, blklen);
602           memcpy (parm->lastblock,(char*)outbuf+inlen, blklen);
603           *outlen = inlen;
604         }
605       else
606         {
607           gcry_cipher_decrypt (parm->hd, outbuf, inlen, inbuf, inlen);
608           memcpy (parm->lastblock, (char*)outbuf+inlen-blklen, blklen);
609           *outlen = inlen - blklen;
610           parm->any_data = 1;
611         }
612     }
613   else
614     *outlen = 0;
615   return 0;
616 }
617
618
619 \f
620 /* Perform a decrypt operation.  */
621 int
622 gpgsm_decrypt (ctrl_t ctrl, int in_fd, estream_t out_fp)
623 {
624   int rc;
625   gnupg_ksba_io_t b64reader = NULL;
626   gnupg_ksba_io_t b64writer = NULL;
627   ksba_reader_t reader;
628   ksba_writer_t writer;
629   ksba_cms_t cms = NULL;
630   ksba_stop_reason_t stopreason;
631   KEYDB_HANDLE kh;
632   int recp;
633   estream_t in_fp = NULL;
634   struct decrypt_filter_parm_s dfparm;
635
636   memset (&dfparm, 0, sizeof dfparm);
637
638   audit_set_type (ctrl->audit, AUDIT_TYPE_DECRYPT);
639
640   kh = keydb_new (ctrl);
641   if (!kh)
642     {
643       log_error (_("failed to allocate keyDB handle\n"));
644       rc = gpg_error (GPG_ERR_GENERAL);
645       goto leave;
646     }
647
648   in_fp = es_fdopen_nc (in_fd, "rb");
649   if (!in_fp)
650     {
651       rc = gpg_error_from_syserror ();
652       log_error ("fdopen() failed: %s\n", strerror (errno));
653       goto leave;
654     }
655
656   rc = gnupg_ksba_create_reader
657     (&b64reader, ((ctrl->is_pem? GNUPG_KSBA_IO_PEM : 0)
658                   | (ctrl->is_base64? GNUPG_KSBA_IO_BASE64 : 0)
659                   | (ctrl->autodetect_encoding? GNUPG_KSBA_IO_AUTODETECT : 0)),
660      in_fp, &reader);
661   if (rc)
662     {
663       log_error ("can't create reader: %s\n", gpg_strerror (rc));
664       goto leave;
665     }
666
667   rc = gnupg_ksba_create_writer
668     (&b64writer, ((ctrl->create_pem? GNUPG_KSBA_IO_PEM : 0)
669                   | (ctrl->create_base64? GNUPG_KSBA_IO_BASE64 : 0)),
670      ctrl->pem_name, out_fp, &writer);
671   if (rc)
672     {
673       log_error ("can't create writer: %s\n", gpg_strerror (rc));
674       goto leave;
675     }
676
677   rc = ksba_cms_new (&cms);
678   if (rc)
679     goto leave;
680
681   rc = ksba_cms_set_reader_writer (cms, reader, writer);
682   if (rc)
683     {
684       log_error ("ksba_cms_set_reader_writer failed: %s\n",
685                  gpg_strerror (rc));
686       goto leave;
687     }
688
689   audit_log (ctrl->audit, AUDIT_SETUP_READY);
690
691   /* Parser loop. */
692   do
693     {
694       rc = ksba_cms_parse (cms, &stopreason);
695       if (rc)
696         {
697           log_error ("ksba_cms_parse failed: %s\n", gpg_strerror (rc));
698           goto leave;
699         }
700
701       if (stopreason == KSBA_SR_BEGIN_DATA
702           || stopreason == KSBA_SR_DETACHED_DATA)
703         {
704           int algo, mode;
705           const char *algoid;
706           int any_key = 0;
707           int is_de_vs; /* Computed compliance with CO_DE_VS.  */
708
709           audit_log (ctrl->audit, AUDIT_GOT_DATA);
710
711           algoid = ksba_cms_get_content_oid (cms, 2/* encryption algo*/);
712           algo = gcry_cipher_map_name (algoid);
713           mode = gcry_cipher_mode_from_oid (algoid);
714           if (!algo || !mode)
715             {
716               rc = gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
717               log_error ("unsupported algorithm '%s'\n", algoid? algoid:"?");
718               if (algoid && !strcmp (algoid, "1.2.840.113549.3.2"))
719                 log_info (_("(this is the RC2 algorithm)\n"));
720               else if (!algoid)
721                 log_info (_("(this does not seem to be an encrypted"
722                             " message)\n"));
723               {
724                 char numbuf[50];
725                 sprintf (numbuf, "%d", rc);
726                 gpgsm_status2 (ctrl, STATUS_ERROR, "decrypt.algorithm",
727                                numbuf, algoid?algoid:"?", NULL);
728                 audit_log_s (ctrl->audit, AUDIT_BAD_DATA_CIPHER_ALGO, algoid);
729               }
730
731               /* If it seems that this is not an encrypted message we
732                  return a more sensible error code. */
733               if (!algoid)
734                 rc = gpg_error (GPG_ERR_NO_DATA);
735
736               goto leave;
737             }
738
739           /* Check compliance.  */
740           if (! gnupg_cipher_is_allowed (opt.compliance, 0, algo, mode))
741             {
742               log_error (_("cipher algorithm '%s'"
743                            " may not be used in %s mode\n"),
744                          gcry_cipher_algo_name (algo),
745                          gnupg_compliance_option_string (opt.compliance));
746               rc = gpg_error (GPG_ERR_CIPHER_ALGO);
747               goto leave;
748             }
749
750           /* For CMS, CO_DE_VS demands CBC mode.  */
751           is_de_vs = gnupg_cipher_is_compliant (CO_DE_VS, algo, mode);
752
753           audit_log_i (ctrl->audit, AUDIT_DATA_CIPHER_ALGO, algo);
754           dfparm.algo = algo;
755           dfparm.mode = mode;
756           dfparm.blklen = gcry_cipher_get_algo_blklen (algo);
757           if (dfparm.blklen > sizeof (dfparm.helpblock))
758             return gpg_error (GPG_ERR_BUG);
759
760           rc = ksba_cms_get_content_enc_iv (cms,
761                                             dfparm.iv,
762                                             sizeof (dfparm.iv),
763                                             &dfparm.ivlen);
764           if (rc)
765             {
766               log_error ("error getting IV: %s\n", gpg_strerror (rc));
767               goto leave;
768             }
769
770           for (recp=0; !any_key; recp++)
771             {
772               char *issuer;
773               ksba_sexp_t serial;
774               ksba_sexp_t enc_val;
775               char *hexkeygrip = NULL;
776               char *pkalgostr = NULL;
777               char *pkfpr = NULL;
778               char *desc = NULL;
779               char kidbuf[16+1];
780               int tmp_rc;
781               ksba_cert_t cert = NULL;
782               unsigned int nbits;
783               int pk_algo = 0;
784
785               *kidbuf = 0;
786
787               tmp_rc = ksba_cms_get_issuer_serial (cms, recp, &issuer, &serial);
788               if (tmp_rc == -1 && recp)
789                 break; /* no more recipients */
790               audit_log_i (ctrl->audit, AUDIT_NEW_RECP, recp);
791               if (tmp_rc)
792                 log_error ("recp %d - error getting info: %s\n",
793                            recp, gpg_strerror (tmp_rc));
794               else
795                 {
796                   if (opt.verbose)
797                     {
798                       log_info ("recp %d - issuer: '%s'\n",
799                                  recp, issuer? issuer:"[NONE]");
800                       log_info ("recp %d - serial: ", recp);
801                       gpgsm_dump_serial (serial);
802                       log_printf ("\n");
803                     }
804
805                   if (ctrl->audit)
806                     {
807                       char *tmpstr = gpgsm_format_sn_issuer (serial, issuer);
808                       audit_log_s (ctrl->audit, AUDIT_RECP_NAME, tmpstr);
809                       xfree (tmpstr);
810                     }
811
812                   keydb_search_reset (kh);
813                   rc = keydb_search_issuer_sn (ctrl, kh, issuer, serial);
814                   if (rc)
815                     {
816                       log_error ("failed to find the certificate: %s\n",
817                                  gpg_strerror(rc));
818                       goto oops;
819                     }
820
821                   rc = keydb_get_cert (kh, &cert);
822                   if (rc)
823                     {
824                       log_error ("failed to get cert: %s\n", gpg_strerror (rc));
825                       goto oops;
826                     }
827
828                   /* Print the ENC_TO status line.  Note that we can
829                      do so only if we have the certificate.  This is
830                      in contrast to gpg where the keyID is commonly
831                      included in the encrypted messages. It is too
832                      cumbersome to retrieve the used algorithm, thus
833                      we don't print it for now.  We also record the
834                      keyid for later use.  */
835                   {
836                     unsigned long kid[2];
837
838                     kid[0] = gpgsm_get_short_fingerprint (cert, kid+1);
839                     snprintf (kidbuf, sizeof kidbuf, "%08lX%08lX",
840                               kid[1], kid[0]);
841                     gpgsm_status2 (ctrl, STATUS_ENC_TO,
842                                    kidbuf, "0", "0", NULL);
843                   }
844
845                   /* Put the certificate into the audit log.  */
846                   audit_log_cert (ctrl->audit, AUDIT_SAVE_CERT, cert, 0);
847
848                   /* Just in case there is a problem with the own
849                      certificate we print this message - should never
850                      happen of course */
851                   rc = gpgsm_cert_use_decrypt_p (cert);
852                   if (rc)
853                     {
854                       char numbuf[50];
855                       sprintf (numbuf, "%d", rc);
856                       gpgsm_status2 (ctrl, STATUS_ERROR, "decrypt.keyusage",
857                                      numbuf, NULL);
858                       rc = 0;
859                     }
860
861                   hexkeygrip = gpgsm_get_keygrip_hexstring (cert);
862                   desc = gpgsm_format_keydesc (cert);
863
864                   pkfpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1);
865                   pkalgostr = gpgsm_pubkey_algo_string (cert, NULL);
866                   pk_algo = gpgsm_get_key_algo_info (cert, &nbits);
867                   if (!opt.quiet)
868                     log_info (_("encrypted to %s key %s\n"), pkalgostr, pkfpr);
869
870                   /* Check compliance.  */
871                   if (!gnupg_pk_is_allowed (opt.compliance,
872                                             PK_USE_DECRYPTION,
873                                             pk_algo, 0, NULL, nbits, NULL))
874                     {
875                       char  kidstr[10+1];
876
877                       snprintf (kidstr, sizeof kidstr, "0x%08lX",
878                                 gpgsm_get_short_fingerprint (cert, NULL));
879                       log_info (_("key %s is not suitable for decryption"
880                                   " in %s mode\n"),
881                                 kidstr,
882                                 gnupg_compliance_option_string(opt.compliance));
883                       rc = gpg_error (GPG_ERR_PUBKEY_ALGO);
884                       goto oops;
885                     }
886
887                   /* Check that all certs are compliant with CO_DE_VS.  */
888                   is_de_vs = (is_de_vs
889                               && gnupg_pk_is_compliant (CO_DE_VS, pk_algo, 0,
890                                                         NULL, nbits, NULL));
891
892                 oops:
893                   if (rc)
894                     {
895                       /* We cannot check compliance of certs that we
896                        * don't have.  */
897                       is_de_vs = 0;
898                     }
899                   xfree (issuer);
900                   xfree (serial);
901                   ksba_cert_release (cert);
902                 }
903
904               if (!hexkeygrip || !pk_algo)
905                 ;
906               else if (!(enc_val = ksba_cms_get_enc_val (cms, recp)))
907                 log_error ("recp %d - error getting encrypted session key\n",
908                            recp);
909               else
910                 {
911                   rc = prepare_decryption (ctrl, hexkeygrip, pk_algo, nbits,
912                                            desc, enc_val, &dfparm);
913                   xfree (enc_val);
914                   if (rc)
915                     {
916                       log_info ("decrypting session key failed: %s\n",
917                                 gpg_strerror (rc));
918                       if (gpg_err_code (rc) == GPG_ERR_NO_SECKEY && *kidbuf)
919                         gpgsm_status2 (ctrl, STATUS_NO_SECKEY, kidbuf, NULL);
920                     }
921                   else
922                     { /* setup the bulk decrypter */
923                       any_key = 1;
924                       ksba_writer_set_filter (writer,
925                                               decrypt_filter,
926                                               &dfparm);
927
928                       if (is_de_vs && gnupg_gcrypt_is_compliant (CO_DE_VS))
929                         gpgsm_status (ctrl, STATUS_DECRYPTION_COMPLIANCE_MODE,
930                                       gnupg_status_compliance_flag (CO_DE_VS));
931
932                     }
933                   audit_log_ok (ctrl->audit, AUDIT_RECP_RESULT, rc);
934                 }
935               xfree (pkalgostr);
936               xfree (pkfpr);
937               xfree (hexkeygrip);
938               xfree (desc);
939             }
940
941           /* If we write an audit log add the unused recipients to the
942              log as well.  */
943           if (ctrl->audit && any_key)
944             {
945               for (;; recp++)
946                 {
947                   char *issuer;
948                   ksba_sexp_t serial;
949                   int tmp_rc;
950
951                   tmp_rc = ksba_cms_get_issuer_serial (cms, recp,
952                                                        &issuer, &serial);
953                   if (tmp_rc == -1)
954                     break; /* no more recipients */
955                   audit_log_i (ctrl->audit, AUDIT_NEW_RECP, recp);
956                   if (tmp_rc)
957                     log_error ("recp %d - error getting info: %s\n",
958                                recp, gpg_strerror (tmp_rc));
959                   else
960                     {
961                       char *tmpstr = gpgsm_format_sn_issuer (serial, issuer);
962                       audit_log_s (ctrl->audit, AUDIT_RECP_NAME, tmpstr);
963                       xfree (tmpstr);
964                       xfree (issuer);
965                       xfree (serial);
966                     }
967                 }
968             }
969
970           if (!any_key)
971             {
972               if (!rc)
973                 rc = gpg_error (GPG_ERR_NO_SECKEY);
974               goto leave;
975             }
976         }
977       else if (stopreason == KSBA_SR_END_DATA)
978         {
979           ksba_writer_set_filter (writer, NULL, NULL);
980           if (dfparm.any_data)
981             { /* write the last block with padding removed */
982               int i, npadding = dfparm.lastblock[dfparm.blklen-1];
983               if (!npadding || npadding > dfparm.blklen)
984                 {
985                   log_error ("invalid padding with value %d\n", npadding);
986                   rc = gpg_error (GPG_ERR_INV_DATA);
987                   goto leave;
988                 }
989               rc = ksba_writer_write (writer,
990                                       dfparm.lastblock,
991                                       dfparm.blklen - npadding);
992               if (rc)
993                 goto leave;
994
995               for (i=dfparm.blklen - npadding; i < dfparm.blklen; i++)
996                 {
997                   if (dfparm.lastblock[i] != npadding)
998                     {
999                       log_error ("inconsistent padding\n");
1000                       rc = gpg_error (GPG_ERR_INV_DATA);
1001                       goto leave;
1002                     }
1003                 }
1004             }
1005         }
1006
1007     }
1008   while (stopreason != KSBA_SR_READY);
1009
1010   rc = gnupg_ksba_finish_writer (b64writer);
1011   if (rc)
1012     {
1013       log_error ("write failed: %s\n", gpg_strerror (rc));
1014       goto leave;
1015     }
1016   gpgsm_status (ctrl, STATUS_DECRYPTION_OKAY, NULL);
1017
1018
1019  leave:
1020   audit_log_ok (ctrl->audit, AUDIT_DECRYPTION_RESULT, rc);
1021   if (rc)
1022     {
1023       gpgsm_status (ctrl, STATUS_DECRYPTION_FAILED, NULL);
1024       log_error ("message decryption failed: %s <%s>\n",
1025                  gpg_strerror (rc), gpg_strsource (rc));
1026     }
1027   ksba_cms_release (cms);
1028   gnupg_ksba_destroy_reader (b64reader);
1029   gnupg_ksba_destroy_writer (b64writer);
1030   keydb_release (kh);
1031   es_fclose (in_fp);
1032   if (dfparm.hd)
1033     gcry_cipher_close (dfparm.hd);
1034   return rc;
1035 }