1
0
mirror of git://git.gnupg.org/gnupg.git synced 2024-12-23 10:29:58 +01:00
gnupg/g10/pubkey-enc.c

432 lines
12 KiB
C
Raw Normal View History

2010-04-21 17:30:07 +00:00
/* pubkey-enc.c - Process a public key encoded packet.
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2006, 2009,
* 2010 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
2007-07-04 19:49:40 +00:00
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GnuPG is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
2007-07-04 19:49:40 +00:00
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "gpg.h"
#include "util.h"
#include "packet.h"
#include "keydb.h"
#include "trustdb.h"
#include "cipher.h"
#include "status.h"
#include "options.h"
#include "main.h"
#include "i18n.h"
#include "pkglue.h"
#include "call-agent.h"
2010-04-21 17:30:07 +00:00
static gpg_error_t get_it (PKT_pubkey_enc *k,
DEK *dek, PKT_public_key *sk, u32 *keyid);
2010-04-21 17:30:07 +00:00
/* Check that the given algo is mentioned in one of the valid user-ids. */
static int
2010-04-21 17:30:07 +00:00
is_algo_in_prefs (kbnode_t keyblock, preftype_t type, int algo)
{
2010-04-21 17:30:07 +00:00
kbnode_t k;
for (k = keyblock; k; k = k->next)
{
if (k->pkt->pkttype == PKT_USER_ID)
{
PKT_user_id *uid = k->pkt->pkt.user_id;
prefitem_t *prefs = uid->prefs;
if (uid->created && prefs && !uid->is_revoked && !uid->is_expired)
{
for (; prefs->type; prefs++)
if (prefs->type == type && prefs->value == algo)
return 1;
}
}
}
2010-04-21 17:30:07 +00:00
return 0;
}
2010-04-21 17:30:07 +00:00
/*
* Get the session key from a pubkey enc packet and return it in DEK,
* which should have been allocated in secure memory by the caller.
*/
2010-04-21 17:30:07 +00:00
gpg_error_t
get_session_key (PKT_pubkey_enc * k, DEK * dek)
{
PKT_public_key *sk = NULL;
2010-04-21 17:30:07 +00:00
int rc;
gpg: Cache keybox searches. * common/iobuf.c (iobuf_seek): Fix for temp streams. * g10/pubkey-enc.c (get_session_key, get_it): Add some log_clock calls. * g10/keydb.c (dump_search_desc): New. (enum_keyblock_states, struct keyblock_cache): New. (keyblock_cache_clear): New. (keydb_get_keyblock, keydb_search): Implement a keyblock cache. (keydb_update_keyblock, keydb_insert_keyblock, keydb_delete_keyblock) (keydb_rebuild_caches, keydb_search_reset): Clear the cache. -- Gpg uses the key database at several places without a central coordination. This leads to several scans of the keybox for the same key. To improve that we now use a simple cache to store a retrieved keyblock in certain cases. In theory this caching could also be done for old keyrings, but it is a bit more work and questionable whether it is needed; the keybox scheme is anyway much faster than keyrings. Using a keybox with 20000 384 bit ECDSA/ECHD keypairs and a 252 byte sample text we get these values for encrypt and decrypt operations on an Core i5 4*3.33Ghz system. The option --trust-model=always is used. Times are given in milliseconds wall time. | | enc | dec | dec,q | |-----------+-----+-----+-------| | key 1 | 48 | 96 | 70 | | key 10000 | 60 | 98 | 80 | | key 20000 | 69 | 106 | 88 | | 10 keys | 540 | 290 | 70 | The 10 keys test uses a mix of keys, the first one is used for decryption but all keys are looked up so that information about are printed. The last column gives decryption results w/o information printing (--quiet). The keybox is always scanned sequentially without using any index. By adding an index to the keybox it will be possible to further reduce the time required for keys stored to the end of the file.
2013-01-08 14:44:49 +01:00
if (DBG_CLOCK)
log_clock ("get_session_key enter");
2010-04-21 17:30:07 +00:00
rc = openpgp_pk_test_algo2 (k->pubkey_algo, PUBKEY_USAGE_ENC);
if (rc)
goto leave;
if ((k->keyid[0] || k->keyid[1]) && !opt.try_all_secrets)
{
sk = xmalloc_clear (sizeof *sk);
sk->pubkey_algo = k->pubkey_algo; /* We want a pubkey with this algo. */
2010-04-21 17:30:07 +00:00
if (!(rc = get_seckey (sk, k->keyid)))
rc = get_it (k, dek, sk, k->keyid);
}
2010-04-21 17:30:07 +00:00
else if (opt.skip_hidden_recipients)
rc = gpg_error (GPG_ERR_NO_SECKEY);
else /* Anonymous receiver: Try all available secret keys. */
{
void *enum_context = NULL;
u32 keyid[2];
for (;;)
{
2011-09-20 19:24:52 +02:00
free_public_key (sk);
2010-04-21 17:30:07 +00:00
sk = xmalloc_clear (sizeof *sk);
2010-10-13 15:57:08 +00:00
rc = enum_secret_keys (&enum_context, sk);
2010-04-21 17:30:07 +00:00
if (rc)
{
rc = G10ERR_NO_SECKEY;
break;
}
if (sk->pubkey_algo != k->pubkey_algo)
continue;
2010-10-13 15:57:08 +00:00
if (!(sk->pubkey_usage & PUBKEY_USAGE_ENC))
continue;
keyid_from_pk (sk, keyid);
if (!opt.quiet)
log_info (_("anonymous recipient; trying secret key %s ...\n"),
keystr (keyid));
2010-04-21 17:30:07 +00:00
2010-10-13 15:57:08 +00:00
rc = get_it (k, dek, sk, keyid);
2010-04-21 17:30:07 +00:00
if (!rc)
{
if (!opt.quiet)
log_info (_("okay, we are the anonymous recipient.\n"));
2010-04-21 17:30:07 +00:00
break;
}
2010-10-13 15:57:08 +00:00
else if (gpg_err_code (rc) == GPG_ERR_FULLY_CANCELED)
break; /* Don't try any more secret keys. */
2010-04-21 17:30:07 +00:00
}
2010-10-13 15:57:08 +00:00
enum_secret_keys (&enum_context, NULL); /* free context */
}
2010-04-21 17:30:07 +00:00
leave:
2011-09-20 19:24:52 +02:00
free_public_key (sk);
gpg: Cache keybox searches. * common/iobuf.c (iobuf_seek): Fix for temp streams. * g10/pubkey-enc.c (get_session_key, get_it): Add some log_clock calls. * g10/keydb.c (dump_search_desc): New. (enum_keyblock_states, struct keyblock_cache): New. (keyblock_cache_clear): New. (keydb_get_keyblock, keydb_search): Implement a keyblock cache. (keydb_update_keyblock, keydb_insert_keyblock, keydb_delete_keyblock) (keydb_rebuild_caches, keydb_search_reset): Clear the cache. -- Gpg uses the key database at several places without a central coordination. This leads to several scans of the keybox for the same key. To improve that we now use a simple cache to store a retrieved keyblock in certain cases. In theory this caching could also be done for old keyrings, but it is a bit more work and questionable whether it is needed; the keybox scheme is anyway much faster than keyrings. Using a keybox with 20000 384 bit ECDSA/ECHD keypairs and a 252 byte sample text we get these values for encrypt and decrypt operations on an Core i5 4*3.33Ghz system. The option --trust-model=always is used. Times are given in milliseconds wall time. | | enc | dec | dec,q | |-----------+-----+-----+-------| | key 1 | 48 | 96 | 70 | | key 10000 | 60 | 98 | 80 | | key 20000 | 69 | 106 | 88 | | 10 keys | 540 | 290 | 70 | The 10 keys test uses a mix of keys, the first one is used for decryption but all keys are looked up so that information about are printed. The last column gives decryption results w/o information printing (--quiet). The keybox is always scanned sequentially without using any index. By adding an index to the keybox it will be possible to further reduce the time required for keys stored to the end of the file.
2013-01-08 14:44:49 +01:00
if (DBG_CLOCK)
log_clock ("get_session_key leave");
2010-04-21 17:30:07 +00:00
return rc;
}
2010-04-21 17:30:07 +00:00
static gpg_error_t
get_it (PKT_pubkey_enc *enc, DEK *dek, PKT_public_key *sk, u32 *keyid)
{
gpg_error_t err;
byte *frame = NULL;
unsigned int n;
size_t nframe;
u16 csum, csum2;
int padding;
gcry_sexp_t s_data;
char *desc;
char *keygrip;
byte fp[MAX_FINGERPRINT_LEN];
size_t fpn;
const int pkalgo = map_pk_openpgp_to_gcry (sk->pubkey_algo);
gpg: Cache keybox searches. * common/iobuf.c (iobuf_seek): Fix for temp streams. * g10/pubkey-enc.c (get_session_key, get_it): Add some log_clock calls. * g10/keydb.c (dump_search_desc): New. (enum_keyblock_states, struct keyblock_cache): New. (keyblock_cache_clear): New. (keydb_get_keyblock, keydb_search): Implement a keyblock cache. (keydb_update_keyblock, keydb_insert_keyblock, keydb_delete_keyblock) (keydb_rebuild_caches, keydb_search_reset): Clear the cache. -- Gpg uses the key database at several places without a central coordination. This leads to several scans of the keybox for the same key. To improve that we now use a simple cache to store a retrieved keyblock in certain cases. In theory this caching could also be done for old keyrings, but it is a bit more work and questionable whether it is needed; the keybox scheme is anyway much faster than keyrings. Using a keybox with 20000 384 bit ECDSA/ECHD keypairs and a 252 byte sample text we get these values for encrypt and decrypt operations on an Core i5 4*3.33Ghz system. The option --trust-model=always is used. Times are given in milliseconds wall time. | | enc | dec | dec,q | |-----------+-----+-----+-------| | key 1 | 48 | 96 | 70 | | key 10000 | 60 | 98 | 80 | | key 20000 | 69 | 106 | 88 | | 10 keys | 540 | 290 | 70 | The 10 keys test uses a mix of keys, the first one is used for decryption but all keys are looked up so that information about are printed. The last column gives decryption results w/o information printing (--quiet). The keybox is always scanned sequentially without using any index. By adding an index to the keybox it will be possible to further reduce the time required for keys stored to the end of the file.
2013-01-08 14:44:49 +01:00
if (DBG_CLOCK)
log_clock ("decryption start");
/* Get the keygrip. */
err = hexkeygrip_from_pk (sk, &keygrip);
if (err)
goto leave;
/* Convert the data to an S-expression. */
if (pkalgo == GCRY_PK_ELG || pkalgo == GCRY_PK_ELG_E)
{
if (!enc->data[0] || !enc->data[1])
err = gpg_error (GPG_ERR_BAD_MPI);
else
err = gcry_sexp_build (&s_data, NULL, "(enc-val(elg(a%m)(b%m)))",
enc->data[0], enc->data[1]);
}
else if (pkalgo == GCRY_PK_RSA || pkalgo == GCRY_PK_RSA_E)
{
if (!enc->data[0])
err = gpg_error (GPG_ERR_BAD_MPI);
else
err = gcry_sexp_build (&s_data, NULL, "(enc-val(rsa(a%m)))",
enc->data[0]);
}
else if (pkalgo == GCRY_PK_ECDH)
{
if (!enc->data[0] || !enc->data[1])
err = gpg_error (GPG_ERR_BAD_MPI);
else
err = gcry_sexp_build (&s_data, NULL, "(enc-val(ecdh(s%m)(e%m)))",
enc->data[0], enc->data[1]);
}
else
err = gpg_error (GPG_ERR_BUG);
if (err)
goto leave;
if (sk->pubkey_algo == PUBKEY_ALGO_ECDH)
{
fingerprint_from_pk (sk, fp, &fpn);
assert (fpn == 20);
}
/* Decrypt. */
desc = gpg_format_keydesc (sk, 0, 1);
gpg: Add pinentry-mode feature. * g10/gpg.c: Include shareddefs.h. (main): Add option --pinentry-mode. * g10/options.h (struct opt): Add field pinentry_mode. * g10/passphrase.c: Include shareddefs.h. (have_static_passphrase): Take care of loopback pinentry_mode. (read_passphrase_from_fd): Ditto. (get_static_passphrase): New. (passphrase_to_dek_ext): Factor some code out to ... (emit_status_need_passphrase): new. * g10/call-agent.c (start_agent): Send the pinentry mode. (default_inq_cb): Take care of the PASSPHRASE inquiry. Return a proper error code. (agent_pksign): Add args keyid, mainkeyid and pubkey_algo. (agent_pkdecrypt): Ditto. * g10/pubkey-enc.c (get_it): Pass new args. * g10/sign.c (do_sign): Pass new args. * g10/call-agent.c (struct default_inq_parm_s): New. Change all similar structs to reference this one. Change all users and inquire callback to use this struct, instead of NULL or some undefined but not used structs. This change will help to eventually get rid of global variables. -- This new features allows to use gpg without a Pinentry. As a prerequisite the agent must be configured to allow the loopback pinentry mode (option --allow-loopback-pinentry). For example gpg2 --pinentry-mode=loopback FILE.gpg may be used to decrypt FILE.gpg while entering the passphrase on the tty. If batch is used, --passphrase et al. may be used, if --command-fd is used, the passphrase may be provided by another process. Note that there are no try-again prompts in case of a bad passphrase.
2013-02-07 20:37:58 +01:00
err = agent_pkdecrypt (NULL, keygrip,
desc, sk->keyid, sk->main_keyid, sk->pubkey_algo,
s_data, &frame, &nframe, &padding);
xfree (desc);
gcry_sexp_release (s_data);
if (err)
goto leave;
2010-04-21 17:30:07 +00:00
/* Now get the DEK (data encryption key) from the frame
*
* Old versions encode the DEK in in this format (msb is left):
*
* 0 1 DEK(16 bytes) CSUM(2 bytes) 0 RND(n bytes) 2
*
* Later versions encode the DEK like this:
*
* 0 2 RND(n bytes) 0 A DEK(k bytes) CSUM(2 bytes)
*
* (mpi_get_buffer already removed the leading zero).
*
* RND are non-zero randow bytes.
* A is the cipher algorithm
* DEK is the encryption key (session key) with length k
* CSUM
*/
if (DBG_CIPHER)
log_printhex ("DEK frame:", frame, nframe);
n = 0;
if (sk->pubkey_algo == PUBKEY_ALGO_ECDH)
{
gcry_mpi_t shared_mpi;
gcry_mpi_t decoded;
/* At the beginning the frame are the bytes of shared point MPI. */
err = gcry_mpi_scan (&shared_mpi, GCRYMPI_FMT_USG, frame, nframe, NULL);
if (err)
{
err = gpg_error (GPG_ERR_WRONG_SECKEY);
goto leave;
}
err = pk_ecdh_decrypt (&decoded, fp, enc->data[1]/*encr data as an MPI*/,
shared_mpi, sk->pkey);
mpi_release (shared_mpi);
if(err)
goto leave;
/* Reuse NFRAME, which size is sufficient to include the session key. */
err = gcry_mpi_print (GCRYMPI_FMT_USG, frame, nframe, &nframe, decoded);
mpi_release (decoded);
if (err)
goto leave;
/* Now the frame are the bytes decrypted but padded session key. */
/* Allow double padding for the benefit of DEK size concealment.
Higher than this is wasteful. */
if (!nframe || frame[nframe-1] > 8*2 || nframe <= 8
|| frame[nframe-1] > nframe)
{
err = gpg_error (GPG_ERR_WRONG_SECKEY);
goto leave;
}
nframe -= frame[nframe-1]; /* Remove padding. */
assert (!n); /* (used just below) */
}
else
{
if (padding)
{
if (n + 7 > nframe)
{
err = gpg_error (GPG_ERR_WRONG_SECKEY);
goto leave;
}
if (frame[n] == 1 && frame[nframe - 1] == 2)
{
log_info (_("old encoding of the DEK is not supported\n"));
err = gpg_error (GPG_ERR_CIPHER_ALGO);
goto leave;
}
if (frame[n] != 2) /* Something went wrong. */
{
err = gpg_error (GPG_ERR_WRONG_SECKEY);
goto leave;
}
for (n++; n < nframe && frame[n]; n++) /* Skip the random bytes. */
;
n++; /* Skip the zero byte. */
}
}
2010-04-21 17:30:07 +00:00
if (n + 4 > nframe)
{
err = gpg_error (GPG_ERR_WRONG_SECKEY);
2010-04-21 17:30:07 +00:00
goto leave;
}
2010-04-21 17:30:07 +00:00
dek->keylen = nframe - (n + 1) - 2;
dek->algo = frame[n++];
err = openpgp_cipher_test_algo (dek->algo);
if (err)
2010-04-21 17:30:07 +00:00
{
if (!opt.quiet && gpg_err_code (err) == GPG_ERR_CIPHER_ALGO)
2010-04-21 17:30:07 +00:00
{
log_info (_("cipher algorithm %d%s is unknown or disabled\n"),
dek->algo,
dek->algo == CIPHER_ALGO_IDEA ? " (IDEA)" : "");
}
dek->algo = 0;
goto leave;
}
2010-04-21 17:30:07 +00:00
if (dek->keylen != openpgp_cipher_get_algo_keylen (dek->algo))
{
err = gpg_error (GPG_ERR_WRONG_SECKEY);
2010-04-21 17:30:07 +00:00
goto leave;
}
2010-04-21 17:30:07 +00:00
/* Copy the key to DEK and compare the checksum. */
csum = frame[nframe - 2] << 8;
csum |= frame[nframe - 1];
memcpy (dek->key, frame + n, dek->keylen);
for (csum2 = 0, n = 0; n < dek->keylen; n++)
csum2 += dek->key[n];
if (csum != csum2)
{
err = gpg_error (GPG_ERR_WRONG_SECKEY);
2010-04-21 17:30:07 +00:00
goto leave;
}
gpg: Cache keybox searches. * common/iobuf.c (iobuf_seek): Fix for temp streams. * g10/pubkey-enc.c (get_session_key, get_it): Add some log_clock calls. * g10/keydb.c (dump_search_desc): New. (enum_keyblock_states, struct keyblock_cache): New. (keyblock_cache_clear): New. (keydb_get_keyblock, keydb_search): Implement a keyblock cache. (keydb_update_keyblock, keydb_insert_keyblock, keydb_delete_keyblock) (keydb_rebuild_caches, keydb_search_reset): Clear the cache. -- Gpg uses the key database at several places without a central coordination. This leads to several scans of the keybox for the same key. To improve that we now use a simple cache to store a retrieved keyblock in certain cases. In theory this caching could also be done for old keyrings, but it is a bit more work and questionable whether it is needed; the keybox scheme is anyway much faster than keyrings. Using a keybox with 20000 384 bit ECDSA/ECHD keypairs and a 252 byte sample text we get these values for encrypt and decrypt operations on an Core i5 4*3.33Ghz system. The option --trust-model=always is used. Times are given in milliseconds wall time. | | enc | dec | dec,q | |-----------+-----+-----+-------| | key 1 | 48 | 96 | 70 | | key 10000 | 60 | 98 | 80 | | key 20000 | 69 | 106 | 88 | | 10 keys | 540 | 290 | 70 | The 10 keys test uses a mix of keys, the first one is used for decryption but all keys are looked up so that information about are printed. The last column gives decryption results w/o information printing (--quiet). The keybox is always scanned sequentially without using any index. By adding an index to the keybox it will be possible to further reduce the time required for keys stored to the end of the file.
2013-01-08 14:44:49 +01:00
if (DBG_CLOCK)
log_clock ("decryption ready");
2010-04-21 17:30:07 +00:00
if (DBG_CIPHER)
log_printhex ("DEK is:", dek->key, dek->keylen);
2010-04-21 17:30:07 +00:00
/* Check that the algo is in the preferences and whether it has expired. */
{
PKT_public_key *pk = NULL;
KBNODE pkb = get_pubkeyblock (keyid);
2010-04-21 17:30:07 +00:00
if (!pkb)
{
err = -1;
2010-04-21 17:30:07 +00:00
log_error ("oops: public key not found for preference check\n");
}
else if (pkb->pkt->pkt.public_key->selfsigversion > 3
&& dek->algo != CIPHER_ALGO_3DES
&& !opt.quiet
&& !is_algo_in_prefs (pkb, PREFTYPE_SYM, dek->algo))
log_info (_("WARNING: cipher algorithm %s not found in recipient"
" preferences\n"), openpgp_cipher_algo_name (dek->algo));
if (!err)
2010-04-21 17:30:07 +00:00
{
KBNODE k;
for (k = pkb; k; k = k->next)
{
if (k->pkt->pkttype == PKT_PUBLIC_KEY
|| k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
{
u32 aki[2];
keyid_from_pk (k->pkt->pkt.public_key, aki);
if (aki[0] == keyid[0] && aki[1] == keyid[1])
{
pk = k->pkt->pkt.public_key;
break;
}
}
}
if (!pk)
BUG ();
if (pk->expiredate && pk->expiredate <= make_timestamp ())
{
log_info (_("NOTE: secret key %s expired at %s\n"),
keystr (keyid), asctimestamp (pk->expiredate));
}
}
if (pk && pk->flags.revoked)
2010-04-21 17:30:07 +00:00
{
log_info (_("NOTE: key has been revoked"));
log_printf ("\n");
show_revocation_reason (pk, 1);
}
release_kbnode (pkb);
err = 0;
2010-04-21 17:30:07 +00:00
}
leave:
2010-04-21 17:30:07 +00:00
xfree (frame);
xfree (keygrip);
return err;
}
2010-04-21 17:30:07 +00:00
/*
* Get the session key from the given string.
* String is supposed to be formatted as this:
* <algo-id>:<even-number-of-hex-digits>
*/
2010-04-21 17:30:07 +00:00
gpg_error_t
get_override_session_key (DEK *dek, const char *string)
{
2010-04-21 17:30:07 +00:00
const char *s;
int i;
if (!string)
return G10ERR_BAD_KEY;
dek->algo = atoi (string);
if (dek->algo < 1)
return G10ERR_BAD_KEY;
if (!(s = strchr (string, ':')))
return G10ERR_BAD_KEY;
s++;
for (i = 0; i < DIM (dek->key) && *s; i++, s += 2)
{
int c = hextobyte (s);
if (c == -1)
return G10ERR_BAD_KEY;
dek->key[i] = c;
}
2010-04-21 17:30:07 +00:00
if (*s)
return G10ERR_BAD_KEY;
dek->keylen = i;
return 0;
}