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"
41 struct decrypt_filter_parm_s
49 int any_data; /* did we push anything through the filter at all? */
50 unsigned char lastblock[16]; /* to strip the padding we have to
52 char helpblock[16]; /* needed because there is no block buffering in
55 int is_de_vs; /* Helper to track CO_DE_VS state. */
59 /* Return the hash algorithm's algo id from its name given in the
60 * non-null termnated string in (buffer,buflen). Returns 0 on failure
61 * or if the algo is not known. */
63 string_from_gcry_buffer (gcry_buffer_t *buffer)
67 string = xtrymalloc (buffer->len + 1);
70 memcpy (string, buffer->data, buffer->len);
71 string[buffer->len] = 0;
76 /* Helper to construct and hash the
77 * ECC-CMS-SharedInfo ::= SEQUENCE {
78 * keyInfo AlgorithmIdentifier,
79 * entityUInfo [0] EXPLICIT OCTET STRING OPTIONAL,
80 * suppPubInfo [2] EXPLICIT OCTET STRING }
81 * as described in RFC-5753, 7.2. */
83 hash_ecc_cms_shared_info (gcry_md_hd_t hash_hd, const char *wrap_algo_str,
85 const void *ukm, unsigned int ukmlen)
90 size_t n, oidlen, toidlen, tkeyinfo, tukmlen, tsupppubinfo;
91 unsigned char keylenbuf[6];
92 membuf_t mb = MEMBUF_ZERO;
94 err = ksba_oid_from_str (wrap_algo_str, &oid, &oidlen);
97 toidlen = get_tlv_length (CLASS_UNIVERSAL, TAG_OBJECT_ID, 0, oidlen);
98 tkeyinfo = get_tlv_length (CLASS_UNIVERSAL, TAG_SEQUENCE, 1, toidlen);
100 tukmlen = ukm? get_tlv_length (CLASS_CONTEXT, 0, 1, ukmlen) : 0;
103 keylenbuf[0] = TAG_OCTET_STRING;
105 keylenbuf[2] = (keylen >> 24);
106 keylenbuf[3] = (keylen >> 16);
107 keylenbuf[4] = (keylen >> 8);
108 keylenbuf[5] = keylen;
110 tsupppubinfo = get_tlv_length (CLASS_CONTEXT, 2, 1, sizeof keylenbuf);
112 put_tlv_to_membuf (&mb, CLASS_UNIVERSAL, TAG_SEQUENCE, 1,
113 tkeyinfo + tukmlen + tsupppubinfo);
114 put_tlv_to_membuf (&mb, CLASS_UNIVERSAL, TAG_SEQUENCE, 1,
116 put_tlv_to_membuf (&mb, CLASS_UNIVERSAL, TAG_OBJECT_ID, 0, oidlen);
117 put_membuf (&mb, oid, oidlen);
122 put_tlv_to_membuf (&mb, CLASS_CONTEXT, 0, 1, ukmlen);
123 put_membuf (&mb, ukm, ukmlen);
126 put_tlv_to_membuf (&mb, CLASS_CONTEXT, 2, 1, sizeof keylenbuf);
127 put_membuf (&mb, keylenbuf, sizeof keylenbuf);
129 p = get_membuf (&mb, &n);
131 return gpg_error_from_syserror ();
133 gcry_md_write (hash_hd, p, n);
140 /* Derive a KEK (key wrapping key) using (SECRET,SECRETLEN), an
141 * optional (UKM,ULMLEN), the wrap algorithm WRAP_ALGO_STR in decimal
142 * dotted form, and the hash algorithm HASH_ALGO. On success a key of
143 * length KEYLEN is stored at KEY. */
145 ecdh_derive_kek (unsigned char *key, unsigned int keylen,
146 int hash_algo, const char *wrap_algo_str,
147 const void *secret, unsigned int secretlen,
148 const void *ukm, unsigned int ukmlen)
151 unsigned int hashlen;
152 gcry_md_hd_t hash_hd;
153 unsigned char counter;
154 unsigned int n, ncopy;
156 hashlen = gcry_md_get_algo_dlen (hash_algo);
158 return gpg_error (GPG_ERR_INV_ARG);
160 err = gcry_md_open (&hash_hd, hash_algo, 0);
164 /* According to SEC1 3.6.1 we should check that
165 * SECRETLEN + UKMLEN + 4 < maxhashlen
166 * However, we have no practical limit on the hash length and thus
167 * there is no point in checking this. The second check that
168 * KEYLEN < hashlen*(2^32-1)
169 * is obviously also not needed.
171 for (n=0, counter=1; n < keylen; counter++)
174 gcry_md_reset (hash_hd);
175 gcry_md_write (hash_hd, secret, secretlen);
176 gcry_md_write (hash_hd, "\x00\x00\x00", 3); /* MSBs of counter */
177 gcry_md_write (hash_hd, &counter, 1);
178 err = hash_ecc_cms_shared_info (hash_hd, wrap_algo_str, keylen,
182 gcry_md_final (hash_hd);
183 if (n + hashlen > keylen)
187 memcpy (key+n, gcry_md_read (hash_hd, 0), ncopy);
191 gcry_md_close (hash_hd);
196 /* This function will modify SECRET. NBITS is the size of the curve
197 * which which we took from the certificate. */
199 ecdh_decrypt (unsigned char *secret, size_t secretlen,
200 unsigned int nbits, gcry_sexp_t enc_val,
201 unsigned char **r_result, unsigned int *r_resultlen)
204 gcry_buffer_t ioarray[4] = { {0}, {0}, {0}, {0} };
205 char *encr_algo_str = NULL;
206 char *wrap_algo_str = NULL;
207 int hash_algo, cipher_algo;
208 const unsigned char *ukm; /* Alias for ioarray[2]. */
210 const unsigned char *data; /* Alias for ioarray[3]. */
211 unsigned int datalen;
213 unsigned char key[32];
214 gcry_cipher_hd_t cipher_hd = NULL;
215 unsigned char *result = NULL;
216 unsigned int resultlen;
221 /* Extract X from SECRET; this is the actual secret. Unless a
222 * smartcard diretcly returns X, it must be in the format of:
229 return gpg_error (GPG_ERR_BAD_DATA);
230 if (secretlen == (nbits+7)/8)
231 ; /* Matches curve length - this is already the X coordinate. */
232 else if (*secret == 0x04)
235 memmove (secret, secret+1, secretlen);
237 return gpg_error (GPG_ERR_BAD_DATA);
240 else if (*secret == 0x40 || *secret == 0x41)
243 memmove (secret, secret+1, secretlen);
246 return gpg_error (GPG_ERR_BAD_DATA);
248 return gpg_error (GPG_ERR_BAD_DATA);
251 log_printhex (secret, secretlen, "ECDH X ..:");
253 /* We have now the shared secret bytes in (SECRET,SECRETLEN). Now
254 * we will compute the KEK using a value dervied from the secret
256 err = gcry_sexp_extract_param (enc_val, "enc-val",
257 "&'encr-algo''wrap-algo''ukm'?s",
258 ioarray+0, ioarray+1,
259 ioarray+2, ioarray+3, NULL);
262 log_error ("extracting ECDH parameter failed: %s\n", gpg_strerror (err));
265 encr_algo_str = string_from_gcry_buffer (ioarray);
268 err = gpg_error_from_syserror ();
271 wrap_algo_str = string_from_gcry_buffer (ioarray+1);
274 err = gpg_error_from_syserror ();
277 ukm = ioarray[2].data;
278 ukmlen = ioarray[2].len;
279 data = ioarray[3].data;
280 datalen = ioarray[3].len;
282 /* Check parameters. */
285 log_debug ("encr_algo: %s\n", encr_algo_str);
286 log_debug ("wrap_algo: %s\n", wrap_algo_str);
287 log_printhex (ukm, ukmlen, "ukm .....:");
288 log_printhex (data, datalen, "data ....:");
291 if (!strcmp (encr_algo_str, "1.3.132.1.11.1"))
293 /* dhSinglePass-stdDH-sha256kdf-scheme */
294 hash_algo = GCRY_MD_SHA256;
296 else if (!strcmp (encr_algo_str, "1.3.132.1.11.2"))
298 /* dhSinglePass-stdDH-sha384kdf-scheme */
299 hash_algo = GCRY_MD_SHA384;
301 else if (!strcmp (encr_algo_str, "1.3.132.1.11.3"))
303 /* dhSinglePass-stdDH-sha512kdf-scheme */
304 hash_algo = GCRY_MD_SHA512;
306 else if (!strcmp (encr_algo_str, "1.3.133.16.840.63.0.2"))
308 /* dhSinglePass-stdDH-sha1kdf-scheme */
309 hash_algo = GCRY_MD_SHA1;
313 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
317 if (!strcmp (wrap_algo_str, "2.16.840.1.101.3.4.1.5"))
319 cipher_algo = GCRY_CIPHER_AES128;
322 else if (!strcmp (wrap_algo_str, "2.16.840.1.101.3.4.1.25"))
324 cipher_algo = GCRY_CIPHER_AES192;
327 else if (!strcmp (wrap_algo_str, "2.16.840.1.101.3.4.1.45"))
329 cipher_algo = GCRY_CIPHER_AES256;
334 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
338 err = ecdh_derive_kek (key, keylen, hash_algo, wrap_algo_str,
339 secret, secretlen, ukm, ukmlen);
344 log_printhex (key, keylen, "KEK .....:");
346 /* Unwrap the key. */
347 if ((datalen % 8) || datalen < 16)
349 log_error ("can't use a shared secret of %u bytes for ecdh\n", datalen);
350 err = gpg_error (GPG_ERR_BAD_DATA);
354 resultlen = datalen - 8;
355 result = xtrymalloc_secure (resultlen);
358 err = gpg_error_from_syserror ();
362 err = gcry_cipher_open (&cipher_hd, cipher_algo, GCRY_CIPHER_MODE_AESWRAP, 0);
365 log_error ("ecdh failed to initialize AESWRAP: %s\n", gpg_strerror (err));
369 err = gcry_cipher_setkey (cipher_hd, key, keylen);
370 wipememory (key, sizeof key);
373 log_error ("ecdh failed in gcry_cipher_setkey: %s\n", gpg_strerror (err));
377 err = gcry_cipher_decrypt (cipher_hd, result, resultlen, data, datalen);
380 log_error ("ecdh failed in gcry_cipher_decrypt: %s\n",gpg_strerror (err));
384 *r_resultlen = resultlen;
391 wipememory (result, resultlen);
394 gcry_cipher_close (cipher_hd);
395 xfree (encr_algo_str);
396 xfree (wrap_algo_str);
397 xfree (ioarray[0].data);
398 xfree (ioarray[1].data);
399 xfree (ioarray[2].data);
400 xfree (ioarray[3].data);
405 /* Helper for pwri_decrypt to parse the derive info.
406 * Example data for (DER,DERLEN):
409 * 60 76 4B E9 5E DF 3C F8 B2 F9 B6 C2 7D 5A FB 90
414 * hmacWithSHA512 (1 2 840 113549 2 11)
420 pwri_parse_pbkdf2 (const unsigned char *der, size_t derlen,
421 unsigned char const **r_salt, unsigned int *r_saltlen,
422 unsigned long *r_iterations,
426 size_t objlen, hdrlen;
427 int class, tag, constructed, ndef;
430 err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
431 &ndef, &objlen, &hdrlen);
432 if (!err && (objlen > derlen || tag != TAG_SEQUENCE
433 || !constructed || ndef))
434 err = gpg_error (GPG_ERR_INV_OBJ);
439 err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
440 &ndef, &objlen, &hdrlen);
441 if (!err && (objlen > derlen || tag != TAG_OCTET_STRING
442 || constructed || ndef))
443 err = gpg_error (GPG_ERR_INV_OBJ);
451 err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
452 &ndef, &objlen, &hdrlen);
453 if (!err && (objlen > derlen || tag != TAG_INTEGER
454 || constructed || ndef))
455 err = gpg_error (GPG_ERR_INV_OBJ);
459 for (; objlen; objlen--)
462 *r_iterations |= (*der++) & 0xff;
466 err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
467 &ndef, &objlen, &hdrlen);
468 if (!err && (objlen > derlen || tag != TAG_SEQUENCE
469 || !constructed || ndef))
470 err = gpg_error (GPG_ERR_INV_OBJ);
475 err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
476 &ndef, &objlen, &hdrlen);
477 if (!err && (objlen > derlen || tag != TAG_OBJECT_ID
478 || constructed || ndef))
479 err = gpg_error (GPG_ERR_INV_OBJ);
483 oidstr = ksba_oid_to_str (der, objlen);
485 return gpg_error_from_syserror ();
486 *r_digest = gcry_md_map_name (oidstr);
489 else if (!strcmp (oidstr, "1.2.840.113549.2.7"))
490 *r_digest = GCRY_MD_SHA1;
491 else if (!strcmp (oidstr, "1.2.840.113549.2.8"))
492 *r_digest = GCRY_MD_SHA224;
493 else if (!strcmp (oidstr, "1.2.840.113549.2.9"))
494 *r_digest = GCRY_MD_SHA256;
495 else if (!strcmp (oidstr, "1.2.840.113549.2.10"))
496 *r_digest = GCRY_MD_SHA384;
497 else if (!strcmp (oidstr, "1.2.840.113549.2.11"))
498 *r_digest = GCRY_MD_SHA512;
500 err = gpg_error (GPG_ERR_DIGEST_ALGO);
507 /* Password based decryption.
508 * ENC_VAL has the form:
511 * (derive-algo <oid>) --| both are optional
512 * (derive-parm <der>) --|
515 * (encr-key <key>))) -- this is the encrypted session key
519 pwri_decrypt (ctrl_t ctrl, gcry_sexp_t enc_val,
520 unsigned char **r_result, unsigned int *r_resultlen,
521 struct decrypt_filter_parm_s *parm)
524 gcry_buffer_t ioarray[5] = { {0} };
525 char *derive_algo_str = NULL;
526 char *encr_algo_str = NULL;
527 const unsigned char *dparm; /* Alias for ioarray[1]. */
528 unsigned int dparmlen;
529 const unsigned char *eparm; /* Alias for ioarray[3]. */
530 unsigned int eparmlen;
531 const unsigned char *ekey; /* Alias for ioarray[4]. */
532 unsigned int ekeylen;
533 unsigned char kek[32];
536 enum gcry_cipher_modes encr_mode;
537 gcry_cipher_hd_t encr_hd = NULL;
538 unsigned char *result = NULL;
539 unsigned int resultlen;
541 const unsigned char *salt; /* Points int dparm. */
542 unsigned int saltlen;
543 unsigned long iterations;
545 char *passphrase = NULL;
551 err = gcry_sexp_extract_param (enc_val, "enc-val!pwri",
552 "&'derive-algo'?'derive-parm'?"
553 "'encr-algo''encr-parm''encr-key'",
554 ioarray+0, ioarray+1,
555 ioarray+2, ioarray+3, ioarray+4, NULL);
558 /* If this is not pwri element, it is likly a kekri element
559 * which we do not yet support. Change the error back to the
560 * original as returned by ksba_cms_get_issuer. */
561 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
562 err = gpg_error (GPG_ERR_UNSUPPORTED_CMS_OBJ);
564 log_error ("extracting PWRI parameter failed: %s\n",
571 derive_algo_str = string_from_gcry_buffer (ioarray+0);
572 if (!derive_algo_str)
574 err = gpg_error_from_syserror ();
578 dparm = ioarray[1].data;
579 dparmlen = ioarray[1].len;
580 encr_algo_str = string_from_gcry_buffer (ioarray+2);
583 err = gpg_error_from_syserror ();
586 eparm = ioarray[3].data;
587 eparmlen = ioarray[3].len;
588 ekey = ioarray[4].data;
589 ekeylen = ioarray[4].len;
591 /* Check parameters. */
596 log_debug ("derive algo: %s\n", derive_algo_str);
597 log_printhex (dparm, dparmlen, "derive parm:");
599 log_debug ("encr algo .: %s\n", encr_algo_str);
600 log_printhex (eparm, eparmlen, "encr parm .:");
601 log_printhex (ekey, ekeylen, "encr key .:");
604 if (!derive_algo_str)
606 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
607 log_info ("PWRI with no key derivation detected\n");
610 if (strcmp (derive_algo_str, "1.2.840.113549.1.5.12"))
612 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
613 log_info ("PWRI does not use PBKDF2 (but %s)\n", derive_algo_str);
617 digest_algo = 0; /*(silence cc warning)*/
618 err = pwri_parse_pbkdf2 (dparm, dparmlen,
619 &salt, &saltlen, &iterations, &digest_algo);
622 log_error ("parsing PWRI parameter failed: %s\n", gpg_strerror (err));
626 parm->is_de_vs = (parm->is_de_vs
627 && gnupg_digest_is_compliant (CO_DE_VS, digest_algo));
630 encr_algo = gcry_cipher_map_name (encr_algo_str);
631 encr_mode = gcry_cipher_mode_from_oid (encr_algo_str);
632 if (!encr_algo || !encr_mode)
634 log_error ("PWRI uses unknown algorithm %s\n", encr_algo_str);
635 err = gpg_error (GPG_ERR_CIPHER_ALGO);
641 && gnupg_cipher_is_compliant (CO_DE_VS, encr_algo, encr_mode));
643 keklen = gcry_cipher_get_algo_keylen (encr_algo);
644 blklen = gcry_cipher_get_algo_blklen (encr_algo);
645 if (!keklen || keklen > sizeof kek || blklen != 16 )
647 log_error ("PWRI algorithm %s cannot be used\n", encr_algo_str);
648 err = gpg_error (GPG_ERR_INV_KEYLEN);
651 if ((ekeylen % blklen) || (ekeylen / blklen < 2))
653 /* Note that we need at least two full blocks. */
654 log_error ("PWRI uses a wrong length of encrypted key\n");
655 err = gpg_error (GPG_ERR_INV_KEYLEN);
659 err = gpgsm_agent_ask_passphrase
661 i18n_utf8 (N_("Please enter the passphrase for decryption.")),
666 err = gcry_kdf_derive (passphrase, strlen (passphrase),
667 GCRY_KDF_PBKDF2, digest_algo,
668 salt, saltlen, iterations,
672 wipememory (passphrase, strlen (passphrase));
678 log_error ("deriving key from passphrase failed: %s\n",
684 log_printhex (kek, keklen, "KEK .......:");
686 /* Unwrap the key. */
688 result = xtrymalloc_secure (resultlen);
691 err = gpg_error_from_syserror ();
695 err = gcry_cipher_open (&encr_hd, encr_algo, encr_mode, 0);
698 log_error ("PWRI failed to open cipher: %s\n", gpg_strerror (err));
702 err = gcry_cipher_setkey (encr_hd, kek, keklen);
703 wipememory (kek, sizeof kek);
705 err = gcry_cipher_setiv (encr_hd, ekey + ekeylen - 2 * blklen, blklen);
707 err = gcry_cipher_decrypt (encr_hd, result + ekeylen - blklen, blklen,
708 ekey + ekeylen - blklen, blklen);
710 err = gcry_cipher_setiv (encr_hd, result + ekeylen - blklen, blklen);
712 err = gcry_cipher_decrypt (encr_hd, result, ekeylen - blklen,
713 ekey, ekeylen - blklen);
714 /* (We assume that that eparm is the octet string with the IV) */
716 err = gcry_cipher_setiv (encr_hd, eparm, eparmlen);
718 err = gcry_cipher_decrypt (encr_hd, result, resultlen, NULL, 0);
722 log_error ("KEK decryption failed for PWRI: %s\n", gpg_strerror (err));
727 log_printhex (result, resultlen, "Frame .....:");
729 if (result[0] < 8 /* At least 64 bits */
730 || (result[0] % 8) /* Multiple of 64 bits */
731 || result[0] > resultlen - 4 /* Not more than the size of the input */
732 || ( (result[1] ^ result[4]) /* Matching check bytes. */
733 & (result[2] ^ result[5])
734 & (result[3] ^ result[6]) ) != 0xff)
736 err = gpg_error (GPG_ERR_BAD_PASSPHRASE);
740 *r_resultlen = result[0];
741 *r_result = memmove (result, result + 4, result[0]);
747 wipememory (result, resultlen);
752 wipememory (passphrase, strlen (passphrase));
755 gcry_cipher_close (encr_hd);
756 xfree (derive_algo_str);
757 xfree (encr_algo_str);
758 xfree (ioarray[0].data);
759 xfree (ioarray[1].data);
760 xfree (ioarray[2].data);
761 xfree (ioarray[3].data);
762 xfree (ioarray[4].data);
767 /* Decrypt the session key and fill in the parm structure. The
768 algo and the IV is expected to be already in PARM. */
770 prepare_decryption (ctrl_t ctrl, const char *hexkeygrip,
771 int pk_algo, unsigned int nbits, const char *desc,
772 ksba_const_sexp_t enc_val,
773 struct decrypt_filter_parm_s *parm)
777 int pwri = !hexkeygrip && !pk_algo;
781 log_printcanon ("decrypting:", enc_val, 0);
785 rc = gpgsm_agent_pkdecrypt (ctrl, hexkeygrip, desc, enc_val,
786 &seskey, &seskeylen);
789 log_error ("error decrypting session key: %s\n", gpg_strerror (rc));
794 log_printhex (seskey, seskeylen, "DEK frame:");
798 if (pwri) /* Password based encryption. */
800 gcry_sexp_t s_enc_val;
801 unsigned char *decrypted;
802 unsigned int decryptedlen;
804 rc = gcry_sexp_sscan (&s_enc_val, NULL, enc_val,
805 gcry_sexp_canon_len (enc_val, 0, NULL, NULL));
809 rc = pwri_decrypt (ctrl, s_enc_val, &decrypted, &decryptedlen, parm);
810 gcry_sexp_release (s_enc_val);
815 seskeylen = decryptedlen;
817 else if (pk_algo == GCRY_PK_ECC)
819 gcry_sexp_t s_enc_val;
820 unsigned char *decrypted;
821 unsigned int decryptedlen;
823 rc = gcry_sexp_sscan (&s_enc_val, NULL, enc_val,
824 gcry_sexp_canon_len (enc_val, 0, NULL, NULL));
828 rc = ecdh_decrypt (seskey, seskeylen, nbits, s_enc_val,
829 &decrypted, &decryptedlen);
830 gcry_sexp_release (s_enc_val);
835 seskeylen = decryptedlen;
838 else if (seskeylen == 32 || seskeylen == 24 || seskeylen == 16)
840 /* Smells like an AES-128, 3-DES, or AES-256 key. This might
841 * happen because a SC has already done the unpacking. A better
842 * solution would be to test for this only after we triggered
843 * the GPG_ERR_INV_SESSION_KEY. */
847 if (n + 7 > seskeylen )
849 rc = gpg_error (GPG_ERR_INV_SESSION_KEY);
853 /* FIXME: Actually the leading zero is required but due to the way
854 we encode the output in libgcrypt as an MPI we are not able to
855 encode that leading zero. However, when using a Smartcard we are
856 doing it the right way and therefore we have to skip the zero. This
857 should be fixed in gpg-agent of course. */
861 if (seskey[n] != 2 ) /* Wrong block type version. */
863 rc = gpg_error (GPG_ERR_INV_SESSION_KEY);
867 for (n++; n < seskeylen && seskey[n]; n++) /* Skip the random bytes. */
869 n++; /* and the zero byte */
872 rc = gpg_error (GPG_ERR_INV_SESSION_KEY);
879 log_printhex (seskey+n, seskeylen-n, "CEK .......:");
880 log_printhex (parm->iv, parm->ivlen, "IV ........:");
884 log_info (_("%s.%s encrypted data\n"),
885 gcry_cipher_algo_name (parm->algo),
886 cipher_mode_to_string (parm->mode));
888 rc = gcry_cipher_open (&parm->hd, parm->algo, parm->mode, 0);
891 log_error ("error creating decryptor: %s\n", gpg_strerror (rc));
895 rc = gcry_cipher_setkey (parm->hd, seskey+n, seskeylen-n);
896 if (gpg_err_code (rc) == GPG_ERR_WEAK_KEY)
898 log_info (_("WARNING: message was encrypted with "
899 "a weak key in the symmetric cipher.\n"));
904 log_error("key setup failed: %s\n", gpg_strerror(rc) );
908 rc = gcry_cipher_setiv (parm->hd, parm->iv, parm->ivlen);
911 log_error("IV setup failed: %s\n", gpg_strerror(rc) );
915 if (parm->mode == GCRY_CIPHER_MODE_GCM)
917 /* GCM mode really sucks in CMS. We need to know the AAD before
918 * we start decrypting but CMS puts the AAD after the content.
919 * Thus temporary files are required. Let's hope that no real
920 * messages with actual AAD are ever used. OCB Rules! */
929 /* This function is called by the KSBA writer just before the actual
930 write is done. The function must take INLEN bytes from INBUF,
931 decrypt it and store it inoutbuf which has a maximum size of
932 maxoutlen. The valid bytes in outbuf should be return in outlen.
933 Due to different buffer sizes or different length of input and
934 output, it may happen that fewer bytes are processed or fewer bytes
937 decrypt_filter (void *arg,
938 const void *inbuf, size_t inlen, size_t *inused,
939 void *outbuf, size_t maxoutlen, size_t *outlen)
941 struct decrypt_filter_parm_s *parm = arg;
942 int blklen = parm->blklen;
943 size_t orig_inlen = inlen;
945 /* fixme: Should we issue an error when we have not seen one full block? */
947 return gpg_error (GPG_ERR_BUG);
949 if (maxoutlen < 2*parm->blklen)
950 return gpg_error (GPG_ERR_BUG);
951 /* Make some space because we will later need an extra block at the end. */
954 if (parm->helpblocklen)
958 for (i=parm->helpblocklen,j=0; i < blklen && j < inlen; i++, j++)
959 parm->helpblock[i] = ((const char*)inbuf)[j];
961 if (blklen > maxoutlen)
962 return gpg_error (GPG_ERR_BUG);
965 parm->helpblocklen = i;
970 parm->helpblocklen = 0;
973 memcpy (outbuf, parm->lastblock, blklen);
978 gcry_cipher_decrypt (parm->hd, parm->lastblock, blklen,
979 parm->helpblock, blklen);
982 *inused = orig_inlen - inlen;
987 if (inlen > maxoutlen)
990 { /* store the remainder away */
991 parm->helpblocklen = inlen%blklen;
992 inlen = inlen/blklen*blklen;
993 memcpy (parm->helpblock, (const char*)inbuf+inlen, parm->helpblocklen);
996 *inused = inlen + parm->helpblocklen;
999 log_assert (inlen >= blklen);
1002 gcry_cipher_decrypt (parm->hd, (char*)outbuf+blklen, inlen,
1004 memcpy (outbuf, parm->lastblock, blklen);
1005 memcpy (parm->lastblock,(char*)outbuf+inlen, blklen);
1010 gcry_cipher_decrypt (parm->hd, outbuf, inlen, inbuf, inlen);
1011 memcpy (parm->lastblock, (char*)outbuf+inlen-blklen, blklen);
1012 *outlen = inlen - blklen;
1022 /* This is the GCM version of decrypt_filter. */
1024 decrypt_gcm_filter (void *arg,
1025 const void *inbuf, size_t inlen, size_t *inused,
1026 void *outbuf, size_t maxoutlen, size_t *outlen)
1028 struct decrypt_filter_parm_s *parm = arg;
1031 return gpg_error (GPG_ERR_BUG);
1033 if (maxoutlen < parm->blklen)
1034 return gpg_error (GPG_ERR_BUG);
1036 if (inlen > maxoutlen)
1042 gcry_cipher_decrypt (parm->hd, outbuf, inlen, inbuf, inlen);
1053 /* Perform a decrypt operation. */
1055 gpgsm_decrypt (ctrl_t ctrl, int in_fd, estream_t out_fp)
1058 gnupg_ksba_io_t b64reader = NULL;
1059 gnupg_ksba_io_t b64writer = NULL;
1060 ksba_reader_t reader;
1061 ksba_writer_t writer;
1062 ksba_cms_t cms = NULL;
1063 ksba_stop_reason_t stopreason;
1066 estream_t in_fp = NULL;
1067 struct decrypt_filter_parm_s dfparm;
1069 memset (&dfparm, 0, sizeof dfparm);
1071 audit_set_type (ctrl->audit, AUDIT_TYPE_DECRYPT);
1073 kh = keydb_new (ctrl);
1076 log_error (_("failed to allocate keyDB handle\n"));
1077 rc = gpg_error (GPG_ERR_GENERAL);
1081 in_fp = es_fdopen_nc (in_fd, "rb");
1084 rc = gpg_error_from_syserror ();
1085 log_error ("fdopen() failed: %s\n", strerror (errno));
1089 rc = gnupg_ksba_create_reader
1090 (&b64reader, ((ctrl->is_pem? GNUPG_KSBA_IO_PEM : 0)
1091 | (ctrl->is_base64? GNUPG_KSBA_IO_BASE64 : 0)
1092 | (ctrl->autodetect_encoding? GNUPG_KSBA_IO_AUTODETECT : 0)),
1096 log_error ("can't create reader: %s\n", gpg_strerror (rc));
1100 rc = gnupg_ksba_create_writer
1101 (&b64writer, ((ctrl->create_pem? GNUPG_KSBA_IO_PEM : 0)
1102 | (ctrl->create_base64? GNUPG_KSBA_IO_BASE64 : 0)),
1103 ctrl->pem_name, out_fp, &writer);
1106 log_error ("can't create writer: %s\n", gpg_strerror (rc));
1110 gnupg_ksba_set_progress_cb (b64writer, gpgsm_progress_cb, ctrl);
1111 if (ctrl->input_size_hint)
1112 gnupg_ksba_set_total (b64writer, ctrl->input_size_hint);
1114 rc = ksba_cms_new (&cms);
1118 rc = ksba_cms_set_reader_writer (cms, reader, writer);
1121 log_error ("ksba_cms_set_reader_writer failed: %s\n",
1126 audit_log (ctrl->audit, AUDIT_SETUP_READY);
1131 rc = ksba_cms_parse (cms, &stopreason);
1134 log_error ("ksba_cms_parse failed: %s\n", gpg_strerror (rc));
1138 if (stopreason == KSBA_SR_BEGIN_DATA
1139 || stopreason == KSBA_SR_DETACHED_DATA)
1145 audit_log (ctrl->audit, AUDIT_GOT_DATA);
1147 algoid = ksba_cms_get_content_oid (cms, 2/* encryption algo*/);
1148 algo = gcry_cipher_map_name (algoid);
1149 mode = gcry_cipher_mode_from_oid (algoid);
1152 rc = gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
1153 log_error ("unsupported algorithm '%s'\n", algoid? algoid:"?");
1154 if (algoid && !strcmp (algoid, "1.2.840.113549.3.2"))
1155 log_info (_("(this is the RC2 algorithm)\n"));
1157 log_info (_("(this does not seem to be an encrypted"
1161 sprintf (numbuf, "%d", rc);
1162 gpgsm_status2 (ctrl, STATUS_ERROR, "decrypt.algorithm",
1163 numbuf, algoid?algoid:"?", NULL);
1164 audit_log_s (ctrl->audit, AUDIT_BAD_DATA_CIPHER_ALGO, algoid);
1167 /* If it seems that this is not an encrypted message we
1168 return a more sensible error code. */
1170 rc = gpg_error (GPG_ERR_NO_DATA);
1175 /* Check compliance. */
1176 if (! gnupg_cipher_is_allowed (opt.compliance, 0, algo, mode))
1178 log_error (_("cipher algorithm '%s'"
1179 " may not be used in %s mode\n"),
1180 gcry_cipher_algo_name (algo),
1181 gnupg_compliance_option_string (opt.compliance));
1182 rc = gpg_error (GPG_ERR_CIPHER_ALGO);
1186 /* For CMS, CO_DE_VS demands CBC mode. */
1187 dfparm.is_de_vs = gnupg_cipher_is_compliant (CO_DE_VS, algo, mode);
1189 audit_log_i (ctrl->audit, AUDIT_DATA_CIPHER_ALGO, algo);
1192 dfparm.blklen = gcry_cipher_get_algo_blklen (algo);
1193 if (dfparm.blklen > sizeof (dfparm.helpblock))
1195 rc = gpg_error (GPG_ERR_BUG);
1199 rc = ksba_cms_get_content_enc_iv (cms,
1205 log_error ("error getting IV: %s\n", gpg_strerror (rc));
1209 for (recp=0; !any_key; recp++)
1213 ksba_sexp_t enc_val;
1214 char *hexkeygrip = NULL;
1215 char *pkalgostr = NULL;
1220 ksba_cert_t cert = NULL;
1227 tmp_rc = ksba_cms_get_issuer_serial (cms, recp, &issuer, &serial);
1228 if (tmp_rc == -1 && recp)
1229 break; /* no more recipients */
1230 audit_log_i (ctrl->audit, AUDIT_NEW_RECP, recp);
1231 if (gpg_err_code (tmp_rc) == GPG_ERR_UNSUPPORTED_CMS_OBJ)
1237 log_error ("recp %d - error getting info: %s\n",
1238 recp, gpg_strerror (tmp_rc));
1244 log_info ("recp %d - issuer: '%s'\n",
1245 recp, issuer? issuer:"[NONE]");
1246 log_info ("recp %d - serial: ", recp);
1247 gpgsm_dump_serial (serial);
1253 char *tmpstr = gpgsm_format_sn_issuer (serial, issuer);
1254 audit_log_s (ctrl->audit, AUDIT_RECP_NAME, tmpstr);
1258 keydb_search_reset (kh);
1259 rc = keydb_search_issuer_sn (ctrl, kh, issuer, serial);
1262 log_error ("failed to find the certificate: %s\n",
1267 rc = keydb_get_cert (kh, &cert);
1270 log_error ("failed to get cert: %s\n", gpg_strerror (rc));
1274 /* Print the ENC_TO status line. Note that we can
1275 do so only if we have the certificate. This is
1276 in contrast to gpg where the keyID is commonly
1277 included in the encrypted messages. It is too
1278 cumbersome to retrieve the used algorithm, thus
1279 we don't print it for now. We also record the
1280 keyid for later use. */
1282 unsigned long kid[2];
1284 kid[0] = gpgsm_get_short_fingerprint (cert, kid+1);
1285 snprintf (kidbuf, sizeof kidbuf, "%08lX%08lX",
1287 gpgsm_status2 (ctrl, STATUS_ENC_TO,
1288 kidbuf, "0", "0", NULL);
1291 /* Put the certificate into the audit log. */
1292 audit_log_cert (ctrl->audit, AUDIT_SAVE_CERT, cert, 0);
1294 /* Just in case there is a problem with the own
1295 certificate we print this message - should never
1297 rc = gpgsm_cert_use_decrypt_p (cert);
1301 sprintf (numbuf, "%d", rc);
1302 gpgsm_status2 (ctrl, STATUS_ERROR, "decrypt.keyusage",
1307 hexkeygrip = gpgsm_get_keygrip_hexstring (cert);
1308 desc = gpgsm_format_keydesc (cert);
1310 pkfpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1);
1311 pkalgostr = gpgsm_pubkey_algo_string (cert, NULL);
1312 pk_algo = gpgsm_get_key_algo_info (cert, &nbits);
1314 log_info (_("encrypted to %s key %s\n"), pkalgostr, pkfpr);
1316 /* Check compliance. */
1317 if (!gnupg_pk_is_allowed (opt.compliance,
1319 pk_algo, 0, NULL, nbits, NULL))
1323 snprintf (kidstr, sizeof kidstr, "0x%08lX",
1324 gpgsm_get_short_fingerprint (cert, NULL));
1325 log_info (_("key %s is not suitable for decryption"
1328 gnupg_compliance_option_string(opt.compliance));
1329 rc = gpg_error (GPG_ERR_PUBKEY_ALGO);
1333 /* Check that all certs are compliant with CO_DE_VS. */
1336 && gnupg_pk_is_compliant (CO_DE_VS, pk_algo, 0,
1337 NULL, nbits, NULL));
1342 /* We cannot check compliance of certs that we
1344 dfparm.is_de_vs = 0;
1348 ksba_cert_release (cert);
1351 if ((!hexkeygrip || !pk_algo) && !maybe_pwri)
1353 else if (!(enc_val = ksba_cms_get_enc_val (cms, recp)))
1355 log_error ("recp %d - error getting encrypted session key\n",
1358 log_info ("(possibly unsupported KEK info)\n");
1362 if (maybe_pwri && opt.verbose)
1363 log_info ("recp %d - KEKRI or PWRI\n", recp);
1365 rc = prepare_decryption (ctrl, hexkeygrip, pk_algo, nbits,
1366 desc, enc_val, &dfparm);
1370 log_info ("decrypting session key failed: %s\n",
1372 if (gpg_err_code (rc) == GPG_ERR_NO_SECKEY && *kidbuf)
1373 gpgsm_status2 (ctrl, STATUS_NO_SECKEY, kidbuf, NULL);
1376 { /* setup the bulk decrypter */
1378 ksba_writer_set_filter
1380 dfparm.mode == GCRY_CIPHER_MODE_GCM?
1381 decrypt_gcm_filter : decrypt_filter,
1385 && gnupg_gcrypt_is_compliant (CO_DE_VS))
1386 gpgsm_status (ctrl, STATUS_DECRYPTION_COMPLIANCE_MODE,
1387 gnupg_status_compliance_flag (CO_DE_VS));
1388 else if (opt.require_compliance
1389 && opt.compliance == CO_DE_VS)
1391 log_error (_("operation forced to fail due to"
1392 " unfulfilled compliance rules\n"));
1393 gpgsm_errors_seen = 1;
1396 audit_log_ok (ctrl->audit, AUDIT_RECP_RESULT, rc);
1404 /* If we write an audit log add the unused recipients to the
1406 if (ctrl->audit && any_key)
1414 tmp_rc = ksba_cms_get_issuer_serial (cms, recp,
1417 break; /* no more recipients */
1418 audit_log_i (ctrl->audit, AUDIT_NEW_RECP, recp);
1420 log_error ("recp %d - error getting info: %s\n",
1421 recp, gpg_strerror (tmp_rc));
1424 char *tmpstr = gpgsm_format_sn_issuer (serial, issuer);
1425 audit_log_s (ctrl->audit, AUDIT_RECP_NAME, tmpstr);
1436 rc = gpg_error (GPG_ERR_NO_SECKEY);
1440 else if (stopreason == KSBA_SR_END_DATA)
1442 ksba_writer_set_filter (writer, NULL, NULL);
1443 if (dfparm.mode == GCRY_CIPHER_MODE_GCM)
1445 /* Nothing yet to do. We wait for the ready event. */
1447 else if (dfparm.any_data )
1448 { /* write the last block with padding removed */
1449 int i, npadding = dfparm.lastblock[dfparm.blklen-1];
1450 if (!npadding || npadding > dfparm.blklen)
1452 log_error ("invalid padding with value %d\n", npadding);
1453 rc = gpg_error (GPG_ERR_INV_DATA);
1456 rc = ksba_writer_write (writer,
1458 dfparm.blklen - npadding);
1462 for (i=dfparm.blklen - npadding; i < dfparm.blklen; i++)
1464 if (dfparm.lastblock[i] != npadding)
1466 log_error ("inconsistent padding\n");
1467 rc = gpg_error (GPG_ERR_INV_DATA);
1473 else if (stopreason == KSBA_SR_READY)
1475 if (dfparm.mode == GCRY_CIPHER_MODE_GCM)
1480 rc = ksba_cms_get_message_digest (cms, 0, &authtag, &authtaglen);
1483 log_error ("error getting authtag: %s\n", gpg_strerror (rc));
1487 log_printhex (authtag, authtaglen, "Authtag ...:");
1488 rc = gcry_cipher_checktag (dfparm.hd, authtag, authtaglen);
1491 log_error ("data is not authentic: %s\n", gpg_strerror (rc));
1496 while (stopreason != KSBA_SR_READY);
1498 rc = gnupg_ksba_finish_writer (b64writer);
1501 log_error ("write failed: %s\n", gpg_strerror (rc));
1504 gpgsm_status (ctrl, STATUS_DECRYPTION_OKAY, NULL);
1508 audit_log_ok (ctrl->audit, AUDIT_DECRYPTION_RESULT, rc);
1511 gpgsm_status (ctrl, STATUS_DECRYPTION_FAILED, NULL);
1512 log_error ("message decryption failed: %s <%s>\n",
1513 gpg_strerror (rc), gpg_strsource (rc));
1515 ksba_cms_release (cms);
1516 gnupg_ksba_destroy_reader (b64reader);
1517 gnupg_ksba_destroy_writer (b64writer);
1521 gcry_cipher_close (dfparm.hd);