1 /* decrypt.c - Decrypt a message
2 * Copyright (C) 2001, 2003, 2010 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <https://www.gnu.org/licenses/>.
34 #include "../common/i18n.h"
35 #include "../common/compliance.h"
37 struct decrypt_filter_parm_s
45 int any_data; /* did we push anything through the filter at all? */
46 unsigned char lastblock[16]; /* to strip the padding we have to
48 char helpblock[16]; /* needed because there is no block buffering in
55 /* Decrypt the session key and fill in the parm structure. The
56 algo and the IV is expected to be already in PARM. */
58 prepare_decryption (ctrl_t ctrl, const char *hexkeygrip, const char *desc,
59 ksba_const_sexp_t enc_val,
60 struct decrypt_filter_parm_s *parm)
66 rc = gpgsm_agent_pkdecrypt (ctrl, hexkeygrip, desc, enc_val,
70 log_error ("error decrypting session key: %s\n", gpg_strerror (rc));
75 log_printhex ("pkcs1 encoded session key:", seskey, seskeylen);
78 if (seskeylen == 32 || seskeylen == 24 || seskeylen == 16)
80 /* Smells like an AES-128, 3-DES, or AES-256 key. This might
81 * happen because a SC has already done the unpacking. A better
82 * solution would be to test for this only after we triggered
83 * the GPG_ERR_INV_SESSION_KEY. */
87 if (n + 7 > seskeylen )
89 rc = gpg_error (GPG_ERR_INV_SESSION_KEY);
93 /* FIXME: Actually the leading zero is required but due to the way
94 we encode the output in libgcrypt as an MPI we are not able to
95 encode that leading zero. However, when using a Smartcard we are
96 doing it the right way and therefore we have to skip the zero. This
97 should be fixed in gpg-agent of course. */
101 if (seskey[n] != 2 ) /* Wrong block type version. */
103 rc = gpg_error (GPG_ERR_INV_SESSION_KEY);
107 for (n++; n < seskeylen && seskey[n]; n++) /* Skip the random bytes. */
109 n++; /* and the zero byte */
112 rc = gpg_error (GPG_ERR_INV_SESSION_KEY);
118 log_printhex ("session key:", seskey+n, seskeylen-n);
120 rc = gcry_cipher_open (&parm->hd, parm->algo, parm->mode, 0);
123 log_error ("error creating decryptor: %s\n", gpg_strerror (rc));
127 rc = gcry_cipher_setkey (parm->hd, seskey+n, seskeylen-n);
128 if (gpg_err_code (rc) == GPG_ERR_WEAK_KEY)
130 log_info (_("WARNING: message was encrypted with "
131 "a weak key in the symmetric cipher.\n"));
136 log_error("key setup failed: %s\n", gpg_strerror(rc) );
140 gcry_cipher_setiv (parm->hd, parm->iv, parm->ivlen);
148 /* This function is called by the KSBA writer just before the actual
149 write is done. The function must take INLEN bytes from INBUF,
150 decrypt it and store it inoutbuf which has a maximum size of
151 maxoutlen. The valid bytes in outbuf should be return in outlen.
152 Due to different buffer sizes or different length of input and
153 output, it may happen that fewer bytes are processed or fewer bytes
156 decrypt_filter (void *arg,
157 const void *inbuf, size_t inlen, size_t *inused,
158 void *outbuf, size_t maxoutlen, size_t *outlen)
160 struct decrypt_filter_parm_s *parm = arg;
161 int blklen = parm->blklen;
162 size_t orig_inlen = inlen;
164 /* fixme: Should we issue an error when we have not seen one full block? */
166 return gpg_error (GPG_ERR_BUG);
168 if (maxoutlen < 2*parm->blklen)
169 return gpg_error (GPG_ERR_BUG);
170 /* Make some space because we will later need an extra block at the end. */
173 if (parm->helpblocklen)
177 for (i=parm->helpblocklen,j=0; i < blklen && j < inlen; i++, j++)
178 parm->helpblock[i] = ((const char*)inbuf)[j];
180 if (blklen > maxoutlen)
181 return gpg_error (GPG_ERR_BUG);
184 parm->helpblocklen = i;
189 parm->helpblocklen = 0;
192 memcpy (outbuf, parm->lastblock, blklen);
197 gcry_cipher_decrypt (parm->hd, parm->lastblock, blklen,
198 parm->helpblock, blklen);
201 *inused = orig_inlen - inlen;
206 if (inlen > maxoutlen)
209 { /* store the remainder away */
210 parm->helpblocklen = inlen%blklen;
211 inlen = inlen/blklen*blklen;
212 memcpy (parm->helpblock, (const char*)inbuf+inlen, parm->helpblocklen);
215 *inused = inlen + parm->helpblocklen;
218 assert (inlen >= blklen);
221 gcry_cipher_decrypt (parm->hd, (char*)outbuf+blklen, inlen,
223 memcpy (outbuf, parm->lastblock, blklen);
224 memcpy (parm->lastblock,(char*)outbuf+inlen, blklen);
229 gcry_cipher_decrypt (parm->hd, outbuf, inlen, inbuf, inlen);
230 memcpy (parm->lastblock, (char*)outbuf+inlen-blklen, blklen);
231 *outlen = inlen - blklen;
242 /* Perform a decrypt operation. */
244 gpgsm_decrypt (ctrl_t ctrl, int in_fd, estream_t out_fp)
247 gnupg_ksba_io_t b64reader = NULL;
248 gnupg_ksba_io_t b64writer = NULL;
249 ksba_reader_t reader;
250 ksba_writer_t writer;
251 ksba_cms_t cms = NULL;
252 ksba_stop_reason_t stopreason;
255 estream_t in_fp = NULL;
256 struct decrypt_filter_parm_s dfparm;
258 memset (&dfparm, 0, sizeof dfparm);
260 audit_set_type (ctrl->audit, AUDIT_TYPE_DECRYPT);
265 log_error (_("failed to allocate keyDB handle\n"));
266 rc = gpg_error (GPG_ERR_GENERAL);
270 in_fp = es_fdopen_nc (in_fd, "rb");
273 rc = gpg_error_from_syserror ();
274 log_error ("fdopen() failed: %s\n", strerror (errno));
278 rc = gnupg_ksba_create_reader
279 (&b64reader, ((ctrl->is_pem? GNUPG_KSBA_IO_PEM : 0)
280 | (ctrl->is_base64? GNUPG_KSBA_IO_BASE64 : 0)
281 | (ctrl->autodetect_encoding? GNUPG_KSBA_IO_AUTODETECT : 0)),
285 log_error ("can't create reader: %s\n", gpg_strerror (rc));
289 rc = gnupg_ksba_create_writer
290 (&b64writer, ((ctrl->create_pem? GNUPG_KSBA_IO_PEM : 0)
291 | (ctrl->create_base64? GNUPG_KSBA_IO_BASE64 : 0)),
292 ctrl->pem_name, out_fp, &writer);
295 log_error ("can't create writer: %s\n", gpg_strerror (rc));
299 rc = ksba_cms_new (&cms);
303 rc = ksba_cms_set_reader_writer (cms, reader, writer);
306 log_debug ("ksba_cms_set_reader_writer failed: %s\n",
311 audit_log (ctrl->audit, AUDIT_SETUP_READY);
316 rc = ksba_cms_parse (cms, &stopreason);
319 log_debug ("ksba_cms_parse failed: %s\n", gpg_strerror (rc));
323 if (stopreason == KSBA_SR_BEGIN_DATA
324 || stopreason == KSBA_SR_DETACHED_DATA)
329 int is_de_vs; /* Computed compliance with CO_DE_VS. */
331 audit_log (ctrl->audit, AUDIT_GOT_DATA);
333 algoid = ksba_cms_get_content_oid (cms, 2/* encryption algo*/);
334 algo = gcry_cipher_map_name (algoid);
335 mode = gcry_cipher_mode_from_oid (algoid);
338 rc = gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
339 log_error ("unsupported algorithm '%s'\n", algoid? algoid:"?");
340 if (algoid && !strcmp (algoid, "1.2.840.113549.3.2"))
341 log_info (_("(this is the RC2 algorithm)\n"));
343 log_info (_("(this does not seem to be an encrypted"
347 sprintf (numbuf, "%d", rc);
348 gpgsm_status2 (ctrl, STATUS_ERROR, "decrypt.algorithm",
349 numbuf, algoid?algoid:"?", NULL);
350 audit_log_s (ctrl->audit, AUDIT_BAD_DATA_CIPHER_ALGO, algoid);
353 /* If it seems that this is not an encrypted message we
354 return a more sensible error code. */
356 rc = gpg_error (GPG_ERR_NO_DATA);
361 /* Check compliance. */
362 if (! gnupg_cipher_is_allowed (opt.compliance, 0, algo, mode))
364 log_error (_("cipher algorithm '%s'"
365 " may not be used in %s mode\n"),
366 gcry_cipher_algo_name (algo),
367 gnupg_compliance_option_string (opt.compliance));
368 rc = gpg_error (GPG_ERR_CIPHER_ALGO);
372 /* For CMS, CO_DE_VS demands CBC mode. */
373 is_de_vs = gnupg_cipher_is_compliant (CO_DE_VS, algo, mode);
375 audit_log_i (ctrl->audit, AUDIT_DATA_CIPHER_ALGO, algo);
378 dfparm.blklen = gcry_cipher_get_algo_blklen (algo);
379 if (dfparm.blklen > sizeof (dfparm.helpblock))
380 return gpg_error (GPG_ERR_BUG);
382 rc = ksba_cms_get_content_enc_iv (cms,
388 log_error ("error getting IV: %s\n", gpg_strerror (rc));
392 for (recp=0; !any_key; recp++)
397 char *hexkeygrip = NULL;
403 rc = ksba_cms_get_issuer_serial (cms, recp, &issuer, &serial);
404 if (rc == -1 && recp)
405 break; /* no more recipients */
406 audit_log_i (ctrl->audit, AUDIT_NEW_RECP, recp);
408 log_error ("recp %d - error getting info: %s\n",
409 recp, gpg_strerror (rc));
412 ksba_cert_t cert = NULL;
414 log_debug ("recp %d - issuer: '%s'\n",
415 recp, issuer? issuer:"[NONE]");
416 log_debug ("recp %d - serial: ", recp);
417 gpgsm_dump_serial (serial);
422 char *tmpstr = gpgsm_format_sn_issuer (serial, issuer);
423 audit_log_s (ctrl->audit, AUDIT_RECP_NAME, tmpstr);
427 keydb_search_reset (kh);
428 rc = keydb_search_issuer_sn (ctrl, kh, issuer, serial);
431 log_error ("failed to find the certificate: %s\n",
436 rc = keydb_get_cert (kh, &cert);
439 log_error ("failed to get cert: %s\n", gpg_strerror (rc));
443 /* Print the ENC_TO status line. Note that we can
444 do so only if we have the certificate. This is
445 in contrast to gpg where the keyID is commonly
446 included in the encrypted messages. It is too
447 cumbersome to retrieve the used algorithm, thus
448 we don't print it for now. We also record the
449 keyid for later use. */
451 unsigned long kid[2];
453 kid[0] = gpgsm_get_short_fingerprint (cert, kid+1);
454 snprintf (kidbuf, sizeof kidbuf, "%08lX%08lX",
456 gpgsm_status2 (ctrl, STATUS_ENC_TO,
457 kidbuf, "0", "0", NULL);
460 /* Put the certificate into the audit log. */
461 audit_log_cert (ctrl->audit, AUDIT_SAVE_CERT, cert, 0);
463 /* Just in case there is a problem with the own
464 certificate we print this message - should never
466 rc = gpgsm_cert_use_decrypt_p (cert);
470 sprintf (numbuf, "%d", rc);
471 gpgsm_status2 (ctrl, STATUS_ERROR, "decrypt.keyusage",
476 hexkeygrip = gpgsm_get_keygrip_hexstring (cert);
477 desc = gpgsm_format_keydesc (cert);
481 int pk_algo = gpgsm_get_key_algo_info (cert, &nbits);
483 /* Check compliance. */
484 if (!gnupg_pk_is_allowed (opt.compliance,
486 pk_algo, NULL, nbits, NULL))
490 snprintf (kidstr, sizeof kidstr, "0x%08lX",
491 gpgsm_get_short_fingerprint (cert, NULL));
493 (_("key %s is not suitable for decryption"
496 gnupg_compliance_option_string (opt.compliance));
497 rc = gpg_error (GPG_ERR_PUBKEY_ALGO);
501 /* Check that all certs are compliant with CO_DE_VS. */
504 && gnupg_pk_is_compliant (CO_DE_VS, pk_algo, NULL,
511 /* We cannot check compliance of certs that we
517 ksba_cert_release (cert);
522 else if (!(enc_val = ksba_cms_get_enc_val (cms, recp)))
523 log_error ("recp %d - error getting encrypted session key\n",
527 rc = prepare_decryption (ctrl,
528 hexkeygrip, desc, enc_val, &dfparm);
532 log_info ("decrypting session key failed: %s\n",
534 if (gpg_err_code (rc) == GPG_ERR_NO_SECKEY && *kidbuf)
535 gpgsm_status2 (ctrl, STATUS_NO_SECKEY, kidbuf, NULL);
538 { /* setup the bulk decrypter */
540 ksba_writer_set_filter (writer,
545 gpgsm_status (ctrl, STATUS_DECRYPTION_COMPLIANCE_MODE,
546 gnupg_status_compliance_flag (CO_DE_VS));
549 audit_log_ok (ctrl->audit, AUDIT_RECP_RESULT, rc);
555 /* If we write an audit log add the unused recipients to the
557 if (ctrl->audit && any_key)
565 tmp_rc = ksba_cms_get_issuer_serial (cms, recp,
568 break; /* no more recipients */
569 audit_log_i (ctrl->audit, AUDIT_NEW_RECP, recp);
571 log_error ("recp %d - error getting info: %s\n",
572 recp, gpg_strerror (rc));
575 char *tmpstr = gpgsm_format_sn_issuer (serial, issuer);
576 audit_log_s (ctrl->audit, AUDIT_RECP_NAME, tmpstr);
586 rc = gpg_error (GPG_ERR_NO_SECKEY);
590 else if (stopreason == KSBA_SR_END_DATA)
592 ksba_writer_set_filter (writer, NULL, NULL);
594 { /* write the last block with padding removed */
595 int i, npadding = dfparm.lastblock[dfparm.blklen-1];
596 if (!npadding || npadding > dfparm.blklen)
598 log_error ("invalid padding with value %d\n", npadding);
599 rc = gpg_error (GPG_ERR_INV_DATA);
602 rc = ksba_writer_write (writer,
604 dfparm.blklen - npadding);
608 for (i=dfparm.blklen - npadding; i < dfparm.blklen; i++)
610 if (dfparm.lastblock[i] != npadding)
612 log_error ("inconsistent padding\n");
613 rc = gpg_error (GPG_ERR_INV_DATA);
621 while (stopreason != KSBA_SR_READY);
623 rc = gnupg_ksba_finish_writer (b64writer);
626 log_error ("write failed: %s\n", gpg_strerror (rc));
629 gpgsm_status (ctrl, STATUS_DECRYPTION_OKAY, NULL);
633 audit_log_ok (ctrl->audit, AUDIT_DECRYPTION_RESULT, rc);
636 gpgsm_status (ctrl, STATUS_DECRYPTION_FAILED, NULL);
637 log_error ("message decryption failed: %s <%s>\n",
638 gpg_strerror (rc), gpg_strsource (rc));
640 ksba_cms_release (cms);
641 gnupg_ksba_destroy_reader (b64reader);
642 gnupg_ksba_destroy_writer (b64writer);
646 gcry_cipher_close (dfparm.hd);