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
36 #include "../common/i18n.h"
37 #include "../common/tlv.h"
38 #include "../common/compliance.h"
40 /* We can provide an enum value which is only availabale with KSBA
41 * 1.6.0 so that we can compile even against older versions. Some
42 * calls will of course return an error in this case. This value is
43 * currently not used because the cipher mode is sufficient here. */
44 /* #if KSBA_VERSION_NUMBER < 0x010600 /\* 1.6.0 *\/ */
45 /* # define KSBA_CT_AUTHENVELOPED_DATA 10 */
49 struct decrypt_filter_parm_s
57 int any_data; /* did we push anything through the filter at all? */
58 unsigned char lastblock[16]; /* to strip the padding we have to
60 char helpblock[16]; /* needed because there is no block buffering in
63 int is_de_vs; /* Helper to track CO_DE_VS state. */
67 /* Return the hash algorithm's algo id from its name given in the
68 * non-null termnated string in (buffer,buflen). Returns 0 on failure
69 * or if the algo is not known. */
71 string_from_gcry_buffer (gcry_buffer_t *buffer)
75 string = xtrymalloc (buffer->len + 1);
78 memcpy (string, buffer->data, buffer->len);
79 string[buffer->len] = 0;
84 /* Helper to construct and hash the
85 * ECC-CMS-SharedInfo ::= SEQUENCE {
86 * keyInfo AlgorithmIdentifier,
87 * entityUInfo [0] EXPLICIT OCTET STRING OPTIONAL,
88 * suppPubInfo [2] EXPLICIT OCTET STRING }
89 * as described in RFC-5753, 7.2. */
91 hash_ecc_cms_shared_info (gcry_md_hd_t hash_hd, const char *wrap_algo_str,
93 const void *ukm, unsigned int ukmlen)
98 size_t n, oidlen, toidlen, tkeyinfo, tukmlen, tsupppubinfo;
99 unsigned char keylenbuf[6];
100 membuf_t mb = MEMBUF_ZERO;
102 err = ksba_oid_from_str (wrap_algo_str, &oid, &oidlen);
105 toidlen = get_tlv_length (CLASS_UNIVERSAL, TAG_OBJECT_ID, 0, oidlen);
106 tkeyinfo = get_tlv_length (CLASS_UNIVERSAL, TAG_SEQUENCE, 1, toidlen);
108 tukmlen = ukm? get_tlv_length (CLASS_CONTEXT, 0, 1, ukmlen) : 0;
111 keylenbuf[0] = TAG_OCTET_STRING;
113 keylenbuf[2] = (keylen >> 24);
114 keylenbuf[3] = (keylen >> 16);
115 keylenbuf[4] = (keylen >> 8);
116 keylenbuf[5] = keylen;
118 tsupppubinfo = get_tlv_length (CLASS_CONTEXT, 2, 1, sizeof keylenbuf);
120 put_tlv_to_membuf (&mb, CLASS_UNIVERSAL, TAG_SEQUENCE, 1,
121 tkeyinfo + tukmlen + tsupppubinfo);
122 put_tlv_to_membuf (&mb, CLASS_UNIVERSAL, TAG_SEQUENCE, 1,
124 put_tlv_to_membuf (&mb, CLASS_UNIVERSAL, TAG_OBJECT_ID, 0, oidlen);
125 put_membuf (&mb, oid, oidlen);
130 put_tlv_to_membuf (&mb, CLASS_CONTEXT, 0, 1, ukmlen);
131 put_membuf (&mb, ukm, ukmlen);
134 put_tlv_to_membuf (&mb, CLASS_CONTEXT, 2, 1, sizeof keylenbuf);
135 put_membuf (&mb, keylenbuf, sizeof keylenbuf);
137 p = get_membuf (&mb, &n);
139 return gpg_error_from_syserror ();
141 gcry_md_write (hash_hd, p, n);
148 /* Derive a KEK (key wrapping key) using (SECRET,SECRETLEN), an
149 * optional (UKM,ULMLEN), the wrap algorithm WRAP_ALGO_STR in decimal
150 * dotted form, and the hash algorithm HASH_ALGO. On success a key of
151 * length KEYLEN is stored at KEY. */
153 ecdh_derive_kek (unsigned char *key, unsigned int keylen,
154 int hash_algo, const char *wrap_algo_str,
155 const void *secret, unsigned int secretlen,
156 const void *ukm, unsigned int ukmlen)
159 unsigned int hashlen;
160 gcry_md_hd_t hash_hd;
161 unsigned char counter;
162 unsigned int n, ncopy;
164 hashlen = gcry_md_get_algo_dlen (hash_algo);
166 return gpg_error (GPG_ERR_INV_ARG);
168 err = gcry_md_open (&hash_hd, hash_algo, 0);
172 /* According to SEC1 3.6.1 we should check that
173 * SECRETLEN + UKMLEN + 4 < maxhashlen
174 * However, we have no practical limit on the hash length and thus
175 * there is no point in checking this. The second check that
176 * KEYLEN < hashlen*(2^32-1)
177 * is obviously also not needed.
179 for (n=0, counter=1; n < keylen; counter++)
182 gcry_md_reset (hash_hd);
183 gcry_md_write (hash_hd, secret, secretlen);
184 gcry_md_write (hash_hd, "\x00\x00\x00", 3); /* MSBs of counter */
185 gcry_md_write (hash_hd, &counter, 1);
186 err = hash_ecc_cms_shared_info (hash_hd, wrap_algo_str, keylen,
190 gcry_md_final (hash_hd);
191 if (n + hashlen > keylen)
195 memcpy (key+n, gcry_md_read (hash_hd, 0), ncopy);
199 gcry_md_close (hash_hd);
204 /* This function will modify SECRET. NBITS is the size of the curve
205 * which which we took from the certificate. */
207 ecdh_decrypt (unsigned char *secret, size_t secretlen,
208 unsigned int nbits, gcry_sexp_t enc_val,
209 unsigned char **r_result, unsigned int *r_resultlen)
212 gcry_buffer_t ioarray[4] = { {0}, {0}, {0}, {0} };
213 char *encr_algo_str = NULL;
214 char *wrap_algo_str = NULL;
215 int hash_algo, cipher_algo;
216 const unsigned char *ukm; /* Alias for ioarray[2]. */
218 const unsigned char *data; /* Alias for ioarray[3]. */
219 unsigned int datalen;
221 unsigned char key[32];
222 gcry_cipher_hd_t cipher_hd = NULL;
223 unsigned char *result = NULL;
224 unsigned int resultlen;
229 /* Extract X from SECRET; this is the actual secret. Unless a
230 * smartcard diretcly returns X, it must be in the format of:
237 return gpg_error (GPG_ERR_BAD_DATA);
238 if (secretlen == (nbits+7)/8)
239 ; /* Matches curve length - this is already the X coordinate. */
240 else if (*secret == 0x04)
243 memmove (secret, secret+1, secretlen);
245 return gpg_error (GPG_ERR_BAD_DATA);
248 else if (*secret == 0x40 || *secret == 0x41)
251 memmove (secret, secret+1, secretlen);
254 return gpg_error (GPG_ERR_BAD_DATA);
256 return gpg_error (GPG_ERR_BAD_DATA);
259 log_printhex (secret, secretlen, "ECDH X ..:");
261 /* We have now the shared secret bytes in (SECRET,SECRETLEN). Now
262 * we will compute the KEK using a value dervied from the secret
264 err = gcry_sexp_extract_param (enc_val, "enc-val",
265 "&'encr-algo''wrap-algo''ukm'?s",
266 ioarray+0, ioarray+1,
267 ioarray+2, ioarray+3, NULL);
270 log_error ("extracting ECDH parameter failed: %s\n", gpg_strerror (err));
273 encr_algo_str = string_from_gcry_buffer (ioarray);
276 err = gpg_error_from_syserror ();
279 wrap_algo_str = string_from_gcry_buffer (ioarray+1);
282 err = gpg_error_from_syserror ();
285 ukm = ioarray[2].data;
286 ukmlen = ioarray[2].len;
287 data = ioarray[3].data;
288 datalen = ioarray[3].len;
290 /* Check parameters. */
293 log_debug ("encr_algo: %s\n", encr_algo_str);
294 log_debug ("wrap_algo: %s\n", wrap_algo_str);
295 log_printhex (ukm, ukmlen, "ukm .....:");
296 log_printhex (data, datalen, "data ....:");
299 if (!strcmp (encr_algo_str, "1.3.132.1.11.1"))
301 /* dhSinglePass-stdDH-sha256kdf-scheme */
302 hash_algo = GCRY_MD_SHA256;
304 else if (!strcmp (encr_algo_str, "1.3.132.1.11.2"))
306 /* dhSinglePass-stdDH-sha384kdf-scheme */
307 hash_algo = GCRY_MD_SHA384;
309 else if (!strcmp (encr_algo_str, "1.3.132.1.11.3"))
311 /* dhSinglePass-stdDH-sha512kdf-scheme */
312 hash_algo = GCRY_MD_SHA512;
314 else if (!strcmp (encr_algo_str, "1.3.133.16.840.63.0.2"))
316 /* dhSinglePass-stdDH-sha1kdf-scheme */
317 hash_algo = GCRY_MD_SHA1;
321 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
325 if (!strcmp (wrap_algo_str, "2.16.840.1.101.3.4.1.5"))
327 cipher_algo = GCRY_CIPHER_AES128;
330 else if (!strcmp (wrap_algo_str, "2.16.840.1.101.3.4.1.25"))
332 cipher_algo = GCRY_CIPHER_AES192;
335 else if (!strcmp (wrap_algo_str, "2.16.840.1.101.3.4.1.45"))
337 cipher_algo = GCRY_CIPHER_AES256;
342 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
346 err = ecdh_derive_kek (key, keylen, hash_algo, wrap_algo_str,
347 secret, secretlen, ukm, ukmlen);
352 log_printhex (key, keylen, "KEK .....:");
354 /* Unwrap the key. */
355 if ((datalen % 8) || datalen < 16)
357 log_error ("can't use a shared secret of %u bytes for ecdh\n", datalen);
358 err = gpg_error (GPG_ERR_BAD_DATA);
362 resultlen = datalen - 8;
363 result = xtrymalloc_secure (resultlen);
366 err = gpg_error_from_syserror ();
370 err = gcry_cipher_open (&cipher_hd, cipher_algo, GCRY_CIPHER_MODE_AESWRAP, 0);
373 log_error ("ecdh failed to initialize AESWRAP: %s\n", gpg_strerror (err));
377 err = gcry_cipher_setkey (cipher_hd, key, keylen);
378 wipememory (key, sizeof key);
381 log_error ("ecdh failed in gcry_cipher_setkey: %s\n", gpg_strerror (err));
385 err = gcry_cipher_decrypt (cipher_hd, result, resultlen, data, datalen);
388 log_error ("ecdh failed in gcry_cipher_decrypt: %s\n",gpg_strerror (err));
392 *r_resultlen = resultlen;
399 wipememory (result, resultlen);
402 gcry_cipher_close (cipher_hd);
403 xfree (encr_algo_str);
404 xfree (wrap_algo_str);
405 xfree (ioarray[0].data);
406 xfree (ioarray[1].data);
407 xfree (ioarray[2].data);
408 xfree (ioarray[3].data);
413 /* Helper for pwri_decrypt to parse the derive info.
414 * Example data for (DER,DERLEN):
417 * 60 76 4B E9 5E DF 3C F8 B2 F9 B6 C2 7D 5A FB 90
422 * hmacWithSHA512 (1 2 840 113549 2 11)
428 pwri_parse_pbkdf2 (const unsigned char *der, size_t derlen,
429 unsigned char const **r_salt, unsigned int *r_saltlen,
430 unsigned long *r_iterations,
434 size_t objlen, hdrlen;
435 int class, tag, constructed, ndef;
438 err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
439 &ndef, &objlen, &hdrlen);
440 if (!err && (objlen > derlen || tag != TAG_SEQUENCE
441 || !constructed || ndef))
442 err = gpg_error (GPG_ERR_INV_OBJ);
447 err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
448 &ndef, &objlen, &hdrlen);
449 if (!err && (objlen > derlen || tag != TAG_OCTET_STRING
450 || constructed || ndef))
451 err = gpg_error (GPG_ERR_INV_OBJ);
459 err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
460 &ndef, &objlen, &hdrlen);
461 if (!err && (objlen > derlen || tag != TAG_INTEGER
462 || constructed || ndef))
463 err = gpg_error (GPG_ERR_INV_OBJ);
467 for (; objlen; objlen--)
470 *r_iterations |= (*der++) & 0xff;
474 err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
475 &ndef, &objlen, &hdrlen);
476 if (!err && (objlen > derlen || tag != TAG_SEQUENCE
477 || !constructed || ndef))
478 err = gpg_error (GPG_ERR_INV_OBJ);
483 err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
484 &ndef, &objlen, &hdrlen);
485 if (!err && (objlen > derlen || tag != TAG_OBJECT_ID
486 || constructed || ndef))
487 err = gpg_error (GPG_ERR_INV_OBJ);
491 oidstr = ksba_oid_to_str (der, objlen);
493 return gpg_error_from_syserror ();
494 *r_digest = gcry_md_map_name (oidstr);
497 else if (!strcmp (oidstr, "1.2.840.113549.2.7"))
498 *r_digest = GCRY_MD_SHA1;
499 else if (!strcmp (oidstr, "1.2.840.113549.2.8"))
500 *r_digest = GCRY_MD_SHA224;
501 else if (!strcmp (oidstr, "1.2.840.113549.2.9"))
502 *r_digest = GCRY_MD_SHA256;
503 else if (!strcmp (oidstr, "1.2.840.113549.2.10"))
504 *r_digest = GCRY_MD_SHA384;
505 else if (!strcmp (oidstr, "1.2.840.113549.2.11"))
506 *r_digest = GCRY_MD_SHA512;
508 err = gpg_error (GPG_ERR_DIGEST_ALGO);
515 /* Password based decryption.
516 * ENC_VAL has the form:
519 * (derive-algo <oid>) --| both are optional
520 * (derive-parm <der>) --|
523 * (encr-key <key>))) -- this is the encrypted session key
527 pwri_decrypt (ctrl_t ctrl, gcry_sexp_t enc_val,
528 unsigned char **r_result, unsigned int *r_resultlen,
529 struct decrypt_filter_parm_s *parm)
532 gcry_buffer_t ioarray[5] = { {0} };
533 char *derive_algo_str = NULL;
534 char *encr_algo_str = NULL;
535 const unsigned char *dparm; /* Alias for ioarray[1]. */
536 unsigned int dparmlen;
537 const unsigned char *eparm; /* Alias for ioarray[3]. */
538 unsigned int eparmlen;
539 const unsigned char *ekey; /* Alias for ioarray[4]. */
540 unsigned int ekeylen;
541 unsigned char kek[32];
544 enum gcry_cipher_modes encr_mode;
545 gcry_cipher_hd_t encr_hd = NULL;
546 unsigned char *result = NULL;
547 unsigned int resultlen;
549 const unsigned char *salt; /* Points int dparm. */
550 unsigned int saltlen;
551 unsigned long iterations;
553 char *passphrase = NULL;
559 err = gcry_sexp_extract_param (enc_val, "enc-val!pwri",
560 "&'derive-algo'?'derive-parm'?"
561 "'encr-algo''encr-parm''encr-key'",
562 ioarray+0, ioarray+1,
563 ioarray+2, ioarray+3, ioarray+4, NULL);
566 /* If this is not pwri element, it is likly a kekri element
567 * which we do not yet support. Change the error back to the
568 * original as returned by ksba_cms_get_issuer. */
569 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
570 err = gpg_error (GPG_ERR_UNSUPPORTED_CMS_OBJ);
572 log_error ("extracting PWRI parameter failed: %s\n",
579 derive_algo_str = string_from_gcry_buffer (ioarray+0);
580 if (!derive_algo_str)
582 err = gpg_error_from_syserror ();
586 dparm = ioarray[1].data;
587 dparmlen = ioarray[1].len;
588 encr_algo_str = string_from_gcry_buffer (ioarray+2);
591 err = gpg_error_from_syserror ();
594 eparm = ioarray[3].data;
595 eparmlen = ioarray[3].len;
596 ekey = ioarray[4].data;
597 ekeylen = ioarray[4].len;
599 /* Check parameters. */
604 log_debug ("derive algo: %s\n", derive_algo_str);
605 log_printhex (dparm, dparmlen, "derive parm:");
607 log_debug ("encr algo .: %s\n", encr_algo_str);
608 log_printhex (eparm, eparmlen, "encr parm .:");
609 log_printhex (ekey, ekeylen, "encr key .:");
612 if (!derive_algo_str)
614 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
615 log_info ("PWRI with no key derivation detected\n");
618 if (strcmp (derive_algo_str, "1.2.840.113549.1.5.12"))
620 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
621 log_info ("PWRI does not use PBKDF2 (but %s)\n", derive_algo_str);
625 digest_algo = 0; /*(silence cc warning)*/
626 err = pwri_parse_pbkdf2 (dparm, dparmlen,
627 &salt, &saltlen, &iterations, &digest_algo);
630 log_error ("parsing PWRI parameter failed: %s\n", gpg_strerror (err));
634 parm->is_de_vs = (parm->is_de_vs
635 && gnupg_digest_is_compliant (CO_DE_VS, digest_algo));
638 encr_algo = gcry_cipher_map_name (encr_algo_str);
639 encr_mode = gcry_cipher_mode_from_oid (encr_algo_str);
640 if (!encr_algo || !encr_mode)
642 log_error ("PWRI uses unknown algorithm %s\n", encr_algo_str);
643 err = gpg_error (GPG_ERR_CIPHER_ALGO);
649 && gnupg_cipher_is_compliant (CO_DE_VS, encr_algo, encr_mode));
651 keklen = gcry_cipher_get_algo_keylen (encr_algo);
652 blklen = gcry_cipher_get_algo_blklen (encr_algo);
653 if (!keklen || keklen > sizeof kek || blklen != 16 )
655 log_error ("PWRI algorithm %s cannot be used\n", encr_algo_str);
656 err = gpg_error (GPG_ERR_INV_KEYLEN);
659 if ((ekeylen % blklen) || (ekeylen / blklen < 2))
661 /* Note that we need at least two full blocks. */
662 log_error ("PWRI uses a wrong length of encrypted key\n");
663 err = gpg_error (GPG_ERR_INV_KEYLEN);
667 err = gpgsm_agent_ask_passphrase
669 i18n_utf8 (N_("Please enter the passphrase for decryption.")),
674 err = gcry_kdf_derive (passphrase, strlen (passphrase),
675 GCRY_KDF_PBKDF2, digest_algo,
676 salt, saltlen, iterations,
680 wipememory (passphrase, strlen (passphrase));
686 log_error ("deriving key from passphrase failed: %s\n",
692 log_printhex (kek, keklen, "KEK .......:");
694 /* Unwrap the key. */
696 result = xtrymalloc_secure (resultlen);
699 err = gpg_error_from_syserror ();
703 err = gcry_cipher_open (&encr_hd, encr_algo, encr_mode, 0);
706 log_error ("PWRI failed to open cipher: %s\n", gpg_strerror (err));
710 err = gcry_cipher_setkey (encr_hd, kek, keklen);
711 wipememory (kek, sizeof kek);
713 err = gcry_cipher_setiv (encr_hd, ekey + ekeylen - 2 * blklen, blklen);
715 err = gcry_cipher_decrypt (encr_hd, result + ekeylen - blklen, blklen,
716 ekey + ekeylen - blklen, blklen);
718 err = gcry_cipher_setiv (encr_hd, result + ekeylen - blklen, blklen);
720 err = gcry_cipher_decrypt (encr_hd, result, ekeylen - blklen,
721 ekey, ekeylen - blklen);
722 /* (We assume that that eparm is the octet string with the IV) */
724 err = gcry_cipher_setiv (encr_hd, eparm, eparmlen);
726 err = gcry_cipher_decrypt (encr_hd, result, resultlen, NULL, 0);
730 log_error ("KEK decryption failed for PWRI: %s\n", gpg_strerror (err));
735 log_printhex (result, resultlen, "Frame .....:");
737 if (result[0] < 8 /* At least 64 bits */
738 || (result[0] % 8) /* Multiple of 64 bits */
739 || result[0] > resultlen - 4 /* Not more than the size of the input */
740 || ( (result[1] ^ result[4]) /* Matching check bytes. */
741 & (result[2] ^ result[5])
742 & (result[3] ^ result[6]) ) != 0xff)
744 err = gpg_error (GPG_ERR_BAD_PASSPHRASE);
748 *r_resultlen = result[0];
749 *r_result = memmove (result, result + 4, result[0]);
755 wipememory (result, resultlen);
760 wipememory (passphrase, strlen (passphrase));
763 gcry_cipher_close (encr_hd);
764 xfree (derive_algo_str);
765 xfree (encr_algo_str);
766 xfree (ioarray[0].data);
767 xfree (ioarray[1].data);
768 xfree (ioarray[2].data);
769 xfree (ioarray[3].data);
770 xfree (ioarray[4].data);
775 /* Decrypt the session key and fill in the parm structure. The
776 algo and the IV is expected to be already in PARM. */
778 prepare_decryption (ctrl_t ctrl, const char *hexkeygrip,
779 int pk_algo, unsigned int nbits, const char *desc,
780 ksba_const_sexp_t enc_val,
781 struct decrypt_filter_parm_s *parm)
785 int pwri = !hexkeygrip && !pk_algo;
789 log_printcanon ("decrypting:", enc_val, 0);
793 rc = gpgsm_agent_pkdecrypt (ctrl, hexkeygrip, desc, enc_val,
794 &seskey, &seskeylen);
797 log_error ("error decrypting session key: %s\n", gpg_strerror (rc));
802 log_printhex (seskey, seskeylen, "DEK frame:");
806 if (pwri) /* Password based encryption. */
808 gcry_sexp_t s_enc_val;
809 unsigned char *decrypted;
810 unsigned int decryptedlen;
812 rc = gcry_sexp_sscan (&s_enc_val, NULL, enc_val,
813 gcry_sexp_canon_len (enc_val, 0, NULL, NULL));
817 rc = pwri_decrypt (ctrl, s_enc_val, &decrypted, &decryptedlen, parm);
818 gcry_sexp_release (s_enc_val);
823 seskeylen = decryptedlen;
825 else if (pk_algo == GCRY_PK_ECC)
827 gcry_sexp_t s_enc_val;
828 unsigned char *decrypted;
829 unsigned int decryptedlen;
831 rc = gcry_sexp_sscan (&s_enc_val, NULL, enc_val,
832 gcry_sexp_canon_len (enc_val, 0, NULL, NULL));
836 rc = ecdh_decrypt (seskey, seskeylen, nbits, s_enc_val,
837 &decrypted, &decryptedlen);
838 gcry_sexp_release (s_enc_val);
843 seskeylen = decryptedlen;
846 else if (seskeylen == 32 || seskeylen == 24 || seskeylen == 16)
848 /* Smells like an AES-128, 3-DES, or AES-256 key. This might
849 * happen because a SC has already done the unpacking. A better
850 * solution would be to test for this only after we triggered
851 * the GPG_ERR_INV_SESSION_KEY. */
855 if (n + 7 > seskeylen )
857 rc = gpg_error (GPG_ERR_INV_SESSION_KEY);
861 /* FIXME: Actually the leading zero is required but due to the way
862 we encode the output in libgcrypt as an MPI we are not able to
863 encode that leading zero. However, when using a Smartcard we are
864 doing it the right way and therefore we have to skip the zero. This
865 should be fixed in gpg-agent of course. */
869 if (seskey[n] != 2 ) /* Wrong block type version. */
871 rc = gpg_error (GPG_ERR_INV_SESSION_KEY);
875 for (n++; n < seskeylen && seskey[n]; n++) /* Skip the random bytes. */
877 n++; /* and the zero byte */
880 rc = gpg_error (GPG_ERR_INV_SESSION_KEY);
887 log_printhex (seskey+n, seskeylen-n, "CEK .......:");
888 log_printhex (parm->iv, parm->ivlen, "IV ........:");
892 log_info (_("%s.%s encrypted data\n"),
893 gcry_cipher_algo_name (parm->algo),
894 cipher_mode_to_string (parm->mode));
896 rc = gcry_cipher_open (&parm->hd, parm->algo, parm->mode, 0);
899 log_error ("error creating decryptor: %s\n", gpg_strerror (rc));
903 rc = gcry_cipher_setkey (parm->hd, seskey+n, seskeylen-n);
904 if (gpg_err_code (rc) == GPG_ERR_WEAK_KEY)
906 log_info (_("WARNING: message was encrypted with "
907 "a weak key in the symmetric cipher.\n"));
912 log_error("key setup failed: %s\n", gpg_strerror(rc) );
916 rc = gcry_cipher_setiv (parm->hd, parm->iv, parm->ivlen);
919 log_error("IV setup failed: %s\n", gpg_strerror(rc) );
923 if (parm->mode == GCRY_CIPHER_MODE_GCM)
925 /* GCM mode really sucks in CMS. We need to know the AAD before
926 * we start decrypting but CMS puts the AAD after the content.
927 * Thus temporary files are required. Let's hope that no real
928 * messages with actual AAD are ever used. OCB Rules! */
937 /* This function is called by the KSBA writer just before the actual
938 write is done. The function must take INLEN bytes from INBUF,
939 decrypt it and store it inoutbuf which has a maximum size of
940 maxoutlen. The valid bytes in outbuf should be return in outlen.
941 Due to different buffer sizes or different length of input and
942 output, it may happen that fewer bytes are processed or fewer bytes
945 decrypt_filter (void *arg,
946 const void *inbuf, size_t inlen, size_t *inused,
947 void *outbuf, size_t maxoutlen, size_t *outlen)
949 struct decrypt_filter_parm_s *parm = arg;
950 int blklen = parm->blklen;
951 size_t orig_inlen = inlen;
953 /* fixme: Should we issue an error when we have not seen one full block? */
955 return gpg_error (GPG_ERR_BUG);
957 if (maxoutlen < 2*parm->blklen)
958 return gpg_error (GPG_ERR_BUG);
959 /* Make some space because we will later need an extra block at the end. */
962 if (parm->helpblocklen)
966 for (i=parm->helpblocklen,j=0; i < blklen && j < inlen; i++, j++)
967 parm->helpblock[i] = ((const char*)inbuf)[j];
969 if (blklen > maxoutlen)
970 return gpg_error (GPG_ERR_BUG);
973 parm->helpblocklen = i;
978 parm->helpblocklen = 0;
981 memcpy (outbuf, parm->lastblock, blklen);
986 gcry_cipher_decrypt (parm->hd, parm->lastblock, blklen,
987 parm->helpblock, blklen);
990 *inused = orig_inlen - inlen;
995 if (inlen > maxoutlen)
998 { /* store the remainder away */
999 parm->helpblocklen = inlen%blklen;
1000 inlen = inlen/blklen*blklen;
1001 memcpy (parm->helpblock, (const char*)inbuf+inlen, parm->helpblocklen);
1004 *inused = inlen + parm->helpblocklen;
1007 log_assert (inlen >= blklen);
1010 gcry_cipher_decrypt (parm->hd, (char*)outbuf+blklen, inlen,
1012 memcpy (outbuf, parm->lastblock, blklen);
1013 memcpy (parm->lastblock,(char*)outbuf+inlen, blklen);
1018 gcry_cipher_decrypt (parm->hd, outbuf, inlen, inbuf, inlen);
1019 memcpy (parm->lastblock, (char*)outbuf+inlen-blklen, blklen);
1020 *outlen = inlen - blklen;
1030 /* This is the GCM version of decrypt_filter. */
1032 decrypt_gcm_filter (void *arg,
1033 const void *inbuf, size_t inlen, size_t *inused,
1034 void *outbuf, size_t maxoutlen, size_t *outlen)
1036 struct decrypt_filter_parm_s *parm = arg;
1039 return gpg_error (GPG_ERR_BUG);
1041 if (maxoutlen < parm->blklen)
1042 return gpg_error (GPG_ERR_BUG);
1044 if (inlen > maxoutlen)
1050 gcry_cipher_decrypt (parm->hd, outbuf, inlen, inbuf, inlen);
1061 /* Perform a decrypt operation. */
1063 gpgsm_decrypt (ctrl_t ctrl, int in_fd, estream_t out_fp)
1066 gnupg_ksba_io_t b64reader = NULL;
1067 gnupg_ksba_io_t b64writer = NULL;
1068 ksba_reader_t reader;
1069 ksba_writer_t writer;
1070 ksba_cms_t cms = NULL;
1071 ksba_stop_reason_t stopreason;
1074 estream_t in_fp = NULL;
1075 struct decrypt_filter_parm_s dfparm;
1077 memset (&dfparm, 0, sizeof dfparm);
1079 audit_set_type (ctrl->audit, AUDIT_TYPE_DECRYPT);
1081 kh = keydb_new (ctrl);
1084 log_error (_("failed to allocate keyDB handle\n"));
1085 rc = gpg_error (GPG_ERR_GENERAL);
1089 in_fp = es_fdopen_nc (in_fd, "rb");
1092 rc = gpg_error_from_syserror ();
1093 log_error ("fdopen() failed: %s\n", strerror (errno));
1097 rc = gnupg_ksba_create_reader
1098 (&b64reader, ((ctrl->is_pem? GNUPG_KSBA_IO_PEM : 0)
1099 | (ctrl->is_base64? GNUPG_KSBA_IO_BASE64 : 0)
1100 | (ctrl->autodetect_encoding? GNUPG_KSBA_IO_AUTODETECT : 0)),
1104 log_error ("can't create reader: %s\n", gpg_strerror (rc));
1108 rc = gnupg_ksba_create_writer
1109 (&b64writer, ((ctrl->create_pem? GNUPG_KSBA_IO_PEM : 0)
1110 | (ctrl->create_base64? GNUPG_KSBA_IO_BASE64 : 0)),
1111 ctrl->pem_name, out_fp, &writer);
1114 log_error ("can't create writer: %s\n", gpg_strerror (rc));
1118 rc = ksba_cms_new (&cms);
1122 rc = ksba_cms_set_reader_writer (cms, reader, writer);
1125 log_error ("ksba_cms_set_reader_writer failed: %s\n",
1130 audit_log (ctrl->audit, AUDIT_SETUP_READY);
1135 rc = ksba_cms_parse (cms, &stopreason);
1138 log_error ("ksba_cms_parse failed: %s\n", gpg_strerror (rc));
1142 if (stopreason == KSBA_SR_BEGIN_DATA
1143 || stopreason == KSBA_SR_DETACHED_DATA)
1149 audit_log (ctrl->audit, AUDIT_GOT_DATA);
1151 algoid = ksba_cms_get_content_oid (cms, 2/* encryption algo*/);
1152 algo = gcry_cipher_map_name (algoid);
1153 mode = gcry_cipher_mode_from_oid (algoid);
1156 rc = gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
1157 log_error ("unsupported algorithm '%s'\n", algoid? algoid:"?");
1158 if (algoid && !strcmp (algoid, "1.2.840.113549.3.2"))
1159 log_info (_("(this is the RC2 algorithm)\n"));
1161 log_info (_("(this does not seem to be an encrypted"
1165 sprintf (numbuf, "%d", rc);
1166 gpgsm_status2 (ctrl, STATUS_ERROR, "decrypt.algorithm",
1167 numbuf, algoid?algoid:"?", NULL);
1168 audit_log_s (ctrl->audit, AUDIT_BAD_DATA_CIPHER_ALGO, algoid);
1171 /* If it seems that this is not an encrypted message we
1172 return a more sensible error code. */
1174 rc = gpg_error (GPG_ERR_NO_DATA);
1179 /* Check compliance. */
1180 if (! gnupg_cipher_is_allowed (opt.compliance, 0, algo, mode))
1182 log_error (_("cipher algorithm '%s'"
1183 " may not be used in %s mode\n"),
1184 gcry_cipher_algo_name (algo),
1185 gnupg_compliance_option_string (opt.compliance));
1186 rc = gpg_error (GPG_ERR_CIPHER_ALGO);
1190 /* For CMS, CO_DE_VS demands CBC mode. */
1191 dfparm.is_de_vs = gnupg_cipher_is_compliant (CO_DE_VS, algo, mode);
1193 audit_log_i (ctrl->audit, AUDIT_DATA_CIPHER_ALGO, algo);
1196 dfparm.blklen = gcry_cipher_get_algo_blklen (algo);
1197 if (dfparm.blklen > sizeof (dfparm.helpblock))
1199 rc = gpg_error (GPG_ERR_BUG);
1203 rc = ksba_cms_get_content_enc_iv (cms,
1209 log_error ("error getting IV: %s\n", gpg_strerror (rc));
1213 for (recp=0; !any_key; recp++)
1217 ksba_sexp_t enc_val;
1218 char *hexkeygrip = NULL;
1219 char *pkalgostr = NULL;
1224 ksba_cert_t cert = NULL;
1231 tmp_rc = ksba_cms_get_issuer_serial (cms, recp, &issuer, &serial);
1232 if (tmp_rc == -1 && recp)
1233 break; /* no more recipients */
1234 audit_log_i (ctrl->audit, AUDIT_NEW_RECP, recp);
1235 if (gpg_err_code (tmp_rc) == GPG_ERR_UNSUPPORTED_CMS_OBJ)
1241 log_error ("recp %d - error getting info: %s\n",
1242 recp, gpg_strerror (tmp_rc));
1248 log_info ("recp %d - issuer: '%s'\n",
1249 recp, issuer? issuer:"[NONE]");
1250 log_info ("recp %d - serial: ", recp);
1251 gpgsm_dump_serial (serial);
1257 char *tmpstr = gpgsm_format_sn_issuer (serial, issuer);
1258 audit_log_s (ctrl->audit, AUDIT_RECP_NAME, tmpstr);
1262 keydb_search_reset (kh);
1263 rc = keydb_search_issuer_sn (ctrl, kh, issuer, serial);
1266 log_error ("failed to find the certificate: %s\n",
1271 rc = keydb_get_cert (kh, &cert);
1274 log_error ("failed to get cert: %s\n", gpg_strerror (rc));
1278 /* Print the ENC_TO status line. Note that we can
1279 do so only if we have the certificate. This is
1280 in contrast to gpg where the keyID is commonly
1281 included in the encrypted messages. It is too
1282 cumbersome to retrieve the used algorithm, thus
1283 we don't print it for now. We also record the
1284 keyid for later use. */
1286 unsigned long kid[2];
1288 kid[0] = gpgsm_get_short_fingerprint (cert, kid+1);
1289 snprintf (kidbuf, sizeof kidbuf, "%08lX%08lX",
1291 gpgsm_status2 (ctrl, STATUS_ENC_TO,
1292 kidbuf, "0", "0", NULL);
1295 /* Put the certificate into the audit log. */
1296 audit_log_cert (ctrl->audit, AUDIT_SAVE_CERT, cert, 0);
1298 /* Just in case there is a problem with the own
1299 certificate we print this message - should never
1301 rc = gpgsm_cert_use_decrypt_p (cert);
1305 sprintf (numbuf, "%d", rc);
1306 gpgsm_status2 (ctrl, STATUS_ERROR, "decrypt.keyusage",
1311 hexkeygrip = gpgsm_get_keygrip_hexstring (cert);
1312 desc = gpgsm_format_keydesc (cert);
1314 pkfpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1);
1315 pkalgostr = gpgsm_pubkey_algo_string (cert, NULL);
1316 pk_algo = gpgsm_get_key_algo_info (cert, &nbits);
1318 log_info (_("encrypted to %s key %s\n"), pkalgostr, pkfpr);
1320 /* Check compliance. */
1321 if (!gnupg_pk_is_allowed (opt.compliance,
1323 pk_algo, 0, NULL, nbits, NULL))
1327 snprintf (kidstr, sizeof kidstr, "0x%08lX",
1328 gpgsm_get_short_fingerprint (cert, NULL));
1329 log_info (_("key %s is not suitable for decryption"
1332 gnupg_compliance_option_string(opt.compliance));
1333 rc = gpg_error (GPG_ERR_PUBKEY_ALGO);
1337 /* Check that all certs are compliant with CO_DE_VS. */
1340 && gnupg_pk_is_compliant (CO_DE_VS, pk_algo, 0,
1341 NULL, nbits, NULL));
1346 /* We cannot check compliance of certs that we
1348 dfparm.is_de_vs = 0;
1352 ksba_cert_release (cert);
1355 if ((!hexkeygrip || !pk_algo) && !maybe_pwri)
1357 else if (!(enc_val = ksba_cms_get_enc_val (cms, recp)))
1359 log_error ("recp %d - error getting encrypted session key\n",
1362 log_info ("(possibly unsupported KEK info)\n");
1366 if (maybe_pwri && opt.verbose)
1367 log_info ("recp %d - KEKRI or PWRI\n", recp);
1369 rc = prepare_decryption (ctrl, hexkeygrip, pk_algo, nbits,
1370 desc, enc_val, &dfparm);
1374 log_info ("decrypting session key failed: %s\n",
1376 if (gpg_err_code (rc) == GPG_ERR_NO_SECKEY && *kidbuf)
1377 gpgsm_status2 (ctrl, STATUS_NO_SECKEY, kidbuf, NULL);
1380 { /* setup the bulk decrypter */
1382 ksba_writer_set_filter
1384 dfparm.mode == GCRY_CIPHER_MODE_GCM?
1385 decrypt_gcm_filter : decrypt_filter,
1389 && gnupg_gcrypt_is_compliant (CO_DE_VS))
1390 gpgsm_status (ctrl, STATUS_DECRYPTION_COMPLIANCE_MODE,
1391 gnupg_status_compliance_flag (CO_DE_VS));
1394 audit_log_ok (ctrl->audit, AUDIT_RECP_RESULT, rc);
1402 /* If we write an audit log add the unused recipients to the
1404 if (ctrl->audit && any_key)
1412 tmp_rc = ksba_cms_get_issuer_serial (cms, recp,
1415 break; /* no more recipients */
1416 audit_log_i (ctrl->audit, AUDIT_NEW_RECP, recp);
1418 log_error ("recp %d - error getting info: %s\n",
1419 recp, gpg_strerror (tmp_rc));
1422 char *tmpstr = gpgsm_format_sn_issuer (serial, issuer);
1423 audit_log_s (ctrl->audit, AUDIT_RECP_NAME, tmpstr);
1434 rc = gpg_error (GPG_ERR_NO_SECKEY);
1438 else if (stopreason == KSBA_SR_END_DATA)
1440 ksba_writer_set_filter (writer, NULL, NULL);
1441 if (dfparm.mode == GCRY_CIPHER_MODE_GCM)
1443 /* Nothing yet to do. We wait for the ready event. */
1445 else if (dfparm.any_data )
1446 { /* write the last block with padding removed */
1447 int i, npadding = dfparm.lastblock[dfparm.blklen-1];
1448 if (!npadding || npadding > dfparm.blklen)
1450 log_error ("invalid padding with value %d\n", npadding);
1451 rc = gpg_error (GPG_ERR_INV_DATA);
1454 rc = ksba_writer_write (writer,
1456 dfparm.blklen - npadding);
1460 for (i=dfparm.blklen - npadding; i < dfparm.blklen; i++)
1462 if (dfparm.lastblock[i] != npadding)
1464 log_error ("inconsistent padding\n");
1465 rc = gpg_error (GPG_ERR_INV_DATA);
1471 else if (stopreason == KSBA_SR_READY)
1473 if (dfparm.mode == GCRY_CIPHER_MODE_GCM)
1478 rc = ksba_cms_get_message_digest (cms, 0, &authtag, &authtaglen);
1481 log_error ("error getting authtag: %s\n", gpg_strerror (rc));
1485 log_printhex (authtag, authtaglen, "Authtag ...:");
1486 rc = gcry_cipher_checktag (dfparm.hd, authtag, authtaglen);
1489 log_error ("data is not authentic: %s\n", gpg_strerror (rc));
1494 while (stopreason != KSBA_SR_READY);
1496 rc = gnupg_ksba_finish_writer (b64writer);
1499 log_error ("write failed: %s\n", gpg_strerror (rc));
1502 gpgsm_status (ctrl, STATUS_DECRYPTION_OKAY, NULL);
1506 audit_log_ok (ctrl->audit, AUDIT_DECRYPTION_RESULT, rc);
1509 gpgsm_status (ctrl, STATUS_DECRYPTION_FAILED, NULL);
1510 log_error ("message decryption failed: %s <%s>\n",
1511 gpg_strerror (rc), gpg_strsource (rc));
1513 ksba_cms_release (cms);
1514 gnupg_ksba_destroy_reader (b64reader);
1515 gnupg_ksba_destroy_writer (b64writer);
1519 gcry_cipher_close (dfparm.hd);