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-2021 g10 Code GmbH
6 * This file is part of GnuPG.
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.
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.
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
37 #include "../common/i18n.h"
38 #include "../common/compliance.h"
39 #include "../common/tlv.h"
41 /* We can provide an enum value which is only availabale with KSBA
42 * 1.6.0 so that we can compile even against older versions. Some
43 * calls will of course return an error in this case. This value is
44 * currently not used because the cipher mode is sufficient here. */
45 /* #if KSBA_VERSION_NUMBER < 0x010600 /\* 1.6.0 *\/ */
46 /* # define KSBA_CT_AUTHENVELOPED_DATA 10 */
50 struct decrypt_filter_parm_s
58 int any_data; /* did we push anything through the filter at all? */
59 unsigned char lastblock[16]; /* to strip the padding we have to
61 char helpblock[16]; /* needed because there is no block buffering in
64 int is_de_vs; /* Helper to track CO_DE_VS state. */
68 /* Return the hash algorithm's algo id from its name given in the
69 * non-null termnated string in (buffer,buflen). Returns 0 on failure
70 * or if the algo is not known. */
72 string_from_gcry_buffer (gcry_buffer_t *buffer)
76 string = xtrymalloc (buffer->len + 1);
79 memcpy (string, buffer->data, buffer->len);
80 string[buffer->len] = 0;
85 /* Helper for pwri_decrypt to parse the derive info.
86 * Example data for (DER,DERLEN):
89 * 60 76 4B E9 5E DF 3C F8 B2 F9 B6 C2 7D 5A FB 90
94 * hmacWithSHA512 (1 2 840 113549 2 11)
100 pwri_parse_pbkdf2 (const unsigned char *der, size_t derlen,
101 unsigned char const **r_salt, unsigned int *r_saltlen,
102 unsigned long *r_iterations,
103 enum gcry_md_algos *r_digest)
106 size_t objlen, hdrlen;
107 int class, tag, constructed, ndef;
110 err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
111 &ndef, &objlen, &hdrlen);
112 if (!err && (objlen > derlen || tag != TAG_SEQUENCE
113 || !constructed || ndef))
114 err = gpg_error (GPG_ERR_INV_OBJ);
119 err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
120 &ndef, &objlen, &hdrlen);
121 if (!err && (objlen > derlen || tag != TAG_OCTET_STRING
122 || constructed || ndef))
123 err = gpg_error (GPG_ERR_INV_OBJ);
131 err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
132 &ndef, &objlen, &hdrlen);
133 if (!err && (objlen > derlen || tag != TAG_INTEGER
134 || constructed || ndef))
135 err = gpg_error (GPG_ERR_INV_OBJ);
139 for (; objlen; objlen--)
142 *r_iterations |= (*der++) & 0xff;
146 err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
147 &ndef, &objlen, &hdrlen);
148 if (!err && (objlen > derlen || tag != TAG_SEQUENCE
149 || !constructed || ndef))
150 err = gpg_error (GPG_ERR_INV_OBJ);
155 err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
156 &ndef, &objlen, &hdrlen);
157 if (!err && (objlen > derlen || tag != TAG_OBJECT_ID
158 || constructed || ndef))
159 err = gpg_error (GPG_ERR_INV_OBJ);
163 oidstr = ksba_oid_to_str (der, objlen);
165 return gpg_error_from_syserror ();
166 *r_digest = gcry_md_map_name (oidstr);
169 else if (!strcmp (oidstr, "1.2.840.113549.2.7"))
170 *r_digest = GCRY_MD_SHA1;
171 else if (!strcmp (oidstr, "1.2.840.113549.2.8"))
172 *r_digest = GCRY_MD_SHA224;
173 else if (!strcmp (oidstr, "1.2.840.113549.2.9"))
174 *r_digest = GCRY_MD_SHA256;
175 else if (!strcmp (oidstr, "1.2.840.113549.2.10"))
176 *r_digest = GCRY_MD_SHA384;
177 else if (!strcmp (oidstr, "1.2.840.113549.2.11"))
178 *r_digest = GCRY_MD_SHA512;
180 err = gpg_error (GPG_ERR_DIGEST_ALGO);
187 /* Password based decryption.
188 * ENC_VAL has the form:
191 * (derive-algo <oid>) --| both are optional
192 * (derive-parm <der>) --|
195 * (encr-key <key>))) -- this is the encrypted session key
199 pwri_decrypt (ctrl_t ctrl, gcry_sexp_t enc_val,
200 unsigned char **r_result, unsigned int *r_resultlen,
201 struct decrypt_filter_parm_s *parm)
204 gcry_buffer_t ioarray[5] = { {0} };
205 char *derive_algo_str = NULL;
206 char *encr_algo_str = NULL;
207 const unsigned char *dparm; /* Alias for ioarray[1]. */
208 unsigned int dparmlen;
209 const unsigned char *eparm; /* Alias for ioarray[3]. */
210 unsigned int eparmlen;
211 const unsigned char *ekey; /* Alias for ioarray[4]. */
212 unsigned int ekeylen;
213 unsigned char kek[32];
215 enum gcry_cipher_algos encr_algo;
216 enum gcry_cipher_modes encr_mode;
217 gcry_cipher_hd_t encr_hd = NULL;
218 unsigned char *result = NULL;
219 unsigned int resultlen;
221 const unsigned char *salt; /* Points int dparm. */
222 unsigned int saltlen;
223 unsigned long iterations;
224 enum gcry_md_algos digest_algo;
225 char *passphrase = NULL;
231 err = gcry_sexp_extract_param (enc_val, "enc-val!pwri",
232 "&'derive-algo'?'derive-parm'?"
233 "'encr-algo''encr-parm''encr-key'",
234 ioarray+0, ioarray+1,
235 ioarray+2, ioarray+3, ioarray+4, NULL);
238 /* If this is not pwri element, it is likly a kekri element
239 * which we do not yet support. Change the error back to the
240 * original as returned by ksba_cms_get_issuer. */
241 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
242 err = gpg_error (GPG_ERR_UNSUPPORTED_CMS_OBJ);
244 log_error ("extracting PWRI parameter failed: %s\n",
251 derive_algo_str = string_from_gcry_buffer (ioarray+0);
252 if (!derive_algo_str)
254 err = gpg_error_from_syserror ();
258 dparm = ioarray[1].data;
259 dparmlen = ioarray[1].len;
260 encr_algo_str = string_from_gcry_buffer (ioarray+2);
263 err = gpg_error_from_syserror ();
266 eparm = ioarray[3].data;
267 eparmlen = ioarray[3].len;
268 ekey = ioarray[4].data;
269 ekeylen = ioarray[4].len;
271 /* Check parameters. */
276 log_debug ("derive algo: %s\n", derive_algo_str);
277 log_printhex (dparm, dparmlen, "derive parm:");
279 log_debug ("encr algo .: %s\n", encr_algo_str);
280 log_printhex (eparm, eparmlen, "encr parm .:");
281 log_printhex (ekey, ekeylen, "encr key .:");
284 if (!derive_algo_str)
286 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
287 log_info ("PWRI with no key derivation detected\n");
290 if (strcmp (derive_algo_str, "1.2.840.113549.1.5.12"))
292 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
293 log_info ("PWRI does not use PBKDF2 (but %s)\n", derive_algo_str);
297 digest_algo = 0; /*(silence cc warning)*/
298 err = pwri_parse_pbkdf2 (dparm, dparmlen,
299 &salt, &saltlen, &iterations, &digest_algo);
302 log_error ("parsing PWRI parameter failed: %s\n", gpg_strerror (err));
306 parm->is_de_vs = (parm->is_de_vs
307 && gnupg_digest_is_compliant (CO_DE_VS, digest_algo));
310 encr_algo = gcry_cipher_map_name (encr_algo_str);
311 encr_mode = gcry_cipher_mode_from_oid (encr_algo_str);
312 if (!encr_algo || !encr_mode)
314 log_error ("PWRI uses unknown algorithm %s\n", encr_algo_str);
315 err = gpg_error (GPG_ERR_CIPHER_ALGO);
321 && gnupg_cipher_is_compliant (CO_DE_VS, encr_algo, encr_mode));
323 keklen = gcry_cipher_get_algo_keylen (encr_algo);
324 blklen = gcry_cipher_get_algo_blklen (encr_algo);
325 if (!keklen || keklen > sizeof kek || blklen != 16 )
327 log_error ("PWRI algorithm %s cannot be used\n", encr_algo_str);
328 err = gpg_error (GPG_ERR_INV_KEYLEN);
331 if ((ekeylen % blklen) || (ekeylen / blklen < 2))
333 /* Note that we need at least two full blocks. */
334 log_error ("PWRI uses a wrong length of encrypted key\n");
335 err = gpg_error (GPG_ERR_INV_KEYLEN);
339 err = gpgsm_agent_ask_passphrase
341 i18n_utf8 (N_("Please enter the passphrase for decryption.")),
346 err = gcry_kdf_derive (passphrase, strlen (passphrase),
347 GCRY_KDF_PBKDF2, digest_algo,
348 salt, saltlen, iterations,
352 wipememory (passphrase, strlen (passphrase));
358 log_error ("deriving key from passphrase failed: %s\n",
364 log_printhex (kek, keklen, "KEK .......:");
366 /* Unwrap the key. */
368 result = xtrymalloc_secure (resultlen);
371 err = gpg_error_from_syserror ();
375 err = gcry_cipher_open (&encr_hd, encr_algo, encr_mode, 0);
378 log_error ("PWRI failed to open cipher: %s\n", gpg_strerror (err));
382 err = gcry_cipher_setkey (encr_hd, kek, keklen);
383 wipememory (kek, sizeof kek);
385 err = gcry_cipher_setiv (encr_hd, ekey + ekeylen - 2 * blklen, blklen);
387 err = gcry_cipher_decrypt (encr_hd, result + ekeylen - blklen, blklen,
388 ekey + ekeylen - blklen, blklen);
390 err = gcry_cipher_setiv (encr_hd, result + ekeylen - blklen, blklen);
392 err = gcry_cipher_decrypt (encr_hd, result, ekeylen - blklen,
393 ekey, ekeylen - blklen);
394 /* (We assume that that eparm is the octet string with the IV) */
396 err = gcry_cipher_setiv (encr_hd, eparm, eparmlen);
398 err = gcry_cipher_decrypt (encr_hd, result, resultlen, NULL, 0);
402 log_error ("KEK decryption failed for PWRI: %s\n", gpg_strerror (err));
407 log_printhex (result, resultlen, "Frame .....:");
409 if (result[0] < 8 /* At least 64 bits */
410 || (result[0] % 8) /* Multiple of 64 bits */
411 || result[0] > resultlen - 4 /* Not more than the size of the input */
412 || ( (result[1] ^ result[4]) /* Matching check bytes. */
413 & (result[2] ^ result[5])
414 & (result[3] ^ result[6]) ) != 0xff)
416 err = gpg_error (GPG_ERR_BAD_PASSPHRASE);
420 *r_resultlen = result[0];
421 *r_result = memmove (result, result + 4, result[0]);
427 wipememory (result, resultlen);
432 wipememory (passphrase, strlen (passphrase));
435 gcry_cipher_close (encr_hd);
436 xfree (derive_algo_str);
437 xfree (encr_algo_str);
438 xfree (ioarray[0].data);
439 xfree (ioarray[1].data);
440 xfree (ioarray[2].data);
441 xfree (ioarray[3].data);
442 xfree (ioarray[4].data);
447 /* Decrypt the session key and fill in the parm structure. The
448 algo and the IV is expected to be already in PARM. */
450 prepare_decryption (ctrl_t ctrl, const char *hexkeygrip, const char *desc,
451 ksba_const_sexp_t enc_val,
452 struct decrypt_filter_parm_s *parm)
456 int pwri = !hexkeygrip;
460 log_printcanon ("decrypting:", enc_val, 0);
464 rc = gpgsm_agent_pkdecrypt (ctrl, hexkeygrip, desc, enc_val,
465 &seskey, &seskeylen);
468 log_error ("error decrypting session key: %s\n", gpg_strerror (rc));
474 if (pwri) /* Password based encryption. */
476 gcry_sexp_t s_enc_val;
477 unsigned char *decrypted;
478 unsigned int decryptedlen;
480 rc = gcry_sexp_sscan (&s_enc_val, NULL, enc_val,
481 gcry_sexp_canon_len (enc_val, 0, NULL, NULL));
485 rc = pwri_decrypt (ctrl, s_enc_val, &decrypted, &decryptedlen, parm);
486 gcry_sexp_release (s_enc_val);
491 seskeylen = decryptedlen;
493 else if (seskeylen == 32 || seskeylen == 24 || seskeylen == 16)
495 /* Smells like an AES-128, 3-DES, or AES-256 key. This might
496 * happen because a SC has already done the unpacking. A better
497 * solution would be to test for this only after we triggered
498 * the GPG_ERR_INV_SESSION_KEY. */
502 if (n + 7 > seskeylen )
504 rc = gpg_error (GPG_ERR_INV_SESSION_KEY);
508 /* FIXME: Actually the leading zero is required but due to the way
509 we encode the output in libgcrypt as an MPI we are not able to
510 encode that leading zero. However, when using a Smartcard we are
511 doing it the right way and therefore we have to skip the zero. This
512 should be fixed in gpg-agent of course. */
516 if (seskey[n] != 2 ) /* Wrong block type version. */
518 rc = gpg_error (GPG_ERR_INV_SESSION_KEY);
522 for (n++; n < seskeylen && seskey[n]; n++) /* Skip the random bytes. */
524 n++; /* and the zero byte */
527 rc = gpg_error (GPG_ERR_INV_SESSION_KEY);
533 log_printhex (seskey+n, seskeylen-n, "session key:");
536 log_info (_("%s.%s encrypted data\n"),
537 gcry_cipher_algo_name (parm->algo),
538 cipher_mode_to_string (parm->mode));
540 rc = gcry_cipher_open (&parm->hd, parm->algo, parm->mode, 0);
543 log_error ("error creating decryptor: %s\n", gpg_strerror (rc));
547 rc = gcry_cipher_setkey (parm->hd, seskey+n, seskeylen-n);
548 if (gpg_err_code (rc) == GPG_ERR_WEAK_KEY)
550 log_info (_("WARNING: message was encrypted with "
551 "a weak key in the symmetric cipher.\n"));
556 log_error("key setup failed: %s\n", gpg_strerror(rc) );
560 rc = gcry_cipher_setiv (parm->hd, parm->iv, parm->ivlen);
563 log_error("IV setup failed: %s\n", gpg_strerror(rc) );
567 if (parm->mode == GCRY_CIPHER_MODE_GCM)
569 /* GCM mode really sucks in CMS. We need to know the AAD before
570 * we start decrypting but CMS puts the AAD after the content.
571 * Thus temporary files are required. Let's hope that no real
572 * messages with actual AAD are ever used. OCB Rules! */
581 /* This function is called by the KSBA writer just before the actual
582 write is done. The function must take INLEN bytes from INBUF,
583 decrypt it and store it inoutbuf which has a maximum size of
584 maxoutlen. The valid bytes in outbuf should be return in outlen.
585 Due to different buffer sizes or different length of input and
586 output, it may happen that fewer bytes are processed or fewer bytes
589 decrypt_filter (void *arg,
590 const void *inbuf, size_t inlen, size_t *inused,
591 void *outbuf, size_t maxoutlen, size_t *outlen)
593 struct decrypt_filter_parm_s *parm = arg;
594 int blklen = parm->blklen;
595 size_t orig_inlen = inlen;
597 /* fixme: Should we issue an error when we have not seen one full block? */
599 return gpg_error (GPG_ERR_BUG);
601 if (maxoutlen < 2*parm->blklen)
602 return gpg_error (GPG_ERR_BUG);
603 /* Make some space because we will later need an extra block at the end. */
606 if (parm->helpblocklen)
610 for (i=parm->helpblocklen,j=0; i < blklen && j < inlen; i++, j++)
611 parm->helpblock[i] = ((const char*)inbuf)[j];
613 if (blklen > maxoutlen)
614 return gpg_error (GPG_ERR_BUG);
617 parm->helpblocklen = i;
622 parm->helpblocklen = 0;
625 memcpy (outbuf, parm->lastblock, blklen);
630 gcry_cipher_decrypt (parm->hd, parm->lastblock, blklen,
631 parm->helpblock, blklen);
634 *inused = orig_inlen - inlen;
639 if (inlen > maxoutlen)
642 { /* store the remainder away */
643 parm->helpblocklen = inlen%blklen;
644 inlen = inlen/blklen*blklen;
645 memcpy (parm->helpblock, (const char*)inbuf+inlen, parm->helpblocklen);
648 *inused = inlen + parm->helpblocklen;
651 assert (inlen >= blklen);
654 gcry_cipher_decrypt (parm->hd, (char*)outbuf+blklen, inlen,
656 memcpy (outbuf, parm->lastblock, blklen);
657 memcpy (parm->lastblock,(char*)outbuf+inlen, blklen);
662 gcry_cipher_decrypt (parm->hd, outbuf, inlen, inbuf, inlen);
663 memcpy (parm->lastblock, (char*)outbuf+inlen-blklen, blklen);
664 *outlen = inlen - blklen;
674 /* This is the GCM version of decrypt_filter. */
676 decrypt_gcm_filter (void *arg,
677 const void *inbuf, size_t inlen, size_t *inused,
678 void *outbuf, size_t maxoutlen, size_t *outlen)
680 struct decrypt_filter_parm_s *parm = arg;
683 return gpg_error (GPG_ERR_BUG);
685 if (maxoutlen < parm->blklen)
686 return gpg_error (GPG_ERR_BUG);
688 if (inlen > maxoutlen)
694 gcry_cipher_decrypt (parm->hd, outbuf, inlen, inbuf, inlen);
705 /* Perform a decrypt operation. */
707 gpgsm_decrypt (ctrl_t ctrl, int in_fd, estream_t out_fp)
710 gnupg_ksba_io_t b64reader = NULL;
711 gnupg_ksba_io_t b64writer = NULL;
712 ksba_reader_t reader;
713 ksba_writer_t writer;
714 ksba_cms_t cms = NULL;
715 ksba_stop_reason_t stopreason;
718 estream_t in_fp = NULL;
719 struct decrypt_filter_parm_s dfparm;
721 memset (&dfparm, 0, sizeof dfparm);
723 audit_set_type (ctrl->audit, AUDIT_TYPE_DECRYPT);
728 log_error (_("failed to allocate keyDB handle\n"));
729 rc = gpg_error (GPG_ERR_GENERAL);
733 in_fp = es_fdopen_nc (in_fd, "rb");
736 rc = gpg_error_from_syserror ();
737 log_error ("fdopen() failed: %s\n", strerror (errno));
741 rc = gnupg_ksba_create_reader
742 (&b64reader, ((ctrl->is_pem? GNUPG_KSBA_IO_PEM : 0)
743 | (ctrl->is_base64? GNUPG_KSBA_IO_BASE64 : 0)
744 | (ctrl->autodetect_encoding? GNUPG_KSBA_IO_AUTODETECT : 0)),
748 log_error ("can't create reader: %s\n", gpg_strerror (rc));
752 rc = gnupg_ksba_create_writer
753 (&b64writer, ((ctrl->create_pem? GNUPG_KSBA_IO_PEM : 0)
754 | (ctrl->create_base64? GNUPG_KSBA_IO_BASE64 : 0)),
755 ctrl->pem_name, out_fp, &writer);
758 log_error ("can't create writer: %s\n", gpg_strerror (rc));
762 rc = ksba_cms_new (&cms);
766 rc = ksba_cms_set_reader_writer (cms, reader, writer);
769 log_debug ("ksba_cms_set_reader_writer failed: %s\n",
774 audit_log (ctrl->audit, AUDIT_SETUP_READY);
779 rc = ksba_cms_parse (cms, &stopreason);
782 log_debug ("ksba_cms_parse failed: %s\n", gpg_strerror (rc));
786 if (stopreason == KSBA_SR_BEGIN_DATA
787 || stopreason == KSBA_SR_DETACHED_DATA)
793 audit_log (ctrl->audit, AUDIT_GOT_DATA);
795 algoid = ksba_cms_get_content_oid (cms, 2/* encryption algo*/);
796 algo = gcry_cipher_map_name (algoid);
797 mode = gcry_cipher_mode_from_oid (algoid);
800 rc = gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
801 log_error ("unsupported algorithm '%s'\n", algoid? algoid:"?");
802 if (algoid && !strcmp (algoid, "1.2.840.113549.3.2"))
803 log_info (_("(this is the RC2 algorithm)\n"));
805 log_info (_("(this does not seem to be an encrypted"
809 sprintf (numbuf, "%d", rc);
810 gpgsm_status2 (ctrl, STATUS_ERROR, "decrypt.algorithm",
811 numbuf, algoid?algoid:"?", NULL);
812 audit_log_s (ctrl->audit, AUDIT_BAD_DATA_CIPHER_ALGO, algoid);
815 /* If it seems that this is not an encrypted message we
816 return a more sensible error code. */
818 rc = gpg_error (GPG_ERR_NO_DATA);
823 /* Check compliance. */
824 if (! gnupg_cipher_is_allowed (opt.compliance, 0, algo, mode))
826 log_error (_("cipher algorithm '%s'"
827 " may not be used in %s mode\n"),
828 gcry_cipher_algo_name (algo),
829 gnupg_compliance_option_string (opt.compliance));
830 rc = gpg_error (GPG_ERR_CIPHER_ALGO);
834 /* For CMS, CO_DE_VS demands CBC mode. */
835 dfparm.is_de_vs = gnupg_cipher_is_compliant (CO_DE_VS, algo, mode);
837 audit_log_i (ctrl->audit, AUDIT_DATA_CIPHER_ALGO, algo);
840 dfparm.blklen = gcry_cipher_get_algo_blklen (algo);
841 if (dfparm.blklen > sizeof (dfparm.helpblock))
842 return gpg_error (GPG_ERR_BUG);
844 rc = ksba_cms_get_content_enc_iv (cms,
850 log_error ("error getting IV: %s\n", gpg_strerror (rc));
854 for (recp=0; !any_key; recp++)
859 char *hexkeygrip = NULL;
860 char *pkalgostr = NULL;
865 ksba_cert_t cert = NULL;
872 tmp_rc = ksba_cms_get_issuer_serial (cms, recp, &issuer, &serial);
873 if (tmp_rc == -1 && recp)
874 break; /* no more recipients */
875 audit_log_i (ctrl->audit, AUDIT_NEW_RECP, recp);
876 if (gpg_err_code (tmp_rc) == GPG_ERR_UNSUPPORTED_CMS_OBJ)
882 log_error ("recp %d - error getting info: %s\n",
883 recp, gpg_strerror (tmp_rc));
889 log_debug ("recp %d - issuer: '%s'\n",
890 recp, issuer? issuer:"[NONE]");
891 log_debug ("recp %d - serial: ", recp);
892 gpgsm_dump_serial (serial);
898 char *tmpstr = gpgsm_format_sn_issuer (serial, issuer);
899 audit_log_s (ctrl->audit, AUDIT_RECP_NAME, tmpstr);
903 keydb_search_reset (kh);
904 rc = keydb_search_issuer_sn (ctrl, kh, issuer, serial);
907 log_error ("failed to find the certificate: %s\n",
912 rc = keydb_get_cert (kh, &cert);
915 log_error ("failed to get cert: %s\n", gpg_strerror (rc));
919 /* Print the ENC_TO status line. Note that we can
920 do so only if we have the certificate. This is
921 in contrast to gpg where the keyID is commonly
922 included in the encrypted messages. It is too
923 cumbersome to retrieve the used algorithm, thus
924 we don't print it for now. We also record the
925 keyid for later use. */
927 unsigned long kid[2];
929 kid[0] = gpgsm_get_short_fingerprint (cert, kid+1);
930 snprintf (kidbuf, sizeof kidbuf, "%08lX%08lX",
932 gpgsm_status2 (ctrl, STATUS_ENC_TO,
933 kidbuf, "0", "0", NULL);
936 /* Put the certificate into the audit log. */
937 audit_log_cert (ctrl->audit, AUDIT_SAVE_CERT, cert, 0);
939 /* Just in case there is a problem with the own
940 certificate we print this message - should never
942 rc = gpgsm_cert_use_decrypt_p (cert);
946 sprintf (numbuf, "%d", rc);
947 gpgsm_status2 (ctrl, STATUS_ERROR, "decrypt.keyusage",
952 hexkeygrip = gpgsm_get_keygrip_hexstring (cert);
953 desc = gpgsm_format_keydesc (cert);
954 pkfpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1);
955 pkalgostr = gpgsm_pubkey_algo_string (cert, NULL);
956 pk_algo = gpgsm_get_key_algo_info (cert, &nbits);
958 log_info (_("encrypted to %s key %s\n"), pkalgostr, pkfpr);
960 /* Check compliance. */
961 if (!gnupg_pk_is_allowed (opt.compliance,
963 pk_algo, 0, NULL, nbits, NULL))
967 snprintf (kidstr, sizeof kidstr, "0x%08lX",
968 gpgsm_get_short_fingerprint (cert, NULL));
969 log_info (_("key %s is not suitable for decryption"
972 gnupg_compliance_option_string(opt.compliance));
973 rc = gpg_error (GPG_ERR_PUBKEY_ALGO);
977 /* Check that all certs are compliant with CO_DE_VS. */
980 && gnupg_pk_is_compliant (CO_DE_VS, pk_algo, 0,
986 /* We cannot check compliance of certs that we
992 ksba_cert_release (cert);
995 if ((!hexkeygrip || !pk_algo) && !maybe_pwri)
997 else if (!(enc_val = ksba_cms_get_enc_val (cms, recp)))
999 log_error ("recp %d - error getting encrypted session key\n",
1002 log_info ("(possibly unsupported KEK info)\n");
1006 if (maybe_pwri && opt.verbose)
1007 log_info ("recp %d - KEKRI or PWRI\n", recp);
1009 rc = prepare_decryption (ctrl, hexkeygrip,
1010 desc, enc_val, &dfparm);
1014 log_info ("decrypting session key failed: %s\n",
1016 if (gpg_err_code (rc) == GPG_ERR_NO_SECKEY && *kidbuf)
1017 gpgsm_status2 (ctrl, STATUS_NO_SECKEY, kidbuf, NULL);
1020 { /* setup the bulk decrypter */
1022 ksba_writer_set_filter
1024 dfparm.mode == GCRY_CIPHER_MODE_GCM?
1025 decrypt_gcm_filter : decrypt_filter,
1029 && gnupg_gcrypt_is_compliant (CO_DE_VS))
1030 gpgsm_status (ctrl, STATUS_DECRYPTION_COMPLIANCE_MODE,
1031 gnupg_status_compliance_flag (CO_DE_VS));
1034 audit_log_ok (ctrl->audit, AUDIT_RECP_RESULT, rc);
1042 /* If we write an audit log add the unused recipients to the
1044 if (ctrl->audit && any_key)
1052 tmp_rc = ksba_cms_get_issuer_serial (cms, recp,
1055 break; /* no more recipients */
1056 audit_log_i (ctrl->audit, AUDIT_NEW_RECP, recp);
1058 log_error ("recp %d - error getting info: %s\n",
1059 recp, gpg_strerror (rc));
1062 char *tmpstr = gpgsm_format_sn_issuer (serial, issuer);
1063 audit_log_s (ctrl->audit, AUDIT_RECP_NAME, tmpstr);
1073 rc = gpg_error (GPG_ERR_NO_SECKEY);
1077 else if (stopreason == KSBA_SR_END_DATA)
1079 ksba_writer_set_filter (writer, NULL, NULL);
1080 if (dfparm.mode == GCRY_CIPHER_MODE_GCM)
1082 /* Nothing yet to do. We wait for the ready event. */
1084 else if (dfparm.any_data )
1085 { /* write the last block with padding removed */
1086 int i, npadding = dfparm.lastblock[dfparm.blklen-1];
1087 if (!npadding || npadding > dfparm.blklen)
1089 log_error ("invalid padding with value %d\n", npadding);
1090 rc = gpg_error (GPG_ERR_INV_DATA);
1093 rc = ksba_writer_write (writer,
1095 dfparm.blklen - npadding);
1099 for (i=dfparm.blklen - npadding; i < dfparm.blklen; i++)
1101 if (dfparm.lastblock[i] != npadding)
1103 log_error ("inconsistent padding\n");
1104 rc = gpg_error (GPG_ERR_INV_DATA);
1110 else if (stopreason == KSBA_SR_READY)
1112 if (dfparm.mode == GCRY_CIPHER_MODE_GCM)
1117 rc = ksba_cms_get_message_digest (cms, 0, &authtag, &authtaglen);
1120 log_error ("error getting authtag: %s\n", gpg_strerror (rc));
1124 log_printhex (authtag, authtaglen, "Authtag ...:");
1125 rc = gcry_cipher_checktag (dfparm.hd, authtag, authtaglen);
1128 log_error ("data is not authentic: %s\n", gpg_strerror (rc));
1133 while (stopreason != KSBA_SR_READY);
1135 rc = gnupg_ksba_finish_writer (b64writer);
1138 log_error ("write failed: %s\n", gpg_strerror (rc));
1141 gpgsm_status (ctrl, STATUS_DECRYPTION_OKAY, NULL);
1145 audit_log_ok (ctrl->audit, AUDIT_DECRYPTION_RESULT, rc);
1148 gpgsm_status (ctrl, STATUS_DECRYPTION_FAILED, NULL);
1149 log_error ("message decryption failed: %s <%s>\n",
1150 gpg_strerror (rc), gpg_strsource (rc));
1152 ksba_cms_release (cms);
1153 gnupg_ksba_destroy_reader (b64reader);
1154 gnupg_ksba_destroy_writer (b64writer);
1158 gcry_cipher_close (dfparm.hd);