diff --git a/agent/cvt-openpgp.c b/agent/cvt-openpgp.c
index e6a14c436..3dba79ebd 100644
--- a/agent/cvt-openpgp.c
+++ b/agent/cvt-openpgp.c
@@ -1,1091 +1,1129 @@
/* cvt-openpgp.c - Convert an OpenPGP key to our internal format.
* 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
* 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
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include "agent.h"
#include "i18n.h"
#include "cvt-openpgp.h"
+#include "../include/cipher.h" /* for PUBKEY_ALGO_ECDSA, PUBKEY_ALGO_ECDH */
/* Helper to pass data via the callback to do_unprotect. */
struct try_do_unprotect_arg_s
{
int is_v4;
int is_protected;
int pubkey_algo;
int protect_algo;
char *iv;
int ivlen;
int s2k_mode;
int s2k_algo;
byte *s2k_salt;
u32 s2k_count;
u16 desired_csum;
gcry_mpi_t *skey;
size_t skeysize;
int skeyidx;
gcry_sexp_t *r_key;
};
-
+/* TODO: it is also in misc, which is not linked with the agent */
+static int
+map_pk_openpgp_to_gcry (int algo)
+{
+ return (algo==PUBKEY_ALGO_ECDSA ? GCRY_PK_ECDSA : (algo==PUBKEY_ALGO_ECDH ? GCRY_PK_ECDH : algo));
+}
/* Compute the keygrip from the public key and store it at GRIP. */
static gpg_error_t
get_keygrip (int pubkey_algo, gcry_mpi_t *pkey, unsigned char *grip)
{
gpg_error_t err;
gcry_sexp_t s_pkey = NULL;
switch (pubkey_algo)
{
case GCRY_PK_DSA:
err = gcry_sexp_build (&s_pkey, NULL,
"(public-key(dsa(p%m)(q%m)(g%m)(y%m)))",
pkey[0], pkey[1], pkey[2], pkey[3]);
break;
case GCRY_PK_ELG:
case GCRY_PK_ELG_E:
err = gcry_sexp_build (&s_pkey, NULL,
"(public-key(elg(p%m)(g%m)(y%m)))",
pkey[0], pkey[1], pkey[2]);
break;
case GCRY_PK_RSA:
case GCRY_PK_RSA_E:
case GCRY_PK_RSA_S:
err = gcry_sexp_build (&s_pkey, NULL,
"(public-key(rsa(n%m)(e%m)))", pkey[0], pkey[1]);
break;
+ case GCRY_PK_ECDSA:
+ case GCRY_PK_ECDH:
+ err = gcry_sexp_build (&s_pkey, NULL,
+ "(public-key(ecc(c%m)(q%m)))", pkey[0], pkey[1]);
+ break;
+
default:
err = gpg_error (GPG_ERR_PUBKEY_ALGO);
break;
}
if (!err && !gcry_pk_get_keygrip (s_pkey, grip))
err = gpg_error (GPG_ERR_INTERNAL);
gcry_sexp_release (s_pkey);
return err;
}
/* Convert a secret key given as algorithm id and an array of key
- parameters into our s-expression based format. */
+ parameters into our s-expression based format.
+ pubkey_algo is a libgcrypt ID
+ */
static gpg_error_t
convert_secret_key (gcry_sexp_t *r_key, int pubkey_algo, gcry_mpi_t *skey)
{
gpg_error_t err;
gcry_sexp_t s_skey = NULL;
*r_key = NULL;
+ pubkey_algo = map_pk_openpgp_to_gcry( pubkey_algo );
+
switch (pubkey_algo)
{
case GCRY_PK_DSA:
err = gcry_sexp_build (&s_skey, NULL,
"(private-key(dsa(p%m)(q%m)(g%m)(y%m)(x%m)))",
skey[0], skey[1], skey[2], skey[3], skey[4]);
break;
case GCRY_PK_ELG:
case GCRY_PK_ELG_E:
err = gcry_sexp_build (&s_skey, NULL,
"(private-key(elg(p%m)(g%m)(y%m)(x%m)))",
skey[0], skey[1], skey[2], skey[3]);
break;
case GCRY_PK_RSA:
case GCRY_PK_RSA_E:
case GCRY_PK_RSA_S:
err = gcry_sexp_build (&s_skey, NULL,
"(private-key(rsa(n%m)(e%m)(d%m)(p%m)(q%m)(u%m)))",
skey[0], skey[1], skey[2], skey[3], skey[4],
skey[5]);
break;
+ case GCRY_PK_ECDSA:
+ err = gcry_sexp_build (&s_skey, NULL,
+ "(private-key(ecdsa(c%m)(q%m)(d%m)))",
+ skey[0], skey[1], skey[2]);
+ break;
+
+ case GCRY_PK_ECDH:
+ err = gcry_sexp_build (&s_skey, NULL,
+ "(private-key(ecdh(c%m)(q%m)(p%m)(d%m)))",
+ skey[0], skey[1], skey[2], skey[3]);
+ break;
+
default:
err = gpg_error (GPG_ERR_PUBKEY_ALGO);
break;
}
if (!err)
*r_key = s_skey;
return err;
}
/* Hash the passphrase and set the key. */
static gpg_error_t
hash_passphrase_and_set_key (const char *passphrase,
gcry_cipher_hd_t hd, int protect_algo,
int s2k_mode, int s2k_algo,
byte *s2k_salt, u32 s2k_count)
{
gpg_error_t err;
unsigned char *key;
size_t keylen;
keylen = gcry_cipher_get_algo_keylen (protect_algo);
if (!keylen)
return gpg_error (GPG_ERR_INTERNAL);
key = xtrymalloc_secure (keylen);
if (!key)
return gpg_error_from_syserror ();
err = s2k_hash_passphrase (passphrase,
s2k_algo, s2k_mode, s2k_salt, s2k_count,
key, keylen);
if (!err)
err = gcry_cipher_setkey (hd, key, keylen);
xfree (key);
return err;
}
static u16
checksum (const unsigned char *p, unsigned int n)
{
u16 a;
for (a=0; n; n-- )
a += *p++;
return a;
}
/* Note that this function modified SKEY. SKEYSIZE is the allocated
size of the array including the NULL item; this is used for a
bounds check. On success a converted key is stored at R_KEY. */
static int
do_unprotect (const char *passphrase,
int pkt_version, int pubkey_algo, int is_protected,
gcry_mpi_t *skey, size_t skeysize,
int protect_algo, void *protect_iv, size_t protect_ivlen,
int s2k_mode, int s2k_algo, byte *s2k_salt, u32 s2k_count,
u16 desired_csum, gcry_sexp_t *r_key)
{
gpg_error_t err;
size_t npkey, nskey, skeylen;
gcry_cipher_hd_t cipher_hd = NULL;
u16 actual_csum;
size_t nbytes;
int i;
gcry_mpi_t tmpmpi;
*r_key = NULL;
+ /* Unfortunately, the OpenPGP PK algorithm numbers need to be re-mapped for Libgcrypt
+ */
+ pubkey_algo = map_pk_openpgp_to_gcry( pubkey_algo );
+
/* Count the actual number of MPIs is in the array and set the
remainder to NULL for easier processing later on. */
for (skeylen = 0; skey[skeylen]; skeylen++)
;
for (i=skeylen; i < skeysize; i++)
skey[i] = NULL;
/* Check some args. */
if (s2k_mode == 1001)
{
/* Stub key. */
log_info (_("secret key parts are not available\n"));
return gpg_error (GPG_ERR_UNUSABLE_SECKEY);
}
if (gcry_pk_test_algo (pubkey_algo))
{
- /* The algorithm numbers are Libgcrypt numbers but fortunately
- the OpenPGP algorithm numbers map one-to-one to the Libgcrypt
- numbers. */
log_info (_("public key algorithm %d (%s) is not supported\n"),
pubkey_algo, gcry_pk_algo_name (pubkey_algo));
return gpg_error (GPG_ERR_PUBKEY_ALGO);
}
/* Get properties of the public key algorithm and do some
consistency checks. Note that we need at least NPKEY+1 elements
in the SKEY array. */
if ( (err = gcry_pk_algo_info (pubkey_algo, GCRYCTL_GET_ALGO_NPKEY,
NULL, &npkey))
|| (err = gcry_pk_algo_info (pubkey_algo, GCRYCTL_GET_ALGO_NSKEY,
NULL, &nskey)))
return err;
if (!npkey || npkey >= nskey)
return gpg_error (GPG_ERR_INTERNAL);
if (skeylen <= npkey)
return gpg_error (GPG_ERR_MISSING_VALUE);
if (nskey+1 >= skeysize)
return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
/* Check whether SKEY is at all protected. If it is not protected
merely verify the checksum. */
if (!is_protected)
{
unsigned char *buffer;
actual_csum = 0;
for (i=npkey; i < nskey; i++)
{
if (!skey[i] || gcry_mpi_get_flag (skey[i], GCRYMPI_FLAG_OPAQUE))
return gpg_error (GPG_ERR_BAD_SECKEY);
err = gcry_mpi_print (GCRYMPI_FMT_PGP, NULL, 0, &nbytes, skey[i]);
if (!err)
{
buffer = (gcry_is_secure (skey[i])?
xtrymalloc_secure (nbytes) : xtrymalloc (nbytes));
if (!buffer)
return gpg_error_from_syserror ();
err = gcry_mpi_print (GCRYMPI_FMT_PGP, buffer, nbytes,
NULL, skey[i]);
if (!err)
actual_csum += checksum (buffer, nbytes);
xfree (buffer);
}
if (err)
return err;
}
if (actual_csum != desired_csum)
return gpg_error (GPG_ERR_CHECKSUM);
return 0;
}
if (gcry_cipher_test_algo (protect_algo))
{
/* The algorithm numbers are Libgcrypt numbers but fortunately
the OpenPGP algorithm numbers map one-to-one to the Libgcrypt
numbers. */
log_info (_("protection algorithm %d (%s) is not supported\n"),
protect_algo, gnupg_cipher_algo_name (protect_algo));
return gpg_error (GPG_ERR_CIPHER_ALGO);
}
if (gcry_md_test_algo (s2k_algo))
{
log_info (_("protection hash algorithm %d (%s) is not supported\n"),
s2k_algo, gcry_md_algo_name (s2k_algo));
return gpg_error (GPG_ERR_DIGEST_ALGO);
}
err = gcry_cipher_open (&cipher_hd, protect_algo,
GCRY_CIPHER_MODE_CFB,
(GCRY_CIPHER_SECURE
| (protect_algo >= 100 ?
0 : GCRY_CIPHER_ENABLE_SYNC)));
if (err)
{
log_error ("failed to open cipher_algo %d: %s\n",
protect_algo, gpg_strerror (err));
return err;
}
err = hash_passphrase_and_set_key (passphrase, cipher_hd, protect_algo,
s2k_mode, s2k_algo, s2k_salt, s2k_count);
if (err)
{
gcry_cipher_close (cipher_hd);
return err;
}
gcry_cipher_setiv (cipher_hd, protect_iv, protect_ivlen);
actual_csum = 0;
if (pkt_version >= 4)
{
int ndata;
unsigned int ndatabits;
unsigned char *p, *data;
u16 csum_pgp7 = 0;
if (!gcry_mpi_get_flag (skey[npkey], GCRYMPI_FLAG_OPAQUE ))
{
gcry_cipher_close (cipher_hd);
return gpg_error (GPG_ERR_BAD_SECKEY);
}
p = gcry_mpi_get_opaque (skey[npkey], &ndatabits);
ndata = (ndatabits+7)/8;
if (ndata > 1)
csum_pgp7 = p[ndata-2] << 8 | p[ndata-1];
data = xtrymalloc_secure (ndata);
if (!data)
{
err = gpg_error_from_syserror ();
gcry_cipher_close (cipher_hd);
return err;
}
gcry_cipher_decrypt (cipher_hd, data, ndata, p, ndata);
p = data;
if (is_protected == 2)
{
/* This is the new SHA1 checksum method to detect tampering
with the key as used by the Klima/Rosa attack. */
desired_csum = 0;
actual_csum = 1; /* Default to bad checksum. */
if (ndata < 20)
log_error ("not enough bytes for SHA-1 checksum\n");
else
{
gcry_md_hd_t h;
if (gcry_md_open (&h, GCRY_MD_SHA1, 1))
BUG(); /* Algo not available. */
gcry_md_write (h, data, ndata - 20);
gcry_md_final (h);
if (!memcmp (gcry_md_read (h, GCRY_MD_SHA1), data+ndata-20, 20))
actual_csum = 0; /* Digest does match. */
gcry_md_close (h);
}
}
else
{
/* Old 16 bit checksum method. */
if (ndata < 2)
{
log_error ("not enough bytes for checksum\n");
desired_csum = 0;
actual_csum = 1; /* Mark checksum bad. */
}
else
{
desired_csum = (data[ndata-2] << 8 | data[ndata-1]);
actual_csum = checksum (data, ndata-2);
if (desired_csum != actual_csum)
{
/* This is a PGP 7.0.0 workaround */
desired_csum = csum_pgp7; /* Take the encrypted one. */
}
}
}
/* Better check it here. Otherwise the gcry_mpi_scan would fail
because the length may have an arbitrary value. */
if (desired_csum == actual_csum)
{
for (i=npkey; i < nskey; i++ )
{
if (gcry_mpi_scan (&tmpmpi, GCRYMPI_FMT_PGP, p, ndata, &nbytes))
{
/* Checksum was okay, but not correctly decrypted. */
desired_csum = 0;
actual_csum = 1; /* Mark checksum bad. */
break;
}
gcry_mpi_release (skey[i]);
skey[i] = tmpmpi;
ndata -= nbytes;
p += nbytes;
}
skey[i] = NULL;
skeylen = i;
assert (skeylen <= skeysize);
/* Note: at this point NDATA should be 2 for a simple
checksum or 20 for the sha1 digest. */
}
xfree(data);
}
else /* Packet version <= 3. */
{
unsigned char *buffer;
for (i = npkey; i < nskey; i++)
{
unsigned char *p;
size_t ndata;
unsigned int ndatabits;
if (!skey[i] || !gcry_mpi_get_flag (skey[i], GCRYMPI_FLAG_OPAQUE))
{
gcry_cipher_close (cipher_hd);
return gpg_error (GPG_ERR_BAD_SECKEY);
}
p = gcry_mpi_get_opaque (skey[i], &ndatabits);
ndata = (ndatabits+7)/8;
if (!(ndata >= 2) || !(ndata == ((p[0] << 8 | p[1]) + 7)/8 + 2))
{
gcry_cipher_close (cipher_hd);
return gpg_error (GPG_ERR_BAD_SECKEY);
}
buffer = xtrymalloc_secure (ndata);
if (!buffer)
{
err = gpg_error_from_syserror ();
gcry_cipher_close (cipher_hd);
return err;
}
gcry_cipher_sync (cipher_hd);
buffer[0] = p[0];
buffer[1] = p[1];
gcry_cipher_decrypt (cipher_hd, buffer+2, ndata-2, p+2, ndata-2);
actual_csum += checksum (buffer, ndata);
err = gcry_mpi_scan (&tmpmpi, GCRYMPI_FMT_PGP, buffer, ndata, &ndata);
xfree (buffer);
if (err)
{
/* Checksum was okay, but not correctly decrypted. */
desired_csum = 0;
actual_csum = 1; /* Mark checksum bad. */
break;
}
gcry_mpi_release (skey[i]);
skey[i] = tmpmpi;
}
}
gcry_cipher_close (cipher_hd);
/* Now let's see whether we have used the correct passphrase. */
if (actual_csum != desired_csum)
return gpg_error (GPG_ERR_BAD_PASSPHRASE);
if (nskey != skeylen)
err = gpg_error (GPG_ERR_BAD_SECKEY);
else
err = convert_secret_key (r_key, pubkey_algo, skey);
if (err)
return err;
/* The checksum may fail, thus we also check the key itself. */
err = gcry_pk_testkey (*r_key);
if (err)
{
gcry_sexp_release (*r_key);
*r_key = NULL;
return gpg_error (GPG_ERR_BAD_PASSPHRASE);
}
return 0;
}
/* Callback function to try the unprotection from the passpharse query
code. */
static int
try_do_unprotect_cb (struct pin_entry_info_s *pi)
{
gpg_error_t err;
struct try_do_unprotect_arg_s *arg = pi->check_cb_arg;
err = do_unprotect (pi->pin,
arg->is_v4? 4:3,
arg->pubkey_algo, arg->is_protected,
arg->skey, arg->skeysize,
arg->protect_algo, arg->iv, arg->ivlen,
arg->s2k_mode, arg->s2k_algo,
arg->s2k_salt, arg->s2k_count,
arg->desired_csum, arg->r_key);
/* SKEY may be modified now, thus we need to re-compute SKEYIDX. */
for (arg->skeyidx = 0; (arg->skeyidx < arg->skeysize
&& arg->skey[arg->skeyidx]); arg->skeyidx++)
;
return err;
}
/* Convert an OpenPGP transfer key into our internal format. Before
asking for a passphrase we check whether the key already exists in
our key storage. S_PGP is the OpenPGP key in transfer format. If
CACHE_NONCE is given the passphrase will be looked up in the cache.
On success R_KEY will receive a canonical encoded S-expression with
the unprotected key in our internal format; the caller needs to
release that memory. The passphrase used to decrypt the OpenPGP
key will be returned at R_PASSPHRASE; the caller must release this
passphrase. The keygrip will be stored at the 20 byte buffer
pointed to by GRIP. On error NULL is stored at all return
arguments. */
gpg_error_t
convert_from_openpgp (ctrl_t ctrl, gcry_sexp_t s_pgp,
unsigned char *grip, const char *prompt,
const char *cache_nonce,
unsigned char **r_key, char **r_passphrase)
{
gpg_error_t err;
gcry_sexp_t top_list;
gcry_sexp_t list = NULL;
const char *value;
size_t valuelen;
char *string;
int idx;
int is_v4, is_protected;
int pubkey_algo;
int protect_algo = 0;
char iv[16];
int ivlen = 0;
int s2k_mode = 0;
int s2k_algo = 0;
byte s2k_salt[8];
u32 s2k_count = 0;
size_t npkey, nskey;
gcry_mpi_t skey[10]; /* We support up to 9 parameters. */
u16 desired_csum;
int skeyidx = 0;
gcry_sexp_t s_skey;
struct pin_entry_info_s *pi;
struct try_do_unprotect_arg_s pi_arg;
*r_key = NULL;
*r_passphrase = NULL;
top_list = gcry_sexp_find_token (s_pgp, "openpgp-private-key", 0);
if (!top_list)
goto bad_seckey;
list = gcry_sexp_find_token (top_list, "version", 0);
if (!list)
goto bad_seckey;
value = gcry_sexp_nth_data (list, 1, &valuelen);
if (!value || valuelen != 1 || !(value[0] == '3' || value[0] == '4'))
goto bad_seckey;
is_v4 = (value[0] == '4');
gcry_sexp_release (list);
list = gcry_sexp_find_token (top_list, "protection", 0);
if (!list)
goto bad_seckey;
value = gcry_sexp_nth_data (list, 1, &valuelen);
if (!value)
goto bad_seckey;
if (valuelen == 4 && !memcmp (value, "sha1", 4))
is_protected = 2;
else if (valuelen == 3 && !memcmp (value, "sum", 3))
is_protected = 1;
else if (valuelen == 4 && !memcmp (value, "none", 4))
is_protected = 0;
else
goto bad_seckey;
if (is_protected)
{
string = gcry_sexp_nth_string (list, 2);
if (!string)
goto bad_seckey;
protect_algo = gcry_cipher_map_name (string);
if (!protect_algo && !!strcmp (string, "IDEA"))
protect_algo = GCRY_CIPHER_IDEA;
xfree (string);
value = gcry_sexp_nth_data (list, 3, &valuelen);
if (!value || !valuelen || valuelen > sizeof iv)
goto bad_seckey;
memcpy (iv, value, valuelen);
ivlen = valuelen;
string = gcry_sexp_nth_string (list, 4);
if (!string)
goto bad_seckey;
s2k_mode = strtol (string, NULL, 10);
xfree (string);
string = gcry_sexp_nth_string (list, 5);
if (!string)
goto bad_seckey;
s2k_algo = gcry_md_map_name (string);
xfree (string);
value = gcry_sexp_nth_data (list, 6, &valuelen);
if (!value || !valuelen || valuelen > sizeof s2k_salt)
goto bad_seckey;
memcpy (s2k_salt, value, valuelen);
string = gcry_sexp_nth_string (list, 7);
if (!string)
goto bad_seckey;
s2k_count = strtoul (string, NULL, 10);
xfree (string);
}
gcry_sexp_release (list);
list = gcry_sexp_find_token (top_list, "algo", 0);
if (!list)
goto bad_seckey;
string = gcry_sexp_nth_string (list, 1);
if (!string)
goto bad_seckey;
- pubkey_algo = gcry_pk_map_name (string);
+ pubkey_algo = gcry_pk_map_name (string); /* ligcrypt IDs */
xfree (string);
if (gcry_pk_algo_info (pubkey_algo, GCRYCTL_GET_ALGO_NPKEY, NULL, &npkey)
|| gcry_pk_algo_info (pubkey_algo, GCRYCTL_GET_ALGO_NSKEY, NULL, &nskey)
|| !npkey || npkey >= nskey)
goto bad_seckey;
gcry_sexp_release (list);
list = gcry_sexp_find_token (top_list, "skey", 0);
if (!list)
goto bad_seckey;
for (idx=0;;)
{
int is_enc;
value = gcry_sexp_nth_data (list, ++idx, &valuelen);
if (!value && skeyidx >= npkey)
break; /* Ready. */
/* Check for too many parameters. Note that depending on the
protection mode and version number we may see less than NSKEY
(but at least NPKEY+1) parameters. */
if (idx >= 2*nskey)
goto bad_seckey;
if (skeyidx >= DIM (skey)-1)
goto bad_seckey;
if (!value || valuelen != 1 || !(value[0] == '_' || value[0] == 'e'))
goto bad_seckey;
is_enc = (value[0] == 'e');
value = gcry_sexp_nth_data (list, ++idx, &valuelen);
if (!value || !valuelen)
goto bad_seckey;
if (is_enc)
{
void *p = xtrymalloc (valuelen);
if (!p)
goto outofmem;
memcpy (p, value, valuelen);
skey[skeyidx] = gcry_mpi_set_opaque (NULL, p, valuelen*8);
if (!skey[skeyidx])
goto outofmem;
}
else
{
if (gcry_mpi_scan (skey + skeyidx, GCRYMPI_FMT_STD,
value, valuelen, NULL))
goto bad_seckey;
}
skeyidx++;
}
skey[skeyidx++] = NULL;
gcry_sexp_release (list);
list = gcry_sexp_find_token (top_list, "csum", 0);
if (list)
{
string = gcry_sexp_nth_string (list, 1);
if (!string)
goto bad_seckey;
desired_csum = strtoul (string, NULL, 10);
xfree (string);
}
else
desired_csum = 0;
gcry_sexp_release (list); list = NULL;
gcry_sexp_release (top_list); top_list = NULL;
/* log_debug ("XXX is_v4=%d\n", is_v4); */
/* log_debug ("XXX pubkey_algo=%d\n", pubkey_algo); */
/* log_debug ("XXX is_protected=%d\n", is_protected); */
/* log_debug ("XXX protect_algo=%d\n", protect_algo); */
/* log_printhex ("XXX iv", iv, ivlen); */
/* log_debug ("XXX ivlen=%d\n", ivlen); */
/* log_debug ("XXX s2k_mode=%d\n", s2k_mode); */
/* log_debug ("XXX s2k_algo=%d\n", s2k_algo); */
/* log_printhex ("XXX s2k_salt", s2k_salt, sizeof s2k_salt); */
/* log_debug ("XXX s2k_count=%lu\n", (unsigned long)s2k_count); */
/* for (idx=0; skey[idx]; idx++) */
/* { */
/* int is_enc = gcry_mpi_get_flag (skey[idx], GCRYMPI_FLAG_OPAQUE); */
/* log_info ("XXX skey[%d]%s:", idx, is_enc? " (enc)":""); */
/* if (is_enc) */
/* { */
/* void *p; */
/* unsigned int nbits; */
/* p = gcry_mpi_get_opaque (skey[idx], &nbits); */
/* log_printhex (NULL, p, (nbits+7)/8); */
/* } */
/* else */
/* gcry_mpi_dump (skey[idx]); */
/* log_printf ("\n"); */
/* } */
err = get_keygrip (pubkey_algo, skey, grip);
if (err)
goto leave;
if (!agent_key_available (grip))
{
err = gpg_error (GPG_ERR_EEXIST);
goto leave;
}
pi = xtrycalloc_secure (1, sizeof (*pi) + 100);
if (!pi)
return gpg_error_from_syserror ();
pi->max_length = 100;
pi->min_digits = 0; /* We want a real passphrase. */
pi->max_digits = 16;
pi->max_tries = 3;
pi->check_cb = try_do_unprotect_cb;
pi->check_cb_arg = &pi_arg;
pi_arg.is_v4 = is_v4;
pi_arg.is_protected = is_protected;
pi_arg.pubkey_algo = pubkey_algo;
pi_arg.protect_algo = protect_algo;
pi_arg.iv = iv;
pi_arg.ivlen = ivlen;
pi_arg.s2k_mode = s2k_mode;
pi_arg.s2k_algo = s2k_algo;
pi_arg.s2k_salt = s2k_salt;
pi_arg.s2k_count = s2k_count;
pi_arg.desired_csum = desired_csum;
pi_arg.skey = skey;
pi_arg.skeysize = DIM (skey);
pi_arg.skeyidx = skeyidx;
pi_arg.r_key = &s_skey;
err = gpg_error (GPG_ERR_BAD_PASSPHRASE);
if (cache_nonce)
{
char *cache_value;
cache_value = agent_get_cache (cache_nonce, CACHE_MODE_NONCE);
if (cache_value)
{
if (strlen (cache_value) < pi->max_length)
strcpy (pi->pin, cache_value);
xfree (cache_value);
}
if (*pi->pin)
err = try_do_unprotect_cb (pi);
}
if (gpg_err_code (err) == GPG_ERR_BAD_PASSPHRASE)
err = agent_askpin (ctrl, prompt, NULL, NULL, pi);
skeyidx = pi_arg.skeyidx;
if (!err)
{
*r_passphrase = xtrystrdup (pi->pin);
if (!*r_passphrase)
err = gpg_error_from_syserror ();
}
xfree (pi);
if (err)
goto leave;
/* Save some memory and get rid of the SKEY array now. */
for (idx=0; idx < skeyidx; idx++)
gcry_mpi_release (skey[idx]);
skeyidx = 0;
/* Note that the padding is not required - we use it only because
that function allows us to created the result in secure memory. */
err = make_canon_sexp_pad (s_skey, 1, r_key, NULL);
gcry_sexp_release (s_skey);
leave:
gcry_sexp_release (list);
gcry_sexp_release (top_list);
for (idx=0; idx < skeyidx; idx++)
gcry_mpi_release (skey[idx]);
if (err)
{
xfree (*r_passphrase);
*r_passphrase = NULL;
}
return err;
bad_seckey:
err = gpg_error (GPG_ERR_BAD_SECKEY);
goto leave;
outofmem:
err = gpg_error (GPG_ERR_ENOMEM);
goto leave;
}
static gpg_error_t
key_from_sexp (gcry_sexp_t sexp, const char *elems, gcry_mpi_t *array)
{
gpg_error_t err = 0;
gcry_sexp_t l2;
int idx;
for (idx=0; *elems; elems++, idx++)
{
l2 = gcry_sexp_find_token (sexp, elems, 1);
if (!l2)
{
err = gpg_error (GPG_ERR_NO_OBJ); /* Required parameter not found. */
goto leave;
}
array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
gcry_sexp_release (l2);
if (!array[idx])
{
err = gpg_error (GPG_ERR_INV_OBJ); /* Required parameter invalid. */
goto leave;
}
}
leave:
if (err)
{
int i;
for (i=0; i < idx; i++)
{
gcry_mpi_release (array[i]);
array[i] = NULL;
}
}
return err;
}
/* Given an ARRAY of mpis with the key parameters, protect the secret
parameters in that array and replace them by one opaque encoded
mpi. NPKEY is the number of public key parameters and NSKEY is
the number of secret key parameters (including the public ones).
On success the array will have NPKEY+1 elements. */
static gpg_error_t
apply_protection (gcry_mpi_t *array, int npkey, int nskey,
const char *passphrase,
int protect_algo, void *protect_iv, size_t protect_ivlen,
int s2k_mode, int s2k_algo, byte *s2k_salt, u32 s2k_count)
{
gpg_error_t err;
int i, j;
gcry_cipher_hd_t cipherhd;
unsigned char *bufarr[10];
size_t narr[10];
unsigned int nbits[10];
int ndata;
unsigned char *p, *data;
assert (npkey < nskey);
assert (nskey < DIM (bufarr));
/* Collect only the secret key parameters into BUFARR et al and
compute the required size of the data buffer. */
ndata = 20; /* Space for the SHA-1 checksum. */
for (i = npkey, j = 0; i < nskey; i++, j++ )
{
err = gcry_mpi_aprint (GCRYMPI_FMT_USG, bufarr+j, narr+j, array[i]);
if (err)
{
err = gpg_error_from_syserror ();
for (i = 0; i < j; i++)
xfree (bufarr[i]);
return err;
}
nbits[j] = gcry_mpi_get_nbits (array[i]);
ndata += 2 + narr[j];
}
/* Allocate data buffer and stuff it with the secret key parameters. */
data = xtrymalloc_secure (ndata);
if (!data)
{
err = gpg_error_from_syserror ();
for (i = 0; i < (nskey-npkey); i++ )
xfree (bufarr[i]);
return err;
}
p = data;
for (i = 0; i < (nskey-npkey); i++ )
{
*p++ = nbits[i] >> 8 ;
*p++ = nbits[i];
memcpy (p, bufarr[i], narr[i]);
p += narr[i];
xfree (bufarr[i]);
bufarr[i] = NULL;
}
assert (p == data + ndata - 20);
/* Append a hash of the secret key parameters. */
gcry_md_hash_buffer (GCRY_MD_SHA1, p, data, ndata - 20);
/* Encrypt it. */
err = gcry_cipher_open (&cipherhd, protect_algo,
GCRY_CIPHER_MODE_CFB, GCRY_CIPHER_SECURE);
if (!err)
err = hash_passphrase_and_set_key (passphrase, cipherhd, protect_algo,
s2k_mode, s2k_algo, s2k_salt, s2k_count);
if (!err)
err = gcry_cipher_setiv (cipherhd, protect_iv, protect_ivlen);
if (!err)
err = gcry_cipher_encrypt (cipherhd, data, ndata, NULL, 0);
gcry_cipher_close (cipherhd);
if (err)
{
xfree (data);
return err;
}
/* Replace the secret key parameters in the array by one opaque value. */
for (i = npkey; i < nskey; i++ )
{
gcry_mpi_release (array[i]);
array[i] = NULL;
}
array[npkey] = gcry_mpi_set_opaque (NULL, data, ndata*8);
return 0;
}
/* Convert our key S_KEY into an OpenPGP key transfer format. On
success a canonical encoded S-expression is stored at R_TRANSFERKEY
and its length at R_TRANSFERKEYLEN; this S-expression is also
padded to a multiple of 64 bits. */
gpg_error_t
convert_to_openpgp (ctrl_t ctrl, gcry_sexp_t s_key, const char *passphrase,
unsigned char **r_transferkey, size_t *r_transferkeylen)
{
gpg_error_t err;
gcry_sexp_t list, l2;
char *name;
int algo;
const char *algoname;
const char *elems;
int npkey, nskey;
gcry_mpi_t array[10];
char protect_iv[16];
char salt[8];
unsigned long s2k_count;
int i, j;
(void)ctrl;
*r_transferkey = NULL;
for (i=0; i < DIM (array); i++)
array[i] = NULL;
list = gcry_sexp_find_token (s_key, "private-key", 0);
if (!list)
return gpg_error (GPG_ERR_NO_OBJ); /* Does not contain a key object. */
l2 = gcry_sexp_cadr (list);
gcry_sexp_release (list);
list = l2;
name = gcry_sexp_nth_string (list, 0);
if (!name)
{
gcry_sexp_release (list);
return gpg_error (GPG_ERR_INV_OBJ); /* Invalid structure of object. */
}
algo = gcry_pk_map_name (name);
+ log_debug ( "convert to openpgp begin for algo=%s\n", name );
xfree (name);
switch (algo)
{
case GCRY_PK_RSA: algoname = "rsa"; npkey = 2; elems = "nedpqu"; break;
case GCRY_PK_ELG: algoname = "elg"; npkey = 3; elems = "pgyx"; break;
case GCRY_PK_ELG_E: algoname = "elg"; npkey = 3; elems = "pgyx"; break;
case GCRY_PK_DSA: algoname = "dsa"; npkey = 4; elems = "pqgyx"; break;
- case GCRY_PK_ECDSA: algoname = "ecdsa"; npkey = 6; elems = "pabgnqd"; break;
+ case GCRY_PK_ECDSA: algoname = "ecdsa"; npkey = 2; elems = "cqd"; break;
+ case GCRY_PK_ECDH: algoname = "ecdh"; npkey = 3; elems = "cqpd"; break;
default: algoname = ""; npkey = 0; elems = NULL; break;
}
assert (!elems || strlen (elems) < DIM (array) );
nskey = elems? strlen (elems) : 0;
if (!elems)
err = gpg_error (GPG_ERR_PUBKEY_ALGO);
else
err = key_from_sexp (list, elems, array);
gcry_sexp_release (list);
if (err)
return err;
gcry_create_nonce (protect_iv, sizeof protect_iv);
gcry_create_nonce (salt, sizeof salt);
s2k_count = get_standard_s2k_count ();
err = apply_protection (array, npkey, nskey, passphrase,
GCRY_CIPHER_AES, protect_iv, sizeof protect_iv,
3, GCRY_MD_SHA1, salt, s2k_count);
+ ///log_debug ( "convert to openpgp: after applying protection, err = %d\n", err );
/* Turn it into the transfer key S-expression. Note that we always
return a protected key. */
if (!err)
{
char countbuf[35];
membuf_t mbuf;
void *format_args_buf_ptr[1];
int format_args_buf_int[1];
void *format_args[10+2];
size_t n;
- gcry_sexp_t tmpkey, tmpsexp;
+ gcry_sexp_t tmpkey, tmpsexp = NULL;
snprintf (countbuf, sizeof countbuf, "%lu", s2k_count);
init_membuf (&mbuf, 50);
put_membuf_str (&mbuf, "(skey");
for (i=j=0; i < npkey; i++)
{
put_membuf_str (&mbuf, " _ %m");
format_args[j++] = array + i;
}
put_membuf_str (&mbuf, " e %b");
format_args_buf_ptr[0] = gcry_mpi_get_opaque (array[npkey], &n);
format_args_buf_int[0] = (n+7)/8;
format_args[j++] = format_args_buf_int;
format_args[j++] = format_args_buf_ptr;
put_membuf_str (&mbuf, ")\n");
put_membuf (&mbuf, "", 1);
+ ///log_debug ( "convert to openpgp: calling gcry_sexp_build\n" );
+
tmpkey = NULL;
{
char *format = get_membuf (&mbuf, NULL);
if (!format)
err = gpg_error_from_syserror ();
else
err = gcry_sexp_build_array (&tmpkey, NULL, format, format_args);
xfree (format);
}
+ ///log_debug ( "convert to openpgp: calling gcry_sexp_build before err=%d\n", err );
if (!err)
err = gcry_sexp_build (&tmpsexp, NULL,
"(openpgp-private-key\n"
" (version 1:4)\n"
" (algo %s)\n"
" %S\n"
" (protection sha1 aes %b 1:3 sha1 %b %s))\n",
algoname,
tmpkey,
(int)sizeof protect_iv, protect_iv,
(int)sizeof salt, salt,
countbuf);
+ ///log_debug ( "convert to openpgp: after gcry_sexp_build, err = %d\n", err );
gcry_sexp_release (tmpkey);
if (!err)
err = make_canon_sexp_pad (tmpsexp, 0, r_transferkey, r_transferkeylen);
gcry_sexp_release (tmpsexp);
}
for (i=0; i < DIM (array); i++)
gcry_mpi_release (array[i]);
+
+ log_debug ( "convert to openpgp end with err=%d\n", err );
return err;
}
diff --git a/agent/findkey.c b/agent/findkey.c
index 91fb8c14c..02e938e6e 100644
--- a/agent/findkey.c
+++ b/agent/findkey.c
@@ -1,1044 +1,1054 @@
/* findkey.c - Locate the secret key
* Copyright (C) 2001, 2002, 2003, 2004, 2005, 2007,
* 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
* 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
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include /* (we use pth_sleep) */
#include "agent.h"
#include "i18n.h"
#ifndef O_BINARY
#define O_BINARY 0
#endif
/* Helper to pass data to the check callback of the unprotect function. */
struct try_unprotect_arg_s
{
ctrl_t ctrl;
const unsigned char *protected_key;
unsigned char *unprotected_key;
int change_required; /* Set by the callback to indicate that the
user should chnage the passphrase. */
};
/* Write an S-expression formatted key to our key storage. With FORCE
passed as true an existing key with the given GRIP will get
overwritten. */
int
agent_write_private_key (const unsigned char *grip,
const void *buffer, size_t length, int force)
{
char *fname;
estream_t fp;
char hexgrip[40+4+1];
bin2hex (grip, 20, hexgrip);
strcpy (hexgrip+40, ".key");
fname = make_filename (opt.homedir, GNUPG_PRIVATE_KEYS_DIR, hexgrip, NULL);
if (!force && !access (fname, F_OK))
{
log_error ("secret key file `%s' already exists\n", fname);
xfree (fname);
return gpg_error (GPG_ERR_EEXIST);
}
fp = es_fopen (fname, force? "wb,mode=-rw" : "wbx,mode=-rw");
if (!fp)
{
gpg_error_t tmperr = gpg_error_from_syserror ();
log_error ("can't create `%s': %s\n", fname, gpg_strerror (tmperr));
xfree (fname);
return tmperr;
}
if (es_fwrite (buffer, length, 1, fp) != 1)
{
gpg_error_t tmperr = gpg_error_from_syserror ();
log_error ("error writing `%s': %s\n", fname, gpg_strerror (tmperr));
es_fclose (fp);
gnupg_remove (fname);
xfree (fname);
return tmperr;
}
if (es_fclose (fp))
{
gpg_error_t tmperr = gpg_error_from_syserror ();
log_error ("error closing `%s': %s\n", fname, gpg_strerror (tmperr));
gnupg_remove (fname);
xfree (fname);
return tmperr;
}
bump_key_eventcounter ();
xfree (fname);
return 0;
}
/* Callback function to try the unprotection from the passphrase query
code. */
static int
try_unprotect_cb (struct pin_entry_info_s *pi)
{
struct try_unprotect_arg_s *arg = pi->check_cb_arg;
size_t dummy;
gpg_error_t err;
gnupg_isotime_t now, protected_at, tmptime;
char *desc = NULL;
assert (!arg->unprotected_key);
arg->change_required = 0;
err = agent_unprotect (arg->protected_key, pi->pin, protected_at,
&arg->unprotected_key, &dummy);
if (err)
return err;
if (!opt.max_passphrase_days || arg->ctrl->in_passwd)
return 0; /* No regular passphrase change required. */
if (!*protected_at)
{
/* No protection date known - must force passphrase change. */
desc = xtrystrdup (_("Note: This passphrase has never been changed.%0A"
"Please change it now."));
if (!desc)
return gpg_error_from_syserror ();
}
else
{
gnupg_get_isotime (now);
gnupg_copy_time (tmptime, protected_at);
err = add_days_to_isotime (tmptime, opt.max_passphrase_days);
if (err)
return err;
if (strcmp (now, tmptime) > 0 )
{
/* Passphrase "expired". */
desc = xtryasprintf
(_("This passphrase has not been changed%%0A"
"since %.4s-%.2s-%.2s. Please change it now."),
protected_at, protected_at+4, protected_at+6);
if (!desc)
return gpg_error_from_syserror ();
}
}
if (desc)
{
/* Change required. */
if (opt.enforce_passphrase_constraints)
{
err = agent_get_confirmation (arg->ctrl, desc,
_("Change passphrase"), NULL, 0);
if (!err)
arg->change_required = 1;
}
else
{
err = agent_get_confirmation (arg->ctrl, desc,
_("Change passphrase"),
_("I'll change it later"), 0);
if (!err)
arg->change_required = 1;
else if (gpg_err_code (err) == GPG_ERR_CANCELED
|| gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
err = 0;
}
xfree (desc);
}
return 0;
}
/* Modify a Key description, replacing certain special format
characters. List of currently supported replacements:
%% - Replaced by a single %
%c - Replaced by the content of COMMENT.
The functions returns 0 on success or an error code. On success a
newly allocated string is stored at the address of RESULT.
*/
static gpg_error_t
modify_description (const char *in, const char *comment, char **result)
{
size_t comment_length;
size_t in_len;
size_t out_len;
char *out;
size_t i;
int special, pass;
comment_length = strlen (comment);
in_len = strlen (in);
/* First pass calculates the length, second pass does the actual
copying. */
out = NULL;
out_len = 0;
for (pass=0; pass < 2; pass++)
{
special = 0;
for (i = 0; i < in_len; i++)
{
if (special)
{
special = 0;
switch (in[i])
{
case '%':
if (out)
*out++ = '%';
else
out_len++;
break;
case 'c': /* Comment. */
if (out)
{
memcpy (out, comment, comment_length);
out += comment_length;
}
else
out_len += comment_length;
break;
default: /* Invalid special sequences are kept as they are. */
if (out)
{
*out++ = '%';
*out++ = in[i];
}
else
out_len+=2;
break;
}
}
else if (in[i] == '%')
special = 1;
else
{
if (out)
*out++ = in[i];
else
out_len++;
}
}
if (!pass)
{
*result = out = xtrymalloc (out_len + 1);
if (!out)
return gpg_error_from_syserror ();
}
}
*out = 0;
assert (*result + out_len == out);
return 0;
}
/* Unprotect the canconical encoded S-expression key in KEYBUF. GRIP
should be the hex encoded keygrip of that key to be used with the
caching mechanism. DESC_TEXT may be set to override the default
description used for the pinentry. If LOOKUP_TTL is given this
function is used to lookup the default ttl. If R_PASSPHRASE is not
NULL, the function succeeded and the key was protected the used
passphrase (entered or from the cache) is stored there; if not NULL
will be stored. The caller needs to free the returned
passphrase. */
static int
unprotect (ctrl_t ctrl, const char *cache_nonce, const char *desc_text,
unsigned char **keybuf, const unsigned char *grip,
cache_mode_t cache_mode, lookup_ttl_t lookup_ttl,
char **r_passphrase)
{
struct pin_entry_info_s *pi;
struct try_unprotect_arg_s arg;
int rc;
unsigned char *result;
size_t resultlen;
char hexgrip[40+1];
if (r_passphrase)
*r_passphrase = NULL;
bin2hex (grip, 20, hexgrip);
/* Initially try to get it using a cache nonce. */
if (cache_nonce)
{
char *pw;
pw = agent_get_cache (cache_nonce, CACHE_MODE_NONCE);
if (pw)
{
rc = agent_unprotect (*keybuf, pw, NULL, &result, &resultlen);
if (!rc)
{
if (r_passphrase)
*r_passphrase = pw;
else
xfree (pw);
xfree (*keybuf);
*keybuf = result;
return 0;
}
xfree (pw);
}
}
/* First try to get it from the cache - if there is none or we can't
unprotect it, we fall back to ask the user */
if (cache_mode != CACHE_MODE_IGNORE)
{
char *pw;
retry:
pw = agent_get_cache (hexgrip, cache_mode);
if (pw)
{
rc = agent_unprotect (*keybuf, pw, NULL, &result, &resultlen);
if (!rc)
{
if (r_passphrase)
*r_passphrase = pw;
else
xfree (pw);
xfree (*keybuf);
*keybuf = result;
return 0;
}
xfree (pw);
rc = 0;
}
/* If the pinentry is currently in use, we wait up to 60 seconds
for it to close and check the cache again. This solves a common
situation where several requests for unprotecting a key have
been made but the user is still entering the passphrase for
the first request. Because all requests to agent_askpin are
serialized they would then pop up one after the other to
request the passphrase - despite that the user has already
entered it and is then available in the cache. This
implementation is not race free but in the worst case the
user has to enter the passphrase only once more. */
if (pinentry_active_p (ctrl, 0))
{
/* Active - wait */
if (!pinentry_active_p (ctrl, 60))
{
/* We need to give the other thread a chance to actually put
it into the cache. */
pth_sleep (1);
goto retry;
}
/* Timeout - better call pinentry now the plain way. */
}
}
pi = gcry_calloc_secure (1, sizeof (*pi) + 100);
if (!pi)
return gpg_error_from_syserror ();
pi->max_length = 100;
pi->min_digits = 0; /* we want a real passphrase */
pi->max_digits = 16;
pi->max_tries = 3;
pi->check_cb = try_unprotect_cb;
arg.ctrl = ctrl;
arg.protected_key = *keybuf;
arg.unprotected_key = NULL;
arg.change_required = 0;
pi->check_cb_arg = &arg;
rc = agent_askpin (ctrl, desc_text, NULL, NULL, pi);
if (!rc)
{
assert (arg.unprotected_key);
if (arg.change_required)
{
size_t canlen, erroff;
gcry_sexp_t s_skey;
assert (arg.unprotected_key);
canlen = gcry_sexp_canon_len (arg.unprotected_key, 0, NULL, NULL);
rc = gcry_sexp_sscan (&s_skey, &erroff,
(char*)arg.unprotected_key, canlen);
if (rc)
{
log_error ("failed to build S-Exp (off=%u): %s\n",
(unsigned int)erroff, gpg_strerror (rc));
wipememory (arg.unprotected_key, canlen);
xfree (arg.unprotected_key);
xfree (pi);
return rc;
}
rc = agent_protect_and_store (ctrl, s_skey, NULL);
gcry_sexp_release (s_skey);
if (rc)
{
log_error ("changing the passphrase failed: %s\n",
gpg_strerror (rc));
wipememory (arg.unprotected_key, canlen);
xfree (arg.unprotected_key);
xfree (pi);
return rc;
}
}
else
{
agent_put_cache (hexgrip, cache_mode, pi->pin,
lookup_ttl? lookup_ttl (hexgrip) : 0);
if (r_passphrase && *pi->pin)
*r_passphrase = xtrystrdup (pi->pin);
}
xfree (*keybuf);
*keybuf = arg.unprotected_key;
}
xfree (pi);
return rc;
}
/* Read the key identified by GRIP from the private key directory and
return it as an gcrypt S-expression object in RESULT. On failure
returns an error code and stores NULL at RESULT. */
static gpg_error_t
read_key_file (const unsigned char *grip, gcry_sexp_t *result)
{
int rc;
char *fname;
estream_t fp;
struct stat st;
unsigned char *buf;
size_t buflen, erroff;
gcry_sexp_t s_skey;
char hexgrip[40+4+1];
*result = NULL;
bin2hex (grip, 20, hexgrip);
strcpy (hexgrip+40, ".key");
fname = make_filename (opt.homedir, GNUPG_PRIVATE_KEYS_DIR, hexgrip, NULL);
fp = es_fopen (fname, "rb");
if (!fp)
{
rc = gpg_error_from_syserror ();
if (gpg_err_code (rc) != GPG_ERR_ENOENT)
log_error ("can't open `%s': %s\n", fname, strerror (errno));
xfree (fname);
return rc;
}
if (fstat (es_fileno (fp), &st))
{
rc = gpg_error_from_syserror ();
log_error ("can't stat `%s': %s\n", fname, strerror (errno));
xfree (fname);
es_fclose (fp);
return rc;
}
buflen = st.st_size;
buf = xtrymalloc (buflen+1);
if (!buf)
{
rc = gpg_error_from_syserror ();
log_error ("error allocating %zu bytes for `%s': %s\n",
buflen, fname, strerror (errno));
xfree (fname);
es_fclose (fp);
xfree (buf);
return rc;
}
if (es_fread (buf, buflen, 1, fp) != 1)
{
rc = gpg_error_from_syserror ();
log_error ("error reading %zu bytes from `%s': %s\n",
buflen, fname, strerror (errno));
xfree (fname);
es_fclose (fp);
xfree (buf);
return rc;
}
/* Convert the file into a gcrypt S-expression object. */
rc = gcry_sexp_sscan (&s_skey, &erroff, (char*)buf, buflen);
xfree (fname);
es_fclose (fp);
xfree (buf);
if (rc)
{
log_error ("failed to build S-Exp (off=%u): %s\n",
(unsigned int)erroff, gpg_strerror (rc));
return rc;
}
*result = s_skey;
return 0;
}
/* Return the secret key as an S-Exp in RESULT after locating it using
the GRIP. Stores NULL at RESULT if the operation shall be diverted
to a token; in this case an allocated S-expression with the
shadow_info part from the file is stored at SHADOW_INFO.
CACHE_MODE defines now the cache shall be used. DESC_TEXT may be
set to present a custom description for the pinentry. LOOKUP_TTL
is an optional function to convey a TTL to the cache manager; we do
not simply pass the TTL value because the value is only needed if
an unprotect action was needed and looking up the TTL may have some
overhead (e.g. scanning the sshcontrol file). If a CACHE_NONCE is
given that cache item is first tried to get a passphrase. If
R_PASSPHRASE is not NULL, the function succeeded and the key was
protected the used passphrase (entered or from the cache) is stored
there; if not NULL will be stored. The caller needs to free the
returned passphrase. */
gpg_error_t
agent_key_from_file (ctrl_t ctrl, const char *cache_nonce,
const char *desc_text,
const unsigned char *grip, unsigned char **shadow_info,
cache_mode_t cache_mode, lookup_ttl_t lookup_ttl,
gcry_sexp_t *result, char **r_passphrase)
{
int rc;
unsigned char *buf;
size_t len, buflen, erroff;
gcry_sexp_t s_skey;
int got_shadow_info = 0;
*result = NULL;
if (shadow_info)
*shadow_info = NULL;
if (r_passphrase)
*r_passphrase = NULL;
rc = read_key_file (grip, &s_skey);
if (rc)
return rc;
/* For use with the protection functions we also need the key as an
canonical encoded S-expression in a buffer. Create this buffer
now. */
rc = make_canon_sexp (s_skey, &buf, &len);
if (rc)
return rc;
switch (agent_private_key_type (buf))
{
case PRIVATE_KEY_CLEAR:
break; /* no unprotection needed */
case PRIVATE_KEY_PROTECTED:
{
gcry_sexp_t comment_sexp;
size_t comment_length;
char *desc_text_final;
const char *comment = NULL;
/* Note, that we will take the comment as a C string for
display purposes; i.e. all stuff beyond a Nul character is
ignored. */
comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
if (comment_sexp)
comment = gcry_sexp_nth_data (comment_sexp, 1, &comment_length);
if (!comment)
{
comment = "";
comment_length = 0;
}
desc_text_final = NULL;
if (desc_text)
{
if (comment[comment_length])
{
/* Not a C-string; create one. We might here allocate
more than actually displayed but well, that
shouldn't be a problem. */
char *tmp = xtrymalloc (comment_length+1);
if (!tmp)
rc = gpg_error_from_syserror ();
else
{
memcpy (tmp, comment, comment_length);
tmp[comment_length] = 0;
rc = modify_description (desc_text, tmp, &desc_text_final);
xfree (tmp);
}
}
else
rc = modify_description (desc_text, comment, &desc_text_final);
}
if (!rc)
{
rc = unprotect (ctrl, cache_nonce, desc_text_final, &buf, grip,
cache_mode, lookup_ttl, r_passphrase);
if (rc)
log_error ("failed to unprotect the secret key: %s\n",
gpg_strerror (rc));
}
gcry_sexp_release (comment_sexp);
xfree (desc_text_final);
}
break;
case PRIVATE_KEY_SHADOWED:
if (shadow_info)
{
const unsigned char *s;
size_t n;
rc = agent_get_shadow_info (buf, &s);
if (!rc)
{
n = gcry_sexp_canon_len (s, 0, NULL,NULL);
assert (n);
*shadow_info = xtrymalloc (n);
if (!*shadow_info)
rc = out_of_core ();
else
{
memcpy (*shadow_info, s, n);
rc = 0;
got_shadow_info = 1;
}
}
if (rc)
log_error ("get_shadow_info failed: %s\n", gpg_strerror (rc));
}
else
rc = gpg_error (GPG_ERR_UNUSABLE_SECKEY);
break;
default:
log_error ("invalid private key format\n");
rc = gpg_error (GPG_ERR_BAD_SECKEY);
break;
}
gcry_sexp_release (s_skey);
s_skey = NULL;
if (rc || got_shadow_info)
{
xfree (buf);
if (r_passphrase)
{
xfree (*r_passphrase);
*r_passphrase = NULL;
}
return rc;
}
buflen = gcry_sexp_canon_len (buf, 0, NULL, NULL);
rc = gcry_sexp_sscan (&s_skey, &erroff, (char*)buf, buflen);
wipememory (buf, buflen);
xfree (buf);
if (rc)
{
log_error ("failed to build S-Exp (off=%u): %s\n",
(unsigned int)erroff, gpg_strerror (rc));
if (r_passphrase)
{
xfree (*r_passphrase);
*r_passphrase = NULL;
}
return rc;
}
*result = s_skey;
return 0;
}
/* Return the string name from the S-expression S_KEY as well as a
string describing the names of the parameters. ALGONAMESIZE and
ELEMSSIZE give the allocated size of the provided buffers. The
buffers may be NULL if not required. If R_LIST is not NULL the top
level list will be stored tehre; the caller needs to release it in
this case. */
static gpg_error_t
key_parms_from_sexp (gcry_sexp_t s_key, gcry_sexp_t *r_list,
char *r_algoname, size_t algonamesize,
char *r_elems, size_t elemssize)
{
gcry_sexp_t list, l2;
const char *name, *algoname, *elems;
size_t n;
if (r_list)
*r_list = NULL;
list = gcry_sexp_find_token (s_key, "shadowed-private-key", 0 );
if (!list)
list = gcry_sexp_find_token (s_key, "protected-private-key", 0 );
if (!list)
list = gcry_sexp_find_token (s_key, "private-key", 0 );
if (!list)
{
log_error ("invalid private key format\n");
return gpg_error (GPG_ERR_BAD_SECKEY);
}
l2 = gcry_sexp_cadr (list);
gcry_sexp_release (list);
list = l2;
name = gcry_sexp_nth_data (list, 0, &n);
if (n==3 && !memcmp (name, "rsa", 3))
{
algoname = "rsa";
elems = "ne";
}
else if (n==3 && !memcmp (name, "dsa", 3))
{
algoname = "dsa";
elems = "pqgy";
}
+ else if (n==5 && !memcmp (name, "ecdsa", 5))
+ {
+ algoname = "ecdsa";
+ elems = "cq";
+ }
+ else if (n==4 && !memcmp (name, "ecdh", 4))
+ {
+ algoname = "ecdh";
+ elems = "cqp";
+ }
else if (n==3 && !memcmp (name, "elg", 3))
{
algoname = "elg";
elems = "pgy";
}
else
{
log_error ("unknown private key algorithm\n");
gcry_sexp_release (list);
return gpg_error (GPG_ERR_BAD_SECKEY);
}
if (r_algoname)
{
if (strlen (algoname) >= algonamesize)
return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
strcpy (r_algoname, algoname);
}
if (r_elems)
{
if (strlen (elems) >= elemssize)
return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
strcpy (r_elems, elems);
}
if (r_list)
*r_list = list;
else
gcry_sexp_release (list);
return 0;
}
/* Return the public key algorithm number if S_KEY is a DSA style key.
If it is not a DSA style key, return 0. */
int
agent_is_dsa_key (gcry_sexp_t s_key)
{
char algoname[6];
if (!s_key)
return 0;
if (key_parms_from_sexp (s_key, NULL, algoname, sizeof algoname, NULL, 0))
return 0; /* Error - assume it is not an DSA key. */
if (!strcmp (algoname, "dsa"))
return GCRY_PK_DSA;
else if (!strcmp (algoname, "ecdsa"))
return GCRY_PK_ECDSA;
else
return 0;
}
/* Return the public key for the keygrip GRIP. The result is stored
at RESULT. This function extracts the public key from the private
key database. On failure an error code is returned and NULL stored
at RESULT. */
gpg_error_t
agent_public_key_from_file (ctrl_t ctrl,
const unsigned char *grip,
gcry_sexp_t *result)
{
gpg_error_t err;
int i, idx;
gcry_sexp_t s_skey;
char algoname[6];
char elems[6];
gcry_sexp_t uri_sexp, comment_sexp;
const char *uri, *comment;
size_t uri_length, comment_length;
char *format, *p;
void *args[4+2+2+1]; /* Size is max. # of elements + 2 for uri + 2
for comment + end-of-list. */
int argidx;
gcry_sexp_t list, l2;
const char *s;
gcry_mpi_t *array;
(void)ctrl;
*result = NULL;
err = read_key_file (grip, &s_skey);
if (err)
return err;
err = key_parms_from_sexp (s_skey, &list,
algoname, sizeof algoname,
elems, sizeof elems);
if (err)
{
gcry_sexp_release (s_skey);
return err;
}
/* Allocate an array for the parameters and copy them out of the
secret key. FIXME: We should have a generic copy function. */
array = xtrycalloc (strlen(elems) + 1, sizeof *array);
if (!array)
{
err = gpg_error_from_syserror ();
gcry_sexp_release (list);
gcry_sexp_release (s_skey);
return err;
}
for (idx=0, s=elems; *s; s++, idx++ )
{
l2 = gcry_sexp_find_token (list, s, 1);
if (!l2)
{
/* Required parameter not found. */
for (i=0; i.
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#ifdef HAVE_W32_SYSTEM
# include
#else
# include
#endif
#include "agent.h"
#include "sexp-parse.h"
#define PROT_CIPHER GCRY_CIPHER_AES
#define PROT_CIPHER_STRING "aes"
#define PROT_CIPHER_KEYLEN (128/8)
/* A table containing the information needed to create a protected
private key */
static struct {
const char *algo;
const char *parmlist;
int prot_from, prot_to;
} protect_info[] = {
{ "rsa", "nedpqu", 2, 5 },
{ "dsa", "pqgyx", 4, 4 },
{ "elg", "pgyx", 3, 3 },
+ { "ecdsa","cqd", 2, 2 },
+ { "ecdh", "cqpd", 3, 3 },
{ NULL }
};
/* A helper object for time measurement. */
struct calibrate_time_s
{
#ifdef HAVE_W32_SYSTEM
FILETIME creation_time, exit_time, kernel_time, user_time;
#else
clock_t ticks;
#endif
};
static int
hash_passphrase (const char *passphrase, int hashalgo,
int s2kmode,
const unsigned char *s2ksalt, unsigned long s2kcount,
unsigned char *key, size_t keylen);
/* Get the process time and store it in DATA. */
static void
calibrate_get_time (struct calibrate_time_s *data)
{
#ifdef HAVE_W32_SYSTEM
# ifdef HAVE_W32CE_SYSTEM
GetThreadTimes (GetCurrentThread (),
# else
GetProcessTimes (GetCurrentProcess (),
# endif
&data->creation_time, &data->exit_time,
&data->kernel_time, &data->user_time);
#else
struct tms tmp;
times (&tmp);
data->ticks = tmp.tms_utime;
#endif
}
static unsigned long
calibrate_elapsed_time (struct calibrate_time_s *starttime)
{
struct calibrate_time_s stoptime;
calibrate_get_time (&stoptime);
#ifdef HAVE_W32_SYSTEM
{
unsigned long long t1, t2;
t1 = (((unsigned long long)starttime->kernel_time.dwHighDateTime << 32)
+ starttime->kernel_time.dwLowDateTime);
t1 += (((unsigned long long)starttime->user_time.dwHighDateTime << 32)
+ starttime->user_time.dwLowDateTime);
t2 = (((unsigned long long)stoptime.kernel_time.dwHighDateTime << 32)
+ stoptime.kernel_time.dwLowDateTime);
t2 += (((unsigned long long)stoptime.user_time.dwHighDateTime << 32)
+ stoptime.user_time.dwLowDateTime);
return (unsigned long)((t2 - t1)/10000);
}
#else
return (unsigned long)((((double) (stoptime.ticks - starttime->ticks))
/CLOCKS_PER_SEC)*10000000);
#endif
}
/* Run a test hashing for COUNT and return the time required in
milliseconds. */
static unsigned long
calibrate_s2k_count_one (unsigned long count)
{
int rc;
char keybuf[PROT_CIPHER_KEYLEN];
struct calibrate_time_s starttime;
calibrate_get_time (&starttime);
rc = hash_passphrase ("123456789abcdef0", GCRY_MD_SHA1,
3, "saltsalt", count, keybuf, sizeof keybuf);
if (rc)
BUG ();
return calibrate_elapsed_time (&starttime);
}
/* Measure the time we need to do the hash operations and deduce an
S2K count which requires about 100ms of time. */
static unsigned long
calibrate_s2k_count (void)
{
unsigned long count;
unsigned long ms;
for (count = 65536; count; count *= 2)
{
ms = calibrate_s2k_count_one (count);
if (opt.verbose > 1)
log_info ("S2K calibration: %lu -> %lums\n", count, ms);
if (ms > 100)
break;
}
count = (unsigned long)(((double)count / ms) * 100);
count /= 1024;
count *= 1024;
if (count < 65536)
count = 65536;
if (opt.verbose)
{
ms = calibrate_s2k_count_one (count);
log_info ("S2K calibration: %lu -> %lums\n", count, ms);
}
return count;
}
/* Return the standard S2K count. */
unsigned long
get_standard_s2k_count (void)
{
static unsigned long count;
if (!count)
count = calibrate_s2k_count ();
/* Enforce a lower limit. */
return count < 65536 ? 65536 : count;
}
/* Calculate the MIC for a private key or shared secret S-expression.
SHA1HASH should point to a 20 byte buffer. This function is
suitable for all algorithms. */
static int
calculate_mic (const unsigned char *plainkey, unsigned char *sha1hash)
{
const unsigned char *hash_begin, *hash_end;
const unsigned char *s;
size_t n;
int is_shared_secret;
s = plainkey;
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (smatch (&s, n, "private-key"))
is_shared_secret = 0;
else if (smatch (&s, n, "shared-secret"))
is_shared_secret = 1;
else
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
if (*s != '(')
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
hash_begin = s;
if (!is_shared_secret)
{
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
s += n; /* Skip the algorithm name. */
}
while (*s == '(')
{
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
s += n;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
s += n;
if ( *s != ')' )
return gpg_error (GPG_ERR_INV_SEXP);
s++;
}
if (*s != ')')
return gpg_error (GPG_ERR_INV_SEXP);
s++;
hash_end = s;
gcry_md_hash_buffer (GCRY_MD_SHA1, sha1hash,
hash_begin, hash_end - hash_begin);
return 0;
}
/* Encrypt the parameter block starting at PROTBEGIN with length
PROTLEN using the utf8 encoded key PASSPHRASE and return the entire
encrypted block in RESULT or return with an error code. SHA1HASH
is the 20 byte SHA-1 hash required for the integrity code.
The parameter block is expected to be an incomplete S-Expression of
the form (example in advanced format):
(d #046129F..[some bytes not shown]..81#)
(p #00e861b..[some bytes not shown]..f1#)
(q #00f7a7c..[some bytes not shown]..61#)
(u #304559a..[some bytes not shown]..9b#)
the returned block is the S-Expression:
(protected mode (parms) encrypted_octet_string)
*/
static int
do_encryption (const unsigned char *protbegin, size_t protlen,
const char *passphrase, const unsigned char *sha1hash,
unsigned char **result, size_t *resultlen)
{
gcry_cipher_hd_t hd;
const char *modestr = "openpgp-s2k3-sha1-" PROT_CIPHER_STRING "-cbc";
int blklen, enclen, outlen;
unsigned char *iv = NULL;
int rc;
char *outbuf = NULL;
char *p;
int saltpos, ivpos, encpos;
*resultlen = 0;
*result = NULL;
rc = gcry_cipher_open (&hd, PROT_CIPHER, GCRY_CIPHER_MODE_CBC,
GCRY_CIPHER_SECURE);
if (rc)
return rc;
/* We need to work on a copy of the data because this makes it
easier to add the trailer and the padding and more important we
have to prefix the text with 2 parenthesis, so we have to
allocate enough space for:
(()(4:hash4:sha120:)) + padding
We always append a full block of random bytes as padding but
encrypt only what is needed for a full blocksize. */
blklen = gcry_cipher_get_algo_blklen (PROT_CIPHER);
outlen = 2 + protlen + 2 + 6 + 6 + 23 + 2 + blklen;
enclen = outlen/blklen * blklen;
outbuf = gcry_malloc_secure (outlen);
if (!outbuf)
rc = out_of_core ();
if (!rc)
{
/* Allocate random bytes to be used as IV, padding and s2k salt. */
iv = xtrymalloc (blklen*2+8);
if (!iv)
rc = gpg_error (GPG_ERR_ENOMEM);
else
{
gcry_create_nonce (iv, blklen*2+8);
rc = gcry_cipher_setiv (hd, iv, blklen);
}
}
if (!rc)
{
unsigned char *key;
size_t keylen = PROT_CIPHER_KEYLEN;
key = gcry_malloc_secure (keylen);
if (!key)
rc = out_of_core ();
else
{
rc = hash_passphrase (passphrase, GCRY_MD_SHA1,
3, iv+2*blklen,
get_standard_s2k_count (), key, keylen);
if (!rc)
rc = gcry_cipher_setkey (hd, key, keylen);
xfree (key);
}
}
if (!rc)
{
p = outbuf;
*p++ = '(';
*p++ = '(';
memcpy (p, protbegin, protlen);
p += protlen;
memcpy (p, ")(4:hash4:sha120:", 17);
p += 17;
memcpy (p, sha1hash, 20);
p += 20;
*p++ = ')';
*p++ = ')';
memcpy (p, iv+blklen, blklen);
p += blklen;
assert ( p - outbuf == outlen);
rc = gcry_cipher_encrypt (hd, outbuf, enclen, NULL, 0);
}
gcry_cipher_close (hd);
if (rc)
{
xfree (iv);
xfree (outbuf);
return rc;
}
/* Now allocate the buffer we want to return. This is
(protected openpgp-s2k3-sha1-aes-cbc
((sha1 salt no_of_iterations) 16byte_iv)
encrypted_octet_string)
in canoncical format of course. We use asprintf and %n modifier
and dummy values as placeholders. */
{
char countbuf[35];
snprintf (countbuf, sizeof countbuf, "%lu", get_standard_s2k_count ());
p = xtryasprintf
("(9:protected%d:%s((4:sha18:%n_8bytes_%u:%s)%d:%n%*s)%d:%n%*s)",
(int)strlen (modestr), modestr,
&saltpos,
(unsigned int)strlen (countbuf), countbuf,
blklen, &ivpos, blklen, "",
enclen, &encpos, enclen, "");
if (!p)
{
gpg_error_t tmperr = out_of_core ();
xfree (iv);
xfree (outbuf);
return tmperr;
}
}
*resultlen = strlen (p);
*result = (unsigned char*)p;
memcpy (p+saltpos, iv+2*blklen, 8);
memcpy (p+ivpos, iv, blklen);
memcpy (p+encpos, outbuf, enclen);
xfree (iv);
xfree (outbuf);
return 0;
}
/* Protect the key encoded in canonical format in PLAINKEY. We assume
a valid S-Exp here. */
int
agent_protect (const unsigned char *plainkey, const char *passphrase,
unsigned char **result, size_t *resultlen)
{
int rc;
const unsigned char *s;
const unsigned char *hash_begin, *hash_end;
const unsigned char *prot_begin, *prot_end, *real_end;
size_t n;
int c, infidx, i;
unsigned char hashvalue[20];
char timestamp_exp[35];
unsigned char *protected;
size_t protectedlen;
int depth = 0;
unsigned char *p;
gcry_md_hd_t md;
+ if (opt.debug & DBG_CRYPTO_VALUE)
+ log_info ("Protecting key=%s, passphrase=%s\n", plainkey, passphrase);
+
/* Create an S-expression with the protected-at timestamp. */
memcpy (timestamp_exp, "(12:protected-at15:", 19);
gnupg_get_isotime (timestamp_exp+19);
timestamp_exp[19+15] = ')';
/* Parse original key. */
s = plainkey;
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
depth++;
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (!smatch (&s, n, "private-key"))
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
if (*s != '(')
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
depth++;
hash_begin = s;
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
for (infidx=0; protect_info[infidx].algo
&& !smatch (&s, n, protect_info[infidx].algo); infidx++)
;
- if (!protect_info[infidx].algo)
+ if (!protect_info[infidx].algo) {
+ log_info ("Unsupported alg %d for protection\n", protect_info[infidx].algo);
return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
+ }
prot_begin = prot_end = NULL;
for (i=0; (c=protect_info[infidx].parmlist[i]); i++)
{
if (i == protect_info[infidx].prot_from)
prot_begin = s;
- if (*s != '(')
+ if (*s != '(') {
+ log_info ("Unbalanced bracket in S-expression #1\n");
return gpg_error (GPG_ERR_INV_SEXP);
+ }
depth++;
s++;
n = snext (&s);
- if (!n)
+ if (!n) {
+ log_info ("Cannot get the length of S-expression field\n");
return gpg_error (GPG_ERR_INV_SEXP);
- if (n != 1 || c != *s)
+ }
+ if (n != 1 || c != *s) {
+ log_info ("Invalid length in S-expression field\n");
return gpg_error (GPG_ERR_INV_SEXP);
- s += n;
+ }
+ s += n;
n = snext (&s);
- if (!n)
+ if (!n) {
+ log_info ("Invalid fieled in S-expression field\n");
return gpg_error (GPG_ERR_INV_SEXP);
+ }
s +=n; /* skip value */
- if (*s != ')')
+ if (*s != ')') {
+ log_info ("Unbalanced bracket in S-expression #2\n");
return gpg_error (GPG_ERR_INV_SEXP);
+ }
depth--;
if (i == protect_info[infidx].prot_to)
prot_end = s;
s++;
}
- if (*s != ')' || !prot_begin || !prot_end )
+ if (*s != ')' || !prot_begin || !prot_end ) {
+ log_info ("Unbalanced bracket in S-expression #3\n");
return gpg_error (GPG_ERR_INV_SEXP);
+ }
depth--;
hash_end = s;
s++;
/* skip to the end of the S-exp */
assert (depth == 1);
rc = sskip (&s, &depth);
if (rc)
return rc;
assert (!depth);
real_end = s-1;
/* Hash the stuff. Because the timestamp_exp won't get protected,
we can't simply hash a continuous buffer but need to use several
md_writes. */
rc = gcry_md_open (&md, GCRY_MD_SHA1, 0 );
if (rc)
return rc;
gcry_md_write (md, hash_begin, hash_end - hash_begin);
gcry_md_write (md, timestamp_exp, 35);
gcry_md_write (md, ")", 1);
memcpy (hashvalue, gcry_md_read (md, GCRY_MD_SHA1), 20);
gcry_md_close (md);
rc = do_encryption (prot_begin, prot_end - prot_begin + 1,
passphrase, hashvalue,
&protected, &protectedlen);
if (rc)
return rc;
/* Now create the protected version of the key. Note that the 10
extra bytes are for for the inserted "protected-" string (the
beginning of the plaintext reads: "((11:private-key(" ). The 35
term is the space for (12:protected-at15:). */
*resultlen = (10
+ (prot_begin-plainkey)
+ protectedlen
+ 35
+ (real_end-prot_end));
*result = p = xtrymalloc (*resultlen);
if (!p)
{
gpg_error_t tmperr = out_of_core ();
xfree (protected);
return tmperr;
}
memcpy (p, "(21:protected-", 14);
p += 14;
memcpy (p, plainkey+4, prot_begin - plainkey - 4);
p += prot_begin - plainkey - 4;
memcpy (p, protected, protectedlen);
p += protectedlen;
memcpy (p, timestamp_exp, 35);
p += 35;
memcpy (p, prot_end+1, real_end - prot_end);
p += real_end - prot_end;
assert ( p - *result == *resultlen);
xfree (protected);
return 0;
}
/* Do the actual decryption and check the return list for consistency. */
static int
do_decryption (const unsigned char *protected, size_t protectedlen,
const char *passphrase,
const unsigned char *s2ksalt, unsigned long s2kcount,
const unsigned char *iv, size_t ivlen,
unsigned char **result)
{
int rc = 0;
int blklen;
gcry_cipher_hd_t hd;
unsigned char *outbuf;
size_t reallen;
blklen = gcry_cipher_get_algo_blklen (PROT_CIPHER);
if (protectedlen < 4 || (protectedlen%blklen))
return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
rc = gcry_cipher_open (&hd, PROT_CIPHER, GCRY_CIPHER_MODE_CBC,
GCRY_CIPHER_SECURE);
if (rc)
return rc;
outbuf = gcry_malloc_secure (protectedlen);
if (!outbuf)
rc = out_of_core ();
if (!rc)
rc = gcry_cipher_setiv (hd, iv, ivlen);
if (!rc)
{
unsigned char *key;
size_t keylen = PROT_CIPHER_KEYLEN;
key = gcry_malloc_secure (keylen);
if (!key)
rc = out_of_core ();
else
{
rc = hash_passphrase (passphrase, GCRY_MD_SHA1,
3, s2ksalt, s2kcount, key, keylen);
if (!rc)
rc = gcry_cipher_setkey (hd, key, keylen);
xfree (key);
}
}
if (!rc)
rc = gcry_cipher_decrypt (hd, outbuf, protectedlen,
protected, protectedlen);
gcry_cipher_close (hd);
if (rc)
{
xfree (outbuf);
return rc;
}
/* Do a quick check first. */
if (*outbuf != '(' && outbuf[1] != '(')
{
xfree (outbuf);
return gpg_error (GPG_ERR_BAD_PASSPHRASE);
}
/* Check that we have a consistent S-Exp. */
reallen = gcry_sexp_canon_len (outbuf, protectedlen, NULL, NULL);
if (!reallen || (reallen + blklen < protectedlen) )
{
xfree (outbuf);
return gpg_error (GPG_ERR_BAD_PASSPHRASE);
}
*result = outbuf;
return 0;
}
/* Merge the parameter list contained in CLEARTEXT with the original
protect lists PROTECTEDKEY by replacing the list at REPLACEPOS.
Return the new list in RESULT and the MIC value in the 20 byte
buffer SHA1HASH. CUTOFF and CUTLEN will receive the offset and the
length of the resulting list which should go into the MIC
calculation but then be removed. */
static int
merge_lists (const unsigned char *protectedkey,
size_t replacepos,
const unsigned char *cleartext,
unsigned char *sha1hash,
unsigned char **result, size_t *resultlen,
size_t *cutoff, size_t *cutlen)
{
size_t n, newlistlen;
unsigned char *newlist, *p;
const unsigned char *s;
const unsigned char *startpos, *endpos;
int i, rc;
*result = NULL;
*resultlen = 0;
*cutoff = 0;
*cutlen = 0;
if (replacepos < 26)
return gpg_error (GPG_ERR_BUG);
/* Estimate the required size of the resulting list. We have a large
safety margin of >20 bytes (MIC hash from CLEARTEXT and the
removed "protected-" */
newlistlen = gcry_sexp_canon_len (protectedkey, 0, NULL, NULL);
if (!newlistlen)
return gpg_error (GPG_ERR_BUG);
n = gcry_sexp_canon_len (cleartext, 0, NULL, NULL);
if (!n)
return gpg_error (GPG_ERR_BUG);
newlistlen += n;
newlist = gcry_malloc_secure (newlistlen);
if (!newlist)
return out_of_core ();
/* Copy the initial segment */
strcpy ((char*)newlist, "(11:private-key");
p = newlist + 15;
memcpy (p, protectedkey+15+10, replacepos-15-10);
p += replacepos-15-10;
/* copy the cleartext */
s = cleartext;
if (*s != '(' && s[1] != '(')
return gpg_error (GPG_ERR_BUG); /*we already checked this */
s += 2;
startpos = s;
while ( *s == '(' )
{
s++;
n = snext (&s);
if (!n)
goto invalid_sexp;
s += n;
n = snext (&s);
if (!n)
goto invalid_sexp;
s += n;
if ( *s != ')' )
goto invalid_sexp;
s++;
}
if ( *s != ')' )
goto invalid_sexp;
endpos = s;
s++;
/* Intermezzo: Get the MIC */
if (*s != '(')
goto invalid_sexp;
s++;
n = snext (&s);
if (!smatch (&s, n, "hash"))
goto invalid_sexp;
n = snext (&s);
if (!smatch (&s, n, "sha1"))
goto invalid_sexp;
n = snext (&s);
if (n != 20)
goto invalid_sexp;
memcpy (sha1hash, s, 20);
s += n;
if (*s != ')')
goto invalid_sexp;
/* End intermezzo */
/* append the parameter list */
memcpy (p, startpos, endpos - startpos);
p += endpos - startpos;
/* Skip over the protected list element in the original list. */
s = protectedkey + replacepos;
assert (*s == '(');
s++;
i = 1;
rc = sskip (&s, &i);
if (rc)
goto failure;
/* Record the position of the optional protected-at expression. */
if (*s == '(')
{
const unsigned char *save_s = s;
s++;
n = snext (&s);
if (smatch (&s, n, "protected-at"))
{
i = 1;
rc = sskip (&s, &i);
if (rc)
goto failure;
*cutlen = s - save_s;
}
s = save_s;
}
startpos = s;
i = 2; /* we are inside this level */
rc = sskip (&s, &i);
if (rc)
goto failure;
assert (s[-1] == ')');
endpos = s; /* one behind the end of the list */
/* Append the rest. */
if (*cutlen)
*cutoff = p - newlist;
memcpy (p, startpos, endpos - startpos);
p += endpos - startpos;
/* ready */
*result = newlist;
*resultlen = newlistlen;
return 0;
failure:
wipememory (newlist, newlistlen);
xfree (newlist);
return rc;
invalid_sexp:
wipememory (newlist, newlistlen);
xfree (newlist);
return gpg_error (GPG_ERR_INV_SEXP);
}
/* Unprotect the key encoded in canonical format. We assume a valid
S-Exp here. If a protected-at item is available, its value will
be stored at protocted_at unless this is NULL. */
int
agent_unprotect (const unsigned char *protectedkey, const char *passphrase,
gnupg_isotime_t protected_at,
unsigned char **result, size_t *resultlen)
{
int rc;
const unsigned char *s;
const unsigned char *protect_list;
size_t n;
int infidx, i;
unsigned char sha1hash[20], sha1hash2[20];
const unsigned char *s2ksalt;
unsigned long s2kcount;
const unsigned char *iv;
const unsigned char *prot_begin;
unsigned char *cleartext;
unsigned char *final;
size_t finallen;
size_t cutoff, cutlen;
if (protected_at)
*protected_at = 0;
s = protectedkey;
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (!smatch (&s, n, "protected-private-key"))
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
if (*s != '(')
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
for (infidx=0; protect_info[infidx].algo
&& !smatch (&s, n, protect_info[infidx].algo); infidx++)
;
if (!protect_info[infidx].algo)
return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
/* See wether we have a protected-at timestamp. */
protect_list = s; /* Save for later. */
if (protected_at)
{
while (*s == '(')
{
prot_begin = s;
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (smatch (&s, n, "protected-at"))
{
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (n != 15)
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
memcpy (protected_at, s, 15);
protected_at[15] = 0;
break;
}
s += n;
i = 1;
rc = sskip (&s, &i);
if (rc)
return rc;
}
}
/* Now find the list with the protected information. Here is an
example for such a list:
(protected openpgp-s2k3-sha1-aes-cbc
((sha1 ) )
)
*/
s = protect_list;
for (;;)
{
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
prot_begin = s;
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (smatch (&s, n, "protected"))
break;
s += n;
i = 1;
rc = sskip (&s, &i);
if (rc)
return rc;
}
/* found */
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (!smatch (&s, n, "openpgp-s2k3-sha1-" PROT_CIPHER_STRING "-cbc"))
return gpg_error (GPG_ERR_UNSUPPORTED_PROTECTION);
if (*s != '(' || s[1] != '(')
return gpg_error (GPG_ERR_INV_SEXP);
s += 2;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (!smatch (&s, n, "sha1"))
return gpg_error (GPG_ERR_UNSUPPORTED_PROTECTION);
n = snext (&s);
if (n != 8)
return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
s2ksalt = s;
s += n;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
/* We expect a list close as next, so we can simply use strtoul()
here. We might want to check that we only have digits - but this
is nothing we should worry about */
if (s[n] != ')' )
return gpg_error (GPG_ERR_INV_SEXP);
/* Old versions of gpg-agent used the funny floating point number in
a byte encoding as specified by OpenPGP. However this is not
needed and thus we now store it as a plain unsigned integer. We
can easily distinguish the old format by looking at its value:
Less than 256 is an old-style encoded number; other values are
plain integers. In any case we check that they are at least
65536 because we never used a lower value in the past and we
should have a lower limit. */
s2kcount = strtoul ((const char*)s, NULL, 10);
if (!s2kcount)
return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
if (s2kcount < 256)
s2kcount = (16ul + (s2kcount & 15)) << ((s2kcount >> 4) + 6);
if (s2kcount < 65536)
return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
s += n;
s++; /* skip list end */
n = snext (&s);
if (n != 16) /* Wrong blocksize for IV (we support only aes-128). */
return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
iv = s;
s += n;
if (*s != ')' )
return gpg_error (GPG_ERR_INV_SEXP);
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
cleartext = NULL; /* Avoid cc warning. */
rc = do_decryption (s, n,
passphrase, s2ksalt, s2kcount,
iv, 16,
&cleartext);
if (rc)
return rc;
rc = merge_lists (protectedkey, prot_begin-protectedkey, cleartext,
sha1hash, &final, &finallen, &cutoff, &cutlen);
/* Albeit cleartext has been allocated in secure memory and thus
xfree will wipe it out, we do an extra wipe just in case
somethings goes badly wrong. */
wipememory (cleartext, n);
xfree (cleartext);
if (rc)
return rc;
rc = calculate_mic (final, sha1hash2);
if (!rc && memcmp (sha1hash, sha1hash2, 20))
rc = gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
if (rc)
{
wipememory (final, finallen);
xfree (final);
return rc;
}
/* Now remove the part which is included in the MIC but should not
go into the final thing. */
if (cutlen)
{
memmove (final+cutoff, final+cutoff+cutlen, finallen-cutoff-cutlen);
finallen -= cutlen;
}
*result = final;
*resultlen = gcry_sexp_canon_len (final, 0, NULL, NULL);
return 0;
}
/* Check the type of the private key, this is one of the constants:
PRIVATE_KEY_UNKNOWN if we can't figure out the type (this is the
value 0), PRIVATE_KEY_CLEAR for an unprotected private key.
PRIVATE_KEY_PROTECTED for an protected private key or
PRIVATE_KEY_SHADOWED for a sub key where the secret parts are stored
elsewhere. */
int
agent_private_key_type (const unsigned char *privatekey)
{
const unsigned char *s;
size_t n;
s = privatekey;
if (*s != '(')
return PRIVATE_KEY_UNKNOWN;
s++;
n = snext (&s);
if (!n)
return PRIVATE_KEY_UNKNOWN;
if (smatch (&s, n, "protected-private-key"))
return PRIVATE_KEY_PROTECTED;
if (smatch (&s, n, "shadowed-private-key"))
return PRIVATE_KEY_SHADOWED;
if (smatch (&s, n, "private-key"))
return PRIVATE_KEY_CLEAR;
return PRIVATE_KEY_UNKNOWN;
}
/* Transform a passphrase into a suitable key of length KEYLEN and
store this key in the caller provided buffer KEY. The caller must
provide an HASHALGO, a valid S2KMODE (see rfc-2440) and depending on
that mode an S2KSALT of 8 random bytes and an S2KCOUNT.
Returns an error code on failure. */
static int
hash_passphrase (const char *passphrase, int hashalgo,
int s2kmode,
const unsigned char *s2ksalt,
unsigned long s2kcount,
unsigned char *key, size_t keylen)
{
int rc;
gcry_md_hd_t md;
int pass, i;
int used = 0;
int pwlen = strlen (passphrase);
if ( (s2kmode != 0 && s2kmode != 1 && s2kmode != 3)
|| !hashalgo || !keylen || !key || !passphrase)
return gpg_error (GPG_ERR_INV_VALUE);
if ((s2kmode == 1 ||s2kmode == 3) && !s2ksalt)
return gpg_error (GPG_ERR_INV_VALUE);
rc = gcry_md_open (&md, hashalgo, GCRY_MD_FLAG_SECURE);
if (rc)
return rc;
for (pass=0; used < keylen; pass++)
{
if (pass)
{
gcry_md_reset (md);
for (i=0; i < pass; i++) /* preset the hash context */
gcry_md_putc (md, 0);
}
if (s2kmode == 1 || s2kmode == 3)
{
int len2 = pwlen + 8;
unsigned long count = len2;
if (s2kmode == 3)
{
count = s2kcount;
if (count < len2)
count = len2;
}
while (count > len2)
{
gcry_md_write (md, s2ksalt, 8);
gcry_md_write (md, passphrase, pwlen);
count -= len2;
}
if (count < 8)
gcry_md_write (md, s2ksalt, count);
else
{
gcry_md_write (md, s2ksalt, 8);
count -= 8;
gcry_md_write (md, passphrase, count);
}
}
else
gcry_md_write (md, passphrase, pwlen);
gcry_md_final (md);
i = gcry_md_get_algo_dlen (hashalgo);
if (i > keylen - used)
i = keylen - used;
memcpy (key+used, gcry_md_read (md, hashalgo), i);
used += i;
}
gcry_md_close(md);
return 0;
}
gpg_error_t
s2k_hash_passphrase (const char *passphrase, int hashalgo,
int s2kmode,
const unsigned char *s2ksalt,
unsigned int s2kcount,
unsigned char *key, size_t keylen)
{
return hash_passphrase (passphrase, hashalgo, s2kmode, s2ksalt,
(16ul + (s2kcount & 15)) << ((s2kcount >> 4) + 6),
key, keylen);
}
/* Create an canonical encoded S-expression with the shadow info from
a card's SERIALNO and the IDSTRING. */
unsigned char *
make_shadow_info (const char *serialno, const char *idstring)
{
const char *s;
char *info, *p;
char numbuf[20];
size_t n;
for (s=serialno, n=0; *s && s[1]; s += 2)
n++;
info = p = xtrymalloc (1 + sizeof numbuf + n
+ sizeof numbuf + strlen (idstring) + 1 + 1);
if (!info)
return NULL;
*p++ = '(';
p = stpcpy (p, smklen (numbuf, sizeof numbuf, n, NULL));
for (s=serialno; *s && s[1]; s += 2)
*(unsigned char *)p++ = xtoi_2 (s);
p = stpcpy (p, smklen (numbuf, sizeof numbuf, strlen (idstring), NULL));
p = stpcpy (p, idstring);
*p++ = ')';
*p = 0;
return (unsigned char *)info;
}
/* Create a shadow key from a public key. We use the shadow protocol
"ti-v1" and insert the S-expressionn SHADOW_INFO. The resulting
S-expression is returned in an allocated buffer RESULT will point
to. The input parameters are expected to be valid canonicalized
S-expressions */
int
agent_shadow_key (const unsigned char *pubkey,
const unsigned char *shadow_info,
unsigned char **result)
{
const unsigned char *s;
const unsigned char *point;
size_t n;
int depth = 0;
char *p;
size_t pubkey_len = gcry_sexp_canon_len (pubkey, 0, NULL,NULL);
size_t shadow_info_len = gcry_sexp_canon_len (shadow_info, 0, NULL,NULL);
if (!pubkey_len || !shadow_info_len)
return gpg_error (GPG_ERR_INV_VALUE);
s = pubkey;
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
depth++;
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (!smatch (&s, n, "public-key"))
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
if (*s != '(')
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
depth++;
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
s += n; /* skip over the algorithm name */
while (*s != ')')
{
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
depth++;
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
s += n;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
s +=n; /* skip value */
if (*s != ')')
return gpg_error (GPG_ERR_INV_SEXP);
depth--;
s++;
}
point = s; /* insert right before the point */
depth--;
s++;
assert (depth == 1);
/* Calculate required length by taking in account: the "shadowed-"
prefix, the "shadowed", "t1-v1" as well as some parenthesis */
n = 12 + pubkey_len + 1 + 3+8 + 2+5 + shadow_info_len + 1;
*result = xtrymalloc (n);
p = (char*)*result;
if (!p)
return out_of_core ();
p = stpcpy (p, "(20:shadowed-private-key");
/* (10:public-key ...)*/
memcpy (p, pubkey+14, point - (pubkey+14));
p += point - (pubkey+14);
p = stpcpy (p, "(8:shadowed5:t1-v1");
memcpy (p, shadow_info, shadow_info_len);
p += shadow_info_len;
*p++ = ')';
memcpy (p, point, pubkey_len - (point - pubkey));
p += pubkey_len - (point - pubkey);
return 0;
}
/* Parse a canonical encoded shadowed key and return a pointer to the
inner list with the shadow_info */
int
agent_get_shadow_info (const unsigned char *shadowkey,
unsigned char const **shadow_info)
{
const unsigned char *s;
size_t n;
int depth = 0;
s = shadowkey;
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
depth++;
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (!smatch (&s, n, "shadowed-private-key"))
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
if (*s != '(')
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
depth++;
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
s += n; /* skip over the algorithm name */
for (;;)
{
if (*s == ')')
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
depth++;
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (smatch (&s, n, "shadowed"))
break;
s += n;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
s +=n; /* skip value */
if (*s != ')')
return gpg_error (GPG_ERR_INV_SEXP);
depth--;
s++;
}
/* Found the shadowed list, S points to the protocol */
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (smatch (&s, n, "t1-v1"))
{
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
*shadow_info = s;
}
else
return gpg_error (GPG_ERR_UNSUPPORTED_PROTOCOL);
return 0;
}
/* Parse the canonical encoded SHADOW_INFO S-expression. On success
the hex encoded serial number is returned as a malloced strings at
R_HEXSN and the Id string as a malloced string at R_IDSTR. On
error an error code is returned and NULL is stored at the result
parameters addresses. If the serial number or the ID string is not
required, NULL may be passed for them. */
gpg_error_t
parse_shadow_info (const unsigned char *shadow_info,
char **r_hexsn, char **r_idstr)
{
const unsigned char *s;
size_t n;
if (r_hexsn)
*r_hexsn = NULL;
if (r_idstr)
*r_idstr = NULL;
s = shadow_info;
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (r_hexsn)
{
*r_hexsn = bin2hex (s, n, NULL);
if (!*r_hexsn)
return gpg_error_from_syserror ();
}
s += n;
n = snext (&s);
if (!n)
{
if (r_hexsn)
{
xfree (*r_hexsn);
*r_hexsn = NULL;
}
return gpg_error (GPG_ERR_INV_SEXP);
}
if (r_idstr)
{
*r_idstr = xtrymalloc (n+1);
if (!*r_idstr)
{
if (r_hexsn)
{
xfree (*r_hexsn);
*r_hexsn = NULL;
}
return gpg_error_from_syserror ();
}
memcpy (*r_idstr, s, n);
(*r_idstr)[n] = 0;
}
return 0;
}
diff --git a/common/convert.c b/common/convert.c
index aa3a3a809..0a0c46f8e 100644
--- a/common/convert.c
+++ b/common/convert.c
@@ -1,249 +1,276 @@
/* convert.c - Hex conversion functions.
* Copyright (C) 2006, 2008 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
* 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
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include "util.h"
+#include "gcrypt.h"
#define tohex(n) ((n) < 10 ? ((n) + '0') : (((n) - 10) + 'A'))
/* Convert STRING consisting of hex characters into its binary
representation and store that at BUFFER. BUFFER needs to be of
LENGTH bytes. The function checks that the STRING will convert
exactly to LENGTH bytes. The string is delimited by either end of
string or a white space character. The function returns -1 on
error or the length of the parsed string. */
int
hex2bin (const char *string, void *buffer, size_t length)
{
int i;
const char *s = string;
for (i=0; i < length; )
{
if (!hexdigitp (s) || !hexdigitp (s+1))
return -1; /* Invalid hex digits. */
((unsigned char*)buffer)[i++] = xtoi_2 (s);
s += 2;
}
if (*s && (!isascii (*s) || !isspace (*s)) )
return -1; /* Not followed by Nul or white space. */
if (i != length)
return -1; /* Not of expected length. */
if (*s)
s++; /* Skip the delimiter. */
return s - string;
}
/* Convert STRING consisting of hex characters into its binary representation
and store that at BUFFER. BUFFER needs to be of LENGTH bytes. The
function check that the STRING will convert exactly to LENGTH
bytes. Colons inbetween the hex digits are allowed, if one colon
has been given a colon is expected very 2 characters. The string
is delimited by either end of string or a white space character.
The function returns -1 on error or the length of the parsed
string. */
int
hexcolon2bin (const char *string, void *buffer, size_t length)
{
int i;
const char *s = string;
int need_colon = 0;
for (i=0; i < length; )
{
if (i==1 && *s == ':') /* Skip colons between hex digits. */
{
need_colon = 1;
s++;
}
else if (need_colon && *s == ':')
s++;
else if (need_colon)
return -1; /* Colon expected. */
if (!hexdigitp (s) || !hexdigitp (s+1))
return -1; /* Invalid hex digits. */
((unsigned char*)buffer)[i++] = xtoi_2 (s);
s += 2;
}
if (*s == ':')
return -1; /* Trailing colons are not allowed. */
if (*s && (!isascii (*s) || !isspace (*s)) )
return -1; /* Not followed by Nul or white space. */
if (i != length)
return -1; /* Not of expected length. */
if (*s)
s++; /* Skip the delimiter. */
return s - string;
}
static char *
do_bin2hex (const void *buffer, size_t length, char *stringbuf, int with_colon)
{
const unsigned char *s;
char *p;
if (!stringbuf)
{
/* Not really correct for with_colon but we don't care about the
one wasted byte. */
size_t n = with_colon? 3:2;
size_t nbytes = n * length + 1;
if (length && (nbytes-1) / n != length)
{
gpg_err_set_errno (ENOMEM);
return NULL;
}
stringbuf = xtrymalloc (nbytes);
if (!stringbuf)
return NULL;
}
for (s = buffer, p = stringbuf; length; length--, s++)
{
if (with_colon && s != buffer)
*p++ = ':';
*p++ = tohex ((*s>>4)&15);
*p++ = tohex (*s&15);
}
*p = 0;
return stringbuf;
}
/* Convert LENGTH bytes of data in BUFFER into hex encoding and store
that at the provided STRINGBUF. STRINGBUF must be allocated of at
least (2*LENGTH+1) bytes or be NULL so that the function mallocs an
appropriate buffer. Returns STRINGBUF or NULL on error (which may
only occur if STRINGBUF has been NULL and the internal malloc
failed). */
char *
bin2hex (const void *buffer, size_t length, char *stringbuf)
{
return do_bin2hex (buffer, length, stringbuf, 0);
}
/* Convert LENGTH bytes of data in BUFFER into hex encoding and store
that at the provided STRINGBUF. STRINGBUF must be allocated of at
least (3*LENGTH+1) bytes or be NULL so that the function mallocs an
appropriate buffer. Returns STRINGBUF or NULL on error (which may
only occur if STRINGBUF has been NULL and the internal malloc
failed). */
char *
bin2hexcolon (const void *buffer, size_t length, char *stringbuf)
{
return do_bin2hex (buffer, length, stringbuf, 1);
}
/* Convert HEXSTRING consisting of hex characters into string and
store that at BUFFER. HEXSTRING is either delimited by end of
string or a white space character. The function makes sure that
the resulting string in BUFFER is terminated by a Nul character.
BUFSIZE is the availabe length of BUFFER; if the converted result
plus a possible required Nul character does not fit into this
buffer, the function returns NULL and won't change the existing
conent of buffer. In-place conversion is possible as long as
BUFFER points to HEXSTRING.
If BUFFER is NULL and bufsize is 0 the function scans HEXSTRING but
does not store anything. This may be used to find the end of
hexstring.
On sucess the function returns a pointer to the next character
after HEXSTRING (which is either end-of-string or a the next white
space). If BUFLEN is not NULL the strlen of buffer is stored
there; this will even be done if BUFFER has been passed as NULL. */
const char *
hex2str (const char *hexstring, char *buffer, size_t bufsize, size_t *buflen)
{
const char *s = hexstring;
int idx, count;
int need_nul = 0;
if (buflen)
*buflen = 0;
for (s=hexstring, count=0; hexdigitp (s) && hexdigitp (s+1); s += 2, count++)
;
if (*s && (!isascii (*s) || !isspace (*s)) )
return NULL; /* Not followed by Nul or white space. */
/* We need to append a nul character. However we don't want that if
the hexstring already ends with "00". */
need_nul = ((s == hexstring) || !(s[-2] == '0' && s[-1] == '0'));
if (need_nul)
count++;
if (buffer)
{
if (count > bufsize)
return NULL; /* Too long. */
for (s=hexstring, idx=0; hexdigitp (s) && hexdigitp (s+1); s += 2)
((unsigned char*)buffer)[idx++] = xtoi_2 (s);
if (need_nul)
buffer[idx] = 0;
}
if (buflen)
*buflen = count - 1;
return s;
}
/* Same as hex2str but this function allocated a new string. Returns
NULL on error. If R_COUNT is not NULL, the number of scanned bytes
will be stored there. ERRNO is set on error. */
char *
hex2str_alloc (const char *hexstring, size_t *r_count)
{
const char *tail;
size_t nbytes;
char *result;
tail = hex2str (hexstring, NULL, 0, &nbytes);
if (!tail)
{
if (r_count)
*r_count = 0;
gpg_err_set_errno (EINVAL);
return NULL;
}
if (r_count)
*r_count = tail - hexstring;
result = xtrymalloc (nbytes+1);
if (!result)
return NULL;
if (!hex2str (hexstring, result, nbytes+1, NULL))
BUG ();
return result;
}
+/* returns hex representation of the MPI;
+ * caller must free with xfree
+ * Returns NULL on error, never throws
+ */
+char *mpi2hex( gcry_mpi_t m ) {
+ size_t nbytes;
+ size_t nbytes2;
+ int rc;
+ byte *p;
+
+ nbytes = (mpi_get_nbits ( m )+7)/8;
+ if( nbytes == 0 )
+ return NULL;
+ p = xtrymalloc( nbytes*3+1 );
+ if( p==NULL )
+ return NULL;
+ rc = gcry_mpi_print (GCRYMPI_FMT_USG, p+2*nbytes+1, nbytes, &nbytes2, m);
+ if( rc ) {
+ xfree( p );
+ return NULL;
+ }
+ bin2hex( p+2*nbytes+1, nbytes2, p );
+ p[nbytes2*2] = '\0';
+//printf("%s:%d>>>> Created the string %s from %d bytes %02x %02x ..., MPI was %d bytes\n", __FILE__, __LINE__, p, nbytes2, p[2*nbytes+1], p[2*nbytes+2], nbytes);
+ return p;
+}
diff --git a/common/util.h b/common/util.h
index 7c58b15c5..44a72d90c 100644
--- a/common/util.h
+++ b/common/util.h
@@ -1,327 +1,328 @@
/* util.h - Utility functions for GnuPG
* Copyright (C) 2001, 2002, 2003, 2004, 2009 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
* 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
* along with this program; if not, see .
*/
#ifndef GNUPG_COMMON_UTIL_H
#define GNUPG_COMMON_UTIL_H
#include /* We need this for the memory function protos. */
#include /* We need errno. */
#include /* We need gpg_error_t. */
/* Add error codes available only in newer versions of libgpg-error. */
#ifndef GPG_ERR_MISSING_KEY
#define GPG_ERR_MISSING_KEY 181
#endif
#ifndef GPG_ERR_LIMIT_REACHED
#define GPG_ERR_LIMIT_REACHED 183
#endif
#ifndef GPG_ERR_NOT_INITIALIZED
#define GPG_ERR_NOT_INITIALIZED 184
#endif
#ifndef GPG_ERR_MISSING_ISSUER_CERT
#define GPG_ERR_MISSING_ISSUER_CERT 185
#endif
#ifndef GPG_ERR_FULLY_CANCELED
#define GPG_ERR_FULLY_CANCELED 198
#endif
/* Hash function used with libksba. */
#define HASH_FNC ((void (*)(void *, const void*,size_t))gcry_md_write)
/* Estream replaces most uses of stdio. */
#include "../common/estream.h"
#include "../common/estream-printf.h"
/* Get all the stuff from jnlib. */
#include "../common/logging.h"
#include "../common/argparse.h"
#include "../common/stringhelp.h"
#include "../common/mischelp.h"
#include "../common/strlist.h"
#include "../common/dotlock.h"
#include "../common/utf8conv.h"
#include "../common/dynload.h"
#include "init.h"
#include "gettime.h"
/* Redefine asprintf by our estream version which uses our own memory
allocator.. */
#define asprintf estream_asprintf
#define vasprintf estream_vasprintf
/* Due to a bug in mingw32's snprintf related to the 'l' modifier and
for increased portability we use our snprintf on all systems. */
#define snprintf estream_snprintf
/* GCC attributes. */
#if __GNUC__ >= 4
# define GNUPG_GCC_A_SENTINEL(a) __attribute__ ((sentinel(a)))
#else
# define GNUPG_GCC_A_SENTINEL(a)
#endif
/* We need this type even if we are not using libreadline and or we
did not include libreadline in the current file. */
#ifndef GNUPG_LIBREADLINE_H_INCLUDED
typedef char **rl_completion_func_t (const char *, int, int);
#endif /*!GNUPG_LIBREADLINE_H_INCLUDED*/
/* Handy malloc macros - please use only them. */
#define xtrymalloc(a) gcry_malloc ((a))
#define xtrymalloc_secure(a) gcry_malloc_secure ((a))
#define xtrycalloc(a,b) gcry_calloc ((a),(b))
#define xtrycalloc_secure(a,b) gcry_calloc_secure ((a),(b))
#define xtryrealloc(a,b) gcry_realloc ((a),(b))
#define xtrystrdup(a) gcry_strdup ((a))
#define xfree(a) gcry_free ((a))
#define xfree_fnc gcry_free
#define xmalloc(a) gcry_xmalloc ((a))
#define xmalloc_secure(a) gcry_xmalloc_secure ((a))
#define xcalloc(a,b) gcry_xcalloc ((a),(b))
#define xcalloc_secure(a,b) gcry_xcalloc_secure ((a),(b))
#define xrealloc(a,b) gcry_xrealloc ((a),(b))
#define xstrdup(a) gcry_xstrdup ((a))
/* For compatibility with gpg 1.4 we also define these: */
#define xmalloc_clear(a) gcry_xcalloc (1, (a))
#define xmalloc_secure_clear(a) gcry_xcalloc_secure (1, (a))
/* Convenience function to return a gpg-error code for memory
allocation failures. This function makes sure that an error will
be returned even if accidently ERRNO is not set. */
static inline gpg_error_t
out_of_core (void)
{
return gpg_error_from_syserror ();
}
/*-- signal.c --*/
void gnupg_init_signals (int mode, void (*fast_cleanup)(void));
void gnupg_block_all_signals (void);
void gnupg_unblock_all_signals (void);
/*-- yesno.c --*/
int answer_is_yes (const char *s);
int answer_is_yes_no_default (const char *s, int def_answer);
int answer_is_yes_no_quit (const char *s);
int answer_is_okay_cancel (const char *s, int def_answer);
/*-- xreadline.c --*/
ssize_t read_line (FILE *fp,
char **addr_of_buffer, size_t *length_of_buffer,
size_t *max_length);
/*-- b64enc.c and b64dec.c --*/
struct b64state
{
unsigned int flags;
int idx;
int quad_count;
FILE *fp;
estream_t stream;
char *title;
unsigned char radbuf[4];
u32 crc;
int stop_seen:1;
int invalid_encoding:1;
};
gpg_error_t b64enc_start (struct b64state *state, FILE *fp, const char *title);
gpg_error_t b64enc_start_es (struct b64state *state, estream_t fp,
const char *title);
gpg_error_t b64enc_write (struct b64state *state,
const void *buffer, size_t nbytes);
gpg_error_t b64enc_finish (struct b64state *state);
gpg_error_t b64dec_start (struct b64state *state, const char *title);
gpg_error_t b64dec_proc (struct b64state *state, void *buffer, size_t length,
size_t *r_nbytes);
gpg_error_t b64dec_finish (struct b64state *state);
/*-- sexputil.c */
gpg_error_t make_canon_sexp (gcry_sexp_t sexp,
unsigned char **r_buffer, size_t *r_buflen);
gpg_error_t make_canon_sexp_pad (gcry_sexp_t sexp, int secure,
unsigned char **r_buffer, size_t *r_buflen);
gpg_error_t keygrip_from_canon_sexp (const unsigned char *key, size_t keylen,
unsigned char *grip);
int cmp_simple_canon_sexp (const unsigned char *a, const unsigned char *b);
unsigned char *make_simple_sexp_from_hexstr (const char *line,
size_t *nscanned);
int hash_algo_from_sigval (const unsigned char *sigval);
unsigned char *make_canon_sexp_from_rsa_pk (const void *m, size_t mlen,
const void *e, size_t elen,
size_t *r_len);
gpg_error_t get_rsa_pk_from_canon_sexp (const unsigned char *keydata,
size_t keydatalen,
unsigned char const **r_n,
size_t *r_nlen,
unsigned char const **r_e,
size_t *r_elen);
gpg_error_t get_pk_algo_from_canon_sexp (const unsigned char *keydata,
size_t keydatalen,
int *r_algo);
/*-- convert.c --*/
int hex2bin (const char *string, void *buffer, size_t length);
int hexcolon2bin (const char *string, void *buffer, size_t length);
char *bin2hex (const void *buffer, size_t length, char *stringbuf);
+char *mpi2hex (gcry_mpi_t m);
char *bin2hexcolon (const void *buffer, size_t length, char *stringbuf);
const char *hex2str (const char *hexstring,
char *buffer, size_t bufsize, size_t *buflen);
char *hex2str_alloc (const char *hexstring, size_t *r_count);
/*-- percent.c --*/
char *percent_plus_escape (const char *string);
char *percent_plus_unescape (const char *string, int nulrepl);
char *percent_unescape (const char *string, int nulrepl);
size_t percent_plus_unescape_inplace (char *string, int nulrepl);
size_t percent_unescape_inplace (char *string, int nulrepl);
/*-- homedir.c --*/
const char *standard_homedir (void);
const char *default_homedir (void);
const char *gnupg_sysconfdir (void);
const char *gnupg_bindir (void);
const char *gnupg_libexecdir (void);
const char *gnupg_libdir (void);
const char *gnupg_datadir (void);
const char *gnupg_localedir (void);
const char *gnupg_cachedir (void);
const char *dirmngr_socket_name (void);
/* All module names. We also include gpg and gpgsm for the sake for
gpgconf. */
#define GNUPG_MODULE_NAME_AGENT 1
#define GNUPG_MODULE_NAME_PINENTRY 2
#define GNUPG_MODULE_NAME_SCDAEMON 3
#define GNUPG_MODULE_NAME_DIRMNGR 4
#define GNUPG_MODULE_NAME_PROTECT_TOOL 5
#define GNUPG_MODULE_NAME_CHECK_PATTERN 6
#define GNUPG_MODULE_NAME_GPGSM 7
#define GNUPG_MODULE_NAME_GPG 8
#define GNUPG_MODULE_NAME_CONNECT_AGENT 9
#define GNUPG_MODULE_NAME_GPGCONF 10
#define GNUPG_MODULE_NAME_DIRMNGR_LDAP 11
const char *gnupg_module_name (int which);
/*-- gpgrlhelp.c --*/
void gnupg_rl_initialize (void);
/*-- helpfile.c --*/
char *gnupg_get_help_string (const char *key, int only_current_locale);
/*-- localename.c --*/
const char *gnupg_messages_locale_name (void);
/*-- miscellaneous.c --*/
/* This function is called at startup to tell libgcrypt to use our own
logging subsystem. */
void setup_libgcrypt_logging (void);
/* Same as estream_asprintf but die on memory failure. */
char *xasprintf (const char *fmt, ...) JNLIB_GCC_A_PRINTF(1,2);
/* This is now an alias to estream_asprintf. */
char *xtryasprintf (const char *fmt, ...) JNLIB_GCC_A_PRINTF(1,2);
/* Replacement for gcry_cipher_algo_name. */
const char *gnupg_cipher_algo_name (int algo);
const char *print_fname_stdout (const char *s);
const char *print_fname_stdin (const char *s);
void print_utf8_buffer2 (estream_t fp, const void *p, size_t n, int delim);
void print_utf8_buffer (estream_t fp, const void *p, size_t n);
void print_hexstring (FILE *fp, const void *buffer, size_t length,
int reserved);
char *make_printable_string (const void *p, size_t n, int delim);
int is_file_compressed (const char *s, int *ret_rc);
int match_multistr (const char *multistr,const char *match);
int gnupg_compare_version (const char *a, const char *b);
/*-- Simple replacement functions. */
#ifndef HAVE_TTYNAME
/* Systems without ttyname (W32) will merely return NULL. */
static inline char *
ttyname (int fd)
{
(void)fd;
return NULL;
}
#endif /* !HAVE_TTYNAME */
#ifdef HAVE_W32CE_SYSTEM
#define getpid() GetCurrentProcessId ()
char *_gnupg_getenv (const char *name); /* See sysutils.c */
#define getenv(a) _gnupg_getenv ((a))
char *_gnupg_setenv (const char *name); /* See sysutils.c */
#define setenv(a,b,c) _gnupg_setenv ((a),(b),(c))
int _gnupg_isatty (int fd);
#define gnupg_isatty(a) _gnupg_isatty ((a))
#else
#define gnupg_isatty(a) isatty ((a))
#endif
/*-- Macros to replace ctype ones to avoid locale problems. --*/
#define spacep(p) (*(p) == ' ' || *(p) == '\t')
#define digitp(p) (*(p) >= '0' && *(p) <= '9')
#define hexdigitp(a) (digitp (a) \
|| (*(a) >= 'A' && *(a) <= 'F') \
|| (*(a) >= 'a' && *(a) <= 'f'))
/* Note this isn't identical to a C locale isspace() without \f and
\v, but works for the purposes used here. */
#define ascii_isspace(a) ((a)==' ' || (a)=='\n' || (a)=='\r' || (a)=='\t')
/* The atoi macros assume that the buffer has only valid digits. */
#define atoi_1(p) (*(p) - '0' )
#define atoi_2(p) ((atoi_1(p) * 10) + atoi_1((p)+1))
#define atoi_4(p) ((atoi_2(p) * 100) + atoi_2((p)+2))
#define xtoi_1(p) (*(p) <= '9'? (*(p)- '0'): \
*(p) <= 'F'? (*(p)-'A'+10):(*(p)-'a'+10))
#define xtoi_2(p) ((xtoi_1(p) * 16) + xtoi_1((p)+1))
#define xtoi_4(p) ((xtoi_2(p) * 256) + xtoi_2((p)+2))
/*-- Forward declaration of the commonly used server control structure. */
/* (We need it here as it is used by some callback prototypes.) */
struct server_control_s;
typedef struct server_control_s *ctrl_t;
#endif /*GNUPG_COMMON_UTIL_H*/
diff --git a/configure.ac b/configure.ac
index 975733080..12545e260 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,1710 +1,1710 @@
# configure.ac - for GnuPG 2.1
# Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
# 2006, 2007, 2008, 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
# 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
# along with this program; if not, see .
# Process this file with autoconf to produce a configure script.
AC_PREREQ(2.61)
min_automake_version="1.10"
# Remember to change the version number immediately *after* a release.
# Set my_issvn to "yes" for non-released code. Remember to run an
# "svn up" and "autogen.sh" right before creating a distribution.
-m4_define([my_version], [2.1.0])
+m4_define([my_version], [2.2.0])
m4_define([my_issvn], [yes])
m4_define([svn_revision], m4_esyscmd([printf "%d" $(svn info 2>/dev/null \
| sed -n '/^Revision:/ s/[^0-9]//gp'|head -1)]))
m4_define([git_revision], m4_esyscmd([git branch -v 2>/dev/null \
| awk '/^\* / {printf "%s",$3}']))
AC_INIT([gnupg],
[my_version[]m4_if(my_issvn,[yes],
[m4_if(git_revision,[],[-svn[]svn_revision],[-git[]git_revision])])],
[http://bugs.gnupg.org])
# Set development_version to yes if the minor number is odd or you
# feel that the default check for a development version is not
# sufficient.
development_version=no
NEED_GPG_ERROR_VERSION=1.8
NEED_LIBGCRYPT_API=1
-NEED_LIBGCRYPT_VERSION=1.4.0
+NEED_LIBGCRYPT_VERSION=1.6.0
NEED_LIBASSUAN_API=2
NEED_LIBASSUAN_VERSION=2.0.0
NEED_KSBA_API=1
NEED_KSBA_VERSION=1.1.0
PACKAGE=$PACKAGE_NAME
PACKAGE_GT=${PACKAGE_NAME}2
VERSION=$PACKAGE_VERSION
AC_CONFIG_AUX_DIR(scripts)
AC_CONFIG_SRCDIR(sm/gpgsm.c)
AM_CONFIG_HEADER(config.h)
AM_INIT_AUTOMAKE($PACKAGE, $VERSION)
AC_CANONICAL_HOST
AB_INIT
AC_GNU_SOURCE
# Some status variables.
have_gpg_error=no
have_libgcrypt=no
have_libassuan=no
have_ksba=no
have_pth=no
have_libusb=no
have_adns=no
use_zip=yes
use_bzip2=yes
use_exec=yes
disable_keyserver_path=no
use_ccid_driver=yes
use_standard_socket=yes
dirmngr_auto_start=no
try_ks_ldap=no
GNUPG_BUILD_PROGRAM(gpg, yes)
GNUPG_BUILD_PROGRAM(gpgsm, yes)
GNUPG_BUILD_PROGRAM(agent, yes)
GNUPG_BUILD_PROGRAM(scdaemon, yes)
GNUPG_BUILD_PROGRAM(g13, yes)
GNUPG_BUILD_PROGRAM(dirmngr, yes)
GNUPG_BUILD_PROGRAM(tools, yes)
GNUPG_BUILD_PROGRAM(doc, yes)
GNUPG_BUILD_PROGRAM(symcryptrun, no)
GNUPG_BUILD_PROGRAM(gpgtar, no)
AC_SUBST(PACKAGE)
AC_SUBST(PACKAGE_GT)
AC_SUBST(VERSION)
AC_DEFINE_UNQUOTED(PACKAGE, "$PACKAGE", [Name of this package])
AC_DEFINE_UNQUOTED(PACKAGE_GT, "$PACKAGE_GT",
[Name of this package for gettext])
AC_DEFINE_UNQUOTED(VERSION, "$VERSION", [Version of this package])
AC_DEFINE_UNQUOTED(PACKAGE_BUGREPORT, "$PACKAGE_BUGREPORT",
[Bug report address])
AC_DEFINE_UNQUOTED(NEED_LIBGCRYPT_VERSION, "$NEED_LIBGCRYPT_VERSION",
[Required version of Libgcrypt])
AC_DEFINE_UNQUOTED(NEED_KSBA_VERSION, "$NEED_KSBA_VERSION",
[Required version of Libksba])
# The default is to use the modules from this package and the few
# other packages in a standard place; i.e where this package gets
# installed. With these options it is possible to override these
# ${prefix} depended values with fixed paths, which can't be replaced
# at make time. See also am/cmacros.am and the defaults in AH_BOTTOM.
AC_ARG_WITH(agent-pgm,
[ --with-agent-pgm=PATH Use PATH as the default for the agent)],
GNUPG_AGENT_PGM="$withval", GNUPG_AGENT_PGM="" )
AC_SUBST(GNUPG_AGENT_PGM)
AM_CONDITIONAL(GNUPG_AGENT_PGM, test -n "$GNUPG_AGENT_PGM")
show_gnupg_agent_pgm="(default)"
test -n "$GNUPG_AGENT_PGM" && show_gnupg_agent_pgm="$GNUPG_AGENT_PGM"
AC_ARG_WITH(pinentry-pgm,
[ --with-pinentry-pgm=PATH Use PATH as the default for the pinentry)],
GNUPG_PINENTRY_PGM="$withval", GNUPG_PINENTRY_PGM="" )
AC_SUBST(GNUPG_PINENTRY_PGM)
AM_CONDITIONAL(GNUPG_PINENTRY_PGM, test -n "$GNUPG_PINENTRY_PGM")
show_gnupg_pinentry_pgm="(default)"
test -n "$GNUPG_PINENTRY_PGM" && show_gnupg_pinentry_pgm="$GNUPG_PINENTRY_PGM"
AC_ARG_WITH(scdaemon-pgm,
[ --with-scdaemon-pgm=PATH Use PATH as the default for the scdaemon)],
GNUPG_SCDAEMON_PGM="$withval", GNUPG_SCDAEMON_PGM="" )
AC_SUBST(GNUPG_SCDAEMON_PGM)
AM_CONDITIONAL(GNUPG_SCDAEMON_PGM, test -n "$GNUPG_SCDAEMON_PGM")
show_gnupg_scdaemon_pgm="(default)"
test -n "$GNUPG_SCDAEMON_PGM" && show_gnupg_scdaemon_pgm="$GNUPG_SCDAEMON_PGM"
AC_ARG_WITH(dirmngr-pgm,
[ --with-dirmngr-pgm=PATH Use PATH as the default for the dirmngr)],
GNUPG_DIRMNGR_PGM="$withval", GNUPG_DIRMNGR_PGM="" )
AC_SUBST(GNUPG_DIRMNGR_PGM)
AM_CONDITIONAL(GNUPG_DIRMNGR_PGM, test -n "$GNUPG_DIRMNGR_PGM")
show_gnupg_dirmngr_pgm="(default)"
test -n "$GNUPG_DIRMNGR_PGM" && show_gnupg_dirmngr_pgm="$GNUPG_DIRMNGR_PGM"
AC_ARG_WITH(protect-tool-pgm,
[ --with-protect-tool-pgm=PATH Use PATH as the default for the protect-tool)],
GNUPG_PROTECT_TOOL_PGM="$withval", GNUPG_PROTECT_TOOL_PGM="" )
AC_SUBST(GNUPG_PROTECT_TOOL_PGM)
AM_CONDITIONAL(GNUPG_PROTECT_TOOL_PGM, test -n "$GNUPG_PROTECT_TOOL_PGM")
show_gnupg_protect_tool_pgm="(default)"
test -n "$GNUPG_PROTECT_TOOL_PGM" \
&& show_gnupg_protect_tool_pgm="$GNUPG_PROTECT_TOOL_PGM"
AC_ARG_WITH(dirmngr-ldap-pgm,
[ --with-dirmngr-ldap-pgm=PATH Use PATH as the default for the dirmnge ldap wrapper)],
GNUPG_DIRMNGR_LDAP_PGM="$withval", GNUPG_DIRMNGR_LDAP_PGM="" )
AC_SUBST(GNUPG_DIRMNGR_LDAP_PGM)
AM_CONDITIONAL(GNUPG_DIRMNGR_LDAP_PGM, test -n "$GNUPG_DIRMNGR_LDAP_PGM")
show_gnupg_dirmngr_ldap_pgm="(default)"
test -n "$GNUPG_DIRMNGR_LDAP_PGM" \
&& show_gnupg_dirmngr_ldap_pgm="$GNUPG_DIRMNGR_LDAP_PGM"
# Some folks want to use only the agent from this packet. Make it
# easier for them by providing the configure option
# --enable-only-agent.
AC_ARG_ENABLE(agent-only,
AC_HELP_STRING([--enable-agent-only],[build only the gpg-agent]),
build_agent_only=$enableval)
# SELinux support includes tracking of sensitive files to avoid
# leaking their contents through processing these files by gpg itself
AC_MSG_CHECKING([whether SELinux support is requested])
AC_ARG_ENABLE(selinux-support,
AC_HELP_STRING([--enable-selinux-support],
[enable SELinux support]),
selinux_support=$enableval, selinux_support=no)
AC_MSG_RESULT($selinux_support)
# Allow disabling of zip support.
# This is in general not a good idea because according to rfc4880 OpenPGP
# implementations SHOULD support ZLIB.
AC_MSG_CHECKING([whether to enable the ZIP and ZLIB compression algorithm])
AC_ARG_ENABLE(zip,
AC_HELP_STRING([--disable-zip],
[disable the ZIP and ZLIB compression algorithm]),
use_zip=$enableval)
AC_MSG_RESULT($use_zip)
# Allow disabling of bzib2 support.
# It is defined only after we confirm the library is available later
AC_MSG_CHECKING([whether to enable the BZIP2 compression algorithm])
AC_ARG_ENABLE(bzip2,
AC_HELP_STRING([--disable-bzip2],[disable the BZIP2 compression algorithm]),
use_bzip2=$enableval)
AC_MSG_RESULT($use_bzip2)
# Configure option to allow or disallow execution of external
# programs, like a photo viewer.
AC_MSG_CHECKING([whether to enable external program execution])
AC_ARG_ENABLE(exec,
AC_HELP_STRING([--disable-exec],[disable all external program execution]),
use_exec=$enableval)
AC_MSG_RESULT($use_exec)
if test "$use_exec" = no ; then
AC_DEFINE(NO_EXEC,1,[Define to disable all external program execution])
fi
if test "$use_exec" = yes ; then
AC_MSG_CHECKING([whether to enable photo ID viewing])
AC_ARG_ENABLE(photo-viewers,
[ --disable-photo-viewers disable photo ID viewers],
[if test "$enableval" = no ; then
AC_DEFINE(DISABLE_PHOTO_VIEWER,1,[define to disable photo viewing])
fi],enableval=yes)
gnupg_cv_enable_photo_viewers=$enableval
AC_MSG_RESULT($enableval)
if test "$gnupg_cv_enable_photo_viewers" = yes ; then
AC_MSG_CHECKING([whether to use a fixed photo ID viewer])
AC_ARG_WITH(photo-viewer,
[ --with-photo-viewer=FIXED_VIEWER set a fixed photo ID viewer],
[if test "$withval" = yes ; then
withval=no
elif test "$withval" != no ; then
AC_DEFINE_UNQUOTED(FIXED_PHOTO_VIEWER,"$withval",
[if set, restrict photo-viewer to this])
fi],withval=no)
AC_MSG_RESULT($withval)
fi
AC_MSG_CHECKING([whether to enable external keyserver helpers])
AC_ARG_ENABLE(keyserver-helpers,
[ --disable-keyserver-helpers disable all external keyserver support],
[if test "$enableval" = no ; then
AC_DEFINE(DISABLE_KEYSERVER_HELPERS,1,
[define to disable keyserver helpers])
fi],enableval=yes)
gnupg_cv_enable_keyserver_helpers=$enableval
AC_MSG_RESULT($enableval)
if test "$gnupg_cv_enable_keyserver_helpers" = yes ; then
# LDAP is defined only after we confirm the library is available later
AC_MSG_CHECKING([whether LDAP keyserver support is requested])
AC_ARG_ENABLE(ldap,
AC_HELP_STRING([--disable-ldap],[disable LDAP keyserver interface only]),
try_ks_ldap=$enableval, try_ks_ldap=yes)
AC_MSG_RESULT($try_ks_ldap)
AC_MSG_CHECKING([whether HKP keyserver support is requested])
AC_ARG_ENABLE(hkp,
AC_HELP_STRING([--disable-hkp],[disable HKP keyserver interface only]),
try_hkp=$enableval, try_hkp=yes)
AC_MSG_RESULT($try_hkp)
AC_MSG_CHECKING([whether finger key fetching support is requested])
AC_ARG_ENABLE(finger,
AC_HELP_STRING([--disable-finger],
[disable finger key fetching interface only]),
try_finger=$enableval, try_finger=yes)
AC_MSG_RESULT($try_finger)
AC_MSG_CHECKING([whether generic object key fetching support is requested])
AC_ARG_ENABLE(generic,
AC_HELP_STRING([--disable-generic],
[disable generic object key fetching interface only]),
try_generic=$enableval, try_generic=yes)
AC_MSG_RESULT($try_generic)
AC_MSG_CHECKING([whether email keyserver support is requested])
AC_ARG_ENABLE(mailto,
AC_HELP_STRING([--enable-mailto],
[enable email keyserver interface only]),
try_mailto=$enableval, try_mailto=no)
AC_MSG_RESULT($try_mailto)
fi
AC_MSG_CHECKING([whether keyserver exec-path is enabled])
AC_ARG_ENABLE(keyserver-path,
AC_HELP_STRING([--disable-keyserver-path],
[disable the exec-path option for keyserver helpers]),
[if test "$enableval" = no ; then
disable_keyserver_path=yes
fi],enableval=yes)
AC_MSG_RESULT($enableval)
fi
#
# Check for the key/uid cache size. This can't be zero, but can be
# pretty small on embedded systems. This is used for the gpg part.
#
AC_MSG_CHECKING([for the size of the key and uid cache])
AC_ARG_ENABLE(key-cache,
AC_HELP_STRING([--enable-key-cache=SIZE],
[Set key cache to SIZE (default 4096)]),,enableval=4096)
if test "$enableval" = "no"; then
enableval=5
elif test "$enableval" = "yes" || test "$enableval" = ""; then
enableval=4096
fi
changequote(,)dnl
key_cache_size=`echo "$enableval" | sed 's/[A-Za-z]//g'`
changequote([,])dnl
if test "$enableval" != "$key_cache_size" || test "$key_cache_size" -lt 5; then
AC_MSG_ERROR([invalid key-cache size])
fi
AC_MSG_RESULT($key_cache_size)
AC_DEFINE_UNQUOTED(PK_UID_CACHE_SIZE,$key_cache_size,
[Size of the key and UID caches])
#
# Check whether we want to use Linux capabilities
#
AC_MSG_CHECKING([whether use of capabilities is requested])
AC_ARG_WITH(capabilities,
[ --with-capabilities use linux capabilities [default=no]],
[use_capabilities="$withval"],[use_capabilities=no])
AC_MSG_RESULT($use_capabilities)
#
# Allow disabling of internal CCID support.
# It is defined only after we confirm the library is available later
#
AC_MSG_CHECKING([whether to enable the internal CCID driver])
AC_ARG_ENABLE(ccid-driver,
AC_HELP_STRING([--disable-ccid-driver],
[disable the internal CCID driver]),
use_ccid_driver=$enableval)
AC_MSG_RESULT($use_ccid_driver)
#
# Dirmngr is nowadays a system service and thus it usually does no
# make sense to start it as needed. However on some systems this is
# possible; this option enable the feature.
#
AC_MSG_CHECKING([whether to auto start dirmngr])
AC_ARG_ENABLE(dirmngr-auto-start,
AC_HELP_STRING([--enable-dirmngr-auto-start],
[enable auto starting of the dirmngr]),
dirmngr_auto_start=$enableval)
AC_MSG_RESULT($dirmngr_auto_start)
if test "$dirmngr_auto_start" = yes ; then
AC_DEFINE(USE_DIRMNGR_AUTO_START,1,
[Define to enable auto starting of the dirmngr])
fi
#
# To avoid double inclusion of config.h which might happen at some
# places, we add the usual double inclusion protection at the top of
# config.h.
#
AH_TOP([
#ifndef GNUPG_CONFIG_H_INCLUDED
#define GNUPG_CONFIG_H_INCLUDED
])
#
# Stuff which goes at the bottom of config.h.
#
AH_BOTTOM([
/* This is the major version number of GnuPG so that
source included files can test for this. Note, that
we use 2 here even for GnuPG 1.9.x. */
#define GNUPG_MAJOR_VERSION 2
/* Now to separate file name parts.
Please note that the string version must not contain more
than one character because the code assumes strlen()==1 */
#ifdef HAVE_DOSISH_SYSTEM
#define DIRSEP_C '\\'
#define DIRSEP_S "\\"
#define EXTSEP_C '.'
#define EXTSEP_S "."
#define PATHSEP_C ';'
#define PATHSEP_S ";"
#define EXEEXT_S ".exe"
#else
#define DIRSEP_C '/'
#define DIRSEP_S "/"
#define EXTSEP_C '.'
#define EXTSEP_S "."
#define PATHSEP_C ':'
#define PATHSEP_S ":"
#define EXEEXT_S ""
#endif
/* This is the same as VERSION, but should be overridden if the
platform cannot handle things like dots '.' in filenames. Set
SAFE_VERSION_DOT and SAFE_VERSION_DASH to whatever SAFE_VERSION
uses for dots and dashes. */
#define SAFE_VERSION VERSION
#define SAFE_VERSION_DOT '.'
#define SAFE_VERSION_DASH '-'
/* Some global constants. */
#ifdef HAVE_DOSISH_SYSTEM
# ifdef HAVE_DRIVE_LETTERS
# define GNUPG_DEFAULT_HOMEDIR "c:/gnupg"
# else
# define GNUPG_DEFAULT_HOMEDIR "/gnupg"
# endif
#elif defined(__VMS)
#define GNUPG_DEFAULT_HOMEDIR "/SYS$LOGIN/gnupg"
#else
#define GNUPG_DEFAULT_HOMEDIR "~/.gnupg"
#endif
#define GNUPG_PRIVATE_KEYS_DIR "private-keys-v1.d"
/* For some systems (DOS currently), we hardcode the path here. For
POSIX systems the values are constructed by the Makefiles, so that
the values may be overridden by the make invocations; this is to
comply with the GNU coding standards. Note that these values are
only defaults. */
#ifdef HAVE_DOSISH_SYSTEM
# ifdef HAVE_DRIVE_LETTERS
# define GNUPG_BINDIR "c:\\gnupg"
# define GNUPG_LIBEXECDIR "c:\\gnupg"
# define GNUPG_LIBDIR "c:\\gnupg"
# define GNUPG_DATADIR "c:\\gnupg"
# define GNUPG_SYSCONFDIR "c:\\gnupg"
# else
# define GNUPG_BINDIR "\\gnupg"
# define GNUPG_LIBEXECDIR "\\gnupg"
# define GNUPG_LIBDIR "\\gnupg"
# define GNUPG_DATADIR "\\gnupg"
# define GNUPG_SYSCONFDIR "\\gnupg"
# endif
#endif
/* Derive some other constants. */
#if !(defined(HAVE_FORK) && defined(HAVE_PIPE) && defined(HAVE_WAITPID))
#define EXEC_TEMPFILE_ONLY
#endif
/* We didn't define endianness above, so get it from OS macros. This
is intended for making fat binary builds on OS X. */
#if !defined(BIG_ENDIAN_HOST) && !defined(LITTLE_ENDIAN_HOST)
#if defined(__BIG_ENDIAN__)
#define BIG_ENDIAN_HOST 1
#elif defined(__LITTLE_ENDIAN__)
#define LITTLE_ENDIAN_HOST 1
#else
#error "No endianness found"
#endif
#endif
/* Hack used for W32: ldap.m4 also tests for the ASCII version of
ldap_start_tls_s because that is the actual symbol used in the
library. winldap.h redefines it to our commonly used value,
thus we define our usual macro here. */
#ifdef HAVE_LDAP_START_TLS_SA
# ifndef HAVE_LDAP_START_TLS_S
# define HAVE_LDAP_START_TLS_S 1
# endif
#endif
/* Tell libgcrypt not to use its own libgpg-error implementation. */
#define USE_LIBGPG_ERROR 1
/* We use jnlib, so tell other modules about it. */
#define HAVE_JNLIB_LOGGING 1
/* Our HTTP code is used in estream mode. */
#define HTTP_USE_ESTREAM 1
/* Under W32 we do an explicit socket initialization, thus we need to
avoid the on-demand initialization which would also install an atexit
handler. */
#define HTTP_NO_WSASTARTUP
/* We always include support for the OpenPGP card. */
#define ENABLE_CARD_SUPPORT 1
/* We explicitly need to disable PTH's soft mapping as Debian
currently enables it by default for no reason. */
#define PTH_SYSCALL_SOFT 0
/* We want to use the libgcrypt provided memory allocation for
asprintf. */
#define _ESTREAM_PRINTF_MALLOC gcry_malloc
#define _ESTREAM_PRINTF_FREE gcry_free
#define _ESTREAM_PRINTF_EXTRA_INCLUDE "../common/util.h"
/* Under Windows we use the gettext code from libgpg-error. */
#define GPG_ERR_ENABLE_GETTEXT_MACROS
/* Under WindowsCE we use the strerror replacement from libgpg-error. */
#define GPG_ERR_ENABLE_ERRNO_MACROS
#endif /*GNUPG_CONFIG_H_INCLUDED*/
])
AM_MAINTAINER_MODE
# Checks for programs.
AC_MSG_NOTICE([checking for programs])
AC_PROG_MAKE_SET
AM_SANITY_CHECK
missing_dir=`cd $ac_aux_dir && pwd`
AM_MISSING_PROG(ACLOCAL, aclocal, $missing_dir)
AM_MISSING_PROG(AUTOCONF, autoconf, $missing_dir)
AM_MISSING_PROG(AUTOMAKE, automake, $missing_dir)
AM_MISSING_PROG(AUTOHEADER, autoheader, $missing_dir)
AM_MISSING_PROG(MAKEINFO, makeinfo, $missing_dir)
AC_PROG_AWK
AC_PROG_CC
AC_PROG_CPP
AM_PROG_CC_C_O
if test "x$ac_cv_prog_cc_c89" = "xno" ; then
AC_MSG_ERROR([[No C-89 compiler found]])
fi
AC_PROG_INSTALL
AC_PROG_LN_S
AC_PROG_RANLIB
AC_CHECK_TOOL(AR, ar, :)
AC_PATH_PROG(PERL,"perl")
AC_CHECK_TOOL(WINDRES, windres, :)
AC_ISC_POSIX
gl_EARLY
AC_SYS_LARGEFILE
GNUPG_CHECK_USTAR
# We need to compile and run a program on the build machine. A
# comment in libgpg-error says that the AC_PROG_CC_FOR_BUILD macro in
# the AC archive is broken for autoconf 2.57. Given that there is no
# newer version of that macro, we assume that it is also broken for
# autoconf 2.61 and thus we use a simple but usually sufficient
# approach.
AC_MSG_CHECKING(for cc for build)
if test "$cross_compiling" = "yes"; then
CC_FOR_BUILD="${CC_FOR_BUILD-cc}"
else
CC_FOR_BUILD="${CC_FOR_BUILD-$CC}"
fi
AC_MSG_RESULT($CC_FOR_BUILD)
AC_ARG_VAR(CC_FOR_BUILD,[build system C compiler])
try_gettext=yes
have_dosish_system=no
have_w32_system=no
have_w32ce_system=no
use_simple_gettext=no
use_ldapwrapper=yes
mmap_needed=yes
case "${host}" in
*-mingw32*)
# special stuff for Windoze NT
ac_cv_have_dev_random=no
AC_DEFINE(USE_ONLY_8DOT3,1,
[Set this to limit filenames to the 8.3 format])
AC_DEFINE(USE_SIMPLE_GETTEXT,1,
[Because the Unix gettext has too much overhead on
MingW32 systems and these systems lack Posix functions,
we use a simplified version of gettext])
disable_keyserver_path=yes
have_dosish_system=yes
have_w32_system=yes
use_ldapwrapper=no # Fixme: Do this only for CE.
case "${host}" in
*-mingw32ce*)
have_w32ce_system=yes
;;
*)
AC_DEFINE(HAVE_DRIVE_LETTERS,1,
[Defined if the OS supports drive letters.])
;;
esac
try_gettext="no"
use_simple_gettext=yes
mmap_needed=no
;;
i?86-emx-os2 | i?86-*-os2*emx )
# OS/2 with the EMX environment
ac_cv_have_dev_random=no
AC_DEFINE(HAVE_DRIVE_LETTERS)
have_dosish_system=yes
try_gettext="no"
;;
i?86-*-msdosdjgpp*)
# DOS with the DJGPP environment
ac_cv_have_dev_random=no
AC_DEFINE(HAVE_DRIVE_LETTERS)
have_dosish_system=yes
try_gettext="no"
;;
*-*-freebsd*)
# FreeBSD
CPPFLAGS="$CPPFLAGS -I/usr/local/include"
LDFLAGS="$LDFLAGS -L/usr/local/lib"
;;
*-*-hpux*)
if test -z "$GCC" ; then
CFLAGS="$CFLAGS -Ae -D_HPUX_SOURCE"
fi
;;
*-dec-osf4*)
if test -z "$GCC" ; then
# Suppress all warnings
# to get rid of the unsigned/signed char mismatch warnings.
CFLAGS="$CFLAGS -w"
fi
;;
*-dec-osf5*)
if test -z "$GCC" ; then
# Use the newer compiler `-msg_disable ptrmismatch1' to
# get rid of the unsigned/signed char mismatch warnings.
# Using this may hide other pointer mismatch warnings, but
# it at least lets other warning classes through
CFLAGS="$CFLAGS -msg_disable ptrmismatch1"
fi
;;
m68k-atari-mint)
;;
*)
;;
esac
if test "$have_dosish_system" = yes; then
AC_DEFINE(HAVE_DOSISH_SYSTEM,1,
[Defined if we run on some of the PCDOS like systems
(DOS, Windoze. OS/2) with special properties like
no file modes, case insensitive file names and preferred
use of backslashes as directory name separators.])
fi
AM_CONDITIONAL(HAVE_DOSISH_SYSTEM, test "$have_dosish_system" = yes)
AM_CONDITIONAL(USE_SIMPLE_GETTEXT, test x"$use_simple_gettext" = xyes)
if test "$have_w32_system" = yes; then
AC_DEFINE(HAVE_W32_SYSTEM,1, [Defined if we run on a W32 API based system])
if test "$have_w32ce_system" = yes; then
AC_DEFINE(HAVE_W32CE_SYSTEM,1,[Defined if we run on WindowsCE])
fi
fi
AM_CONDITIONAL(HAVE_W32_SYSTEM, test "$have_w32_system" = yes)
AM_CONDITIONAL(HAVE_W32CE_SYSTEM, test "$have_w32ce_system" = yes)
if test "$use_ldapwrapper" = yes; then
AC_DEFINE(USE_LDAPWRAPPER,1, [Build dirmngr with LDAP wrapper process])
fi
AM_CONDITIONAL(USE_LDAPWRAPPER, test "$use_ldapwrapper" = yes)
if test "$disable_keyserver_path" = yes; then
AC_DEFINE(DISABLE_KEYSERVER_PATH,1,
[Defined to disable exec-path for keyserver helpers])
fi
#
# Allows enabling the use of a standard socket by default This is
# gpg-agent's option --[no-]use-standard-socket. For Windows we force
# the use of this.
#
AC_MSG_CHECKING([whether to use a standard socket by default])
AC_ARG_ENABLE(standard-socket,
AC_HELP_STRING([--disable-standard-socket],
[don't use a standard socket by default]),
use_standard_socket=$enableval)
tmp=""
if test "$use_standard_socket" != yes; then
if test "$have_w32_system" = yes; then
use_standard_socket=yes
tmp=" (forced)"
fi
fi
AC_MSG_RESULT($use_standard_socket$tmp)
if test "$use_standard_socket" = yes; then
AC_DEFINE(USE_STANDARD_SOCKET,1,
[Use the standard socket for the agent by default])
fi
# (These need to go after AC_PROG_CC so that $EXEEXT is defined)
AC_DEFINE_UNQUOTED(EXEEXT,"$EXEEXT",[The executable file extension, if any])
if test x"$try_hkp" = xyes ; then
AC_SUBST(GPGKEYS_HKP,"gpg2keys_hkp$EXEEXT")
fi
if test x"$try_finger" = xyes ; then
AC_SUBST(GPGKEYS_FINGER,"gpg2keys_finger$EXEEXT")
fi
#
# Checks for libraries.
#
AC_MSG_NOTICE([checking for libraries])
#
# libgpg-error is a library with error codes shared between GnuPG
# related projects.
#
AM_PATH_GPG_ERROR("$NEED_GPG_ERROR_VERSION",
have_gpg_error=yes,have_gpg_error=no)
#
# Libgcrypt is our generic crypto library
#
AM_PATH_LIBGCRYPT("$NEED_LIBGCRYPT_API:$NEED_LIBGCRYPT_VERSION",
have_libgcrypt=yes,have_libgcrypt=no)
#
# libassuan is used for IPC
#
AM_PATH_LIBASSUAN("$NEED_LIBASSUAN_API:$NEED_LIBASSUAN_VERSION",
have_libassuan=yes,have_libassuan=no)
if test "$have_libassuan" = "yes"; then
AC_DEFINE_UNQUOTED(GNUPG_LIBASSUAN_VERSION, "$libassuan_version",
[version of the libassuan library])
fi
#
# libksba is our X.509 support library
#
AM_PATH_KSBA("$NEED_KSBA_API:$NEED_KSBA_VERSION",have_ksba=yes,have_ksba=no)
#
# libusb allows us to use the integrated CCID smartcard reader driver.
#
# FiXME: Use GNUPG_CHECK_LIBUSB and modify to use separate AC_SUBSTs.
if test "$use_ccid_driver" = yes ; then
AC_CHECK_LIB(usb, usb_bulk_write,
[ LIBUSB_LIBS="$LIBUSB_LIBS -lusb"
AC_DEFINE(HAVE_LIBUSB,1,
[defined if libusb is available])
have_libusb=yes
])
AC_CHECK_FUNCS(usb_create_match)
fi
AC_SUBST(LIBUSB_LIBS)
#
# Check wether it is necessary to link against libdl.
#
gnupg_dlopen_save_libs="$LIBS"
LIBS=""
AC_SEARCH_LIBS(dlopen, c dl,,,)
DL_LIBS=$LIBS
AC_SUBST(DL_LIBS)
LIBS="$gnupg_dlopen_save_libs"
# Checks for g13
AC_PATH_PROG(ENCFS, encfs, /usr/bin/encfs)
AC_DEFINE_UNQUOTED(ENCFS,
"${ENCFS}", [defines the filename of the encfs program])
AC_PATH_PROG(FUSERMOUNT, fusermount, /usr/bin/fusermount)
AC_DEFINE_UNQUOTED(FUSERMOUNT,
"${FUSERMOUNT}", [defines the filename of the fusermount program])
# Checks for dirmngr
#
# Checks for symcryptrun:
#
# libutil has openpty() and login_tty().
AC_CHECK_LIB(util, openpty,
[ LIBUTIL_LIBS="$LIBUTIL_LIBS -lutil"
AC_DEFINE(HAVE_LIBUTIL,1,
[defined if libutil is available])
])
AC_SUBST(LIBUTIL_LIBS)
# shred is used to clean temporary plain text files.
AC_PATH_PROG(SHRED, shred, /usr/bin/shred)
AC_DEFINE_UNQUOTED(SHRED,
"${SHRED}", [defines the filename of the shred program])
#
# Check whether the GNU Pth library is available
# Note, that we include a Pth emulation for W32.
#
if test "$have_w32_system" = yes; then
GNUPG_PATH_PTH([2.0.4])
else
GNUPG_PATH_PTH
fi
if test "$have_pth" = "yes"; then
AC_DEFINE(USE_GNU_PTH, 1,
[Defined if the GNU Portable Thread Library should be used])
else
AC_MSG_WARN([[
***
*** To support concurrent access to the gpg-agent and the SCdaemon
*** we need the support of the GNU Portable Threads Library.
*** Download it from ftp://ftp.gnu.org/gnu/pth/
*** On a Debian GNU/Linux system you might want to try
*** apt-get install libpth-dev
***]])
fi
AC_MSG_NOTICE([checking for networking options])
#
# Must check for network library requirements before doing link tests
# for ldap, for example. If ldap libs are static (or dynamic and without
# ELF runtime link paths), then link will fail and LDAP support won't
# be detected.
#
AC_CHECK_FUNC(gethostbyname, , AC_CHECK_LIB(nsl, gethostbyname,
[NETLIBS="-lnsl $NETLIBS"]))
AC_CHECK_FUNC(setsockopt, , AC_CHECK_LIB(socket, setsockopt,
[NETLIBS="-lsocket $NETLIBS"]))
#
# Check for ADNS.
#
_cppflags="${CPPFLAGS}"
_ldflags="${LDFLAGS}"
AC_ARG_WITH(adns,
AC_HELP_STRING([--with-adns=DIR],
[look for the adns library in DIR]),
[if test -d "$withval"; then
CPPFLAGS="${CPPFLAGS} -I$withval/include"
LDFLAGS="${LDFLAGS} -L$withval/lib"
fi])
if test "$with_adns" != "no"; then
AC_CHECK_HEADERS(adns.h,
AC_CHECK_LIB(adns, adns_init,
[have_adns=yes],
[CPPFLAGS=${_cppflags} LDFLAGS=${_ldflags}]),
[CPPFLAGS=${_cppflags} LDFLAGS=${_ldflags}])
fi
if test "$have_adns" = "yes"; then
ADNSLIBS="-ladns"
fi
AC_SUBST(ADNSLIBS)
# Newer adns versions feature a free function to be used under W32.
AC_CHECK_FUNCS(adns_free)
#
# Now try for the resolver functions so we can use DNS for SRV, PA and CERT.
#
if test x"$try_hkp" = xyes || test x"$try_http" = xyes ; then
AC_ARG_ENABLE(dns-srv,
AC_HELP_STRING([--disable-dns-srv],
[disable the use of DNS SRV in HKP and HTTP]),
use_dns_srv=$enableval,use_dns_srv=yes)
fi
AC_ARG_ENABLE(dns-pka,
AC_HELP_STRING([--disable-dns-pka],
[disable the use of PKA records in DNS]),
use_dns_pka=$enableval,use_dns_pka=yes)
AC_ARG_ENABLE(dns-cert,
AC_HELP_STRING([--disable-dns-cert],
[disable the use of CERT records in DNS]),
use_dns_cert=$enableval,use_dns_cert=yes)
if test x"$use_dns_pka" = xyes || test x"$use_dns_srv" = xyes \
|| test x"$use_dns_cert" = xyes; then
_dns_save_libs=$LIBS
LIBS=""
# the double underscore thing is a glibc-ism?
AC_SEARCH_LIBS(res_query,resolv bind,,
AC_SEARCH_LIBS(__res_query,resolv bind,,have_resolver=no))
AC_SEARCH_LIBS(dn_expand,resolv bind,,
AC_SEARCH_LIBS(__dn_expand,resolv bind,,have_resolver=no))
AC_SEARCH_LIBS(dn_skipname,resolv bind,,
AC_SEARCH_LIBS(__dn_skipname,resolv bind,,have_resolver=no))
if test x"$have_resolver" != xno ; then
# Make sure that the BIND 4 resolver interface is workable before
# enabling any code that calls it. At some point I'll rewrite the
# code to use the BIND 8 resolver API.
# We might also want to use adns instead. Problem with ADNS is that
# it does not support v6.
AC_MSG_CHECKING([whether the resolver is usable])
AC_LINK_IFELSE([AC_LANG_PROGRAM([#include
#include
#include
#include ],
[[unsigned char answer[PACKETSZ];
res_query("foo.bar",C_IN,T_A,answer,PACKETSZ);
dn_skipname(0,0);
dn_expand(0,0,0,0,0);
]])],have_resolver=yes,have_resolver=no)
AC_MSG_RESULT($have_resolver)
# This is Apple-specific and somewhat bizarre as they changed the
# define in bind 8 for some reason.
if test x"$have_resolver" != xyes ; then
AC_MSG_CHECKING(
[whether I can make the resolver usable with BIND_8_COMPAT])
AC_LINK_IFELSE([AC_LANG_PROGRAM([#define BIND_8_COMPAT
#include
#include
#include
#include ],
[[unsigned char answer[PACKETSZ];
res_query("foo.bar",C_IN,T_A,answer,PACKETSZ);
dn_skipname(0,0); dn_expand(0,0,0,0,0);
]])],[have_resolver=yes ; need_compat=yes])
AC_MSG_RESULT($have_resolver)
fi
fi
if test x"$have_resolver" = xyes ; then
DNSLIBS=$LIBS
if test x"$use_dns_srv" = xyes ; then
AC_DEFINE(USE_DNS_SRV,1,[define to use DNS SRV])
fi
if test x"$use_dns_pka" = xyes ; then
AC_DEFINE(USE_DNS_PKA,1,[define to use our experimental DNS PKA])
fi
if test x"$use_dns_cert" = xyes ; then
AC_DEFINE(USE_DNS_CERT,1,[define to use DNS CERT])
fi
if test x"$need_compat" = xyes ; then
AC_DEFINE(BIND_8_COMPAT,1,[an Apple OSXism])
fi
else
# If we have no resolver library but ADNS (e.g. under W32) enable the
# code parts which can be used with ADNS.
if test x"$have_adns" = xyes ; then
DNSLIBS="$ADNSLIBS"
AC_DEFINE(USE_ADNS,1,[Use ADNS as resolver library.])
if test x"$use_dns_srv" = xyes ; then
AC_DEFINE(USE_DNS_SRV,1)
fi
if test x"$use_dns_pka" = xyes ; then
AC_DEFINE(USE_DNS_PKA,1)
fi
if test x"$use_dns_cert" = xyes ; then
AC_DEFINE(USE_DNS_CERT,1,[define to use DNS CERT])
fi
else
use_dns_srv=no
use_dns_pka=no
use_dns_cert=no
fi
fi
LIBS=$_dns_save_libs
fi
AC_SUBST(DNSLIBS)
AM_CONDITIONAL(USE_DNS_SRV, test x"$use_dns_srv" = xyes)
#
# Check for LDAP
#
if test "$try_ks_ldap" = yes || test "$build_dirmngr" = "yes" ; then
GNUPG_CHECK_LDAP($NETLIBS)
fi
#
# Check for curl. We fake the curl API if libcurl isn't installed.
# We require 7.10 or later as we use curl_version_info().
#
LIBCURL_CHECK_CONFIG([yes],[7.10],,[fake_curl=yes])
AM_CONDITIONAL(FAKE_CURL,test x"$fake_curl" = xyes)
# Generic, for us, means curl
if test x"$try_generic" = xyes ; then
AC_SUBST(GPGKEYS_CURL,"gpg2keys_curl$EXEEXT")
fi
#
# Check for sendmail
#
# This isn't necessarily sendmail itself, but anything that gives a
# sendmail-ish interface to the outside world. That includes Exim,
# Postfix, etc. Basically, anything that can handle "sendmail -t".
if test "$try_mailto" = yes ; then
AC_ARG_WITH(mailprog,
AC_HELP_STRING([--with-mailprog=NAME],
[use "NAME -t" for mail transport]),
,with_mailprog=yes)
if test x"$with_mailprog" = xyes ; then
AC_PATH_PROG(SENDMAIL,sendmail,,$PATH:/usr/sbin:/usr/libexec:/usr/lib)
if test "$ac_cv_path_SENDMAIL" ; then
GPGKEYS_MAILTO="gpg2keys_mailto"
fi
elif test x"$with_mailprog" != xno ; then
AC_MSG_CHECKING([for a mail transport program])
AC_SUBST(SENDMAIL,$with_mailprog)
AC_MSG_RESULT($with_mailprog)
GPGKEYS_MAILTO="gpg2keys_mailto"
fi
fi
AC_SUBST(GPGKEYS_MAILTO)
#
# Construct a printable name of the OS
#
case "${host}" in
*-mingw32ce*)
PRINTABLE_OS_NAME="W32CE"
;;
*-mingw32*)
PRINTABLE_OS_NAME="MingW32"
;;
*-*-cygwin*)
PRINTABLE_OS_NAME="Cygwin"
;;
i?86-emx-os2 | i?86-*-os2*emx )
PRINTABLE_OS_NAME="OS/2"
;;
i?86-*-msdosdjgpp*)
PRINTABLE_OS_NAME="MSDOS/DJGPP"
try_dynload=no
;;
*-linux*)
PRINTABLE_OS_NAME="GNU/Linux"
;;
*)
PRINTABLE_OS_NAME=`uname -s || echo "Unknown"`
;;
esac
AC_DEFINE_UNQUOTED(PRINTABLE_OS_NAME, "$PRINTABLE_OS_NAME",
[A human readable text with the name of the OS])
#
# Checking for iconv
#
AM_ICONV
#
# Check for gettext
#
# This is "GNU gnupg" - The project-id script from gettext
# needs this string
#
AC_MSG_NOTICE([checking for gettext])
AM_PO_SUBDIRS
AM_GNU_GETTEXT_VERSION([0.17])
if test "$try_gettext" = yes; then
AM_GNU_GETTEXT([external],[need-ngettext])
# gettext requires some extra checks. These really should be part of
# the basic AM_GNU_GETTEXT macro. TODO: move other gettext-specific
# function checks to here.
AC_CHECK_FUNCS(strchr)
else
USE_NLS=no
USE_INCLUDED_LIBINTL=no
BUILD_INCLUDED_LIBINTL=no
POSUB=po
AC_SUBST(USE_NLS)
AC_SUBST(USE_INCLUDED_LIBINTL)
AC_SUBST(BUILD_INCLUDED_LIBINTL)
AC_SUBST(POSUB)
fi
# We use HAVE_LANGINFO_CODESET in a couple of places.
AM_LANGINFO_CODESET
# Checks required for our use locales
gt_LC_MESSAGES
#
# SELinux support
#
if test "$selinux_support" = yes ; then
AC_DEFINE(ENABLE_SELINUX_HACKS,1,[Define to enable SELinux support])
fi
#
# Checks for header files.
#
AC_MSG_NOTICE([checking for header files])
AC_HEADER_STDC
AC_CHECK_HEADERS([string.h unistd.h langinfo.h termio.h locale.h getopt.h \
pty.h pwd.h inttypes.h signal.h])
AC_HEADER_TIME
#
# Checks for typedefs, structures, and compiler characteristics.
#
AC_MSG_NOTICE([checking for system characteristics])
AC_C_CONST
AC_C_INLINE
AC_C_VOLATILE
AC_TYPE_SIZE_T
AC_TYPE_MODE_T
AC_TYPE_SIGNAL
AC_DECL_SYS_SIGLIST
gl_HEADER_SYS_SOCKET
gl_TYPE_SOCKLEN_T
AC_ARG_ENABLE(endian-check,
AC_HELP_STRING([--disable-endian-check],
[disable the endian check and trust the OS provided macros]),
endiancheck=$enableval,endiancheck=yes)
if test x"$endiancheck" = xyes ; then
GNUPG_CHECK_ENDIAN
fi
# fixme: we should get rid of the byte type
GNUPG_CHECK_TYPEDEF(byte, HAVE_BYTE_TYPEDEF)
GNUPG_CHECK_TYPEDEF(ushort, HAVE_USHORT_TYPEDEF)
GNUPG_CHECK_TYPEDEF(ulong, HAVE_ULONG_TYPEDEF)
GNUPG_CHECK_TYPEDEF(u16, HAVE_U16_TYPEDEF)
GNUPG_CHECK_TYPEDEF(u32, HAVE_U32_TYPEDEF)
AC_CHECK_SIZEOF(unsigned short)
AC_CHECK_SIZEOF(unsigned int)
AC_CHECK_SIZEOF(unsigned long)
AC_CHECK_SIZEOF(unsigned long long)
AC_HEADER_TIME
AC_CHECK_SIZEOF(time_t,,[[
#include
#if TIME_WITH_SYS_TIME
# include
# include
#else
# if HAVE_SYS_TIME_H
# include
# else
# include
# endif
#endif
]])
GNUPG_TIME_T_UNSIGNED
# Ensure that we have UINT64_C before we bother to check for uint64_t
# Fixme: really needed in gnupg? I think it is only useful in libcgrypt.
AC_CACHE_CHECK([for UINT64_C],[gnupg_cv_uint64_c_works],
AC_COMPILE_IFELSE(AC_LANG_PROGRAM([#include
uint64_t foo=UINT64_C(42);]),
gnupg_cv_uint64_c_works=yes,gnupg_cv_uint64_c_works=no))
if test "$gnupg_cv_uint64_c_works" = "yes" ; then
AC_CHECK_SIZEOF(uint64_t)
fi
if test "$ac_cv_sizeof_unsigned_short" = "0" \
|| test "$ac_cv_sizeof_unsigned_int" = "0" \
|| test "$ac_cv_sizeof_unsigned_long" = "0"; then
AC_MSG_WARN([Hmmm, something is wrong with the sizes - using defaults]);
fi
#
# Checks for library functions.
#
AC_MSG_NOTICE([checking for library functions])
AC_CHECK_DECLS(getpagesize)
AC_FUNC_FSEEKO
AC_FUNC_VPRINTF
AC_FUNC_FORK
AC_CHECK_FUNCS([strerror strlwr tcgetattr mmap canonicalize_file_name])
AC_CHECK_FUNCS([strcasecmp strncasecmp ctermid times gmtime_r strtoull])
AC_CHECK_FUNCS([unsetenv fcntl ftruncate canonicalize_file_name])
AC_CHECK_FUNCS([gettimeofday getrusage getrlimit setrlimit clock_gettime])
AC_CHECK_FUNCS([atexit raise getpagesize strftime nl_langinfo setlocale])
AC_CHECK_FUNCS([waitpid wait4 sigaction sigprocmask pipe getaddrinfo])
AC_CHECK_FUNCS([ttyname rand ftello fsync stat lstat])
AC_CHECK_TYPES([struct sigaction, sigset_t],,,[#include ])
# Dirmngr requires mmap on Unix systems.
if test $ac_cv_func_mmap != yes -a $mmap_needed = yes; then
AC_MSG_ERROR([[Sorry, the current implemenation requires mmap.]])
fi
#
# These are needed by the jnlib parts in common.
# Note: We already checked pwd.h.
AC_CHECK_HEADERS([signal.h])
AC_CHECK_FUNCS([memicmp stpcpy strsep strlwr strtoul memmove stricmp strtol \
memrchr isascii timegm getrusage setrlimit stat setlocale \
flockfile funlockfile fopencookie funopen getpwnam getpwuid \
getenv inet_pton])
# end jnlib checks.
#
# gnulib checks
#
gl_SOURCE_BASE([gl])
gl_M4_BASE([gl/m4])
gl_MODULES([setenv mkdtemp xsize strpbrk])
gl_INIT
#
# W32 specific test
#
GNUPG_FUNC_MKDIR_TAKES_ONE_ARG
#
# Sanity check regex. Tests adapted from mutt.
#
AC_MSG_CHECKING([whether regular expression support is requested])
AC_ARG_ENABLE(regex,
AC_HELP_STRING([--disable-regex],
[do not handle regular expressions in trust signatures]),
use_regex=$enableval, use_regex=yes)
AC_MSG_RESULT($use_regex)
if test "$use_regex" = yes ; then
_cppflags="${CPPFLAGS}"
_ldflags="${LDFLAGS}"
AC_ARG_WITH(regex,
AC_HELP_STRING([--with-regex=DIR],[look for regex in DIR]),
[
if test -d "$withval" ; then
CPPFLAGS="${CPPFLAGS} -I$withval/include"
LDFLAGS="${LDFLAGS} -L$withval/lib"
fi
],withval="")
# Does the system have regex functions at all?
AC_SEARCH_LIBS([regcomp], [regex])
AC_CHECK_FUNC(regcomp, gnupg_cv_have_regex=yes, gnupg_cv_have_regex=no)
if test $gnupg_cv_have_regex = no; then
use_regex=no
else
if test x"$cross_compiling" = xyes; then
AC_MSG_WARN([cross compiling; assuming regexp libray is not broken])
else
AC_CACHE_CHECK([whether your system's regexp library is broken],
[gnupg_cv_regex_broken],
AC_TRY_RUN([
#include
#include
main() { regex_t blah ; regmatch_t p; p.rm_eo = p.rm_eo; return regcomp(&blah, "foo.*bar", REG_NOSUB) || regexec (&blah, "foobar", 0, NULL, 0); }],
gnupg_cv_regex_broken=no, gnupg_cv_regex_broken=yes, gnupg_cv_regex_broken=yes))
if test $gnupg_cv_regex_broken = yes; then
AC_MSG_WARN([your regex is broken - disabling regex use])
use_regex=no
fi
fi
fi
CPPFLAGS="${_cppflags}"
LDFLAGS="${_ldflags}"
fi
if test "$use_regex" != yes ; then
AC_DEFINE(DISABLE_REGEX,1, [Define to disable regular expression support])
fi
AM_CONDITIONAL(DISABLE_REGEX, test x"$use_regex" != xyes)
#
# Do we have zlib? Must do it here because Solaris failed
# when compiling a conftest (due to the "-lz" from LIBS).
# Note that we combine zlib and bzlib2 in ZLIBS.
#
if test "$use_zip" = yes ; then
_cppflags="${CPPFLAGS}"
_ldflags="${LDFLAGS}"
AC_ARG_WITH(zlib,
[ --with-zlib=DIR use libz in DIR],[
if test -d "$withval"; then
CPPFLAGS="${CPPFLAGS} -I$withval/include"
LDFLAGS="${LDFLAGS} -L$withval/lib"
fi
])
AC_CHECK_HEADER(zlib.h,
AC_CHECK_LIB(z, deflateInit2_,
ZLIBS="-lz",
CPPFLAGS=${_cppflags} LDFLAGS=${_ldflags}),
CPPFLAGS=${_cppflags} LDFLAGS=${_ldflags})
AC_DEFINE(HAVE_ZIP,1, [Defined if ZIP and ZLIB are supported])
fi
#
# Check whether we can support bzip2
#
if test "$use_bzip2" = yes ; then
_cppflags="${CPPFLAGS}"
_ldflags="${LDFLAGS}"
AC_ARG_WITH(bzip2,
AC_HELP_STRING([--with-bzip2=DIR],[look for bzip2 in DIR]),
[
if test -d "$withval" ; then
CPPFLAGS="${CPPFLAGS} -I$withval/include"
LDFLAGS="${LDFLAGS} -L$withval/lib"
fi
],withval="")
# Checking alongside stdio.h as an early version of bzip2 (1.0)
# required stdio.h to be included before bzlib.h, and Solaris 9 is
# woefully out of date.
if test "$withval" != no ; then
AC_CHECK_HEADER(bzlib.h,
AC_CHECK_LIB(bz2,BZ2_bzCompressInit,
[
have_bz2=yes
ZLIBS="$ZLIBS -lbz2"
AC_DEFINE(HAVE_BZIP2,1,
[Defined if the bz2 compression library is available])
],
CPPFLAGS=${_cppflags} LDFLAGS=${_ldflags}),
CPPFLAGS=${_cppflags} LDFLAGS=${_ldflags},[#include ])
fi
fi
AM_CONDITIONAL(ENABLE_BZIP2_SUPPORT,test x"$have_bz2" = "xyes")
AC_SUBST(ZLIBS)
# Check for readline support
GNUPG_CHECK_READLINE
#
# Allow users to append something to the version string without
# flagging it as development version. The user version parts is
# considered everything after a dash.
#
if test "$development_version" != yes; then
changequote(,)dnl
tmp_pat='[a-zA-Z]'
changequote([,])dnl
if echo "$VERSION" | sed 's/-.*//' | grep "$tmp_pat" >/dev/null ; then
development_version=yes
fi
fi
if test "$development_version" = yes; then
AC_DEFINE(IS_DEVELOPMENT_VERSION,1,
[Defined if this is not a regular release])
fi
AM_CONDITIONAL(CROSS_COMPILING, test x$cross_compiling = xyes)
GNUPG_CHECK_GNUMAKE
# Add some extra libs here so that previous tests don't fail for
# mysterious reasons - the final link step should bail out.
# W32SOCKLIBS is also defined so that if can be used for tools not
# requiring any network stuff but linking to code in libcommon which
# tracks in winsock stuff (e.g. init_common_subsystems).
if test "$have_w32_system" = yes; then
if test "$have_w32ce_system" = yes; then
W32SOCKLIBS="-lws2"
else
W32SOCKLIBS="-lws2_32"
fi
NETLIBS="${NETLIBS} ${W32SOCKLIBS}"
fi
AC_SUBST(NETLIBS)
AC_SUBST(W32SOCKLIBS)
#
# Setup gcc specific options
#
AC_MSG_NOTICE([checking for cc features])
if test "$GCC" = yes; then
# Note that it is okay to use CFLAGS here because this are just
# warning options and the user should have a chance of overriding
# them.
if test "$USE_MAINTAINER_MODE" = "yes"; then
CFLAGS="$CFLAGS -O3 -Wall -Wcast-align -Wshadow -Wstrict-prototypes"
CFLAGS="$CFLAGS -Wformat -Wno-format-y2k -Wformat-security"
AC_MSG_CHECKING([if gcc supports -Wno-missing-field-initializers])
_gcc_cflags_save=$CFLAGS
CFLAGS="-Wno-missing-field-initializers"
AC_COMPILE_IFELSE(AC_LANG_PROGRAM([]),_gcc_wopt=yes,_gcc_wopt=no)
AC_MSG_RESULT($_gcc_wopt)
CFLAGS=$_gcc_cflags_save;
if test x"$_gcc_wopt" = xyes ; then
CFLAGS="$CFLAGS -W -Wno-sign-compare -Wno-missing-field-initializers"
fi
AC_MSG_CHECKING([if gcc supports -Wdeclaration-after-statement])
_gcc_cflags_save=$CFLAGS
CFLAGS="-Wdeclaration-after-statement"
AC_COMPILE_IFELSE(AC_LANG_PROGRAM([]),_gcc_wopt=yes,_gcc_wopt=no)
AC_MSG_RESULT($_gcc_wopt)
CFLAGS=$_gcc_cflags_save;
if test x"$_gcc_wopt" = xyes ; then
CFLAGS="$CFLAGS -Wdeclaration-after-statement"
fi
else
CFLAGS="$CFLAGS -Wall"
fi
AC_MSG_CHECKING([if gcc supports -Wno-pointer-sign])
_gcc_cflags_save=$CFLAGS
CFLAGS="-Wno-pointer-sign"
AC_COMPILE_IFELSE(AC_LANG_PROGRAM([]),_gcc_psign=yes,_gcc_psign=no)
AC_MSG_RESULT($_gcc_psign)
CFLAGS=$_gcc_cflags_save;
if test x"$_gcc_psign" = xyes ; then
CFLAGS="$CFLAGS -Wno-pointer-sign"
fi
AC_MSG_CHECKING([if gcc supports -Wpointer-arith])
_gcc_cflags_save=$CFLAGS
CFLAGS="-Wpointer-arith"
AC_COMPILE_IFELSE(AC_LANG_PROGRAM([]),_gcc_psign=yes,_gcc_psign=no)
AC_MSG_RESULT($_gcc_psign)
CFLAGS=$_gcc_cflags_save;
if test x"$_gcc_psign" = xyes ; then
CFLAGS="$CFLAGS -Wpointer-arith"
fi
fi
#
# This is handy for debugging so the compiler doesn't rearrange
# things and eliminate variables.
#
AC_ARG_ENABLE(optimization,
AC_HELP_STRING([--disable-optimization],
[disable compiler optimization]),
[if test $enableval = no ; then
- CFLAGS=`echo $CFLAGS | sed s/-O[[1-9]]\ /-O0\ /g`
+ CFLAGS=`echo $CFLAGS | sed s%-O[[1-9]]%-O0\ %g`
fi])
#
# Prepare building of estream
#
estream_INIT
#
# Decide what to build
#
if test "$have_adns" = "yes"; then
AC_SUBST(GPGKEYS_KDNS, "gpg2keys_kdns$EXEEXT")
fi
missing_pth=no
if test $have_ksba = no; then
build_gpgsm=no
build_scdaemon=no
fi
build_agent_threaded=""
if test "$build_agent" = "yes"; then
if test $have_pth = no; then
build_agent_threaded="(not multi-threaded)"
missing_pth=yes
fi
fi
build_scdaemon_extra=""
if test "$build_scdaemon" = "yes"; then
tmp=""
if test $have_pth = no; then
build_scdaemon_extra="not multi-threaded"
tmp=", "
missing_pth=yes
fi
if test $have_libusb = no; then
build_scdaemon_extra="${tmp}without internal CCID driver"
tmp=", "
fi
if test -n "$build_scdaemon_extra"; then
build_scdaemon_extra="(${build_scdaemon_extra})"
fi
fi
if test "$build_agent_only" = "yes" ; then
build_gpg=no
build_gpgsm=no
build_scdaemon=no
build_tools=no
build_doc=no
fi
#
# Set variables for use by th automake makefile.
#
AM_CONDITIONAL(BUILD_GPG, test "$build_gpg" = "yes")
AM_CONDITIONAL(BUILD_GPGSM, test "$build_gpgsm" = "yes")
AM_CONDITIONAL(BUILD_AGENT, test "$build_agent" = "yes")
AM_CONDITIONAL(BUILD_SCDAEMON, test "$build_scdaemon" = "yes")
AM_CONDITIONAL(BUILD_G13, test "$build_g13" = "yes")
AM_CONDITIONAL(BUILD_DIRMNGR, test "$build_dirmngr" = "yes")
AM_CONDITIONAL(BUILD_TOOLS, test "$build_tools" = "yes")
AM_CONDITIONAL(BUILD_DOC, test "$build_doc" = "yes")
AM_CONDITIONAL(BUILD_SYMCRYPTRUN, test "$build_symcryptrun" = "yes")
AM_CONDITIONAL(BUILD_GPGTAR, test "$build_gpgtar" = "yes")
AM_CONDITIONAL(RUN_GPG_TESTS,
test x$cross_compiling = xno -a "$build_gpg" = yes )
#
# Set some defines for use gpgconf.
#
if test "$build_gpg" = yes ; then
AC_DEFINE(BUILD_WITH_GPG,1,[Defined if GPG is to be build])
fi
if test "$build_gpgsm" = yes ; then
AC_DEFINE(BUILD_WITH_GPGSM,1,[Defined if GPGSM is to be build])
fi
if test "$build_agent" = yes ; then
AC_DEFINE(BUILD_WITH_AGENT,1,[Defined if GPG-AGENT is to be build])
fi
if test "$build_scdaemon" = yes ; then
AC_DEFINE(BUILD_WITH_SCDAEMON,1,[Defined if SCDAEMON is to be build])
fi
if test "$build_dirmngr" = yes ; then
AC_DEFINE(BUILD_WITH_DIRMNGR,1,[Defined if SCDAEMON is to be build])
fi
if test "$build_g13" = yes ; then
AC_DEFINE(BUILD_WITH_G13,1,[Defined if G13 is to be build])
fi
#
# Print errors here so that they are visible all
# together and the user can acquire them all together.
#
die=no
if test "$have_gpg_error" = "no"; then
die=yes
AC_MSG_NOTICE([[
***
*** You need libgpg-error to build this program.
** This library is for example available at
*** ftp://ftp.gnupg.org/gcrypt/libgpg-error
*** (at least version $NEED_GPG_ERROR_VERSION is required.)
***]])
fi
if test "$have_libgcrypt" = "no"; then
die=yes
AC_MSG_NOTICE([[
***
*** You need libgcrypt to build this program.
** This library is for example available at
*** ftp://ftp.gnupg.org/gcrypt/libgcrypt/
*** (at least version $NEED_LIBGCRYPT_VERSION using API $NEED_LIBGCRYPT_API is required.)
***]])
fi
if test "$have_libassuan" = "no"; then
die=yes
AC_MSG_NOTICE([[
***
*** You need libassuan to build this program.
*** This library is for example available at
*** ftp://ftp.gnupg.org/gcrypt/libassuan/
*** (at least version $NEED_LIBASSUAN_VERSION (API $NEED_LIBASSUAN_API) is required).
***]])
fi
if test "$have_ksba" = "no"; then
AC_MSG_NOTICE([[
***
*** You need libksba to build this program.
*** This library is for example available at
*** ftp://ftp.gnupg.org/gcrypt/libksba/
*** (at least version $NEED_KSBA_VERSION using API $NEED_KSBA_API is required).
***]])
fi
if test "$gnupg_have_ldap" = "no"; then
die=yes
AC_MSG_NOTICE([[
***
*** You need a LDAP library to build this program.
*** Check out
*** http://www.openldap.org
*** for a suitable implementation.
***]])
if test "$have_w32ce_system" = yes; then
AC_MSG_NOTICE([[
*** Note that CeGCC might be broken, a package fixing this is:
*** http://files.kolab.org/local/windows-ce/
*** source/wldap32_0.1-mingw32ce.orig.tar.gz
*** binary/wldap32-ce-arm-dev_0.1-1_all.deb
***]])
fi
fi
if test "$missing_pth" = "yes"; then
AC_MSG_NOTICE([[
***
*** It is now required to build with support for the
*** GNU Portable Threads Library (Pth). Please install this
*** library first. The library is for example available at
*** ftp://ftp.gnu.org/gnu/pth/
*** On a Debian GNU/Linux system you can install it using
*** apt-get install libpth-dev
*** To build GnuPG for Windows you need to use the W32PTH
*** package; available at:
*** ftp://ftp.g10code.com/g10code/w32pth/
***]])
die=yes
fi
if test "$die" = "yes"; then
AC_MSG_ERROR([[
***
*** Required libraries not found. Please consult the above messages
*** and install them before running configure again.
***]])
fi
AC_CONFIG_FILES([ m4/Makefile
Makefile
po/Makefile.in
gl/Makefile
include/Makefile
common/Makefile
kbx/Makefile
g10/Makefile
sm/Makefile
agent/Makefile
scd/Makefile
g13/Makefile
dirmngr/Makefile
keyserver/Makefile
keyserver/gpg2keys_mailto
keyserver/gpg2keys_test
tools/gpg-zip
tools/Makefile
doc/Makefile
tests/Makefile
tests/openpgp/Makefile
tests/pkits/Makefile
])
AC_OUTPUT
echo "
GnuPG v${VERSION} has been configured as follows:
Platform: $PRINTABLE_OS_NAME ($host)
OpenPGP: $build_gpg
S/MIME: $build_gpgsm
Agent: $build_agent $build_agent_threaded
Smartcard: $build_scdaemon $build_scdaemon_extra
G13: $build_g13
Dirmngr: $build_dirmngr
Gpgtar: $build_gpgtar
Protect tool: $show_gnupg_protect_tool_pgm
LDAP wrapper: $show_gnupg_dirmngr_ldap_pgm
Default agent: $show_gnupg_agent_pgm
Default pinentry: $show_gnupg_pinentry_pgm
Default scdaemon: $show_gnupg_scdaemon_pgm
Default dirmngr: $show_gnupg_dirmngr_pgm
Use standard socket: $use_standard_socket
Dirmngr auto start: $dirmngr_auto_start
"
if test x"$use_regex" != xyes ; then
echo "
Warning: No regular expression support available.
OpenPGP trust signatures won't work.
gpg-check-pattern will not be build.
"
fi
diff --git a/dirmngr/Makefile.am b/dirmngr/Makefile.am
index 5b1fe30be..0285fc8f8 100644
--- a/dirmngr/Makefile.am
+++ b/dirmngr/Makefile.am
@@ -1,85 +1,85 @@
# Makefile.am - dirmngr
# Copyright (C) 2002 Klarälvdalens Datakonsult AB
# Copyright (C) 2004, 2007, 2010 g10 Code GmbH
#
# 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
# 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
# along with this program; if not, see .
## Process this file with automake to produce Makefile.in
EXTRA_DIST = OAUTHORS ONEWS ChangeLog.1
bin_PROGRAMS = dirmngr dirmngr-client
if USE_LDAPWRAPPER
libexec_PROGRAMS = dirmngr_ldap
endif
AM_CPPFLAGS = -I$(top_srcdir)/gl -I$(top_srcdir)/intl -I$(top_srcdir)/common
include $(top_srcdir)/am/cmacros.am
AM_CFLAGS = $(LIBGCRYPT_CFLAGS) $(KSBA_CFLAGS) \
$(LIBASSUAN_CFLAGS) $(GPG_ERROR_CFLAGS) $(PTH_CFLAGS)
BUILT_SOURCES = no-libgcrypt.c
CLEANFILES = no-libgcrypt.c
if HAVE_W32_SYSTEM
ldap_url = ldap-url.h ldap-url.c
else
ldap_url =
endif
noinst_HEADERS = dirmngr.h crlcache.h crlfetch.h misc.h
dirmngr_SOURCES = dirmngr.c dirmngr.h server.c crlcache.c crlfetch.c \
ldapserver.h ldapserver.c certcache.c certcache.h \
cdb.h cdblib.c ldap.c misc.c dirmngr-err.h w32-ldap-help.h \
ocsp.c ocsp.h validate.c validate.h ldap-wrapper.h $(ldap_url)
if USE_LDAPWRAPPER
dirmngr_SOURCES += ldap-wrapper.c
else
dirmngr_SOURCES += ldap-wrapper-ce.c dirmngr_ldap.c
endif
dirmngr_LDADD = $(libcommonpth) ../gl/libgnu.a $(DNSLIBS) $(LIBASSUAN_LIBS) \
$(LIBGCRYPT_LIBS) $(KSBA_LIBS) $(PTH_LIBS) $(LIBINTL) $(LIBICONV)
if !USE_LDAPWRAPPER
-dirmngr_LDADD += $(LDAPLIBS)
+dirmngr_LDADD += $(LDAPLIBS) -llber
endif
dirmngr_LDFLAGS = $(extra_bin_ldflags)
if USE_LDAPWRAPPER
dirmngr_ldap_SOURCES = dirmngr_ldap.c $(ldap_url)
dirmngr_ldap_CFLAGS = $(GPG_ERROR_CFLAGS)
dirmngr_ldap_LDFLAGS =
dirmngr_ldap_LDADD = $(libcommon) no-libgcrypt.o ../gl/libgnu.a $(DNSLIBS) \
$(GPG_ERROR_LIBS) $(LDAPLIBS) $(LIBINTL) $(LIBICONV)
endif
dirmngr_client_SOURCES = dirmngr-client.c
dirmngr_client_LDADD = $(libcommon) no-libgcrypt.o \
../gl/libgnu.a $(LIBASSUAN_LIBS) \
$(GPG_ERROR_LIBS) $(LIBINTL) \
$(LIBICONV)
dirmngr_client_LDFLAGS = $(extra_bin_ldflags)
no-libgcrypt.c : $(top_srcdir)/tools/no-libgcrypt.c
cat $(top_srcdir)/tools/no-libgcrypt.c > no-libgcrypt.c
diff --git a/g10/Makefile.am b/g10/Makefile.am
index c8fc4821e..b82fe07f3 100644
--- a/g10/Makefile.am
+++ b/g10/Makefile.am
@@ -1,153 +1,155 @@
# Copyright (C) 1998, 1999, 2000, 2001, 2002,
# 2003, 2006, 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
# 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
# along with this program; if not, see .
## Process this file with automake to produce Makefile.in
EXTRA_DIST = options.skel
AM_CPPFLAGS = -I$(top_srcdir)/gl -I$(top_srcdir)/common \
-I$(top_srcdir)/include -I$(top_srcdir)/intl
include $(top_srcdir)/am/cmacros.am
AM_CFLAGS = $(LIBGCRYPT_CFLAGS) $(LIBASSUAN_CFLAGS) $(GPG_ERROR_CFLAGS)
needed_libs = $(libcommon) ../gl/libgnu.a
bin_PROGRAMS = gpg2
if !HAVE_W32CE_SYSTEM
bin_PROGRAMS += gpgv2
endif
noinst_PROGRAMS = $(module_tests)
TESTS = $(module_tests)
if ENABLE_BZIP2_SUPPORT
bzip2_source = compress-bz2.c
else
bzip2_source =
endif
common_source = \
gpg.h \
build-packet.c \
compress.c \
$(bzip2_source) \
filter.h \
free-packet.c \
getkey.c \
keydb.c keydb.h \
keyring.c keyring.h \
seskey.c \
kbnode.c \
main.h \
mainproc.c \
armor.c \
mdfilter.c \
textfilter.c \
progress.c \
misc.c \
rmd160.c rmd160.h \
options.h \
openfile.c \
keyid.c \
packet.h \
parse-packet.c \
cpr.c \
plaintext.c \
sig-check.c \
keylist.c \
- pkglue.c pkglue.h
+ pkglue.c pkglue.h \
+ ecdh.c
gpg2_SOURCES = gpg.c \
server.c \
$(common_source) \
pkclist.c \
skclist.c \
pubkey-enc.c \
passphrase.c \
decrypt.c \
decrypt-data.c \
cipher.c \
encrypt.c \
sign.c \
verify.c \
revoke.c \
keyedit.c \
dearmor.c \
import.c \
export.c \
trustdb.c \
trustdb.h \
tdbdump.c \
tdbio.c \
tdbio.h \
delkey.c \
keygen.c \
helptext.c \
keyserver.c \
keyserver-internal.h \
photoid.c photoid.h \
call-agent.c call-agent.h \
card-util.c \
exec.c exec.h
gpgv2_SOURCES = gpgv.c \
$(common_source) \
- verify.c
+ verify.c \
+ verify-stubs.c
#gpgd_SOURCES = gpgd.c \
# ks-proto.h \
# ks-proto.c \
# ks-db.c \
# ks-db.h \
# $(common_source)
LDADD = $(needed_libs) ../common/libgpgrl.a \
$(ZLIBS) $(DNSLIBS) $(LIBREADLINE) \
$(LIBINTL) $(CAPLIBS) $(NETLIBS)
gpg2_LDADD = $(LDADD) $(LIBGCRYPT_LIBS) $(LIBASSUAN_LIBS) $(GPG_ERROR_LIBS) \
$(LIBICONV) $(extra_sys_libs)
gpg2_LDFLAGS = $(extra_bin_ldflags)
gpgv2_LDADD = $(LDADD) $(LIBGCRYPT_LIBS) $(LIBASSUAN_LIBS) $(GPG_ERROR_LIBS) \
$(LIBICONV) $(extra_sys_libs)
gpgv2_LDFLAGS = $(extra_bin_ldflags)
t_common_ldadd =
module_tests = t-rmd160
t_rmd160_SOURCES = t-rmd160.c rmd160.c
t_rmd160_LDADD = $(t_common_ldadd)
$(PROGRAMS): $(needed_libs) ../common/libgpgrl.a
install-data-local:
$(mkinstalldirs) $(DESTDIR)$(pkgdatadir)
$(INSTALL_DATA) $(srcdir)/options.skel \
$(DESTDIR)$(pkgdatadir)/gpg-conf.skel
uninstall-local:
-@rm $(DESTDIR)$(pkgdatadir)/gpg-conf.skel
# There has never been a gpg for WindowsCE, thus we don't need a gpg2 here
if HAVE_W32CE_SYSTEM
install-exec-hook:
mv -f $(DESTDIR)$(bindir)/gpg2$(EXEEXT) \
$(DESTDIR)$(bindir)/gpg$(EXEEXT)
endif
diff --git a/g10/armor.c b/g10/armor.c
index a6195fc3d..8cfd35c1f 100644
--- a/g10/armor.c
+++ b/g10/armor.c
@@ -1,1499 +1,1499 @@
/* armor.c - Armor flter
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
* 2007 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
* 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
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include "gpg.h"
#include "status.h"
#include "iobuf.h"
#include "util.h"
#include "filter.h"
#include "packet.h"
#include "options.h"
#include "main.h"
#include "status.h"
#include "i18n.h"
#define MAX_LINELEN 20000
#define CRCINIT 0xB704CE
#define CRCPOLY 0X864CFB
#define CRCUPDATE(a,c) do { \
a = ((a) << 8) ^ crc_table[((a)&0xff >> 16) ^ (c)]; \
a &= 0x00ffffff; \
} while(0)
static u32 crc_table[256];
static byte bintoasc[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static byte asctobin[256]; /* runtime initialized */
static int is_initialized;
typedef enum {
fhdrHASArmor = 0,
fhdrNOArmor,
fhdrINIT,
fhdrINITCont,
fhdrINITSkip,
fhdrCHECKBegin,
fhdrWAITHeader,
fhdrWAITClearsig,
fhdrSKIPHeader,
fhdrCLEARSIG,
fhdrREADClearsig,
fhdrNullClearsig,
fhdrEMPTYClearsig,
fhdrCHECKClearsig,
fhdrCHECKClearsig2,
fhdrCHECKDashEscaped,
fhdrCHECKDashEscaped2,
fhdrCHECKDashEscaped3,
fhdrREADClearsigNext,
fhdrENDClearsig,
fhdrENDClearsigHelp,
fhdrTESTSpaces,
fhdrCLEARSIGSimple,
fhdrCLEARSIGSimpleNext,
fhdrTEXT,
fhdrTEXTSimple,
fhdrERROR,
fhdrERRORShow,
fhdrEOF
} fhdr_state_t;
/* if we encounter this armor string with this index, go
* into a mode which fakes packets and wait for the next armor */
#define BEGIN_SIGNATURE 2
#define BEGIN_SIGNED_MSG_IDX 3
static char *head_strings[] = {
"BEGIN PGP MESSAGE",
"BEGIN PGP PUBLIC KEY BLOCK",
"BEGIN PGP SIGNATURE",
"BEGIN PGP SIGNED MESSAGE",
"BEGIN PGP ARMORED FILE", /* gnupg extension */
"BEGIN PGP PRIVATE KEY BLOCK",
"BEGIN PGP SECRET KEY BLOCK", /* only used by pgp2 */
NULL
};
static char *tail_strings[] = {
"END PGP MESSAGE",
"END PGP PUBLIC KEY BLOCK",
"END PGP SIGNATURE",
"END dummy",
"END PGP ARMORED FILE",
"END PGP PRIVATE KEY BLOCK",
"END PGP SECRET KEY BLOCK",
NULL
};
static int armor_filter ( void *opaque, int control,
iobuf_t chain, byte *buf, size_t *ret_len);
/* Create a new context for armor filters. */
armor_filter_context_t *
new_armor_context (void)
{
armor_filter_context_t *afx;
afx = xcalloc (1, sizeof *afx);
afx->refcount = 1;
return afx;
}
/* Release an armor filter context. Passing NULL is explicitly
allowed and a no-op. */
void
release_armor_context (armor_filter_context_t *afx)
{
if (!afx)
return;
assert (afx->refcount);
if ( --afx->refcount )
return;
xfree (afx);
}
/* Push the armor filter onto the iobuf stream IOBUF. */
int
push_armor_filter (armor_filter_context_t *afx, iobuf_t iobuf)
{
int rc;
afx->refcount++;
rc = iobuf_push_filter (iobuf, armor_filter, afx);
if (rc)
afx->refcount--;
return rc;
}
static void
initialize(void)
{
int i, j;
u32 t;
byte *s;
/* init the crc lookup table */
crc_table[0] = 0;
for(i=j=0; j < 128; j++ ) {
t = crc_table[j];
if( t & 0x00800000 ) {
t <<= 1;
crc_table[i++] = t ^ CRCPOLY;
crc_table[i++] = t;
}
else {
t <<= 1;
crc_table[i++] = t;
crc_table[i++] = t ^ CRCPOLY;
}
}
/* build the helptable for radix64 to bin conversion */
for(i=0; i < 256; i++ )
asctobin[i] = 255; /* used to detect invalid characters */
for(s=bintoasc,i=0; *s; s++,i++ )
asctobin[*s] = i;
is_initialized=1;
}
/****************
* Check whether this is an armored file or not See also
* parse-packet.c for details on this code For unknown historic
* reasons we use a string here but only the first byte will be used.
* Returns: True if it seems to be armored
*/
static int
is_armored( const byte *buf )
{
int ctb, pkttype;
ctb = *buf;
if( !(ctb & 0x80) )
return 1; /* invalid packet: assume it is armored */
pkttype = ctb & 0x40 ? (ctb & 0x3f) : ((ctb>>2)&0xf);
switch( pkttype ) {
case PKT_MARKER:
case PKT_SYMKEY_ENC:
case PKT_ONEPASS_SIG:
case PKT_PUBLIC_KEY:
case PKT_SECRET_KEY:
case PKT_PUBKEY_ENC:
case PKT_SIGNATURE:
case PKT_COMMENT:
case PKT_OLD_COMMENT:
case PKT_PLAINTEXT:
case PKT_COMPRESSED:
case PKT_ENCRYPTED:
return 0; /* seems to be a regular packet: not armored */
}
return 1;
}
/****************
* Try to check whether the iobuf is armored
* Returns true if this may be the case; the caller should use the
* filter to do further processing.
*/
int
use_armor_filter( IOBUF a )
{
byte buf[1];
int n;
/* fixme: there might be a problem with iobuf_peek */
n = iobuf_peek(a, buf, 1 );
if( n == -1 )
return 0; /* EOF, doesn't matter whether armored or not */
if( !n )
return 1; /* can't check it: try armored */
return is_armored(buf);
}
static void
invalid_armor(void)
{
write_status(STATUS_BADARMOR);
g10_exit(1); /* stop here */
}
/****************
* check whether the armor header is valid on a signed message.
* this is for security reasons: the header lines are not included in the
* hash and by using some creative formatting rules, Mallory could fake
* any text at the beginning of a document; assuming it is read with
* a simple viewer. We only allow the Hash Header.
*/
static int
parse_hash_header( const char *line )
{
const char *s, *s2;
unsigned found = 0;
if( strlen(line) < 6 || strlen(line) > 60 )
return 0; /* too short or too long */
if( memcmp( line, "Hash:", 5 ) )
return 0; /* invalid header */
s = line+5;
for(s=line+5;;s=s2) {
for(; *s && (*s==' ' || *s == '\t'); s++ )
;
if( !*s )
break;
for(s2=s+1; *s2 && *s2!=' ' && *s2 != '\t' && *s2 != ','; s2++ )
;
if( !strncmp( s, "RIPEMD160", s2-s ) )
found |= 1;
else if( !strncmp( s, "SHA1", s2-s ) )
found |= 2;
else if( !strncmp( s, "MD5", s2-s ) )
found |= 4;
else if( !strncmp( s, "SHA224", s2-s ) )
found |= 8;
else if( !strncmp( s, "SHA256", s2-s ) )
found |= 16;
else if( !strncmp( s, "SHA384", s2-s ) )
found |= 32;
else if( !strncmp( s, "SHA512", s2-s ) )
found |= 64;
else
return 0;
for(; *s2 && (*s2==' ' || *s2 == '\t'); s2++ )
;
if( *s2 && *s2 != ',' )
return 0;
if( *s2 )
s2++;
}
return found;
}
/* Returns true if this is a valid armor tag as per RFC-2440bis-21. */
static int
is_armor_tag(const char *line)
{
if(strncmp(line,"Version",7)==0
|| strncmp(line,"Comment",7)==0
|| strncmp(line,"MessageID",9)==0
|| strncmp(line,"Hash",4)==0
|| strncmp(line,"Charset",7)==0)
return 1;
return 0;
}
/****************
* Check whether this is a armor line.
* returns: -1 if it is not a armor header or the index number of the
* armor header.
*/
static int
is_armor_header( byte *line, unsigned len )
{
const char *s;
byte *save_p, *p;
int save_c;
int i;
if( len < 15 )
return -1; /* too short */
if( memcmp( line, "-----", 5 ) )
return -1; /* no */
p = strstr( line+5, "-----");
if( !p )
return -1;
save_p = p;
p += 5;
/* Some Windows environments seem to add whitespace to the end of
the line, so we strip it here. This becomes strict if
--rfc2440 is set since 2440 reads "The header lines, therefore,
MUST start at the beginning of a line, and MUST NOT have text
following them on the same line." It is unclear whether "text"
refers to all text or just non-whitespace text. 4880 clarified
this was only non-whitespace text. */
if(RFC2440)
{
if( *p == '\r' )
p++;
if( *p == '\n' )
p++;
}
else
while(*p==' ' || *p=='\r' || *p=='\n' || *p=='\t')
p++;
if( *p )
return -1; /* garbage after dashes */
save_c = *save_p; *save_p = 0;
p = line+5;
for(i=0; (s=head_strings[i]); i++ )
if( !strcmp(s, p) )
break;
*save_p = save_c;
if( !s )
return -1; /* unknown armor line */
if( opt.verbose > 1 )
log_info(_("armor: %s\n"), head_strings[i]);
return i;
}
/****************
* Parse a header lines
* Return 0: Empty line (end of header lines)
* -1: invalid header line
* >0: Good header line
*/
static int
parse_header_line( armor_filter_context_t *afx, byte *line, unsigned int len )
{
byte *p;
int hashes=0;
unsigned int len2;
len2 = length_sans_trailing_ws ( line, len );
if( !len2 ) {
afx->buffer_pos = len2; /* (it is not the fine way to do it here) */
return 0; /* WS only: same as empty line */
}
/*
This is fussy. The spec says that a header line is delimited
with a colon-space pair. This means that a line such as
"Comment: " (with nothing else) is actually legal as an empty
string comment. However, email and cut-and-paste being what it
is, that trailing space may go away. Therefore, we accept empty
headers delimited with only a colon. --rfc2440, as always,
makes this strict and enforces the colon-space pair. -dms
*/
p = strchr( line, ':');
if( !p || (RFC2440 && p[1]!=' ')
|| (!RFC2440 && p[1]!=' ' && p[1]!='\n' && p[1]!='\r'))
{
log_error (_("invalid armor header: "));
es_write_sanitized (log_get_stream (), line, len, NULL, NULL);
log_printf ("\n");
return -1;
}
/* Chop off the whitespace we detected before */
len=len2;
line[len2]='\0';
if( opt.verbose ) {
log_info(_("armor header: "));
es_write_sanitized (log_get_stream (), line, len, NULL, NULL);
log_printf ("\n");
}
if( afx->in_cleartext )
{
if( (hashes=parse_hash_header( line )) )
afx->hashes |= hashes;
else if( strlen(line) > 15 && !memcmp( line, "NotDashEscaped:", 15 ) )
afx->not_dash_escaped = 1;
else
{
log_error(_("invalid clearsig header\n"));
return -1;
}
}
else if(!is_armor_tag(line))
{
/* Section 6.2: "Unknown keys should be reported to the user,
but OpenPGP should continue to process the message." Note
that in a clearsigned message this applies to the signature
part (i.e. "BEGIN PGP SIGNATURE") and not the signed data
("BEGIN PGP SIGNED MESSAGE"). The only key allowed in the
signed data section is "Hash". */
log_info(_("unknown armor header: "));
es_write_sanitized (log_get_stream (), line, len, NULL, NULL);
log_printf ("\n");
}
return 1;
}
/* figure out whether the data is armored or not */
static int
check_input( armor_filter_context_t *afx, IOBUF a )
{
int rc = 0;
int i;
byte *line;
unsigned len;
unsigned maxlen;
int hdr_line = -1;
/* read the first line to see whether this is armored data */
maxlen = MAX_LINELEN;
len = afx->buffer_len = iobuf_read_line( a, &afx->buffer,
&afx->buffer_size, &maxlen );
line = afx->buffer;
if( !maxlen ) {
/* line has been truncated: assume not armored */
afx->inp_checked = 1;
afx->inp_bypass = 1;
return 0;
}
if( !len ) {
return -1; /* eof */
}
/* (the line is always a C string but maybe longer) */
if( *line == '\n' || ( len && (*line == '\r' && line[1]=='\n') ) )
;
else if( !is_armored( line ) ) {
afx->inp_checked = 1;
afx->inp_bypass = 1;
return 0;
}
/* find the armor header */
while(len) {
i = is_armor_header( line, len );
if( i >= 0 && !(afx->only_keyblocks && i != 1 && i != 5 && i != 6 )) {
hdr_line = i;
if( hdr_line == BEGIN_SIGNED_MSG_IDX ) {
if( afx->in_cleartext ) {
log_error(_("nested clear text signatures\n"));
rc = gpg_error (GPG_ERR_INV_ARMOR);
}
afx->in_cleartext = 1;
}
break;
}
/* read the next line (skip all truncated lines) */
do {
maxlen = MAX_LINELEN;
afx->buffer_len = iobuf_read_line( a, &afx->buffer,
&afx->buffer_size, &maxlen );
line = afx->buffer;
len = afx->buffer_len;
} while( !maxlen );
}
/* Parse the header lines. */
while(len) {
/* Read the next line (skip all truncated lines). */
do {
maxlen = MAX_LINELEN;
afx->buffer_len = iobuf_read_line( a, &afx->buffer,
&afx->buffer_size, &maxlen );
line = afx->buffer;
len = afx->buffer_len;
} while( !maxlen );
i = parse_header_line( afx, line, len );
if( i <= 0 ) {
if (i && RFC2440)
rc = G10ERR_INVALID_ARMOR;
break;
}
}
if( rc )
invalid_armor();
else if( afx->in_cleartext )
afx->faked = 1;
else {
afx->inp_checked = 1;
afx->crc = CRCINIT;
afx->idx = 0;
afx->radbuf[0] = 0;
}
return rc;
}
#define PARTIAL_CHUNK 512
#define PARTIAL_POW 9
/****************
* Fake a literal data packet and wait for the next armor line
* fixme: empty line handling and null length clear text signature are
* not implemented/checked.
*/
static int
fake_packet( armor_filter_context_t *afx, IOBUF a,
size_t *retn, byte *buf, size_t size )
{
int rc = 0;
size_t len = 0;
int lastline = 0;
unsigned maxlen, n;
byte *p;
byte tempbuf[PARTIAL_CHUNK];
size_t tempbuf_len=0;
while( !rc && size-len>=(PARTIAL_CHUNK+1)) {
/* copy what we have in the line buffer */
if( afx->faked == 1 )
afx->faked++; /* skip the first (empty) line */
else
{
/* It's full, so write this partial chunk */
if(tempbuf_len==PARTIAL_CHUNK)
{
buf[len++]=0xE0+PARTIAL_POW;
memcpy(&buf[len],tempbuf,PARTIAL_CHUNK);
len+=PARTIAL_CHUNK;
tempbuf_len=0;
continue;
}
while( tempbuf_len < PARTIAL_CHUNK
&& afx->buffer_pos < afx->buffer_len )
tempbuf[tempbuf_len++] = afx->buffer[afx->buffer_pos++];
if( tempbuf_len==PARTIAL_CHUNK )
continue;
}
/* read the next line */
maxlen = MAX_LINELEN;
afx->buffer_pos = 0;
afx->buffer_len = iobuf_read_line( a, &afx->buffer,
&afx->buffer_size, &maxlen );
if( !afx->buffer_len ) {
rc = -1; /* eof (should not happen) */
continue;
}
if( !maxlen )
afx->truncated++;
p = afx->buffer;
n = afx->buffer_len;
/* Armor header or dash-escaped line? */
if(p[0]=='-')
{
/* 2440bis-10: When reversing dash-escaping, an
implementation MUST strip the string "- " if it occurs
at the beginning of a line, and SHOULD warn on "-" and
any character other than a space at the beginning of a
line. */
if(p[1]==' ' && !afx->not_dash_escaped)
{
/* It's a dash-escaped line, so skip over the
escape. */
afx->buffer_pos = 2;
}
else if(p[1]=='-' && p[2]=='-' && p[3]=='-' && p[4]=='-')
{
/* Five dashes in a row mean it's probably armor
header. */
int type = is_armor_header( p, n );
if( afx->not_dash_escaped && type != BEGIN_SIGNATURE )
; /* this is okay */
else
{
if( type != BEGIN_SIGNATURE )
{
log_info(_("unexpected armor: "));
es_write_sanitized (log_get_stream (), p, n,
NULL, NULL);
log_printf ("\n");
}
lastline = 1;
rc = -1;
}
}
else if(!afx->not_dash_escaped)
{
/* Bad dash-escaping. */
log_info (_("invalid dash escaped line: "));
es_write_sanitized (log_get_stream (), p, n, NULL, NULL);
log_printf ("\n");
}
}
/* Now handle the end-of-line canonicalization */
if( !afx->not_dash_escaped )
{
int crlf = n > 1 && p[n-2] == '\r' && p[n-1]=='\n';
/* PGP2 does not treat a tab as white space character */
afx->buffer_len=
trim_trailing_chars( &p[afx->buffer_pos], n-afx->buffer_pos,
afx->pgp2mode ? " \r\n" : " \t\r\n");
afx->buffer_len+=afx->buffer_pos;
/* the buffer is always allocated with enough space to append
* the removed [CR], LF and a Nul
* The reason for this complicated procedure is to keep at least
* the original type of lineending - handling of the removed
* trailing spaces seems to be impossible in our method
* of faking a packet; either we have to use a temporary file
* or calculate the hash here in this module and somehow find
* a way to send the hash down the processing line (well, a special
* faked packet could do the job).
*/
if( crlf )
afx->buffer[afx->buffer_len++] = '\r';
afx->buffer[afx->buffer_len++] = '\n';
afx->buffer[afx->buffer_len] = '\0';
}
}
if( lastline ) { /* write last (ending) length header */
if(tempbuf_len<192)
buf[len++]=tempbuf_len;
else
{
buf[len++]=((tempbuf_len-192)/256) + 192;
buf[len++]=(tempbuf_len-192) % 256;
}
memcpy(&buf[len],tempbuf,tempbuf_len);
len+=tempbuf_len;
rc = 0;
afx->faked = 0;
afx->in_cleartext = 0;
/* and now read the header lines */
afx->buffer_pos = 0;
for(;;) {
int i;
/* read the next line (skip all truncated lines) */
do {
maxlen = MAX_LINELEN;
afx->buffer_len = iobuf_read_line( a, &afx->buffer,
&afx->buffer_size, &maxlen );
} while( !maxlen );
p = afx->buffer;
n = afx->buffer_len;
if( !n ) {
rc = -1;
break; /* eof */
}
i = parse_header_line( afx, p , n );
if( i <= 0 ) {
if( i )
invalid_armor();
break;
}
}
afx->inp_checked = 1;
afx->crc = CRCINIT;
afx->idx = 0;
afx->radbuf[0] = 0;
}
*retn = len;
return rc;
}
static int
invalid_crc(void)
{
if ( opt.ignore_crc_error )
return 0;
log_inc_errorcount();
return gpg_error (GPG_ERR_INV_ARMOR);
}
static int
radix64_read( armor_filter_context_t *afx, IOBUF a, size_t *retn,
byte *buf, size_t size )
{
byte val;
int c=0, c2; /*init c because gcc is not clever enough for the continue*/
int checkcrc=0;
int rc = 0;
size_t n = 0;
int idx, i, onlypad=0;
u32 crc;
crc = afx->crc;
idx = afx->idx;
val = afx->radbuf[0];
for( n=0; n < size; ) {
if( afx->buffer_pos < afx->buffer_len )
c = afx->buffer[afx->buffer_pos++];
else { /* read the next line */
unsigned maxlen = MAX_LINELEN;
afx->buffer_pos = 0;
afx->buffer_len = iobuf_read_line( a, &afx->buffer,
&afx->buffer_size, &maxlen );
if( !maxlen )
afx->truncated++;
if( !afx->buffer_len )
break; /* eof */
continue;
}
again:
if( c == '\n' || c == ' ' || c == '\r' || c == '\t' )
continue;
else if( c == '=' ) { /* pad character: stop */
/* some mailers leave quoted-printable encoded characters
* so we try to workaround this */
if( afx->buffer_pos+2 < afx->buffer_len ) {
int cc1, cc2, cc3;
cc1 = afx->buffer[afx->buffer_pos];
cc2 = afx->buffer[afx->buffer_pos+1];
cc3 = afx->buffer[afx->buffer_pos+2];
if( isxdigit(cc1) && isxdigit(cc2)
&& strchr( "=\n\r\t ", cc3 )) {
/* well it seems to be the case - adjust */
c = isdigit(cc1)? (cc1 - '0'): (ascii_toupper(cc1)-'A'+10);
c <<= 4;
c |= isdigit(cc2)? (cc2 - '0'): (ascii_toupper(cc2)-'A'+10);
afx->buffer_pos += 2;
afx->qp_detected = 1;
goto again;
}
}
if (!n)
onlypad = 1;
if( idx == 1 )
buf[n++] = val;
checkcrc++;
break;
}
else if( (c = asctobin[(c2=c)]) == 255 ) {
log_error(_("invalid radix64 character %02X skipped\n"), c2);
continue;
}
switch(idx) {
case 0: val = c << 2; break;
case 1: val |= (c>>4)&3; buf[n++]=val;val=(c<<4)&0xf0;break;
case 2: val |= (c>>2)&15; buf[n++]=val;val=(c<<6)&0xc0;break;
case 3: val |= c&0x3f; buf[n++] = val; break;
}
idx = (idx+1) % 4;
}
for(i=0; i < n; i++ )
crc = (crc << 8) ^ crc_table[((crc >> 16)&0xff) ^ buf[i]];
crc &= 0x00ffffff;
afx->crc = crc;
afx->idx = idx;
afx->radbuf[0] = val;
if( checkcrc ) {
afx->any_data = 1;
afx->inp_checked=0;
afx->faked = 0;
for(;;) { /* skip lf and pad characters */
if( afx->buffer_pos < afx->buffer_len )
c = afx->buffer[afx->buffer_pos++];
else { /* read the next line */
unsigned maxlen = MAX_LINELEN;
afx->buffer_pos = 0;
afx->buffer_len = iobuf_read_line( a, &afx->buffer,
&afx->buffer_size, &maxlen );
if( !maxlen )
afx->truncated++;
if( !afx->buffer_len )
break; /* eof */
continue;
}
if( c == '\n' || c == ' ' || c == '\r'
|| c == '\t' || c == '=' )
continue;
break;
}
if( c == -1 )
log_error(_("premature eof (no CRC)\n"));
else {
u32 mycrc = 0;
idx = 0;
do {
if( (c = asctobin[c]) == 255 )
break;
switch(idx) {
case 0: val = c << 2; break;
case 1: val |= (c>>4)&3; mycrc |= val << 16;val=(c<<4)&0xf0;break;
case 2: val |= (c>>2)&15; mycrc |= val << 8;val=(c<<6)&0xc0;break;
case 3: val |= c&0x3f; mycrc |= val; break;
}
for(;;) {
if( afx->buffer_pos < afx->buffer_len )
c = afx->buffer[afx->buffer_pos++];
else { /* read the next line */
unsigned maxlen = MAX_LINELEN;
afx->buffer_pos = 0;
afx->buffer_len = iobuf_read_line( a, &afx->buffer,
&afx->buffer_size,
&maxlen );
if( !maxlen )
afx->truncated++;
if( !afx->buffer_len )
break; /* eof */
continue;
}
break;
}
if( !afx->buffer_len )
break; /* eof */
} while( ++idx < 4 );
if( c == -1 ) {
log_info(_("premature eof (in CRC)\n"));
rc = invalid_crc();
}
else if( idx == 0 ) {
/* No CRC at all is legal ("MAY") */
rc=0;
}
else if( idx != 4 ) {
log_info(_("malformed CRC\n"));
rc = invalid_crc();
}
else if( mycrc != afx->crc ) {
log_info (_("CRC error; %06lX - %06lX\n"),
(ulong)afx->crc, (ulong)mycrc);
rc = invalid_crc();
}
else {
rc = 0;
/* FIXME: Here we should emit another control packet,
* so that we know in mainproc that we are processing
* a clearsign message */
#if 0
for(rc=0;!rc;) {
rc = 0 /*check_trailer( &fhdr, c )*/;
if( !rc ) {
if( (c=iobuf_get(a)) == -1 )
rc = 2;
}
}
if( rc == -1 )
rc = 0;
else if( rc == 2 ) {
log_error(_("premature eof (in trailer)\n"));
rc = G10ERR_INVALID_ARMOR;
}
else {
log_error(_("error in trailer line\n"));
rc = G10ERR_INVALID_ARMOR;
}
#endif
}
}
}
if( !n && !onlypad )
rc = -1;
*retn = n;
return rc;
}
/****************
* This filter is used to handle the armor stuff
*/
static int
armor_filter( void *opaque, int control,
IOBUF a, byte *buf, size_t *ret_len)
{
size_t size = *ret_len;
armor_filter_context_t *afx = opaque;
int rc=0, i, c;
byte radbuf[3];
int idx, idx2;
size_t n=0;
u32 crc;
#if 0
static FILE *fp ;
if( !fp ) {
fp = fopen("armor.out", "w");
assert(fp);
}
#endif
if( DBG_FILTER )
log_debug("armor-filter: control: %d\n", control );
if( control == IOBUFCTRL_UNDERFLOW && afx->inp_bypass ) {
n = 0;
if( afx->buffer_len ) {
for(; n < size && afx->buffer_pos < afx->buffer_len; n++ )
buf[n++] = afx->buffer[afx->buffer_pos++];
if( afx->buffer_pos >= afx->buffer_len )
afx->buffer_len = 0;
}
for(; n < size; n++ ) {
if( (c=iobuf_get(a)) == -1 )
break;
buf[n] = c & 0xff;
}
if( !n )
rc = -1;
*ret_len = n;
}
else if( control == IOBUFCTRL_UNDERFLOW ) {
/* We need some space for the faked packet. The minmum
* required size is the PARTIAL_CHUNK size plus a byte for the
* length itself */
if( size < PARTIAL_CHUNK+1 )
BUG(); /* supplied buffer too short */
if( afx->faked )
rc = fake_packet( afx, a, &n, buf, size );
else if( !afx->inp_checked ) {
rc = check_input( afx, a );
if( afx->inp_bypass ) {
for(n=0; n < size && afx->buffer_pos < afx->buffer_len; )
buf[n++] = afx->buffer[afx->buffer_pos++];
if( afx->buffer_pos >= afx->buffer_len )
afx->buffer_len = 0;
if( !n )
rc = -1;
}
else if( afx->faked ) {
unsigned int hashes = afx->hashes;
const byte *sesmark;
size_t sesmarklen;
sesmark = get_session_marker( &sesmarklen );
if ( sesmarklen > 20 )
BUG();
/* the buffer is at least 15+n*15 bytes long, so it
* is easy to construct the packets */
hashes &= 1|2|4|8|16|32|64;
if( !hashes ) {
hashes |= 4; /* default to MD 5 */
/* This is non-ideal since PGP 5-8 have the same
end-of-line bugs as PGP 2. However, we only
enable pgp2mode if there is no Hash: header. */
if( opt.pgp2_workarounds )
afx->pgp2mode = 1;
}
n=0;
/* First a gpg control packet... */
buf[n++] = 0xff; /* new format, type 63, 1 length byte */
n++; /* see below */
memcpy(buf+n, sesmark, sesmarklen ); n+= sesmarklen;
buf[n++] = CTRLPKT_CLEARSIGN_START;
buf[n++] = afx->not_dash_escaped? 0:1; /* sigclass */
if( hashes & 1 )
buf[n++] = DIGEST_ALGO_RMD160;
if( hashes & 2 )
buf[n++] = DIGEST_ALGO_SHA1;
if( hashes & 4 )
buf[n++] = DIGEST_ALGO_MD5;
if( hashes & 8 )
buf[n++] = DIGEST_ALGO_SHA224;
if( hashes & 16 )
buf[n++] = DIGEST_ALGO_SHA256;
if( hashes & 32 )
buf[n++] = DIGEST_ALGO_SHA384;
if( hashes & 64 )
buf[n++] = DIGEST_ALGO_SHA512;
buf[1] = n - 2;
/* ...followed by an invented plaintext packet.
Amusingly enough, this packet is not compliant with
2440 as the initial partial length is less than 512
bytes. Of course, we'll accept it anyway ;) */
buf[n++] = 0xCB; /* new packet format, type 11 */
buf[n++] = 0xE1; /* 2^1 == 2 bytes */
buf[n++] = 't'; /* canonical text mode */
buf[n++] = 0; /* namelength */
buf[n++] = 0xE2; /* 2^2 == 4 more bytes */
memset(buf+n, 0, 4); /* timestamp */
n += 4;
}
else if( !rc )
rc = radix64_read( afx, a, &n, buf, size );
}
else
rc = radix64_read( afx, a, &n, buf, size );
#if 0
if( n )
if( fwrite(buf, n, 1, fp ) != 1 )
BUG();
#endif
*ret_len = n;
}
else if( control == IOBUFCTRL_FLUSH && !afx->cancel ) {
if( !afx->status ) { /* write the header line */
const char *s;
strlist_t comment=opt.comments;
if( afx->what >= DIM(head_strings) )
log_bug("afx->what=%d", afx->what);
iobuf_writestr(a, "-----");
iobuf_writestr(a, head_strings[afx->what] );
iobuf_writestr(a, "-----" );
iobuf_writestr(a,afx->eol);
if( !opt.no_version )
{
- iobuf_writestr(a, "Version: GnuPG v" VERSION " ("
+ iobuf_writestr(a, "Version: GnuPG v" VERSION "-ecc ("
PRINTABLE_OS_NAME ")" );
iobuf_writestr(a,afx->eol);
}
/* write the comment strings */
for(s=comment->d;comment;comment=comment->next,s=comment->d)
{
iobuf_writestr(a, "Comment: " );
for( ; *s; s++ )
{
if( *s == '\n' )
iobuf_writestr(a, "\\n" );
else if( *s == '\r' )
iobuf_writestr(a, "\\r" );
else if( *s == '\v' )
iobuf_writestr(a, "\\v" );
else
iobuf_put(a, *s );
}
iobuf_writestr(a,afx->eol);
}
if ( afx->hdrlines ) {
for ( s = afx->hdrlines; *s; s++ ) {
#ifdef HAVE_DOSISH_SYSTEM
if ( *s == '\n' )
iobuf_put( a, '\r');
#endif
iobuf_put(a, *s );
}
}
iobuf_writestr(a,afx->eol);
afx->status++;
afx->idx = 0;
afx->idx2 = 0;
afx->crc = CRCINIT;
}
crc = afx->crc;
idx = afx->idx;
idx2 = afx->idx2;
for(i=0; i < idx; i++ )
radbuf[i] = afx->radbuf[i];
for(i=0; i < size; i++ )
crc = (crc << 8) ^ crc_table[((crc >> 16)&0xff) ^ buf[i]];
crc &= 0x00ffffff;
for( ; size; buf++, size-- ) {
radbuf[idx++] = *buf;
if( idx > 2 ) {
idx = 0;
c = bintoasc[(*radbuf >> 2) & 077];
iobuf_put(a, c);
c = bintoasc[(((*radbuf<<4)&060)|((radbuf[1] >> 4)&017))&077];
iobuf_put(a, c);
c = bintoasc[(((radbuf[1]<<2)&074)|((radbuf[2]>>6)&03))&077];
iobuf_put(a, c);
c = bintoasc[radbuf[2]&077];
iobuf_put(a, c);
if( ++idx2 >= (64/4) )
{ /* pgp doesn't like 72 here */
iobuf_writestr(a,afx->eol);
idx2=0;
}
}
}
for(i=0; i < idx; i++ )
afx->radbuf[i] = radbuf[i];
afx->idx = idx;
afx->idx2 = idx2;
afx->crc = crc;
}
else if( control == IOBUFCTRL_INIT )
{
if( !is_initialized )
initialize();
/* Figure out what we're using for line endings if the caller
didn't specify. */
if(afx->eol[0]==0)
{
#ifdef HAVE_DOSISH_SYSTEM
afx->eol[0]='\r';
afx->eol[1]='\n';
#else
afx->eol[0]='\n';
#endif
}
}
else if( control == IOBUFCTRL_CANCEL ) {
afx->cancel = 1;
}
else if( control == IOBUFCTRL_FREE ) {
if( afx->cancel )
;
else if( afx->status ) { /* pad, write cecksum, and bottom line */
crc = afx->crc;
idx = afx->idx;
idx2 = afx->idx2;
for(i=0; i < idx; i++ )
radbuf[i] = afx->radbuf[i];
if( idx ) {
c = bintoasc[(*radbuf>>2)&077];
iobuf_put(a, c);
if( idx == 1 ) {
c = bintoasc[((*radbuf << 4) & 060) & 077];
iobuf_put(a, c);
iobuf_put(a, '=');
iobuf_put(a, '=');
}
else { /* 2 */
c = bintoasc[(((*radbuf<<4)&060)|((radbuf[1]>>4)&017))&077];
iobuf_put(a, c);
c = bintoasc[((radbuf[1] << 2) & 074) & 077];
iobuf_put(a, c);
iobuf_put(a, '=');
}
if( ++idx2 >= (64/4) )
{ /* pgp doesn't like 72 here */
iobuf_writestr(a,afx->eol);
idx2=0;
}
}
/* may need a linefeed */
if( idx2 )
iobuf_writestr(a,afx->eol);
/* write the CRC */
iobuf_put(a, '=');
radbuf[0] = crc >>16;
radbuf[1] = crc >> 8;
radbuf[2] = crc;
c = bintoasc[(*radbuf >> 2) & 077];
iobuf_put(a, c);
c = bintoasc[(((*radbuf<<4)&060)|((radbuf[1] >> 4)&017))&077];
iobuf_put(a, c);
c = bintoasc[(((radbuf[1]<<2)&074)|((radbuf[2]>>6)&03))&077];
iobuf_put(a, c);
c = bintoasc[radbuf[2]&077];
iobuf_put(a, c);
iobuf_writestr(a,afx->eol);
/* and the the trailer */
if( afx->what >= DIM(tail_strings) )
log_bug("afx->what=%d", afx->what);
iobuf_writestr(a, "-----");
iobuf_writestr(a, tail_strings[afx->what] );
iobuf_writestr(a, "-----" );
iobuf_writestr(a,afx->eol);
}
else if( !afx->any_data && !afx->inp_bypass ) {
log_error(_("no valid OpenPGP data found.\n"));
afx->no_openpgp_data = 1;
write_status_text( STATUS_NODATA, "1" );
}
if( afx->truncated )
log_info(_("invalid armor: line longer than %d characters\n"),
MAX_LINELEN );
/* issue an error to enforce dissemination of correct software */
if( afx->qp_detected )
log_error(_("quoted printable character in armor - "
"probably a buggy MTA has been used\n") );
xfree( afx->buffer );
afx->buffer = NULL;
release_armor_context (afx);
}
else if( control == IOBUFCTRL_DESC )
*(char**)buf = "armor_filter";
return rc;
}
/****************
* create a radix64 encoded string.
*/
char *
make_radix64_string( const byte *data, size_t len )
{
char *buffer, *p;
buffer = p = xmalloc( (len+2)/3*4 + 1 );
for( ; len >= 3 ; len -= 3, data += 3 ) {
*p++ = bintoasc[(data[0] >> 2) & 077];
*p++ = bintoasc[(((data[0] <<4)&060)|((data[1] >> 4)&017))&077];
*p++ = bintoasc[(((data[1]<<2)&074)|((data[2]>>6)&03))&077];
*p++ = bintoasc[data[2]&077];
}
if( len == 2 ) {
*p++ = bintoasc[(data[0] >> 2) & 077];
*p++ = bintoasc[(((data[0] <<4)&060)|((data[1] >> 4)&017))&077];
*p++ = bintoasc[((data[1]<<2)&074)];
}
else if( len == 1 ) {
*p++ = bintoasc[(data[0] >> 2) & 077];
*p++ = bintoasc[(data[0] <<4)&060];
}
*p = 0;
return buffer;
}
/***********************************************
* For the pipemode command we can't use the armor filter for various
* reasons, so we use this new unarmor_pump stuff to remove the armor
*/
enum unarmor_state_e {
STA_init = 0,
STA_bypass,
STA_wait_newline,
STA_wait_dash,
STA_first_dash,
STA_compare_header,
STA_found_header_wait_newline,
STA_skip_header_lines,
STA_skip_header_lines_non_ws,
STA_read_data,
STA_wait_crc,
STA_read_crc,
STA_ready
};
struct unarmor_pump_s {
enum unarmor_state_e state;
byte val;
int checkcrc;
int pos; /* counts from 0..3 */
u32 crc;
u32 mycrc; /* the one store in the data */
};
UnarmorPump
unarmor_pump_new (void)
{
UnarmorPump x;
if( !is_initialized )
initialize();
x = xmalloc_clear (sizeof *x);
return x;
}
void
unarmor_pump_release (UnarmorPump x)
{
xfree (x);
}
/*
* Get the next character from the ascii armor taken from the IOBUF
* created earlier by unarmor_pump_new().
* Return: c = Character
* 256 = ignore this value
* -1 = End of current armor
* -2 = Premature EOF (not used)
* -3 = Invalid armor
*/
int
unarmor_pump (UnarmorPump x, int c)
{
int rval = 256; /* default is to ignore the return value */
switch (x->state) {
case STA_init:
{
byte tmp[1];
tmp[0] = c;
if ( is_armored (tmp) )
x->state = c == '-'? STA_first_dash : STA_wait_newline;
else {
x->state = STA_bypass;
return c;
}
}
break;
case STA_bypass:
return c; /* return here to avoid crc calculation */
case STA_wait_newline:
if (c == '\n')
x->state = STA_wait_dash;
break;
case STA_wait_dash:
x->state = c == '-'? STA_first_dash : STA_wait_newline;
break;
case STA_first_dash: /* just need for initalization */
x->pos = 0;
x->state = STA_compare_header;
case STA_compare_header:
if ( "-----BEGIN PGP SIGNATURE-----"[++x->pos] == c ) {
if ( x->pos == 28 )
x->state = STA_found_header_wait_newline;
}
else
x->state = c == '\n'? STA_wait_dash : STA_wait_newline;
break;
case STA_found_header_wait_newline:
/* to make CR,LF issues easier we simply allow for white space
behind the 5 dashes */
if ( c == '\n' )
x->state = STA_skip_header_lines;
else if ( c != '\r' && c != ' ' && c != '\t' )
x->state = STA_wait_dash; /* garbage after the header line */
break;
case STA_skip_header_lines:
/* i.e. wait for one empty line */
if ( c == '\n' ) {
x->state = STA_read_data;
x->crc = CRCINIT;
x->val = 0;
x->pos = 0;
}
else if ( c != '\r' && c != ' ' && c != '\t' )
x->state = STA_skip_header_lines_non_ws;
break;
case STA_skip_header_lines_non_ws:
/* like above but we already encountered non white space */
if ( c == '\n' )
x->state = STA_skip_header_lines;
break;
case STA_read_data:
/* fixme: we don't check for the trailing dash lines but rely
* on the armor stop characters */
if( c == '\n' || c == ' ' || c == '\r' || c == '\t' )
break; /* skip all kind of white space */
if( c == '=' ) { /* pad character: stop */
if( x->pos == 1 ) /* in this case val has some value */
rval = x->val;
x->state = STA_wait_crc;
break;
}
{
int c2;
if( (c = asctobin[(c2=c)]) == 255 ) {
log_error(_("invalid radix64 character %02X skipped\n"), c2);
break;
}
}
switch(x->pos) {
case 0:
x->val = c << 2;
break;
case 1:
x->val |= (c>>4)&3;
rval = x->val;
x->val = (c<<4)&0xf0;
break;
case 2:
x->val |= (c>>2)&15;
rval = x->val;
x->val = (c<<6)&0xc0;
break;
case 3:
x->val |= c&0x3f;
rval = x->val;
break;
}
x->pos = (x->pos+1) % 4;
break;
case STA_wait_crc:
if( c == '\n' || c == ' ' || c == '\r' || c == '\t' || c == '=' )
break; /* skip ws and pad characters */
/* assume that we are at the next line */
x->state = STA_read_crc;
x->pos = 0;
x->mycrc = 0;
case STA_read_crc:
if( (c = asctobin[c]) == 255 ) {
rval = -1; /* ready */
if( x->crc != x->mycrc ) {
log_info (_("CRC error; %06lX - %06lX\n"),
(ulong)x->crc, (ulong)x->mycrc);
if ( invalid_crc() )
rval = -3;
}
x->state = STA_ready; /* not sure whether this is correct */
break;
}
switch(x->pos) {
case 0:
x->val = c << 2;
break;
case 1:
x->val |= (c>>4)&3;
x->mycrc |= x->val << 16;
x->val = (c<<4)&0xf0;
break;
case 2:
x->val |= (c>>2)&15;
x->mycrc |= x->val << 8;
x->val = (c<<6)&0xc0;
break;
case 3:
x->val |= c&0x3f;
x->mycrc |= x->val;
break;
}
x->pos = (x->pos+1) % 4;
break;
case STA_ready:
rval = -1;
break;
}
if ( !(rval & ~255) ) { /* compute the CRC */
x->crc = (x->crc << 8) ^ crc_table[((x->crc >> 16)&0xff) ^ rval];
x->crc &= 0x00ffffff;
}
return rval;
}
diff --git a/g10/build-packet.c b/g10/build-packet.c
index 83d6c7a73..3a2c206c8 100644
--- a/g10/build-packet.c
+++ b/g10/build-packet.c
@@ -1,1331 +1,1365 @@
/* build-packet.c - assemble packets and write them
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
* 2006, 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
* 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
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include
#include "gpg.h"
#include "util.h"
#include "packet.h"
#include "status.h"
#include "iobuf.h"
#include "cipher.h"
#include "i18n.h"
#include "options.h"
static int do_user_id( IOBUF out, int ctb, PKT_user_id *uid );
static int do_key (iobuf_t out, int ctb, PKT_public_key *pk);
static int do_symkey_enc( IOBUF out, int ctb, PKT_symkey_enc *enc );
static int do_pubkey_enc( IOBUF out, int ctb, PKT_pubkey_enc *enc );
static u32 calc_plaintext( PKT_plaintext *pt );
static int do_plaintext( IOBUF out, int ctb, PKT_plaintext *pt );
static int do_encrypted( IOBUF out, int ctb, PKT_encrypted *ed );
static int do_encrypted_mdc( IOBUF out, int ctb, PKT_encrypted *ed );
static int do_compressed( IOBUF out, int ctb, PKT_compressed *cd );
static int do_signature( IOBUF out, int ctb, PKT_signature *sig );
static int do_onepass_sig( IOBUF out, int ctb, PKT_onepass_sig *ops );
static int calc_header_length( u32 len, int new_ctb );
static int write_16(IOBUF inp, u16 a);
static int write_32(IOBUF inp, u32 a);
static int write_header( IOBUF out, int ctb, u32 len );
static int write_sign_packet_header( IOBUF out, int ctb, u32 len );
static int write_header2( IOBUF out, int ctb, u32 len, int hdrlen );
static int write_new_header( IOBUF out, int ctb, u32 len, int hdrlen );
static int write_version( IOBUF out, int ctb );
/****************
* Build a packet and write it to INP
* Returns: 0 := okay
* >0 := error
* Note: Caller must free the packet
*/
int
build_packet( IOBUF out, PACKET *pkt )
{
int new_ctb=0, rc=0, ctb;
int pkttype;
if( DBG_PACKET )
log_debug("build_packet() type=%d\n", pkt->pkttype );
assert( pkt->pkt.generic );
switch ((pkttype = pkt->pkttype))
{
case PKT_PUBLIC_KEY:
if (pkt->pkt.public_key->seckey_info)
pkttype = PKT_SECRET_KEY;
break;
case PKT_PUBLIC_SUBKEY:
if (pkt->pkt.public_key->seckey_info)
pkttype = PKT_SECRET_SUBKEY;
break;
case PKT_PLAINTEXT: new_ctb = pkt->pkt.plaintext->new_ctb; break;
case PKT_ENCRYPTED:
case PKT_ENCRYPTED_MDC: new_ctb = pkt->pkt.encrypted->new_ctb; break;
case PKT_COMPRESSED:new_ctb = pkt->pkt.compressed->new_ctb; break;
case PKT_USER_ID:
if( pkt->pkt.user_id->attrib_data )
pkttype = PKT_ATTRIBUTE;
break;
default: break;
}
if( new_ctb || pkttype > 15 ) /* new format */
ctb = 0xc0 | (pkttype & 0x3f);
else
ctb = 0x80 | ((pkttype & 15)<<2);
switch( pkttype )
{
case PKT_ATTRIBUTE:
case PKT_USER_ID:
rc = do_user_id( out, ctb, pkt->pkt.user_id );
break;
case PKT_OLD_COMMENT:
case PKT_COMMENT:
/*
Ignore these. Theoretically, this will never be called as
we have no way to output comment packets any longer, but
just in case there is some code path that would end up
outputting a comment that was written before comments were
dropped (in the public key?) this is a no-op.
*/
break;
case PKT_PUBLIC_SUBKEY:
case PKT_PUBLIC_KEY:
case PKT_SECRET_SUBKEY:
case PKT_SECRET_KEY:
rc = do_key (out, ctb, pkt->pkt.public_key);
break;
case PKT_SYMKEY_ENC:
rc = do_symkey_enc( out, ctb, pkt->pkt.symkey_enc );
break;
case PKT_PUBKEY_ENC:
rc = do_pubkey_enc( out, ctb, pkt->pkt.pubkey_enc );
break;
case PKT_PLAINTEXT:
rc = do_plaintext( out, ctb, pkt->pkt.plaintext );
break;
case PKT_ENCRYPTED:
rc = do_encrypted( out, ctb, pkt->pkt.encrypted );
break;
case PKT_ENCRYPTED_MDC:
rc = do_encrypted_mdc( out, ctb, pkt->pkt.encrypted );
break;
case PKT_COMPRESSED:
rc = do_compressed( out, ctb, pkt->pkt.compressed );
break;
case PKT_SIGNATURE:
rc = do_signature( out, ctb, pkt->pkt.signature );
break;
case PKT_ONEPASS_SIG:
rc = do_onepass_sig( out, ctb, pkt->pkt.onepass_sig );
break;
case PKT_RING_TRUST:
break; /* ignore it (keyring.c does write it directly)*/
case PKT_MDC: /* we write it directly, so we should never see it here. */
default:
log_bug("invalid packet type in build_packet()\n");
break;
}
return rc;
}
/*
* Write the mpi A to OUT.
*/
static int
mpi_write (iobuf_t out, gcry_mpi_t a)
{
char buffer[(MAX_EXTERN_MPI_BITS+7)/8+2]; /* 2 is for the mpi length. */
size_t nbytes;
int rc;
nbytes = DIM(buffer);
rc = gcry_mpi_print (GCRYMPI_FMT_PGP, buffer, nbytes, &nbytes, a );
if( !rc )
rc = iobuf_write( out, buffer, nbytes );
else if (gpg_err_code(rc) == GPG_ERR_TOO_SHORT )
{
log_info ("mpi too large (%u bits)\n", gcry_mpi_get_nbits (a));
/* The buffer was too small. We better tell the user about the MPI. */
rc = gpg_error (GPG_ERR_TOO_LARGE);
}
return rc;
}
+/*
+ * Write the name OID, encoded as an mpi, to OUT. The format of the content of the MPI is
+ * one byte LEN, following by LEN bytes that are DER representation of an ASN.1 OID.
+ * This is true for each of the 3 following functions.
+ */
+#define iobuf_name_oid_write iobuf_write_size_body_mpi
+/* Write the value of KEK fields for ECDH. */
+#define ecdh_kek_params_write iobuf_write_size_body_mpi
+/* Write the value of encrypted filed for ECDH. */
+#define ecdh_esk_write iobuf_write_size_body_mpi
/****************
* calculate the length of a packet described by PKT
*/
u32
calc_packet_length( PACKET *pkt )
{
u32 n=0;
int new_ctb = 0;
assert( pkt->pkt.generic );
switch( pkt->pkttype ) {
case PKT_PLAINTEXT:
n = calc_plaintext( pkt->pkt.plaintext );
new_ctb = pkt->pkt.plaintext->new_ctb;
break;
case PKT_ATTRIBUTE:
case PKT_USER_ID:
case PKT_COMMENT:
case PKT_PUBLIC_KEY:
case PKT_SECRET_KEY:
case PKT_SYMKEY_ENC:
case PKT_PUBKEY_ENC:
case PKT_ENCRYPTED:
case PKT_SIGNATURE:
case PKT_ONEPASS_SIG:
case PKT_RING_TRUST:
case PKT_COMPRESSED:
default:
log_bug("invalid packet type in calc_packet_length()");
break;
}
n += calc_header_length(n, new_ctb);
return n;
}
static void
write_fake_data (IOBUF out, gcry_mpi_t a)
{
if (a)
{
unsigned int n;
void *p;
p = gcry_mpi_get_opaque ( a, &n );
iobuf_write (out, p, (n+7)/8 );
}
}
static int
do_user_id( IOBUF out, int ctb, PKT_user_id *uid )
{
int rc;
if( uid->attrib_data )
{
write_header(out, ctb, uid->attrib_len);
rc = iobuf_write( out, uid->attrib_data, uid->attrib_len );
}
else
{
write_header2( out, ctb, uid->len, 2 );
rc = iobuf_write( out, uid->name, uid->len );
}
return 0;
}
static int
do_key (iobuf_t out, int ctb, PKT_public_key *pk)
{
gpg_error_t err = 0;
int i, nskey, npkey;
iobuf_t a = iobuf_temp(); /* Build in a self-enlarging buffer. */
/* Write the version number - if none is specified, use 3 */
if ( !pk->version )
iobuf_put ( a, 3 );
else
iobuf_put ( a, pk->version );
write_32 (a, pk->timestamp );
/* v3 needs the expiration time. */
if ( pk->version < 4 )
{
u16 ndays;
if ( pk->expiredate )
ndays = (u16)((pk->expiredate - pk->timestamp) / 86400L);
else
ndays = 0;
write_16(a, ndays);
}
iobuf_put (a, pk->pubkey_algo );
/* Get number of secret and public parameters. They are held in one
array first the public ones, then the secret ones. */
nskey = pubkey_get_nskey (pk->pubkey_algo);
npkey = pubkey_get_npkey (pk->pubkey_algo);
/* If we don't have any public parameters - which is the case if we
don't know the algorithm used - the parameters are stored as one
blob in a faked (opaque) MPI. */
if (!npkey)
{
write_fake_data (a, pk->pkey[0]);
goto leave;
}
assert (npkey < nskey);
- /* Writing the public parameters is easy. */
- for (i=0; i < npkey; i++ )
- if ((err = mpi_write (a, pk->pkey[i])))
- goto leave;
+ if( pk->pubkey_algo != PUBKEY_ALGO_ECDSA && pk->pubkey_algo != PUBKEY_ALGO_ECDH ) {
+ /* Writing the public parameters is easy, */
+ for (i=0; i < npkey; i++ )
+ if ((err = mpi_write (a, pk->pkey[i])))
+ goto leave;
+ }
+ else {
+ /* ... except we do an adjustment for ECC OID and possibly KEK params for ECDH */
+ if( (err=iobuf_name_oid_write(a, pk->pkey[0])) || /* DER of OID with preceeding length byte */
+ (err = mpi_write (a, pk->pkey[1])) ) /* point Q, the public key */
+ {
+ goto leave;
+ }
+ if( pk->pubkey_algo == PUBKEY_ALGO_ECDH && (err=ecdh_kek_params_write(a,pk->pkey[2]))) { /* one more public field for ECDH */
+ goto leave;
+ }
+ /* followed by possibly protected private scalar */
+ }
if (pk->seckey_info)
{
/* This is a secret key packet. */
struct seckey_info *ski = pk->seckey_info;
/* Build the header for protected (encrypted) secret parameters. */
if (ski->is_protected)
{
if ( is_RSA (pk->pubkey_algo) && pk->version < 4 && !ski->s2k.mode )
{
/* The simple rfc1991 (v3) way. */
iobuf_put (a, ski->algo );
iobuf_write (a, ski->iv, ski->ivlen);
}
else
{
/* OpenPGP protection according to rfc2440. */
iobuf_put (a, ski->sha1chk? 0xfe : 0xff);
iobuf_put (a, ski->algo);
if (ski->s2k.mode >= 1000)
{
/* These modes are not possible in OpenPGP, we use
them to implement our extensions, 101 can be
viewed as a private/experimental extension (this
is not specified in rfc2440 but the same scheme
is used for all other algorithm identifiers). */
iobuf_put (a, 101);
iobuf_put (a, ski->s2k.hash_algo);
iobuf_write (a, "GNU", 3 );
iobuf_put (a, ski->s2k.mode - 1000);
}
else
{
iobuf_put (a, ski->s2k.mode);
iobuf_put (a, ski->s2k.hash_algo);
}
if (ski->s2k.mode == 1 || ski->s2k.mode == 3)
iobuf_write (a, ski->s2k.salt, 8);
if (ski->s2k.mode == 3)
iobuf_put (a, ski->s2k.count);
/* For our special modes 1001, 1002 we do not need an IV. */
if (ski->s2k.mode != 1001 && ski->s2k.mode != 1002)
iobuf_write (a, ski->iv, ski->ivlen);
}
}
else /* Not protected. */
iobuf_put (a, 0 );
if (ski->s2k.mode == 1001)
; /* GnuPG extension - don't write a secret key at all. */
else if (ski->s2k.mode == 1002)
{
/* GnuPG extension - divert to OpenPGP smartcard. */
/* Length of the serial number or 0 for no serial number. */
iobuf_put (a, ski->ivlen );
/* The serial number gets stored in the IV field. */
iobuf_write (a, ski->iv, ski->ivlen);
}
else if (ski->is_protected && pk->version >= 4)
{
/* The secret key is protected - write it out as it is. */
byte *p;
unsigned int ndatabits;
assert (gcry_mpi_get_flag (pk->pkey[npkey], GCRYMPI_FLAG_OPAQUE));
p = gcry_mpi_get_opaque (pk->pkey[npkey], &ndatabits);
iobuf_write (a, p, (ndatabits+7)/8 );
}
else if (ski->is_protected)
{
/* The secret key is protected the old v4 way. */
for ( ; i < nskey; i++ )
{
byte *p;
unsigned int ndatabits;
assert (gcry_mpi_get_flag (pk->pkey[i], GCRYMPI_FLAG_OPAQUE));
p = gcry_mpi_get_opaque (pk->pkey[i], &ndatabits);
iobuf_write (a, p, (ndatabits+7)/8);
}
write_16 (a, ski->csum );
}
else
{
/* Non-protected key. */
for ( ; i < nskey; i++ )
if ( (err = mpi_write (a, pk->pkey[i])))
goto leave;
write_16 (a, ski->csum );
}
}
leave:
if (!err)
{
/* Build the header of the packet - which we must do after
writing all the other stuff, so that we know the length of
the packet */
write_header2 (out, ctb, iobuf_get_temp_length(a), pk->hdrbytes);
/* And finally write it out to the real stream. */
err = iobuf_write_temp (out, a);
}
iobuf_close (a); /* Close the temporary buffer */
return err;
}
static int
do_symkey_enc( IOBUF out, int ctb, PKT_symkey_enc *enc )
{
int rc = 0;
IOBUF a = iobuf_temp();
assert( enc->version == 4 );
switch( enc->s2k.mode ) {
case 0: case 1: case 3: break;
default: log_bug("do_symkey_enc: s2k=%d\n", enc->s2k.mode );
}
iobuf_put( a, enc->version );
iobuf_put( a, enc->cipher_algo );
iobuf_put( a, enc->s2k.mode );
iobuf_put( a, enc->s2k.hash_algo );
if( enc->s2k.mode == 1 || enc->s2k.mode == 3 ) {
iobuf_write(a, enc->s2k.salt, 8 );
if( enc->s2k.mode == 3 )
iobuf_put(a, enc->s2k.count);
}
if( enc->seskeylen )
iobuf_write(a, enc->seskey, enc->seskeylen );
write_header(out, ctb, iobuf_get_temp_length(a) );
rc = iobuf_write_temp( out, a );
iobuf_close(a);
return rc;
}
static int
do_pubkey_enc( IOBUF out, int ctb, PKT_pubkey_enc *enc )
{
int rc = 0;
int n, i;
IOBUF a = iobuf_temp();
write_version( a, ctb );
if ( enc->throw_keyid )
{
write_32(a, 0 ); /* Don't tell Eve who can decrypt the message. */
write_32(a, 0 );
}
else
{
write_32(a, enc->keyid[0] );
write_32(a, enc->keyid[1] );
}
iobuf_put(a,enc->pubkey_algo );
n = pubkey_get_nenc( enc->pubkey_algo );
if ( !n )
write_fake_data( a, enc->data[0] );
- for (i=0; i < n && !rc ; i++ )
- rc = mpi_write(a, enc->data[i] );
+
+ if( enc->pubkey_algo != PUBKEY_ALGO_ECDH ) {
+ for (i=0; i < n && !rc ; i++ )
+ rc = mpi_write(a, enc->data[i] );
+ }
+ else {
+ /* the second field persists as a LEN+field structure, even though it is
+ * stored for uniformity as an MPI internally */
+ assert( n==2 );
+ rc = mpi_write(a, enc->data[0] );
+ if( !rc ) rc = ecdh_esk_write(a, enc->data[1] );
+ }
if (!rc)
{
write_header(out, ctb, iobuf_get_temp_length(a) );
rc = iobuf_write_temp( out, a );
}
iobuf_close(a);
return rc;
}
static u32
calc_plaintext( PKT_plaintext *pt )
{
/* Truncate namelen to the maximum 255 characters. Note this means
that a function that calls build_packet with an illegal literal
packet will get it back legalized. */
if(pt->namelen>255)
pt->namelen=255;
return pt->len? (1 + 1 + pt->namelen + 4 + pt->len) : 0;
}
static int
do_plaintext( IOBUF out, int ctb, PKT_plaintext *pt )
{
int i, rc = 0;
u32 n;
byte buf[1000]; /* this buffer has the plaintext! */
int nbytes;
write_header(out, ctb, calc_plaintext( pt ) );
iobuf_put(out, pt->mode );
iobuf_put(out, pt->namelen );
for(i=0; i < pt->namelen; i++ )
iobuf_put(out, pt->name[i] );
rc = write_32(out, pt->timestamp );
if (rc)
return rc;
n = 0;
while( (nbytes=iobuf_read(pt->buf, buf, 1000)) != -1 ) {
rc = iobuf_write (out, buf, nbytes);
if (rc)
break;
n += nbytes;
}
wipememory(buf,1000); /* burn the buffer */
if( (ctb&0x40) && !pt->len )
iobuf_set_partial_block_mode(out, 0 ); /* turn off partial */
if( pt->len && n != pt->len )
log_error("do_plaintext(): wrote %lu bytes but expected %lu bytes\n",
(ulong)n, (ulong)pt->len );
return rc;
}
static int
do_encrypted( IOBUF out, int ctb, PKT_encrypted *ed )
{
int rc = 0;
u32 n;
n = ed->len ? (ed->len + ed->extralen) : 0;
write_header(out, ctb, n );
/* This is all. The caller has to write the real data */
return rc;
}
static int
do_encrypted_mdc( IOBUF out, int ctb, PKT_encrypted *ed )
{
int rc = 0;
u32 n;
assert( ed->mdc_method );
/* Take version number and the following MDC packet in account. */
n = ed->len ? (ed->len + ed->extralen + 1 + 22) : 0;
write_header(out, ctb, n );
iobuf_put(out, 1 ); /* version */
/* This is all. The caller has to write the real data */
return rc;
}
static int
do_compressed( IOBUF out, int ctb, PKT_compressed *cd )
{
int rc = 0;
/* We must use the old convention and don't use blockmode for the
sake of PGP 2 compatibility. However if the new_ctb flag was
set, CTB is already formatted as new style and write_header2
does create a partial length encoding using new the new
style. */
write_header2(out, ctb, 0, 0);
iobuf_put(out, cd->algorithm );
/* This is all. The caller has to write the real data */
return rc;
}
/****************
* Delete all subpackets of type REQTYPE and return a bool whether a packet
* was deleted.
*/
int
delete_sig_subpkt (subpktarea_t *area, sigsubpkttype_t reqtype )
{
int buflen;
sigsubpkttype_t type;
byte *buffer, *bufstart;
size_t n;
size_t unused = 0;
int okay = 0;
if( !area )
return 0;
buflen = area->len;
buffer = area->data;
for(;;) {
if( !buflen ) {
okay = 1;
break;
}
bufstart = buffer;
n = *buffer++; buflen--;
if( n == 255 ) {
if( buflen < 4 )
break;
n = (buffer[0] << 24) | (buffer[1] << 16)
| (buffer[2] << 8) | buffer[3];
buffer += 4;
buflen -= 4;
}
else if( n >= 192 ) {
if( buflen < 2 )
break;
n = (( n - 192 ) << 8) + *buffer + 192;
buffer++;
buflen--;
}
if( buflen < n )
break;
type = *buffer & 0x7f;
if( type == reqtype ) {
buffer++;
buflen--;
n--;
if( n > buflen )
break;
buffer += n; /* point to next subpkt */
buflen -= n;
memmove (bufstart, buffer, buflen); /* shift */
unused += buffer - bufstart;
buffer = bufstart;
}
else {
buffer += n; buflen -=n;
}
}
if (!okay)
log_error ("delete_subpkt: buffer shorter than subpacket\n");
assert (unused <= area->len);
area->len -= unused;
return !!unused;
}
/****************
* Create or update a signature subpacket for SIG of TYPE. This
* functions knows where to put the data (hashed or unhashed). The
* function may move data from the unhashed part to the hashed one.
* Note: All pointers into sig->[un]hashed (e.g. returned by
* parse_sig_subpkt) are not valid after a call to this function. The
* data to put into the subpaket should be in a buffer with a length
* of buflen.
*/
void
build_sig_subpkt (PKT_signature *sig, sigsubpkttype_t type,
const byte *buffer, size_t buflen )
{
byte *p;
int critical, hashed;
subpktarea_t *oldarea, *newarea;
size_t nlen, n, n0;
critical = (type & SIGSUBPKT_FLAG_CRITICAL);
type &= ~SIGSUBPKT_FLAG_CRITICAL;
/* Sanity check buffer sizes */
if(parse_one_sig_subpkt(buffer,buflen,type)<0)
BUG();
switch(type)
{
case SIGSUBPKT_NOTATION:
case SIGSUBPKT_POLICY:
case SIGSUBPKT_REV_KEY:
case SIGSUBPKT_SIGNATURE:
/* we do allow multiple subpackets */
break;
default:
/* we don't allow multiple subpackets */
delete_sig_subpkt(sig->hashed,type);
delete_sig_subpkt(sig->unhashed,type);
break;
}
/* Any special magic that needs to be done for this type so the
packet doesn't need to be reparsed? */
switch(type)
{
case SIGSUBPKT_NOTATION:
sig->flags.notation=1;
break;
case SIGSUBPKT_POLICY:
sig->flags.policy_url=1;
break;
case SIGSUBPKT_PREF_KS:
sig->flags.pref_ks=1;
break;
case SIGSUBPKT_EXPORTABLE:
if(buffer[0])
sig->flags.exportable=1;
else
sig->flags.exportable=0;
break;
case SIGSUBPKT_REVOCABLE:
if(buffer[0])
sig->flags.revocable=1;
else
sig->flags.revocable=0;
break;
case SIGSUBPKT_TRUST:
sig->trust_depth=buffer[0];
sig->trust_value=buffer[1];
break;
case SIGSUBPKT_REGEXP:
sig->trust_regexp=buffer;
break;
/* This should never happen since we don't currently allow
creating such a subpacket, but just in case... */
case SIGSUBPKT_SIG_EXPIRE:
if(buffer_to_u32(buffer)+sig->timestamp<=make_timestamp())
sig->flags.expired=1;
else
sig->flags.expired=0;
break;
default:
break;
}
if( (buflen+1) >= 8384 )
nlen = 5; /* write 5 byte length header */
else if( (buflen+1) >= 192 )
nlen = 2; /* write 2 byte length header */
else
nlen = 1; /* just a 1 byte length header */
switch( type )
{
/* The issuer being unhashed is a historical oddity. It
should work equally as well hashed. Of course, if even an
unhashed issuer is tampered with, it makes it awfully hard
to verify the sig... */
case SIGSUBPKT_ISSUER:
case SIGSUBPKT_SIGNATURE:
hashed = 0;
break;
default:
hashed = 1;
break;
}
if( critical )
type |= SIGSUBPKT_FLAG_CRITICAL;
oldarea = hashed? sig->hashed : sig->unhashed;
/* Calculate new size of the area and allocate */
n0 = oldarea? oldarea->len : 0;
n = n0 + nlen + 1 + buflen; /* length, type, buffer */
if (oldarea && n <= oldarea->size) { /* fits into the unused space */
newarea = oldarea;
/*log_debug ("updating area for type %d\n", type );*/
}
else if (oldarea) {
newarea = xrealloc (oldarea, sizeof (*newarea) + n - 1);
newarea->size = n;
/*log_debug ("reallocating area for type %d\n", type );*/
}
else {
newarea = xmalloc (sizeof (*newarea) + n - 1);
newarea->size = n;
/*log_debug ("allocating area for type %d\n", type );*/
}
newarea->len = n;
p = newarea->data + n0;
if (nlen == 5) {
*p++ = 255;
*p++ = (buflen+1) >> 24;
*p++ = (buflen+1) >> 16;
*p++ = (buflen+1) >> 8;
*p++ = (buflen+1);
*p++ = type;
memcpy (p, buffer, buflen);
}
else if (nlen == 2) {
*p++ = (buflen+1-192) / 256 + 192;
*p++ = (buflen+1-192) % 256;
*p++ = type;
memcpy (p, buffer, buflen);
}
else {
*p++ = buflen+1;
*p++ = type;
memcpy (p, buffer, buflen);
}
if (hashed)
sig->hashed = newarea;
else
sig->unhashed = newarea;
}
/****************
* Put all the required stuff from SIG into subpackets of sig.
* Hmmm, should we delete those subpackets which are in a wrong area?
*/
void
build_sig_subpkt_from_sig( PKT_signature *sig )
{
u32 u;
byte buf[8];
u = sig->keyid[0];
buf[0] = (u >> 24) & 0xff;
buf[1] = (u >> 16) & 0xff;
buf[2] = (u >> 8) & 0xff;
buf[3] = u & 0xff;
u = sig->keyid[1];
buf[4] = (u >> 24) & 0xff;
buf[5] = (u >> 16) & 0xff;
buf[6] = (u >> 8) & 0xff;
buf[7] = u & 0xff;
build_sig_subpkt( sig, SIGSUBPKT_ISSUER, buf, 8 );
u = sig->timestamp;
buf[0] = (u >> 24) & 0xff;
buf[1] = (u >> 16) & 0xff;
buf[2] = (u >> 8) & 0xff;
buf[3] = u & 0xff;
build_sig_subpkt( sig, SIGSUBPKT_SIG_CREATED, buf, 4 );
if(sig->expiredate)
{
if(sig->expiredate>sig->timestamp)
u=sig->expiredate-sig->timestamp;
else
u=1; /* A 1-second expiration time is the shortest one
OpenPGP has */
buf[0] = (u >> 24) & 0xff;
buf[1] = (u >> 16) & 0xff;
buf[2] = (u >> 8) & 0xff;
buf[3] = u & 0xff;
/* Mark this CRITICAL, so if any implementation doesn't
understand sigs that can expire, it'll just disregard this
sig altogether. */
build_sig_subpkt( sig, SIGSUBPKT_SIG_EXPIRE | SIGSUBPKT_FLAG_CRITICAL,
buf, 4 );
}
}
void
build_attribute_subpkt(PKT_user_id *uid,byte type,
const void *buf,u32 buflen,
const void *header,u32 headerlen)
{
byte *attrib;
int idx;
if(1+headerlen+buflen>8383)
idx=5;
else if(1+headerlen+buflen>191)
idx=2;
else
idx=1;
/* realloc uid->attrib_data to the right size */
uid->attrib_data=xrealloc(uid->attrib_data,
uid->attrib_len+idx+1+headerlen+buflen);
attrib=&uid->attrib_data[uid->attrib_len];
if(idx==5)
{
attrib[0]=255;
attrib[1]=(1+headerlen+buflen) >> 24;
attrib[2]=(1+headerlen+buflen) >> 16;
attrib[3]=(1+headerlen+buflen) >> 8;
attrib[4]=1+headerlen+buflen;
}
else if(idx==2)
{
attrib[0]=(1+headerlen+buflen-192) / 256 + 192;
attrib[1]=(1+headerlen+buflen-192) % 256;
}
else
attrib[0]=1+headerlen+buflen; /* Good luck finding a JPEG this small! */
attrib[idx++]=type;
/* Tack on our data at the end */
if(headerlen>0)
memcpy(&attrib[idx],header,headerlen);
memcpy(&attrib[idx+headerlen],buf,buflen);
uid->attrib_len+=idx+headerlen+buflen;
}
struct notation *
string_to_notation(const char *string,int is_utf8)
{
const char *s;
int saw_at=0;
struct notation *notation;
notation=xmalloc_clear(sizeof(*notation));
if(*string=='-')
{
notation->flags.ignore=1;
string++;
}
if(*string=='!')
{
notation->flags.critical=1;
string++;
}
/* If and when the IETF assigns some official name tags, we'll have
to add them here. */
for( s=string ; *s != '='; s++ )
{
if( *s=='@')
saw_at++;
/* -notationname is legal without an = sign */
if(!*s && notation->flags.ignore)
break;
if( !*s || !isascii (*s) || (!isgraph(*s) && !isspace(*s)) )
{
log_error(_("a notation name must have only printable characters"
" or spaces, and end with an '='\n") );
goto fail;
}
}
notation->name=xmalloc((s-string)+1);
strncpy(notation->name,string,s-string);
notation->name[s-string]='\0';
if(!saw_at && !opt.expert)
{
log_error(_("a user notation name must contain the '@' character\n"));
goto fail;
}
if (saw_at > 1)
{
log_error(_("a notation name must not contain more than"
" one '@' character\n"));
goto fail;
}
if(*s)
{
const char *i=s+1;
int highbit=0;
/* we only support printable text - therefore we enforce the use
of only printable characters (an empty value is valid) */
for(s++; *s ; s++ )
{
if ( !isascii (*s) )
highbit=1;
else if (iscntrl(*s))
{
log_error(_("a notation value must not use any"
" control characters\n"));
goto fail;
}
}
if(!highbit || is_utf8)
notation->value=xstrdup(i);
else
notation->value=native_to_utf8(i);
}
return notation;
fail:
free_notation(notation);
return NULL;
}
struct notation *
sig_to_notation(PKT_signature *sig)
{
const byte *p;
size_t len;
int seq=0,crit;
struct notation *list=NULL;
while((p=enum_sig_subpkt(sig->hashed,SIGSUBPKT_NOTATION,&len,&seq,&crit)))
{
int n1,n2;
struct notation *n=NULL;
if(len<8)
{
log_info(_("WARNING: invalid notation data found\n"));
continue;
}
n1=(p[4]<<8)|p[5];
n2=(p[6]<<8)|p[7];
if(8+n1+n2!=len)
{
log_info(_("WARNING: invalid notation data found\n"));
continue;
}
n=xmalloc_clear(sizeof(*n));
n->name=xmalloc(n1+1);
memcpy(n->name,&p[8],n1);
n->name[n1]='\0';
if(p[0]&0x80)
{
n->value=xmalloc(n2+1);
memcpy(n->value,&p[8+n1],n2);
n->value[n2]='\0';
}
else
{
n->bdat=xmalloc(n2);
n->blen=n2;
memcpy(n->bdat,&p[8+n1],n2);
n->value=xmalloc(2+strlen(_("not human readable"))+2+1);
strcpy(n->value,"[ ");
strcat(n->value,_("not human readable"));
strcat(n->value," ]");
}
n->flags.critical=crit;
n->next=list;
list=n;
}
return list;
}
void
free_notation(struct notation *notation)
{
while(notation)
{
struct notation *n=notation;
xfree(n->name);
xfree(n->value);
xfree(n->altvalue);
xfree(n->bdat);
notation=n->next;
xfree(n);
}
}
static int
do_signature( IOBUF out, int ctb, PKT_signature *sig )
{
int rc = 0;
int n, i;
IOBUF a = iobuf_temp();
if ( !sig->version )
iobuf_put( a, 3 );
else
iobuf_put( a, sig->version );
if ( sig->version < 4 )
iobuf_put (a, 5 ); /* Constant */
iobuf_put (a, sig->sig_class );
if ( sig->version < 4 )
{
write_32(a, sig->timestamp );
write_32(a, sig->keyid[0] );
write_32(a, sig->keyid[1] );
}
iobuf_put(a, sig->pubkey_algo );
iobuf_put(a, sig->digest_algo );
if ( sig->version >= 4 )
{
size_t nn;
/* Timestamp and keyid must have been packed into the subpackets
prior to the call of this function, because these subpackets
are hashed. */
nn = sig->hashed? sig->hashed->len : 0;
write_16(a, nn);
if (nn)
iobuf_write( a, sig->hashed->data, nn );
nn = sig->unhashed? sig->unhashed->len : 0;
write_16(a, nn);
if (nn)
iobuf_write( a, sig->unhashed->data, nn );
}
iobuf_put(a, sig->digest_start[0] );
iobuf_put(a, sig->digest_start[1] );
n = pubkey_get_nsig( sig->pubkey_algo );
if ( !n )
write_fake_data( a, sig->data[0] );
for (i=0; i < n && !rc ; i++ )
rc = mpi_write(a, sig->data[i] );
if (!rc)
{
if ( is_RSA(sig->pubkey_algo) && sig->version < 4 )
write_sign_packet_header(out, ctb, iobuf_get_temp_length(a) );
else
write_header(out, ctb, iobuf_get_temp_length(a) );
rc = iobuf_write_temp( out, a );
}
iobuf_close(a);
return rc;
}
static int
do_onepass_sig( IOBUF out, int ctb, PKT_onepass_sig *ops )
{
int rc = 0;
IOBUF a = iobuf_temp();
write_version( a, ctb );
iobuf_put(a, ops->sig_class );
iobuf_put(a, ops->digest_algo );
iobuf_put(a, ops->pubkey_algo );
write_32(a, ops->keyid[0] );
write_32(a, ops->keyid[1] );
iobuf_put(a, ops->last );
write_header(out, ctb, iobuf_get_temp_length(a) );
rc = iobuf_write_temp( out, a );
iobuf_close(a);
return rc;
}
static int
write_16(IOBUF out, u16 a)
{
iobuf_put(out, a>>8);
if( iobuf_put(out,a) )
return -1;
return 0;
}
static int
write_32(IOBUF out, u32 a)
{
iobuf_put(out, a>> 24);
iobuf_put(out, a>> 16);
iobuf_put(out, a>> 8);
return iobuf_put(out, a);
}
/****************
* calculate the length of a header
*/
static int
calc_header_length( u32 len, int new_ctb )
{
if( !len )
return 1; /* only the ctb */
if( new_ctb ) {
if( len < 192 )
return 2;
if( len < 8384 )
return 3;
else
return 6;
}
if( len < 256 )
return 2;
if( len < 65536 )
return 3;
return 5;
}
/****************
* Write the CTB and the packet length
*/
static int
write_header( IOBUF out, int ctb, u32 len )
{
return write_header2( out, ctb, len, 0 );
}
static int
write_sign_packet_header (IOBUF out, int ctb, u32 len)
{
(void)ctb;
/* Work around a bug in the pgp read function for signature packets,
which are not correctly coded and silently assume at some point 2
byte length headers.*/
iobuf_put (out, 0x89 );
iobuf_put (out, len >> 8 );
return iobuf_put (out, len) == -1 ? -1:0;
}
/****************
* If HDRLEN is > 0, try to build a header of this length. We need
* this so that we can hash packets without reading them again. If
* len is 0, write a partial or indeterminate length header, unless
* hdrlen is specified in which case write an actual zero length
* (using the specified hdrlen).
*/
static int
write_header2( IOBUF out, int ctb, u32 len, int hdrlen )
{
if( ctb & 0x40 )
return write_new_header( out, ctb, len, hdrlen );
if( hdrlen )
{
if( hdrlen == 2 && len < 256 )
;
else if( hdrlen == 3 && len < 65536 )
ctb |= 1;
else
ctb |= 2;
}
else
{
if( !len )
ctb |= 3;
else if( len < 256 )
;
else if( len < 65536 )
ctb |= 1;
else
ctb |= 2;
}
if( iobuf_put(out, ctb ) )
return -1;
if( len || hdrlen )
{
if( ctb & 2 )
{
if(iobuf_put(out, len >> 24 ))
return -1;
if(iobuf_put(out, len >> 16 ))
return -1;
}
if( ctb & 3 )
if(iobuf_put(out, len >> 8 ))
return -1;
if( iobuf_put(out, len ) )
return -1;
}
return 0;
}
static int
write_new_header( IOBUF out, int ctb, u32 len, int hdrlen )
{
if( hdrlen )
log_bug("can't cope with hdrlen yet\n");
if( iobuf_put(out, ctb ) )
return -1;
if( !len ) {
iobuf_set_partial_block_mode(out, 512 );
}
else {
if( len < 192 ) {
if( iobuf_put(out, len ) )
return -1;
}
else if( len < 8384 ) {
len -= 192;
if( iobuf_put( out, (len / 256) + 192) )
return -1;
if( iobuf_put( out, (len % 256) ) )
return -1;
}
else {
if( iobuf_put( out, 0xff ) )
return -1;
if( iobuf_put( out, (len >> 24)&0xff ) )
return -1;
if( iobuf_put( out, (len >> 16)&0xff ) )
return -1;
if( iobuf_put( out, (len >> 8)&0xff ) )
return -1;
if( iobuf_put( out, len & 0xff ) )
return -1;
}
}
return 0;
}
static int
write_version (IOBUF out, int ctb)
{
(void)ctb;
if (iobuf_put (out, 3))
return -1;
return 0;
}
diff --git a/g10/call-agent.c b/g10/call-agent.c
index 9528e1427..25f9a537e 100644
--- a/g10/call-agent.c
+++ b/g10/call-agent.c
@@ -1,2044 +1,2047 @@
/* call-agent.c - Divert GPG operations to the agent.
* Copyright (C) 2001, 2002, 2003, 2006, 2007, 2008, 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
* 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
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#ifdef HAVE_LOCALE_H
#include
#endif
#include "gpg.h"
#include
#include "util.h"
#include "membuf.h"
#include "options.h"
#include "i18n.h"
#include "asshelp.h"
#include "sysutils.h"
#include "call-agent.h"
#include "status.h"
#ifndef DBG_ASSUAN
# define DBG_ASSUAN 1
#endif
static assuan_context_t agent_ctx = NULL;
static int did_early_card_test;
struct cipher_parm_s
{
ctrl_t ctrl;
assuan_context_t ctx;
unsigned char *ciphertext;
size_t ciphertextlen;
};
struct writecert_parm_s
{
assuan_context_t ctx;
const unsigned char *certdata;
size_t certdatalen;
};
struct writekey_parm_s
{
assuan_context_t ctx;
const unsigned char *keydata;
size_t keydatalen;
};
struct genkey_parm_s
{
ctrl_t ctrl;
assuan_context_t ctx;
const char *keyparms;
};
struct import_key_parm_s
{
ctrl_t ctrl;
assuan_context_t ctx;
const void *key;
size_t keylen;
};
struct cache_nonce_parm_s
{
char **cache_nonce_addr;
char **passwd_nonce_addr;
};
static gpg_error_t learn_status_cb (void *opaque, const char *line);
/* If RC is not 0, write an appropriate status message. */
static void
status_sc_op_failure (int rc)
{
switch (gpg_err_code (rc))
{
case 0:
break;
case GPG_ERR_CANCELED:
case GPG_ERR_FULLY_CANCELED:
write_status_text (STATUS_SC_OP_FAILURE, "1");
break;
case GPG_ERR_BAD_PIN:
write_status_text (STATUS_SC_OP_FAILURE, "2");
break;
default:
write_status (STATUS_SC_OP_FAILURE);
break;
}
}
/* Try to connect to the agent via socket or fork it off and work by
pipes. Handle the server's initial greeting */
static int
start_agent (ctrl_t ctrl, int for_card)
{
int rc;
(void)ctrl; /* Not yet used. */
/* Fixme: We need a context for each thread or serialize the access
to the agent. */
if (agent_ctx)
rc = 0;
else
{
rc = start_new_gpg_agent (&agent_ctx,
GPG_ERR_SOURCE_DEFAULT,
opt.homedir,
opt.agent_program,
opt.lc_ctype, opt.lc_messages,
opt.session_env,
opt.verbose, DBG_ASSUAN,
NULL, NULL);
if (!rc)
{
/* Tell the agent that we support Pinentry notifications.
No error checking so that it will work also with older
agents. */
assuan_transact (agent_ctx, "OPTION allow-pinentry-notify",
NULL, NULL, NULL, NULL, NULL, NULL);
/* Tell the agent about what version we are aware. This is
here used to indirectly enable GPG_ERR_FULLY_CANCELED. */
assuan_transact (agent_ctx, "OPTION agent-awareness=2.1.0",
NULL, NULL, NULL, NULL, NULL, NULL);
}
}
if (!rc && for_card && !did_early_card_test)
{
/* Request the serial number of the card for an early test. */
struct agent_card_info_s info;
memset (&info, 0, sizeof info);
rc = assuan_transact (agent_ctx, "SCD SERIALNO openpgp",
NULL, NULL, NULL, NULL,
learn_status_cb, &info);
if (rc)
{
switch (gpg_err_code (rc))
{
case GPG_ERR_NOT_SUPPORTED:
case GPG_ERR_NO_SCDAEMON:
write_status_text (STATUS_CARDCTRL, "6");
break;
default:
write_status_text (STATUS_CARDCTRL, "4");
log_info ("selecting openpgp failed: %s\n", gpg_strerror (rc));
break;
}
}
if (!rc && is_status_enabled () && info.serialno)
{
char *buf;
buf = xasprintf ("3 %s", info.serialno);
write_status_text (STATUS_CARDCTRL, buf);
xfree (buf);
}
agent_release_card_info (&info);
if (!rc)
did_early_card_test = 1;
}
return rc;
}
/* Return a new malloced string by unescaping the string S. Escaping
is percent escaping and '+'/space mapping. A binary nul will
silently be replaced by a 0xFF. Function returns NULL to indicate
an out of memory status. */
static char *
unescape_status_string (const unsigned char *s)
{
return percent_plus_unescape (s, 0xff);
}
/* Take a 20 byte hexencoded string and put it into the the provided
20 byte buffer FPR in binary format. */
static int
unhexify_fpr (const char *hexstr, unsigned char *fpr)
{
const char *s;
int n;
for (s=hexstr, n=0; hexdigitp (s); s++, n++)
;
if (*s || (n != 40))
return 0; /* no fingerprint (invalid or wrong length). */
for (s=hexstr, n=0; *s; s += 2, n++)
fpr[n] = xtoi_2 (s);
return 1; /* okay */
}
/* Take the serial number from LINE and return it verbatim in a newly
allocated string. We make sure that only hex characters are
returned. */
static char *
store_serialno (const char *line)
{
const char *s;
char *p;
for (s=line; hexdigitp (s); s++)
;
p = xtrymalloc (s + 1 - line);
if (p)
{
memcpy (p, line, s-line);
p[s-line] = 0;
}
return p;
}
/* This is a dummy data line callback. */
static gpg_error_t
dummy_data_cb (void *opaque, const void *buffer, size_t length)
{
(void)opaque;
(void)buffer;
(void)length;
return 0;
}
/* A simple callback used to return the serialnumber of a card. */
static gpg_error_t
get_serialno_cb (void *opaque, const char *line)
{
char **serialno = opaque;
const char *keyword = line;
const char *s;
int keywordlen, n;
for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
;
while (spacep (line))
line++;
if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen))
{
if (*serialno)
return gpg_error (GPG_ERR_CONFLICT); /* Unexpected status line. */
for (n=0,s=line; hexdigitp (s); s++, n++)
;
if (!n || (n&1)|| !(spacep (s) || !*s) )
return gpg_error (GPG_ERR_ASS_PARAMETER);
*serialno = xtrymalloc (n+1);
if (!*serialno)
return out_of_core ();
memcpy (*serialno, line, n);
(*serialno)[n] = 0;
}
return 0;
}
/* This is the default inquiry callback. It mainly handles the
Pinentry notifications. */
static gpg_error_t
default_inq_cb (void *opaque, const char *line)
{
(void)opaque;
if (!strncmp (line, "PINENTRY_LAUNCHED", 17) && (line[17]==' '||!line[17]))
{
/* There is no working server mode yet thus we use
AllowSetForegroundWindow window right here. We might want to
do this anyway in case gpg is called on the console. */
gnupg_allow_set_foregound_window ((pid_t)strtoul (line+17, NULL, 10));
/* We do not pass errors to avoid breaking other code. */
}
else
log_debug ("ignoring gpg-agent inquiry `%s'\n", line);
return 0;
}
/* Release the card info structure INFO. */
void
agent_release_card_info (struct agent_card_info_s *info)
{
if (!info)
return;
xfree (info->serialno); info->serialno = NULL;
xfree (info->apptype); info->apptype = NULL;
xfree (info->disp_name); info->disp_name = NULL;
xfree (info->disp_lang); info->disp_lang = NULL;
xfree (info->pubkey_url); info->pubkey_url = NULL;
xfree (info->login_data); info->login_data = NULL;
info->cafpr1valid = info->cafpr2valid = info->cafpr3valid = 0;
info->fpr1valid = info->fpr2valid = info->fpr3valid = 0;
}
static gpg_error_t
learn_status_cb (void *opaque, const char *line)
{
struct agent_card_info_s *parm = opaque;
const char *keyword = line;
int keywordlen;
int i;
for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
;
while (spacep (line))
line++;
if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen))
{
xfree (parm->serialno);
parm->serialno = store_serialno (line);
parm->is_v2 = (strlen (parm->serialno) >= 16
&& xtoi_2 (parm->serialno+12) >= 2 );
}
else if (keywordlen == 7 && !memcmp (keyword, "APPTYPE", keywordlen))
{
xfree (parm->apptype);
parm->apptype = unescape_status_string (line);
}
else if (keywordlen == 9 && !memcmp (keyword, "DISP-NAME", keywordlen))
{
xfree (parm->disp_name);
parm->disp_name = unescape_status_string (line);
}
else if (keywordlen == 9 && !memcmp (keyword, "DISP-LANG", keywordlen))
{
xfree (parm->disp_lang);
parm->disp_lang = unescape_status_string (line);
}
else if (keywordlen == 8 && !memcmp (keyword, "DISP-SEX", keywordlen))
{
parm->disp_sex = *line == '1'? 1 : *line == '2' ? 2: 0;
}
else if (keywordlen == 10 && !memcmp (keyword, "PUBKEY-URL", keywordlen))
{
xfree (parm->pubkey_url);
parm->pubkey_url = unescape_status_string (line);
}
else if (keywordlen == 10 && !memcmp (keyword, "LOGIN-DATA", keywordlen))
{
xfree (parm->login_data);
parm->login_data = unescape_status_string (line);
}
else if (keywordlen == 11 && !memcmp (keyword, "SIG-COUNTER", keywordlen))
{
parm->sig_counter = strtoul (line, NULL, 0);
}
else if (keywordlen == 10 && !memcmp (keyword, "CHV-STATUS", keywordlen))
{
char *p, *buf;
buf = p = unescape_status_string (line);
if (buf)
{
while (spacep (p))
p++;
parm->chv1_cached = atoi (p);
while (*p && !spacep (p))
p++;
while (spacep (p))
p++;
for (i=0; *p && i < 3; i++)
{
parm->chvmaxlen[i] = atoi (p);
while (*p && !spacep (p))
p++;
while (spacep (p))
p++;
}
for (i=0; *p && i < 3; i++)
{
parm->chvretry[i] = atoi (p);
while (*p && !spacep (p))
p++;
while (spacep (p))
p++;
}
xfree (buf);
}
}
else if (keywordlen == 6 && !memcmp (keyword, "EXTCAP", keywordlen))
{
char *p, *p2, *buf;
int abool;
buf = p = unescape_status_string (line);
if (buf)
{
for (p = strtok (buf, " "); p; p = strtok (NULL, " "))
{
p2 = strchr (p, '=');
if (p2)
{
*p2++ = 0;
abool = (*p2 == '1');
if (!strcmp (p, "ki"))
parm->extcap.ki = abool;
else if (!strcmp (p, "aac"))
parm->extcap.aac = abool;
}
}
xfree (buf);
}
}
else if (keywordlen == 7 && !memcmp (keyword, "KEY-FPR", keywordlen))
{
int no = atoi (line);
while (*line && !spacep (line))
line++;
while (spacep (line))
line++;
if (no == 1)
parm->fpr1valid = unhexify_fpr (line, parm->fpr1);
else if (no == 2)
parm->fpr2valid = unhexify_fpr (line, parm->fpr2);
else if (no == 3)
parm->fpr3valid = unhexify_fpr (line, parm->fpr3);
}
else if (keywordlen == 8 && !memcmp (keyword, "KEY-TIME", keywordlen))
{
int no = atoi (line);
while (* line && !spacep (line))
line++;
while (spacep (line))
line++;
if (no == 1)
parm->fpr1time = strtoul (line, NULL, 10);
else if (no == 2)
parm->fpr2time = strtoul (line, NULL, 10);
else if (no == 3)
parm->fpr3time = strtoul (line, NULL, 10);
}
else if (keywordlen == 6 && !memcmp (keyword, "CA-FPR", keywordlen))
{
int no = atoi (line);
while (*line && !spacep (line))
line++;
while (spacep (line))
line++;
if (no == 1)
parm->cafpr1valid = unhexify_fpr (line, parm->cafpr1);
else if (no == 2)
parm->cafpr2valid = unhexify_fpr (line, parm->cafpr2);
else if (no == 3)
parm->cafpr3valid = unhexify_fpr (line, parm->cafpr3);
}
else if (keywordlen == 8 && !memcmp (keyword, "KEY-ATTR", keywordlen))
{
int keyno, algo, nbits;
sscanf (line, "%d %d %d", &keyno, &algo, &nbits);
keyno--;
if (keyno >= 0 && keyno < DIM (parm->key_attr))
{
parm->key_attr[keyno].algo = algo;
parm->key_attr[keyno].nbits = nbits;
}
}
return 0;
}
/* Call the agent to learn about a smartcard */
int
agent_learn (struct agent_card_info_s *info)
{
int rc;
rc = start_agent (NULL, 1);
if (rc)
return rc;
/* Send the serialno command to initialize the connection. We don't
care about the data returned. If the card has already been
initialized, this is a very fast command. The main reason we
need to do this here is to handle a card removed case so that an
"l" command in --card-edit can be used to show ta newly inserted
card. We request the openpgp card because that is what we
expect. */
rc = assuan_transact (agent_ctx, "SCD SERIALNO openpgp",
NULL, NULL, NULL, NULL, NULL, NULL);
if (rc)
return rc;
memset (info, 0, sizeof *info);
rc = assuan_transact (agent_ctx, "SCD LEARN --force",
dummy_data_cb, NULL, default_inq_cb, NULL,
learn_status_cb, info);
/* Also try to get the key attributes. */
if (!rc)
agent_scd_getattr ("KEY-ATTR", info);
return rc;
}
/* Call the agent to retrieve a data object. This function returns
the data in the same structure as used by the learn command. It is
allowed to update such a structure using this commmand. */
int
agent_scd_getattr (const char *name, struct agent_card_info_s *info)
{
int rc;
char line[ASSUAN_LINELENGTH];
if (!*name)
return gpg_error (GPG_ERR_INV_VALUE);
/* We assume that NAME does not need escaping. */
if (12 + strlen (name) > DIM(line)-1)
return gpg_error (GPG_ERR_TOO_LARGE);
stpcpy (stpcpy (line, "SCD GETATTR "), name);
rc = start_agent (NULL, 1);
if (rc)
return rc;
rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, NULL,
learn_status_cb, info);
return rc;
}
/* Send an setattr command to the SCdaemon. SERIALNO is not actually
used here but required by gpg 1.4's implementation of this code in
cardglue.c. */
int
agent_scd_setattr (const char *name,
const unsigned char *value, size_t valuelen,
const char *serialno)
{
int rc;
char line[ASSUAN_LINELENGTH];
char *p;
(void)serialno;
if (!*name || !valuelen)
return gpg_error (GPG_ERR_INV_VALUE);
/* We assume that NAME does not need escaping. */
if (12 + strlen (name) > DIM(line)-1)
return gpg_error (GPG_ERR_TOO_LARGE);
p = stpcpy (stpcpy (line, "SCD SETATTR "), name);
*p++ = ' ';
for (; valuelen; value++, valuelen--)
{
if (p >= line + DIM(line)-5 )
return gpg_error (GPG_ERR_TOO_LARGE);
if (*value < ' ' || *value == '+' || *value == '%')
{
sprintf (p, "%%%02X", *value);
p += 3;
}
else if (*value == ' ')
*p++ = '+';
else
*p++ = *value;
}
*p = 0;
rc = start_agent (NULL, 1);
if (!rc)
{
rc = assuan_transact (agent_ctx, line, NULL, NULL,
default_inq_cb, NULL, NULL, NULL);
}
status_sc_op_failure (rc);
return rc;
}
/* Handle a CERTDATA inquiry. Note, we only send the data,
assuan_transact takes care of flushing and writing the END
command. */
static gpg_error_t
inq_writecert_parms (void *opaque, const char *line)
{
int rc;
struct writecert_parm_s *parm = opaque;
if (!strncmp (line, "CERTDATA", 8) && (line[8]==' '||!line[8]))
{
rc = assuan_send_data (parm->ctx, parm->certdata, parm->certdatalen);
}
else
rc = default_inq_cb (opaque, line);
return rc;
}
/* Send a WRITECERT command to the SCdaemon. */
int
agent_scd_writecert (const char *certidstr,
const unsigned char *certdata, size_t certdatalen)
{
int rc;
char line[ASSUAN_LINELENGTH];
struct writecert_parm_s parms;
rc = start_agent (NULL, 1);
if (rc)
return rc;
memset (&parms, 0, sizeof parms);
snprintf (line, DIM(line)-1, "SCD WRITECERT %s", certidstr);
line[DIM(line)-1] = 0;
parms.ctx = agent_ctx;
parms.certdata = certdata;
parms.certdatalen = certdatalen;
rc = assuan_transact (agent_ctx, line, NULL, NULL,
inq_writecert_parms, &parms, NULL, NULL);
return rc;
}
/* Handle a KEYDATA inquiry. Note, we only send the data,
assuan_transact takes care of flushing and writing the end */
static gpg_error_t
inq_writekey_parms (void *opaque, const char *line)
{
int rc;
struct writekey_parm_s *parm = opaque;
if (!strncmp (line, "KEYDATA", 7) && (line[7]==' '||!line[7]))
{
rc = assuan_send_data (parm->ctx, parm->keydata, parm->keydatalen);
}
else
rc = default_inq_cb (opaque, line);
return rc;
}
/* Send a WRITEKEY command to the SCdaemon. */
int
agent_scd_writekey (int keyno, const char *serialno,
const unsigned char *keydata, size_t keydatalen)
{
int rc;
char line[ASSUAN_LINELENGTH];
struct writekey_parm_s parms;
(void)serialno;
rc = start_agent (NULL, 1);
if (rc)
return rc;
memset (&parms, 0, sizeof parms);
snprintf (line, DIM(line)-1, "SCD WRITEKEY --force OPENPGP.%d", keyno);
line[DIM(line)-1] = 0;
parms.ctx = agent_ctx;
parms.keydata = keydata;
parms.keydatalen = keydatalen;
rc = assuan_transact (agent_ctx, line, NULL, NULL,
inq_writekey_parms, &parms, NULL, NULL);
status_sc_op_failure (rc);
return rc;
}
/* Status callback for the SCD GENKEY command. */
static gpg_error_t
scd_genkey_cb (void *opaque, const char *line)
{
struct agent_card_genkey_s *parm = opaque;
const char *keyword = line;
int keywordlen;
gpg_error_t rc;
for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
;
while (spacep (line))
line++;
if (keywordlen == 7 && !memcmp (keyword, "KEY-FPR", keywordlen))
{
parm->fprvalid = unhexify_fpr (line, parm->fpr);
}
else if (keywordlen == 8 && !memcmp (keyword, "KEY-DATA", keywordlen))
{
gcry_mpi_t a;
const char *name = line;
while (*line && !spacep (line))
line++;
while (spacep (line))
line++;
rc = gcry_mpi_scan (&a, GCRYMPI_FMT_HEX, line, 0, NULL);
if (rc)
log_error ("error parsing received key data: %s\n", gpg_strerror (rc));
else if (*name == 'n' && spacep (name+1))
parm->n = a;
else if (*name == 'e' && spacep (name+1))
parm->e = a;
else
{
log_info ("unknown parameter name in received key data\n");
gcry_mpi_release (a);
}
}
else if (keywordlen == 14 && !memcmp (keyword,"KEY-CREATED-AT", keywordlen))
{
parm->created_at = (u32)strtoul (line, NULL, 10);
}
else if (keywordlen == 8 && !memcmp (keyword, "PROGRESS", keywordlen))
{
write_status_text (STATUS_PROGRESS, line);
}
return 0;
}
/* Send a GENKEY command to the SCdaemon. SERIALNO is not used in
this implementation. If CREATEDATE is not 0, it will be passed to
SCDAEMON so that the key is created with this timestamp. INFO will
receive information about the generated key. */
int
agent_scd_genkey (struct agent_card_genkey_s *info, int keyno, int force,
const char *serialno, u32 createtime)
{
int rc;
char line[ASSUAN_LINELENGTH];
gnupg_isotime_t tbuf;
(void)serialno;
rc = start_agent (NULL, 1);
if (rc)
return rc;
if (createtime)
epoch2isotime (tbuf, createtime);
else
*tbuf = 0;
snprintf (line, DIM(line)-1, "SCD GENKEY %s%s %s %d",
*tbuf? "--timestamp=":"", tbuf,
force? "--force":"",
keyno);
line[DIM(line)-1] = 0;
memset (info, 0, sizeof *info);
rc = assuan_transact (agent_ctx, line,
NULL, NULL, default_inq_cb, NULL,
scd_genkey_cb, info);
status_sc_op_failure (rc);
return rc;
}
/* Issue an SCD SERIALNO openpgp command and if SERIALNO is not NULL
ask the user to insert the requested card. */
gpg_error_t
select_openpgp (const char *serialno)
{
gpg_error_t err;
/* Send the serialno command to initialize the connection. Without
a given S/N we don't care about the data returned. If the card
has already been initialized, this is a very fast command. We
request the openpgp card because that is what we expect.
Note that an opt.limit_card_insert_tries of 1 means: No tries at
all whereas 0 means do not limit the number of tries. Due to the
sue of a pinentry prompt with a cancel option we use it here in a
boolean sense. */
if (!serialno || opt.limit_card_insert_tries == 1)
err = assuan_transact (agent_ctx, "SCD SERIALNO openpgp",
NULL, NULL, NULL, NULL, NULL, NULL);
else
{
char *this_sn = NULL;
char *desc;
int ask;
char *want_sn;
char *p;
want_sn = xtrystrdup (serialno);
if (!want_sn)
return gpg_error_from_syserror ();
p = strchr (want_sn, '/');
if (p)
*p = 0;
do
{
ask = 0;
err = assuan_transact (agent_ctx, "SCD SERIALNO openpgp",
NULL, NULL, NULL, NULL,
get_serialno_cb, &this_sn);
if (gpg_err_code (err) == GPG_ERR_CARD_NOT_PRESENT)
ask = 1;
else if (gpg_err_code (err) == GPG_ERR_NOT_SUPPORTED)
ask = 2;
else if (err)
;
else if (this_sn)
{
if (strcmp (want_sn, this_sn))
ask = 2;
}
xfree (this_sn);
this_sn = NULL;
if (ask)
{
char *formatted = NULL;
char *ocodeset = i18n_switchto_utf8 ();
if (!strncmp (want_sn, "D27600012401", 12)
&& strlen (want_sn) == 32 )
formatted = xtryasprintf ("(%.4s) %.8s",
want_sn + 16, want_sn + 20);
err = 0;
desc = xtryasprintf
("%s:\n\n"
" \"%s\"",
ask == 1
? _("Please insert the card with serial number")
: _("Please remove the current card and "
"insert the one with serial number"),
formatted? formatted : want_sn);
if (!desc)
err = gpg_error_from_syserror ();
xfree (formatted);
i18n_switchback (ocodeset);
if (!err)
err = gpg_agent_get_confirmation (desc);
xfree (desc);
}
}
while (ask && !err);
xfree (want_sn);
}
return err;
}
static gpg_error_t
membuf_data_cb (void *opaque, const void *buffer, size_t length)
{
membuf_t *data = opaque;
if (buffer)
put_membuf (data, buffer, length);
return 0;
}
/* Helper returning a command option to describe the used hash
algorithm. See scd/command.c:cmd_pksign. */
static const char *
hash_algo_option (int algo)
{
switch (algo)
{
case GCRY_MD_RMD160: return "--hash=rmd160";
case GCRY_MD_SHA1 : return "--hash=sha1";
case GCRY_MD_SHA224: return "--hash=sha224";
case GCRY_MD_SHA256: return "--hash=sha256";
case GCRY_MD_SHA384: return "--hash=sha384";
case GCRY_MD_SHA512: return "--hash=sha512";
case GCRY_MD_MD5 : return "--hash=md5";
default: return "";
}
}
/* Send a sign command to the scdaemon via gpg-agent's pass thru
mechanism. */
int
agent_scd_pksign (const char *serialno, int hashalgo,
const unsigned char *indata, size_t indatalen,
unsigned char **r_buf, size_t *r_buflen)
{
int rc;
char line[ASSUAN_LINELENGTH];
membuf_t data;
size_t len;
/* Note, hashalgo is not yet used but hardwired to SHA1 in SCdaemon. */
*r_buf = NULL;
*r_buflen = 0;
rc = start_agent (NULL, 1);
if (gpg_err_code (rc) == GPG_ERR_CARD_NOT_PRESENT
|| gpg_err_code (rc) == GPG_ERR_NOT_SUPPORTED)
rc = 0; /* We check later. */
if (rc)
return rc;
if (indatalen*2 + 50 > DIM(line))
return gpg_error (GPG_ERR_GENERAL);
rc = select_openpgp (serialno);
if (rc)
return rc;
strcpy (line, "SCD SETDATA ");
bin2hex (indata, indatalen, line + strlen (line));
rc = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL);
if (rc)
return rc;
init_membuf (&data, 1024);
/* if (!hashalgo) /\* Temporary test hack. *\/ */
/* snprintf (line, DIM(line)-1, "SCD PKAUTH %s", serialno); */
/* else */
snprintf (line, DIM(line)-1, "SCD PKSIGN %s %s",
hash_algo_option (hashalgo), serialno);
line[DIM(line)-1] = 0;
rc = assuan_transact (agent_ctx, line, membuf_data_cb, &data,
default_inq_cb, NULL, NULL, NULL);
if (rc)
{
xfree (get_membuf (&data, &len));
}
else
*r_buf = get_membuf (&data, r_buflen);
status_sc_op_failure (rc);
return rc;
}
/* Decrypt INDATA of length INDATALEN using the card identified by
SERIALNO. Return the plaintext in a nwly allocated buffer stored
at the address of R_BUF.
Note, we currently support only RSA or more exactly algorithms
taking one input data element. */
int
agent_scd_pkdecrypt (const char *serialno,
const unsigned char *indata, size_t indatalen,
unsigned char **r_buf, size_t *r_buflen)
{
int rc;
char line[ASSUAN_LINELENGTH];
membuf_t data;
size_t len;
*r_buf = NULL;
rc = start_agent (NULL, 1);
if (gpg_err_code (rc) == GPG_ERR_CARD_NOT_PRESENT
|| gpg_err_code (rc) == GPG_ERR_NOT_SUPPORTED)
rc = 0; /* We check later. */
if (rc)
return rc;
/* FIXME: use secure memory where appropriate */
if (indatalen*2 + 50 > DIM(line))
return gpg_error (GPG_ERR_GENERAL);
rc = select_openpgp (serialno);
if (rc)
return rc;
strcpy (line, "SCD SETDATA ");
bin2hex (indata, indatalen, line + strlen (line));
rc = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL);
if (rc)
return rc;
init_membuf (&data, 1024);
snprintf (line, DIM(line)-1, "SCD PKDECRYPT %s", serialno);
line[DIM(line)-1] = 0;
rc = assuan_transact (agent_ctx, line,
membuf_data_cb, &data,
default_inq_cb, NULL, NULL, NULL);
if (rc)
{
xfree (get_membuf (&data, &len));
}
else
{
*r_buf = get_membuf (&data, r_buflen);
if (!*r_buf)
rc = gpg_error (GPG_ERR_ENOMEM);
}
status_sc_op_failure (rc);
return rc;
}
/* Send a READCERT command to the SCdaemon. */
int
agent_scd_readcert (const char *certidstr,
void **r_buf, size_t *r_buflen)
{
int rc;
char line[ASSUAN_LINELENGTH];
membuf_t data;
size_t len;
*r_buf = NULL;
rc = start_agent (NULL, 1);
if (rc)
return rc;
init_membuf (&data, 2048);
snprintf (line, DIM(line)-1, "SCD READCERT %s", certidstr);
line[DIM(line)-1] = 0;
rc = assuan_transact (agent_ctx, line,
membuf_data_cb, &data,
default_inq_cb, NULL, NULL, NULL);
if (rc)
{
xfree (get_membuf (&data, &len));
return rc;
}
*r_buf = get_membuf (&data, r_buflen);
if (!*r_buf)
return gpg_error (GPG_ERR_ENOMEM);
return 0;
}
/* Change the PIN of an OpenPGP card or reset the retry counter.
CHVNO 1: Change the PIN
2: For v1 cards: Same as 1.
For v2 cards: Reset the PIN using the Reset Code.
3: Change the admin PIN
101: Set a new PIN and reset the retry counter
102: For v1 cars: Same as 101.
For v2 cards: Set a new Reset Code.
SERIALNO is not used.
*/
int
agent_scd_change_pin (int chvno, const char *serialno)
{
int rc;
char line[ASSUAN_LINELENGTH];
const char *reset = "";
(void)serialno;
if (chvno >= 100)
reset = "--reset";
chvno %= 100;
rc = start_agent (NULL, 1);
if (rc)
return rc;
snprintf (line, DIM(line)-1, "SCD PASSWD %s %d", reset, chvno);
line[DIM(line)-1] = 0;
rc = assuan_transact (agent_ctx, line, NULL, NULL,
default_inq_cb, NULL, NULL, NULL);
status_sc_op_failure (rc);
return rc;
}
/* Perform a CHECKPIN operation. SERIALNO should be the serial
number of the card - optionally followed by the fingerprint;
however the fingerprint is ignored here. */
int
agent_scd_checkpin (const char *serialno)
{
int rc;
char line[ASSUAN_LINELENGTH];
rc = start_agent (NULL, 1);
if (rc)
return rc;
snprintf (line, DIM(line)-1, "SCD CHECKPIN %s", serialno);
line[DIM(line)-1] = 0;
rc = assuan_transact (agent_ctx, line,
NULL, NULL,
default_inq_cb, NULL, NULL, NULL);
status_sc_op_failure (rc);
return rc;
}
/* Dummy function, only used by the gpg 1.4 implementation. */
void
agent_clear_pin_cache (const char *sn)
{
(void)sn;
}
/* Note: All strings shall be UTF-8. On success the caller needs to
free the string stored at R_PASSPHRASE. On error NULL will be
stored at R_PASSPHRASE and an appropriate fpf error code
returned. */
gpg_error_t
agent_get_passphrase (const char *cache_id,
const char *err_msg,
const char *prompt,
const char *desc_msg,
int repeat,
int check,
char **r_passphrase)
{
int rc;
char line[ASSUAN_LINELENGTH];
char *arg1 = NULL;
char *arg2 = NULL;
char *arg3 = NULL;
char *arg4 = NULL;
membuf_t data;
*r_passphrase = NULL;
rc = start_agent (NULL, 0);
if (rc)
return rc;
/* Check that the gpg-agent understands the repeat option. */
if (assuan_transact (agent_ctx,
"GETINFO cmd_has_option GET_PASSPHRASE repeat",
NULL, NULL, NULL, NULL, NULL, NULL))
return gpg_error (GPG_ERR_NOT_SUPPORTED);
if (cache_id && *cache_id)
if (!(arg1 = percent_plus_escape (cache_id)))
goto no_mem;
if (err_msg && *err_msg)
if (!(arg2 = percent_plus_escape (err_msg)))
goto no_mem;
if (prompt && *prompt)
if (!(arg3 = percent_plus_escape (prompt)))
goto no_mem;
if (desc_msg && *desc_msg)
if (!(arg4 = percent_plus_escape (desc_msg)))
goto no_mem;
snprintf (line, DIM(line)-1,
"GET_PASSPHRASE --data --repeat=%d%s -- %s %s %s %s",
repeat,
check? " --check --qualitybar":"",
arg1? arg1:"X",
arg2? arg2:"X",
arg3? arg3:"X",
arg4? arg4:"X");
line[DIM(line)-1] = 0;
xfree (arg1);
xfree (arg2);
xfree (arg3);
xfree (arg4);
init_membuf_secure (&data, 64);
rc = assuan_transact (agent_ctx, line,
membuf_data_cb, &data,
default_inq_cb, NULL, NULL, NULL);
if (rc)
xfree (get_membuf (&data, NULL));
else
{
put_membuf (&data, "", 1);
*r_passphrase = get_membuf (&data, NULL);
if (!*r_passphrase)
rc = gpg_error_from_syserror ();
}
return rc;
no_mem:
rc = gpg_error_from_syserror ();
xfree (arg1);
xfree (arg2);
xfree (arg3);
xfree (arg4);
return rc;
}
gpg_error_t
agent_clear_passphrase (const char *cache_id)
{
int rc;
char line[ASSUAN_LINELENGTH];
if (!cache_id || !*cache_id)
return 0;
rc = start_agent (NULL, 0);
if (rc)
return rc;
snprintf (line, DIM(line)-1, "CLEAR_PASSPHRASE %s", cache_id);
line[DIM(line)-1] = 0;
return assuan_transact (agent_ctx, line, NULL, NULL,
default_inq_cb, NULL, NULL, NULL);
}
/* Ask the agent to pop up a confirmation dialog with the text DESC
and an okay and cancel button. */
gpg_error_t
gpg_agent_get_confirmation (const char *desc)
{
int rc;
char *tmp;
char line[ASSUAN_LINELENGTH];
rc = start_agent (NULL, 0);
if (rc)
return rc;
tmp = percent_plus_escape (desc);
if (!tmp)
return gpg_error_from_syserror ();
snprintf (line, DIM(line)-1, "GET_CONFIRMATION %s", tmp);
line[DIM(line)-1] = 0;
xfree (tmp);
rc = assuan_transact (agent_ctx, line, NULL, NULL,
default_inq_cb, NULL, NULL, NULL);
return rc;
}
/* Return the S2K iteration count as computed by gpg-agent. */
gpg_error_t
agent_get_s2k_count (unsigned long *r_count)
{
gpg_error_t err;
membuf_t data;
char *buf;
*r_count = 0;
err = start_agent (NULL, 0);
if (err)
return err;
init_membuf (&data, 32);
err = assuan_transact (agent_ctx, "GETINFO s2k_count",
membuf_data_cb, &data,
NULL, NULL, NULL, NULL);
if (err)
xfree (get_membuf (&data, NULL));
else
{
put_membuf (&data, "", 1);
buf = get_membuf (&data, NULL);
if (!buf)
err = gpg_error_from_syserror ();
else
{
*r_count = strtoul (buf, NULL, 10);
xfree (buf);
}
}
return err;
}
/* Ask the agent whether a secret key for the given public key is
available. Returns 0 if available. */
gpg_error_t
agent_probe_secret_key (ctrl_t ctrl, PKT_public_key *pk)
{
gpg_error_t err;
char line[ASSUAN_LINELENGTH];
char *hexgrip;
err = start_agent (ctrl, 0);
if (err)
return err;
err = hexkeygrip_from_pk (pk, &hexgrip);
if (err)
return err;
snprintf (line, sizeof line, "HAVEKEY %s", hexgrip);
xfree (hexgrip);
err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL);
return err;
}
/* Ask the agent whether a secret key is availabale for any of the
keys (primary or sub) in KEYBLOCK. Returns 0 if available. */
gpg_error_t
agent_probe_any_secret_key (ctrl_t ctrl, kbnode_t keyblock)
{
gpg_error_t err;
char line[ASSUAN_LINELENGTH];
char *p;
kbnode_t kbctx, node;
int nkeys;
unsigned char grip[20];
err = start_agent (ctrl, 0);
if (err)
return err;
err = gpg_error (GPG_ERR_NO_SECKEY); /* Just in case no key was
found in KEYBLOCK. */
p = stpcpy (line, "HAVEKEY");
for (kbctx=NULL, nkeys=0; (node = walk_kbnode (keyblock, &kbctx, 0)); )
if (node->pkt->pkttype == PKT_PUBLIC_KEY
|| node->pkt->pkttype == PKT_PUBLIC_SUBKEY
|| node->pkt->pkttype == PKT_SECRET_KEY
|| node->pkt->pkttype == PKT_SECRET_SUBKEY)
{
if (nkeys && ((p - line) + 41) > (ASSUAN_LINELENGTH - 2))
{
err = assuan_transact (agent_ctx, line,
NULL, NULL, NULL, NULL, NULL, NULL);
if (err != gpg_err_code (GPG_ERR_NO_SECKEY))
break; /* Seckey available or unexpected error - ready. */
p = stpcpy (line, "HAVEKEY");
nkeys = 0;
}
err = keygrip_from_pk (node->pkt->pkt.public_key, grip);
if (err)
return err;
*p++ = ' ';
bin2hex (grip, 20, p);
p += 40;
nkeys++;
}
if (!err && nkeys)
err = assuan_transact (agent_ctx, line,
NULL, NULL, NULL, NULL, NULL, NULL);
return err;
}
static gpg_error_t
keyinfo_status_cb (void *opaque, const char *line)
{
char **serialno = opaque;
const char *s, *s2;
if (!strncmp (line, "KEYINFO ", 8) && !*serialno)
{
s = strchr (line+8, ' ');
if (s && s[1] == 'T' && s[2] == ' ' && s[3])
{
s += 3;
s2 = strchr (s, ' ');
if ( s2 > s )
{
*serialno = xtrymalloc ((s2 - s)+1);
if (*serialno)
{
memcpy (*serialno, s, s2 - s);
(*serialno)[s2 - s] = 0;
}
}
}
}
return 0;
}
/* Return the serial number for a secret key. If the returned serial
number is NULL, the key is not stored on a smartcard. Caller needs
to free R_SERIALNO. */
gpg_error_t
agent_get_keyinfo (ctrl_t ctrl, const char *hexkeygrip, char **r_serialno)
{
gpg_error_t err;
char line[ASSUAN_LINELENGTH];
char *serialno = NULL;
*r_serialno = NULL;
err = start_agent (ctrl, 0);
if (err)
return err;
if (!hexkeygrip || strlen (hexkeygrip) != 40)
return gpg_error (GPG_ERR_INV_VALUE);
snprintf (line, DIM(line)-1, "KEYINFO %s", hexkeygrip);
line[DIM(line)-1] = 0;
err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL,
keyinfo_status_cb, &serialno);
if (!err && serialno)
{
/* Sanity check for bad characters. */
if (strpbrk (serialno, ":\n\r"))
err = GPG_ERR_INV_VALUE;
}
if (err)
xfree (serialno);
else
*r_serialno = serialno;
return err;
}
/* Status callback for agent_import_key, agent_export_key and
agent_genkey. */
static gpg_error_t
cache_nonce_status_cb (void *opaque, const char *line)
{
struct cache_nonce_parm_s *parm = opaque;
const char *keyword = line;
int keywordlen;
for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
;
while (spacep (line))
line++;
if (keywordlen == 11 && !memcmp (keyword, "CACHE_NONCE", keywordlen))
{
if (parm->cache_nonce_addr)
{
xfree (*parm->cache_nonce_addr);
*parm->cache_nonce_addr = xtrystrdup (line);
}
}
else if (keywordlen == 12 && !memcmp (keyword, "PASSWD_NONCE", keywordlen))
{
if (parm->passwd_nonce_addr)
{
xfree (*parm->passwd_nonce_addr);
*parm->passwd_nonce_addr = xtrystrdup (line);
}
}
return 0;
}
/* Handle a KEYPARMS inquiry. Note, we only send the data,
assuan_transact takes care of flushing and writing the end */
static gpg_error_t
inq_genkey_parms (void *opaque, const char *line)
{
struct genkey_parm_s *parm = opaque;
gpg_error_t err;
if (!strncmp (line, "KEYPARAM", 8) && (line[8]==' '||!line[8]))
{
err = assuan_send_data (parm->ctx,
parm->keyparms, strlen (parm->keyparms));
}
else
err = default_inq_cb (parm->ctrl, line);
return err;
}
/* Call the agent to generate a new key. KEYPARMS is the usual
S-expression giving the parameters of the key. gpg-agent passes it
gcry_pk_genkey. If NO_PROTECTION is true the agent is advised not
to protect the generated key. */
gpg_error_t
agent_genkey (ctrl_t ctrl, char **cache_nonce_addr,
const char *keyparms, int no_protection, gcry_sexp_t *r_pubkey)
{
gpg_error_t err;
struct genkey_parm_s gk_parm;
struct cache_nonce_parm_s cn_parm;
membuf_t data;
size_t len;
unsigned char *buf;
char line[ASSUAN_LINELENGTH];
*r_pubkey = NULL;
err = start_agent (ctrl, 0);
if (err)
return err;
err = assuan_transact (agent_ctx, "RESET",
NULL, NULL, NULL, NULL, NULL, NULL);
if (err)
return err;
init_membuf (&data, 1024);
gk_parm.ctrl = ctrl;
gk_parm.ctx = agent_ctx;
gk_parm.keyparms = keyparms;
snprintf (line, sizeof line, "GENKEY%s%s%s",
no_protection? " --no-protection":"",
cache_nonce_addr && *cache_nonce_addr? " ":"",
cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:"");
cn_parm.cache_nonce_addr = cache_nonce_addr;
cn_parm.passwd_nonce_addr = NULL;
err = assuan_transact (agent_ctx, line,
membuf_data_cb, &data,
inq_genkey_parms, &gk_parm,
cache_nonce_status_cb, &cn_parm);
if (err)
{
xfree (get_membuf (&data, &len));
return err;
}
buf = get_membuf (&data, &len);
if (!buf)
err = gpg_error_from_syserror ();
else
{
err = gcry_sexp_sscan (r_pubkey, NULL, buf, len);
xfree (buf);
}
return err;
}
/* FIXME: Call the agent to read the public key part for a given keygrip. If
FROMCARD is true, the key is directly read from the current
smartcard. In this case HEXKEYGRIP should be the keyID
(e.g. OPENPGP.3). */
/* int */
/* agent_readkey (ctrl_t ctrl, int fromcard, const char *hexkeygrip, */
/* ksba_sexp_t *r_pubkey) */
/* { */
/* int rc; */
/* membuf_t data; */
/* size_t len; */
/* unsigned char *buf; */
/* char line[ASSUAN_LINELENGTH]; */
/* *r_pubkey = NULL; */
/* rc = start_agent (ctrl); */
/* if (rc) */
/* return rc; */
/* rc = assuan_transact (agent_ctx, "RESET",NULL, NULL, NULL, NULL, NULL, NULL); */
/* if (rc) */
/* return rc; */
/* snprintf (line, DIM(line)-1, "%sREADKEY %s", */
/* fromcard? "SCD ":"", hexkeygrip); */
/* line[DIM(line)-1] = 0; */
/* init_membuf (&data, 1024); */
/* rc = assuan_transact (agent_ctx, line, */
/* membuf_data_cb, &data, */
/* default_inq_cb, ctrl, NULL, NULL); */
/* if (rc) */
/* { */
/* xfree (get_membuf (&data, &len)); */
/* return rc; */
/* } */
/* buf = get_membuf (&data, &len); */
/* if (!buf) */
/* return gpg_error (GPG_ERR_ENOMEM); */
/* if (!gcry_sexp_canon_len (buf, len, NULL, NULL)) */
/* { */
/* xfree (buf); */
/* return gpg_error (GPG_ERR_INV_SEXP); */
/* } */
/* *r_pubkey = buf; */
/* return 0; */
/* } */
/* Call the agent to do a sign operation using the key identified by
the hex string KEYGRIP. DESC is a description of the key to be
displayed if the agent needs to ask for the PIN. DIGEST and
DIGESTLEN is the hash value to sign and DIGESTALGO the algorithm id
used to compute the digest. If CACHE_NONCE is used the agent is
advised to first try a passphrase associated with that nonce. */
gpg_error_t
agent_pksign (ctrl_t ctrl, const char *cache_nonce,
const char *keygrip, const char *desc,
unsigned char *digest, size_t digestlen, int digestalgo,
gcry_sexp_t *r_sigval)
{
gpg_error_t err;
char line[ASSUAN_LINELENGTH];
membuf_t data;
*r_sigval = NULL;
err = start_agent (ctrl, 0);
if (err)
return err;
if (digestlen*2 + 50 > DIM(line))
return gpg_error (GPG_ERR_GENERAL);
err = assuan_transact (agent_ctx, "RESET",
NULL, NULL, NULL, NULL, NULL, NULL);
if (err)
return err;
snprintf (line, DIM(line)-1, "SIGKEY %s", keygrip);
line[DIM(line)-1] = 0;
err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL);
if (err)
return err;
if (desc)
{
snprintf (line, DIM(line)-1, "SETKEYDESC %s", desc);
line[DIM(line)-1] = 0;
err = assuan_transact (agent_ctx, line,
NULL, NULL, NULL, NULL, NULL, NULL);
if (err)
return err;
}
snprintf (line, sizeof line, "SETHASH %d ", digestalgo);
bin2hex (digest, digestlen, line + strlen (line));
err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL);
if (err)
return err;
init_membuf (&data, 1024);
snprintf (line, sizeof line, "PKSIGN%s%s",
cache_nonce? " -- ":"",
cache_nonce? cache_nonce:"");
err = assuan_transact (agent_ctx, line,
membuf_data_cb, &data, default_inq_cb, ctrl,
NULL, NULL);
if (err)
xfree (get_membuf (&data, NULL));
else
{
unsigned char *buf;
size_t len;
buf = get_membuf (&data, &len);
if (!buf)
err = gpg_error_from_syserror ();
else
{
err = gcry_sexp_sscan (r_sigval, NULL, buf, len);
xfree (buf);
}
}
return err;
}
/* Handle a CIPHERTEXT inquiry. Note, we only send the data,
assuan_transact takes care of flushing and writing the END. */
static gpg_error_t
inq_ciphertext_cb (void *opaque, const char *line)
{
struct cipher_parm_s *parm = opaque;
int rc;
if (!strncmp (line, "CIPHERTEXT", 10) && (line[10]==' '||!line[10]))
{
assuan_begin_confidential (parm->ctx);
rc = assuan_send_data (parm->ctx, parm->ciphertext, parm->ciphertextlen);
assuan_end_confidential (parm->ctx);
}
else
rc = default_inq_cb (parm->ctrl, line);
return rc;
}
/* Call the agent to do a decrypt operation using the key identified
by the hex string KEYGRIP and the input data S_CIPHERTEXT. On the
success the decoded value is stored verbatim at R_BUF and its
length at R_BUF; the callers needs to release it. */
gpg_error_t
agent_pkdecrypt (ctrl_t ctrl, const char *keygrip, const char *desc,
gcry_sexp_t s_ciphertext,
+ const byte sk_fp[MAX_FINGERPRINT_LEN],
unsigned char **r_buf, size_t *r_buflen)
{
gpg_error_t err;
char line[ASSUAN_LINELENGTH];
membuf_t data;
size_t n, len;
char *p, *buf, *endp;
+
+ /*TODO: use sk_fp */
if (!keygrip || strlen(keygrip) != 40 || !s_ciphertext || !r_buf || !r_buflen)
return gpg_error (GPG_ERR_INV_VALUE);
*r_buf = NULL;
err = start_agent (ctrl, 0);
if (err)
return err;
err = assuan_transact (agent_ctx, "RESET",
NULL, NULL, NULL, NULL, NULL, NULL);
if (err)
return err;
snprintf (line, sizeof line, "SETKEY %s", keygrip);
err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL);
if (err)
return err;
if (desc)
{
snprintf (line, DIM(line)-1, "SETKEYDESC %s", desc);
line[DIM(line)-1] = 0;
err = assuan_transact (agent_ctx, line,
NULL, NULL, NULL, NULL, NULL, NULL);
if (err)
return err;
}
init_membuf_secure (&data, 1024);
{
struct cipher_parm_s parm;
parm.ctrl = ctrl;
parm.ctx = agent_ctx;
err = make_canon_sexp (s_ciphertext, &parm.ciphertext, &parm.ciphertextlen);
if (err)
return err;
err = assuan_transact (agent_ctx, "PKDECRYPT",
membuf_data_cb, &data,
inq_ciphertext_cb, &parm, NULL, NULL);
xfree (parm.ciphertext);
}
if (err)
{
xfree (get_membuf (&data, &len));
return err;
}
put_membuf (&data, "", 1); /* Make sure it is 0 terminated. */
buf = get_membuf (&data, &len);
if (!buf)
return gpg_error_from_syserror ();
assert (len); /* (we forced Nul termination.) */
if (*buf != '(')
{
xfree (buf);
return gpg_error (GPG_ERR_INV_SEXP);
}
if (len < 13 || memcmp (buf, "(5:value", 8) ) /* "(5:valueN:D)\0" */
{
xfree (buf);
return gpg_error (GPG_ERR_INV_SEXP);
}
len -= 11; /* Count only the data of the second part. */
p = buf + 8; /* Skip leading parenthesis and the value tag. */
n = strtoul (p, &endp, 10);
if (!n || *endp != ':')
{
xfree (buf);
return gpg_error (GPG_ERR_INV_SEXP);
}
endp++;
if (endp-p+n > len)
{
xfree (buf);
return gpg_error (GPG_ERR_INV_SEXP); /* Oops: Inconsistent S-Exp. */
}
memmove (buf, endp, n);
*r_buflen = n;
*r_buf = buf;
return 0;
}
/* Retrieve a key encryption key from the agent. With FOREXPORT true
the key shall be used for export, with false for import. On success
the new key is stored at R_KEY and its length at R_KEKLEN. */
gpg_error_t
agent_keywrap_key (ctrl_t ctrl, int forexport, void **r_kek, size_t *r_keklen)
{
gpg_error_t err;
membuf_t data;
size_t len;
unsigned char *buf;
char line[ASSUAN_LINELENGTH];
*r_kek = NULL;
err = start_agent (ctrl, 0);
if (err)
return err;
snprintf (line, DIM(line)-1, "KEYWRAP_KEY %s",
forexport? "--export":"--import");
init_membuf_secure (&data, 64);
err = assuan_transact (agent_ctx, line,
membuf_data_cb, &data,
default_inq_cb, ctrl, NULL, NULL);
if (err)
{
xfree (get_membuf (&data, &len));
return err;
}
buf = get_membuf (&data, &len);
if (!buf)
return gpg_error_from_syserror ();
*r_kek = buf;
*r_keklen = len;
return 0;
}
/* Handle the inquiry for an IMPORT_KEY command. */
static gpg_error_t
inq_import_key_parms (void *opaque, const char *line)
{
struct import_key_parm_s *parm = opaque;
gpg_error_t err;
if (!strncmp (line, "KEYDATA", 7) && (line[7]==' '||!line[7]))
{
err = assuan_send_data (parm->ctx, parm->key, parm->keylen);
}
else
err = default_inq_cb (parm->ctrl, line);
return err;
}
/* Call the agent to import a key into the agent. */
gpg_error_t
agent_import_key (ctrl_t ctrl, const char *desc, char **cache_nonce_addr,
const void *key, size_t keylen)
{
gpg_error_t err;
struct import_key_parm_s parm;
struct cache_nonce_parm_s cn_parm;
char line[ASSUAN_LINELENGTH];
err = start_agent (ctrl, 0);
if (err)
return err;
if (desc)
{
snprintf (line, DIM(line)-1, "SETKEYDESC %s", desc);
line[DIM(line)-1] = 0;
err = assuan_transact (agent_ctx, line,
NULL, NULL, NULL, NULL, NULL, NULL);
if (err)
return err;
}
parm.ctrl = ctrl;
parm.ctx = agent_ctx;
parm.key = key;
parm.keylen = keylen;
snprintf (line, sizeof line, "IMPORT_KEY%s%s",
cache_nonce_addr && *cache_nonce_addr? " ":"",
cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:"");
cn_parm.cache_nonce_addr = cache_nonce_addr;
cn_parm.passwd_nonce_addr = NULL;
err = assuan_transact (agent_ctx, line,
NULL, NULL, inq_import_key_parms, &parm,
cache_nonce_status_cb, &cn_parm);
return err;
}
/* Receive a secret key from the agent. HEXKEYGRIP is the hexified
keygrip, DESC a prompt to be displayed with the agent's passphrase
question (needs to be plus+percent escaped). On success the key is
stored as a canonical S-expression at R_RESULT and R_RESULTLEN. */
gpg_error_t
agent_export_key (ctrl_t ctrl, const char *hexkeygrip, const char *desc,
char **cache_nonce_addr,
unsigned char **r_result, size_t *r_resultlen)
{
gpg_error_t err;
struct cache_nonce_parm_s cn_parm;
membuf_t data;
size_t len;
unsigned char *buf;
char line[ASSUAN_LINELENGTH];
*r_result = NULL;
err = start_agent (ctrl, 0);
if (err)
return err;
if (desc)
{
snprintf (line, DIM(line)-1, "SETKEYDESC %s", desc);
err = assuan_transact (agent_ctx, line,
NULL, NULL, NULL, NULL, NULL, NULL);
if (err)
return err;
}
snprintf (line, DIM(line)-1, "EXPORT_KEY --openpgp %s%s %s",
cache_nonce_addr && *cache_nonce_addr? "--cache-nonce=":"",
cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:"",
hexkeygrip);
init_membuf_secure (&data, 1024);
cn_parm.cache_nonce_addr = cache_nonce_addr;
cn_parm.passwd_nonce_addr = NULL;
err = assuan_transact (agent_ctx, line,
membuf_data_cb, &data,
default_inq_cb, ctrl,
cache_nonce_status_cb, &cn_parm);
if (err)
{
xfree (get_membuf (&data, &len));
return err;
}
buf = get_membuf (&data, &len);
if (!buf)
return gpg_error_from_syserror ();
*r_result = buf;
*r_resultlen = len;
return 0;
}
/* Ask the agent to change the passphrase of the key identified by
HEXKEYGRIP. If DESC is not NULL, display DESC instead of the
default description message. If CACHE_NONCE_ADDR is not NULL the
agent is advised to first try a passphrase associated with that
nonce. If PASSWD_NONCE_ADDR is not NULL the agent will try to use
the passphrase associated with that nonce. */
gpg_error_t
agent_passwd (ctrl_t ctrl, const char *hexkeygrip, const char *desc,
char **cache_nonce_addr, char **passwd_nonce_addr)
{
gpg_error_t err;
struct cache_nonce_parm_s cn_parm;
char line[ASSUAN_LINELENGTH];
err = start_agent (ctrl, 0);
if (err)
return err;
if (!hexkeygrip || strlen (hexkeygrip) != 40)
return gpg_error (GPG_ERR_INV_VALUE);
if (desc)
{
snprintf (line, DIM(line)-1, "SETKEYDESC %s", desc);
err = assuan_transact (agent_ctx, line,
NULL, NULL, NULL, NULL, NULL, NULL);
if (err)
return err;
}
snprintf (line, DIM(line)-1, "PASSWD %s%s %s%s %s",
cache_nonce_addr && *cache_nonce_addr? "--cache-nonce=":"",
cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:"",
passwd_nonce_addr && *passwd_nonce_addr? "--passwd-nonce=":"",
passwd_nonce_addr && *passwd_nonce_addr? *passwd_nonce_addr:"",
hexkeygrip);
cn_parm.cache_nonce_addr = cache_nonce_addr;
cn_parm.passwd_nonce_addr = passwd_nonce_addr;
err = assuan_transact (agent_ctx, line, NULL, NULL,
default_inq_cb, ctrl,
cache_nonce_status_cb, &cn_parm);
return err;
}
diff --git a/g10/call-agent.h b/g10/call-agent.h
index e09c30990..45e593bb8 100644
--- a/g10/call-agent.h
+++ b/g10/call-agent.h
@@ -1,192 +1,193 @@
/* call-agent.h - Divert operations to the agent
* Copyright (C) 2003 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
* 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
* along with this program; if not, see .
*/
#ifndef GNUPG_G10_CALL_AGENT_H
#define GNUPG_G10_CALL_AGENT_H
struct agent_card_info_s
{
int error; /* private. */
char *apptype; /* Malloced application type string. */
char *serialno; /* malloced hex string. */
char *disp_name; /* malloced. */
char *disp_lang; /* malloced. */
int disp_sex; /* 0 = unspecified, 1 = male, 2 = female */
char *pubkey_url; /* malloced. */
char *login_data; /* malloced. */
char *private_do[4]; /* malloced. */
char cafpr1valid;
char cafpr2valid;
char cafpr3valid;
char cafpr1[20];
char cafpr2[20];
char cafpr3[20];
char fpr1valid;
char fpr2valid;
char fpr3valid;
char fpr1[20];
char fpr2[20];
char fpr3[20];
u32 fpr1time;
u32 fpr2time;
u32 fpr3time;
unsigned long sig_counter;
int chv1_cached; /* True if a PIN is not required for each
signing. Note that the gpg-agent might cache
it anyway. */
int is_v2; /* True if this is a v2 card. */
int chvmaxlen[3]; /* Maximum allowed length of a CHV. */
int chvretry[3]; /* Allowed retries for the CHV; 0 = blocked. */
struct { /* Array with key attributes. */
int algo; /* Algorithm identifier. */
unsigned int nbits; /* Supported keysize. */
} key_attr[3];
struct {
unsigned int ki:1; /* Key import available. */
unsigned int aac:1; /* Algorithm attributes are changeable. */
} extcap;
};
struct agent_card_genkey_s {
char fprvalid;
char fpr[20];
u32 created_at;
gcry_mpi_t n;
gcry_mpi_t e;
};
/* Release the card info structure. */
void agent_release_card_info (struct agent_card_info_s *info);
/* Return card info. */
int agent_learn (struct agent_card_info_s *info);
/* Update INFO with the attribute NAME. */
int agent_scd_getattr (const char *name, struct agent_card_info_s *info);
/* Send a SETATTR command to the SCdaemon. */
int agent_scd_setattr (const char *name,
const unsigned char *value, size_t valuelen,
const char *serialno);
/* Send a WRITECERT command to the SCdaemon. */
int agent_scd_writecert (const char *certidstr,
const unsigned char *certdata, size_t certdatalen);
/* Send a WRITEKEY command to the SCdaemon. */
int agent_scd_writekey (int keyno, const char *serialno,
const unsigned char *keydata, size_t keydatalen);
/* Send a GENKEY command to the SCdaemon. */
int agent_scd_genkey (struct agent_card_genkey_s *info, int keyno, int force,
const char *serialno, u32 createtime);
/* Send a PKSIGN command to the SCdaemon. */
int agent_scd_pksign (const char *keyid, int hashalgo,
const unsigned char *indata, size_t indatalen,
unsigned char **r_buf, size_t *r_buflen);
/* Send a PKDECRYPT command to the SCdaemon. */
int agent_scd_pkdecrypt (const char *serialno,
const unsigned char *indata, size_t indatalen,
unsigned char **r_buf, size_t *r_buflen);
/* Send a READKEY command to the SCdaemon. */
int agent_scd_readcert (const char *certidstr,
void **r_buf, size_t *r_buflen);
/* Change the PIN of an OpenPGP card or reset the retry counter. */
int agent_scd_change_pin (int chvno, const char *serialno);
/* Send the CHECKPIN command to the SCdaemon. */
int agent_scd_checkpin (const char *serialno);
/* Dummy function, only implemented by gpg 1.4. */
void agent_clear_pin_cache (const char *sn);
/* Send the GET_PASSPHRASE command to the agent. */
gpg_error_t agent_get_passphrase (const char *cache_id,
const char *err_msg,
const char *prompt,
const char *desc_msg,
int repeat,
int check,
char **r_passphrase);
/* Send the CLEAR_PASSPHRASE command to the agent. */
gpg_error_t agent_clear_passphrase (const char *cache_id);
/* Present the prompt DESC and ask the user to confirm. */
gpg_error_t gpg_agent_get_confirmation (const char *desc);
/* Return the S2K iteration count as computed by gpg-agent. */
gpg_error_t agent_get_s2k_count (unsigned long *r_count);
/* Check whether a secret key for public key PK is available. Returns
0 if the secret key is available. */
gpg_error_t agent_probe_secret_key (ctrl_t ctrl, PKT_public_key *pk);
/* Ask the agent whether a secret key is availabale for any of the
keys (primary or sub) in KEYBLOCK. Returns 0 if available. */
gpg_error_t agent_probe_any_secret_key (ctrl_t ctrl, kbnode_t keyblock);
/* Return infos about the secret key with HEXKEYGRIP. */
gpg_error_t agent_get_keyinfo (ctrl_t ctrl, const char *hexkeygrip,
char **r_serialno);
/* Generate a new key. */
gpg_error_t agent_genkey (ctrl_t ctrl, char **cache_nonce_addr,
const char *keyparms, int no_protection,
gcry_sexp_t *r_pubkey);
/* Create a signature. */
gpg_error_t agent_pksign (ctrl_t ctrl, const char *cache_nonce,
const char *hexkeygrip, const char *desc,
unsigned char *digest, size_t digestlen,
int digestalgo,
gcry_sexp_t *r_sigval);
/* Decrypt a ciphertext. */
gpg_error_t agent_pkdecrypt (ctrl_t ctrl, const char *keygrip, const char *desc,
gcry_sexp_t s_ciphertext,
+ const byte sk_fp[MAX_FINGERPRINT_LEN],
unsigned char **r_buf, size_t *r_buflen);
/* Retrieve a key encryption key. */
gpg_error_t agent_keywrap_key (ctrl_t ctrl, int forexport,
void **r_kek, size_t *r_keklen);
/* Send a key to the agent. */
gpg_error_t agent_import_key (ctrl_t ctrl, const char *desc,
char **cache_nonce_addr,
const void *key, size_t keylen);
/* Receive a key from the agent. */
gpg_error_t agent_export_key (ctrl_t ctrl, const char *keygrip,
const char *desc, char **cache_nonce_addr,
unsigned char **r_result, size_t *r_resultlen);
/* Change the passphrase of a key. */
gpg_error_t agent_passwd (ctrl_t ctrl, const char *hexkeygrip, const char *desc,
char **cache_nonce_addr, char **passwd_nonce_addr);
#endif /*GNUPG_G10_CALL_AGENT_H*/
diff --git a/g10/ecdh.c b/g10/ecdh.c
new file mode 100644
index 000000000..6615b75a4
--- /dev/null
+++ b/g10/ecdh.c
@@ -0,0 +1,477 @@
+/* ecdh.c - ECDH public key operations used in public key glue code
+ * Copyright (C) 2000, 2003 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
+ * 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
+ * along with this program; if not, see .
+ */
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "gpg.h"
+#include "util.h"
+#include "pkglue.h"
+#include "main.h"
+#include "options.h"
+
+gcry_mpi_t
+pk_ecdh_default_params_to_mpi( int qbits ) {
+ gpg_error_t err;
+ gcry_mpi_t result;
+ /* Defaults are the strongest possible choices. Performance is not an issue here, only interoperability. */
+ byte kek_params[4] = {
+ 3 /*size of following field*/,
+ 1 /*fixed version for KDF+AESWRAP*/,
+ DIGEST_ALGO_SHA512 /* KEK MD */,
+ CIPHER_ALGO_AES256 /*KEK AESWRAP alg*/
+ };
+ int i;
+
+ static const struct {
+ int qbits;
+ int openpgp_hash_id;
+ int openpgp_cipher_id;
+ } kek_params_table[] = {
+ { 256, DIGEST_ALGO_SHA256, CIPHER_ALGO_AES },
+ { 384, DIGEST_ALGO_SHA384, CIPHER_ALGO_AES256 },
+ { 528, DIGEST_ALGO_SHA512, CIPHER_ALGO_AES256 } // 528 is 521 rounded to the 8 bit boundary
+ };
+
+ for( i=0; i= qbits ) {
+ kek_params[2] = kek_params_table[i].openpgp_hash_id;
+ kek_params[3] = kek_params_table[i].openpgp_cipher_id;
+ break;
+ }
+ }
+ if( DBG_CIPHER )
+ log_printhex ("ecdh kek params are", kek_params, sizeof(kek_params) );
+
+ err = gcry_mpi_scan (&result, GCRYMPI_FMT_USG, kek_params, sizeof(kek_params), NULL);
+ if (err)
+ log_fatal ("mpi_scan failed: %s\n", gpg_strerror (err));
+
+ return result;
+}
+
+/* returns allocated (binary) KEK parameters; the size is returned in sizeout.
+ * The caller must free returned value with xfree.
+ * Returns NULL on error
+ */
+byte *
+pk_ecdh_default_params( int qbits, size_t *sizeout ) {
+ gpg_error_t err;
+ gcry_mpi_t result;
+ /* Defaults are the strongest possible choices. Performance is not an issue here, only interoperability. */
+ byte kek_params[4] = {
+ 3 /*size of following field*/,
+ 1 /*fixed version for KDF+AESWRAP*/,
+ DIGEST_ALGO_SHA512 /* KEK MD */,
+ CIPHER_ALGO_AES256 /*KEK AESWRAP alg*/
+ };
+ int i;
+
+ static const struct {
+ int qbits;
+ int openpgp_hash_id;
+ int openpgp_cipher_id;
+ } kek_params_table[] = {
+ { 256, DIGEST_ALGO_SHA256, CIPHER_ALGO_AES },
+ { 384, DIGEST_ALGO_SHA384, CIPHER_ALGO_AES256 },
+ { 528, DIGEST_ALGO_SHA512, CIPHER_ALGO_AES256 } // 528 is 521 rounded to the 8 bit boundary
+ };
+
+ byte *p;
+
+ *sizeout = 0;
+
+ for( i=0; i= qbits ) {
+ kek_params[2] = kek_params_table[i].openpgp_hash_id;
+ kek_params[3] = kek_params_table[i].openpgp_cipher_id;
+ break;
+ }
+ }
+ if( DBG_CIPHER )
+ log_printhex ("ecdh kek params are", kek_params, sizeof(kek_params) );
+
+ p = xtrymalloc( sizeof(kek_params) );
+ if( p == NULL )
+ return NULL;
+ memcpy( p, kek_params, sizeof(kek_params) );
+ *sizeout = sizeof(kek_params);
+ return p;
+}
+
+/* Encrypts/decrypts 'data' with a key derived from shared_mpi ECC point using FIPS SP 800-56A compliant method, which is
+ * key derivation + key wrapping. The direction is determined by the first parameter (is_encrypt=1 --> this is encryption).
+ * The result is returned in out as a size+value MPI.
+ * TODO: memory leaks (x_secret).
+ */
+static int
+pk_ecdh_encrypt_with_shared_point ( int is_encrypt, gcry_mpi_t shared_mpi,
+ const byte pk_fp[MAX_FINGERPRINT_LEN], gcry_mpi_t data, gcry_mpi_t * pkey, gcry_mpi_t *out)
+{
+ byte *secret_x;
+ int secret_x_size;
+ byte kdf_params[256];
+ int kdf_params_size=0;
+ int nbits;
+ int kdf_hash_algo;
+ int kdf_encr_algo;
+ int rc;
+
+ *out = NULL;
+
+ nbits = pubkey_nbits( PUBKEY_ALGO_ECDH, pkey );
+
+ {
+ size_t nbytes;
+ /* extract x component of the shared point: this is the actual shared secret */
+ nbytes = (mpi_get_nbits (pkey[1] /* public point */)+7)/8;
+ secret_x = xmalloc_secure( nbytes );
+ rc = gcry_mpi_print (GCRYMPI_FMT_USG, secret_x, nbytes, &nbytes, shared_mpi);
+ if( rc ) {
+ xfree( secret_x );
+ log_error ("ec ephemeral export of shared point failed: %s\n", gpg_strerror (rc) );
+ return rc;
+ }
+ secret_x_size = (nbits+7)/8;
+ assert( nbytes > secret_x_size );
+ memmove( secret_x, secret_x+1, secret_x_size );
+ memset( secret_x+secret_x_size, 0, nbytes-secret_x_size );
+
+ if( DBG_CIPHER )
+ log_printhex ("ecdh shared secret X is:", secret_x, secret_x_size );
+ }
+
+ /*** We have now the shared secret bytes in secret_x ***/
+
+ /* At this point we are done with PK encryption and the rest of the function uses symmetric
+ * key encryption techniques to protect the input 'data'. The following two sections will
+ * simply replace current secret_x with a value derived from it. This will become a KEK.
+ */
+ {
+ IOBUF obuf = iobuf_temp();
+ rc = iobuf_write_size_body_mpi ( obuf, pkey[2] ); /* KEK params */
+
+ kdf_params_size = iobuf_temp_to_buffer( obuf, kdf_params, sizeof(kdf_params) );
+
+ if( DBG_CIPHER )
+ log_printhex ("ecdh KDF public key params are:", kdf_params, kdf_params_size );
+
+ if( kdf_params_size != 4 || kdf_params[0] != 3 || kdf_params[1] != 1 ) /* expect 4 bytes 03 01 hash_alg symm_alg */
+ return GPG_ERR_BAD_PUBKEY;
+
+ kdf_hash_algo = kdf_params[2];
+ kdf_encr_algo = kdf_params[3];
+
+ if( DBG_CIPHER )
+ log_debug ("ecdh KDF algorithms %s+%s with aeswrap\n", gcry_md_algo_name (kdf_hash_algo), openpgp_cipher_algo_name (kdf_encr_algo) );
+
+ if( kdf_hash_algo != GCRY_MD_SHA256 && kdf_hash_algo != GCRY_MD_SHA384 && kdf_hash_algo != GCRY_MD_SHA512 )
+ return GPG_ERR_BAD_PUBKEY;
+ if( kdf_encr_algo != GCRY_CIPHER_AES128 && kdf_encr_algo != GCRY_CIPHER_AES192 && kdf_encr_algo != GCRY_CIPHER_AES256 )
+ return GPG_ERR_BAD_PUBKEY;
+ }
+
+ /* build kdf_params */
+ {
+ IOBUF obuf;
+
+ obuf = iobuf_temp();
+ /* variable-length field 1, curve name OID */
+ rc = iobuf_write_size_body_mpi ( obuf, pkey[0] );
+ /* fixed-length field 2 */
+ iobuf_put (obuf, PUBKEY_ALGO_ECDH);
+ /* variable-length field 3, KDF params */
+ rc = (rc ? rc : iobuf_write_size_body_mpi ( obuf, pkey[2] ));
+ /* fixed-length field 4 */
+ iobuf_write (obuf, "Anonymous Sender ", 20);
+ /* fixed-length field 5, recipient fp */
+ iobuf_write (obuf, pk_fp, 20);
+
+ kdf_params_size = iobuf_temp_to_buffer( obuf, kdf_params, sizeof(kdf_params) );
+ iobuf_close( obuf );
+ if( rc ) {
+ return rc;
+ }
+ if( DBG_CIPHER )
+ log_printhex ("ecdh KDF message params are:", kdf_params, kdf_params_size );
+ }
+
+ /* Derive a KEK (key wrapping key) using kdf_params and secret_x. */
+ {
+ gcry_md_hd_t h;
+ int old_size;
+
+ rc = gcry_md_open (&h, kdf_hash_algo, 0);
+ if(rc)
+ log_bug ("gcry_md_open failed for algo %d: %s",
+ kdf_hash_algo, gpg_strerror (gcry_error(rc)));
+ gcry_md_write(h, "\x00\x00\x00\x01", 4); /* counter = 1 */
+ gcry_md_write(h, secret_x, secret_x_size); /* x of the point X */
+ gcry_md_write(h, kdf_params, kdf_params_size); /* KDF parameters */
+
+ gcry_md_final (h);
+
+ assert( gcry_md_get_algo_dlen (kdf_hash_algo) >= 32 );
+
+ memcpy (secret_x, gcry_md_read (h, kdf_hash_algo), gcry_md_get_algo_dlen (kdf_hash_algo));
+ gcry_md_close (h);
+
+ old_size = secret_x_size;
+ assert( old_size >= gcry_cipher_get_algo_keylen( kdf_encr_algo ) );
+ secret_x_size = gcry_cipher_get_algo_keylen( kdf_encr_algo );
+ assert( secret_x_size <= gcry_md_get_algo_dlen (kdf_hash_algo) );
+
+ memset( secret_x+secret_x_size, old_size-secret_x_size, 0 ); /* we could have allocated more, so clean the tail before returning */
+ if( DBG_CIPHER )
+ log_printhex ("ecdh KEK is:", secret_x, secret_x_size );
+ }
+
+ /* And, finally, aeswrap with key secret_x */
+ {
+ gcry_cipher_hd_t hd;
+ size_t nbytes;
+
+ byte *data_buf;
+ int data_buf_size;
+
+ gcry_mpi_t result;
+
+ rc = gcry_cipher_open (&hd, kdf_encr_algo, GCRY_CIPHER_MODE_AESWRAP, 0);
+ if (rc)
+ {
+ log_error( "ecdh failed to initialize AESWRAP: %s\n", gpg_strerror (rc));
+ return rc;
+ }
+
+ rc = gcry_cipher_setkey (hd, secret_x, secret_x_size);
+ xfree( secret_x );
+ if (rc)
+ {
+ gcry_cipher_close (hd);
+ log_error("ecdh failed in gcry_cipher_setkey: %s\n", gpg_strerror (rc));
+ return rc;
+ }
+
+ data_buf_size = (gcry_mpi_get_nbits(data)+7)/8;
+ assert( (data_buf_size & 7) == (is_encrypt ? 0 : 1) );
+
+ data_buf = xmalloc_secure( 1 + 2*data_buf_size + 8 );
+ if( !data_buf ) {
+ gcry_cipher_close (hd);
+ return GPG_ERR_ENOMEM;
+ }
+
+ if( is_encrypt ) {
+ byte *in = data_buf+1+data_buf_size+8;
+
+ /* write data MPI into the end of data_buf. data_buf is size aeswrap data */
+ rc = gcry_mpi_print (GCRYMPI_FMT_USG, in, data_buf_size, &nbytes, data/*in*/);
+ if( rc ) {
+ log_error("ecdh failed to export DEK: %s\n", gpg_strerror (rc));
+ gcry_cipher_close (hd);
+ xfree( data_buf );
+ return rc;
+ }
+
+ if( DBG_CIPHER )
+ log_printhex ("ecdh encrypting :", in, data_buf_size );
+
+ rc = gcry_cipher_encrypt (hd, data_buf+1, data_buf_size+8, in, data_buf_size);
+ memset( in, 0, data_buf_size);
+ gcry_cipher_close (hd);
+ if(rc)
+ {
+ log_error("ecdh failed in gcry_cipher_encrypt: %s\n", gpg_strerror (rc));
+ xfree( data_buf );
+ return rc;
+ }
+ data_buf[0] = data_buf_size+8;
+
+ if( DBG_CIPHER )
+ log_printhex ("ecdh encrypted to:", data_buf+1, data_buf[0] );
+
+ rc = gcry_mpi_scan ( &result, GCRYMPI_FMT_USG, data_buf, 1+data_buf[0], NULL); /* (byte)size + aeswrap of DEK */
+ xfree( data_buf );
+ if(rc)
+ {
+ log_error("ecdh failed to create an MPI: %s\n", gpg_strerror (rc));
+ return rc;
+ }
+
+ *out = result;
+ }
+ else {
+ byte *in;
+
+ rc = gcry_mpi_print (GCRYMPI_FMT_USG, data_buf, data_buf_size, &nbytes, data/*in*/);
+ if( nbytes != data_buf_size || data_buf[0] != data_buf_size-1 ) {
+ log_error("ecdh inconsistent size\n");
+ xfree( data_buf );
+ return GPG_ERR_BAD_MPI;
+ }
+ in = data_buf+data_buf_size;
+ data_buf_size = data_buf[0];
+
+ if( DBG_CIPHER )
+ log_printhex ("ecdh decrypting :", data_buf+1, data_buf_size );
+
+ rc = gcry_cipher_decrypt (hd, in, data_buf_size, data_buf+1, data_buf_size );
+ gcry_cipher_close (hd);
+ if(rc)
+ {
+ log_error("ecdh failed in gcry_cipher_decrypt: %s\n", gpg_strerror (rc));
+ xfree( data_buf );
+ return rc;
+ }
+
+ data_buf_size-=8;
+
+ if( DBG_CIPHER )
+ log_printhex ("ecdh decrypted to :", in, data_buf_size );
+
+ /* padding is removed later */
+ //if( in[data_buf_size-1] > 8 ) {
+ // log_error("ecdh failed at decryption: invalid padding. %02x > 8\n", in[data_buf_size-1] );
+ // return GPG_ERR_BAD_KEY;
+ //}
+
+ rc = gcry_mpi_scan ( &result, GCRYMPI_FMT_USG, in, data_buf_size, NULL);
+ xfree( data_buf );
+ if(rc)
+ {
+ log_error("ecdh failed to create a plain text MPI: %s\n", gpg_strerror (rc));
+ return rc;
+ }
+
+ *out = result;
+ }
+ }
+
+ return rc;
+}
+
+/* Perform ECDH encryption, which involves ECDH key generation.
+ */
+int
+pk_ecdh_encrypt (gcry_mpi_t * resarr, const byte pk_fp[MAX_FINGERPRINT_LEN], gcry_mpi_t data, gcry_mpi_t * pkey)
+{
+ gcry_sexp_t s_ciph, s_data, s_pkey;
+
+ PKT_public_key *pk_eph;
+ int nbits;
+ int rc;
+
+ nbits = pubkey_nbits( PUBKEY_ALGO_ECDH, pkey );
+
+ /*** Generate an ephemeral key ***/
+
+ rc = pk_ecc_keypair_gen( &pk_eph, PUBKEY_ALGO_ECDH, KEYGEN_FLAG_TRANSIENT_KEY | KEYGEN_FLAG_NO_PROTECTION /*this is ephemeral*/, "", nbits );
+ if( rc )
+ return rc;
+ if( DBG_CIPHER ) {
+ unsigned char *buffer;
+ if (gcry_mpi_aprint (GCRYMPI_FMT_HEX, &buffer, NULL, pk_eph->pkey[1]))
+ BUG ();
+ log_debug("ephemeral key MPI #0: %s\n", buffer);
+ gcry_free( buffer );
+ }
+ free_public_key (pk_eph);
+
+ /*** Done with ephemeral key generation.
+ * Now use ephemeral secret to get the shared secret. ***/
+
+ rc = gcry_sexp_build (&s_pkey, NULL,
+ "(public-key(ecdh(c%m)(q%m)(p%m)))", pkey[0], pkey[1], pkey[2]);
+ if (rc)
+ BUG ();
+
+ /* put the data into a simple list */
+ if (gcry_sexp_build (&s_data, NULL, "%m", pk_eph->pkey[3])) /* ephemeral scalar goes as data */
+ BUG ();
+
+ /* pass it to libgcrypt */
+ rc = gcry_pk_encrypt (&s_ciph, s_data, s_pkey);
+ gcry_sexp_release (s_data);
+ gcry_sexp_release (s_pkey);
+ if (rc)
+ return rc;
+
+ /* finally, perform encryption */
+
+ {
+ gcry_mpi_t shared = mpi_from_sexp (s_ciph, "a"); /* ... and get the shared point */
+ gcry_sexp_release (s_ciph);
+ resarr[0] = pk_eph->pkey[1]; /* ephemeral public key */
+
+ if( DBG_CIPHER ) {
+ unsigned char *buffer;
+ if (gcry_mpi_aprint (GCRYMPI_FMT_HEX, &buffer, NULL, resarr[0]))
+ BUG ();
+ log_debug("ephemeral key MPI: %s\n", buffer);
+ gcry_free( buffer );
+ }
+
+ rc = pk_ecdh_encrypt_with_shared_point ( 1 /*=encrypton*/, shared, pk_fp, data, pkey, resarr+1 );
+ mpi_release( shared );
+ }
+
+ return rc;
+}
+
+/* Perform ECDH decryption.
+ */
+int
+pk_ecdh_decrypt (gcry_mpi_t * result, const byte sk_fp[MAX_FINGERPRINT_LEN], gcry_mpi_t *data, gcry_mpi_t * skey) {
+ gcry_sexp_t s_skey, s_data, s_ciph;
+ int rc;
+
+ if (!data[0] || !data[1])
+ return gpg_error (GPG_ERR_BAD_MPI);
+
+ rc = gcry_sexp_build (&s_skey, NULL,
+ "(public-key(ecdh(c%m)(q%m)(p%m)))",
+ skey[0]/*curve*/, data[0]/*ephemeral key*/, skey[2]/*KDF params*/);
+ if (rc)
+ BUG ();
+
+ /* put the data into a simple list */
+ if (gcry_sexp_build (&s_data, NULL, "%m", skey[3])) /* static private key (scalar) goes as data */
+ BUG ();
+
+ rc = gcry_pk_encrypt (&s_ciph, s_data, s_skey); /* encrypting ephemeral key with our private scalar yields the shared point */
+ gcry_sexp_release (s_skey);
+ gcry_sexp_release (s_data);
+ if (rc)
+ return rc;
+
+ {
+ gcry_mpi_t shared = mpi_from_sexp (s_ciph, "a"); /* get the shared point */
+ gcry_sexp_release (s_ciph);
+ rc = pk_ecdh_encrypt_with_shared_point ( 0 /*=decryption*/, shared, sk_fp, data[1]/*encr data as an MPI*/, skey, result );
+ mpi_release( shared );
+ }
+
+ return rc;
+}
+
+
diff --git a/g10/encrypt.c b/g10/encrypt.c
index 55f9b27fb..3c16309d0 100644
--- a/g10/encrypt.c
+++ b/g10/encrypt.c
@@ -1,985 +1,990 @@
/* encrypt.c - Main encryption driver
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
* 2006, 2009 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
* 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
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include
#include "gpg.h"
#include "options.h"
#include "packet.h"
#include "status.h"
#include "iobuf.h"
#include "keydb.h"
#include "util.h"
#include "main.h"
#include "filter.h"
#include "trustdb.h"
#include "i18n.h"
#include "status.h"
#include "pkglue.h"
static int encrypt_simple( const char *filename, int mode, int use_seskey );
static int write_pubkey_enc_from_list( PK_LIST pk_list, DEK *dek, iobuf_t out );
/****************
* Encrypt FILENAME with only the symmetric cipher. Take input from
* stdin if FILENAME is NULL.
*/
int
encrypt_symmetric (const char *filename)
{
return encrypt_simple( filename, 1, 0 );
}
/****************
* Encrypt FILENAME as a literal data packet only. Take input from
* stdin if FILENAME is NULL.
*/
int
encrypt_store (const char *filename)
{
return encrypt_simple( filename, 0, 0 );
}
static void
encrypt_seskey (DEK *dek, DEK **seskey, byte *enckey)
{
gcry_cipher_hd_t hd;
byte buf[33];
assert ( dek->keylen <= 32 );
if (!*seskey)
{
*seskey=xmalloc_clear(sizeof(DEK));
(*seskey)->keylen=dek->keylen;
(*seskey)->algo=dek->algo;
make_session_key(*seskey);
/*log_hexdump( "thekey", c->key, c->keylen );*/
}
/* The encrypted session key is prefixed with a one-octet algorithm id. */
buf[0] = (*seskey)->algo;
memcpy( buf + 1, (*seskey)->key, (*seskey)->keylen );
/* We only pass already checked values to the following fucntion,
thus we consider any failure as fatal. */
if (openpgp_cipher_open (&hd, dek->algo, GCRY_CIPHER_MODE_CFB, 1))
BUG ();
if (gcry_cipher_setkey (hd, dek->key, dek->keylen))
BUG ();
gcry_cipher_setiv (hd, NULL, 0);
gcry_cipher_encrypt (hd, buf, (*seskey)->keylen + 1, NULL, 0);
gcry_cipher_close (hd);
memcpy( enckey, buf, (*seskey)->keylen + 1 );
wipememory( buf, sizeof buf ); /* burn key */
}
/* We try very hard to use a MDC */
static int
use_mdc(PK_LIST pk_list,int algo)
{
/* RFC-1991 and 2440 don't have MDC */
if(RFC1991 || RFC2440)
return 0;
/* --force-mdc overrides --disable-mdc */
if(opt.force_mdc)
return 1;
if(opt.disable_mdc)
return 0;
/* Do the keys really support MDC? */
if(select_mdc_from_pklist(pk_list))
return 1;
/* The keys don't support MDC, so now we do a bit of a hack - if any
of the AESes or TWOFISH are in the prefs, we assume that the user
can handle a MDC. This is valid for PGP 7, which can handle MDCs
though it will not generate them. 2440bis allows this, by the
way. */
if(select_algo_from_prefs(pk_list,PREFTYPE_SYM,
CIPHER_ALGO_AES,NULL)==CIPHER_ALGO_AES)
return 1;
if(select_algo_from_prefs(pk_list,PREFTYPE_SYM,
CIPHER_ALGO_AES192,NULL)==CIPHER_ALGO_AES192)
return 1;
if(select_algo_from_prefs(pk_list,PREFTYPE_SYM,
CIPHER_ALGO_AES256,NULL)==CIPHER_ALGO_AES256)
return 1;
if(select_algo_from_prefs(pk_list,PREFTYPE_SYM,
CIPHER_ALGO_TWOFISH,NULL)==CIPHER_ALGO_TWOFISH)
return 1;
/* Last try. Use MDC for the modern ciphers. */
if (openpgp_cipher_get_algo_blklen (algo) != 8)
return 1;
if (opt.verbose)
warn_missing_mdc_from_pklist (pk_list);
return 0; /* No MDC */
}
/* We don't want to use use_seskey yet because older gnupg versions
can't handle it, and there isn't really any point unless we're
making a message that can be decrypted by a public key or
passphrase. */
static int
encrypt_simple (const char *filename, int mode, int use_seskey)
{
iobuf_t inp, out;
PACKET pkt;
PKT_plaintext *pt = NULL;
STRING2KEY *s2k = NULL;
byte enckey[33];
int rc = 0;
int seskeylen = 0;
u32 filesize;
cipher_filter_context_t cfx;
armor_filter_context_t *afx = NULL;
compress_filter_context_t zfx;
text_filter_context_t tfx;
progress_filter_context_t *pfx;
int do_compress = !RFC1991 && default_compress_algo();
pfx = new_progress_context ();
memset( &cfx, 0, sizeof cfx);
memset( &zfx, 0, sizeof zfx);
memset( &tfx, 0, sizeof tfx);
init_packet(&pkt);
/* Prepare iobufs. */
inp = iobuf_open(filename);
if (inp)
iobuf_ioctl (inp, IOBUF_IOCTL_NO_CACHE, 1, NULL);
if (inp && is_secured_file (iobuf_get_fd (inp)))
{
iobuf_close (inp);
inp = NULL;
gpg_err_set_errno (EPERM);
}
if (!inp)
{
rc = gpg_error_from_syserror ();
log_error(_("can't open `%s': %s\n"), filename? filename: "[stdin]",
strerror(errno) );
release_progress_context (pfx);
return rc;
}
handle_progress (pfx, inp, filename);
if (opt.textmode)
iobuf_push_filter( inp, text_filter, &tfx );
/* Due the the fact that we use don't use an IV to encrypt the
session key we can't use the new mode with RFC1991 because it has
no S2K salt. RFC1991 always uses simple S2K. */
if ( RFC1991 && use_seskey )
use_seskey = 0;
cfx.dek = NULL;
if ( mode )
{
int canceled;
s2k = xmalloc_clear( sizeof *s2k );
s2k->mode = RFC1991? 0:opt.s2k_mode;
s2k->hash_algo = S2K_DIGEST_ALGO;
cfx.dek = passphrase_to_dek (NULL, 0,
default_cipher_algo(), s2k, 4,
NULL, &canceled);
if ( !cfx.dek || !cfx.dek->keylen )
{
rc = gpg_error (canceled? GPG_ERR_CANCELED:GPG_ERR_INV_PASSPHRASE);
xfree (cfx.dek);
xfree (s2k);
iobuf_close (inp);
log_error (_("error creating passphrase: %s\n"), gpg_strerror (rc));
release_progress_context (pfx);
return rc;
}
if (use_seskey && s2k->mode != 1 && s2k->mode != 3)
{
use_seskey = 0;
log_info (_("can't use a symmetric ESK packet "
"due to the S2K mode\n"));
}
if ( use_seskey )
{
DEK *dek = NULL;
seskeylen = openpgp_cipher_get_algo_keylen (default_cipher_algo ());
encrypt_seskey( cfx.dek, &dek, enckey );
xfree( cfx.dek ); cfx.dek = dek;
}
if (opt.verbose)
log_info(_("using cipher %s\n"),
openpgp_cipher_algo_name (cfx.dek->algo));
cfx.dek->use_mdc=use_mdc(NULL,cfx.dek->algo);
}
if (do_compress && cfx.dek && cfx.dek->use_mdc
&& is_file_compressed(filename, &rc))
{
if (opt.verbose)
log_info(_("`%s' already compressed\n"), filename);
do_compress = 0;
}
if ( rc || (rc = open_outfile (-1, filename, opt.armor? 1:0, &out )))
{
iobuf_cancel (inp);
xfree (cfx.dek);
xfree (s2k);
release_progress_context (pfx);
return rc;
}
if ( opt.armor )
{
afx = new_armor_context ();
push_armor_filter (afx, out);
}
if ( s2k && !RFC1991 )
{
PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc + seskeylen + 1 );
enc->version = 4;
enc->cipher_algo = cfx.dek->algo;
enc->s2k = *s2k;
if ( use_seskey && seskeylen )
{
enc->seskeylen = seskeylen + 1; /* algo id */
memcpy (enc->seskey, enckey, seskeylen + 1 );
}
pkt.pkttype = PKT_SYMKEY_ENC;
pkt.pkt.symkey_enc = enc;
if ((rc = build_packet( out, &pkt )))
log_error("build symkey packet failed: %s\n", g10_errstr(rc) );
xfree (enc);
}
if (!opt.no_literal)
pt = setup_plaintext_name (filename, inp);
/* Note that PGP 5 has problems decrypting symmetrically encrypted
data if the file length is in the inner packet. It works when
only partial length headers are use. In the past, we always used
partial body length here, but since PGP 2, PGP 6, and PGP 7 need
the file length, and nobody should be using PGP 5 nowadays
anyway, this is now set to the file length. Note also that this
only applies to the RFC-1991 style symmetric messages, and not
the RFC-2440 style. PGP 6 and 7 work with either partial length
or fixed length with the new style messages. */
if ( !iobuf_is_pipe_filename (filename) && *filename && !opt.textmode )
{
off_t tmpsize;
int overflow;
if ( !(tmpsize = iobuf_get_filelength(inp, &overflow))
&& !overflow && opt.verbose)
log_info(_("WARNING: `%s' is an empty file\n"), filename );
/* We can't encode the length of very large files because
OpenPGP uses only 32 bit for file sizes. So if the the
size of a file is larger than 2^32 minus some bytes for
packet headers, we switch to partial length encoding. */
if ( tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
filesize = tmpsize;
else
filesize = 0;
}
else
filesize = opt.set_filesize ? opt.set_filesize : 0; /* stdin */
if (!opt.no_literal)
{
pt->timestamp = make_timestamp();
pt->mode = opt.textmode? 't' : 'b';
pt->len = filesize;
pt->new_ctb = !pt->len && !RFC1991;
pt->buf = inp;
pkt.pkttype = PKT_PLAINTEXT;
pkt.pkt.plaintext = pt;
cfx.datalen = filesize && !do_compress ? calc_packet_length( &pkt ) : 0;
}
else
{
cfx.datalen = filesize && !do_compress ? filesize : 0;
pkt.pkttype = 0;
pkt.pkt.generic = NULL;
}
/* Register the cipher filter. */
if (mode)
iobuf_push_filter ( out, cipher_filter, &cfx );
/* Register the compress filter. */
if ( do_compress )
{
if (cfx.dek && cfx.dek->use_mdc)
zfx.new_ctb = 1;
push_compress_filter (out, &zfx, default_compress_algo());
}
/* Do the work. */
if (!opt.no_literal)
{
if ( (rc = build_packet( out, &pkt )) )
log_error("build_packet failed: %s\n", g10_errstr(rc) );
}
else
{
/* User requested not to create a literal packet, so we copy the
plain data. */
byte copy_buffer[4096];
int bytes_copied;
while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1)
if ( (rc=iobuf_write(out, copy_buffer, bytes_copied)) ) {
log_error ("copying input to output failed: %s\n",
gpg_strerror (rc) );
break;
}
wipememory (copy_buffer, 4096); /* burn buffer */
}
/* Finish the stuff. */
iobuf_close (inp);
if (rc)
iobuf_cancel(out);
else
{
iobuf_close (out); /* fixme: check returncode */
if (mode)
write_status ( STATUS_END_ENCRYPTION );
}
if (pt)
pt->buf = NULL;
free_packet (&pkt);
xfree (cfx.dek);
xfree (s2k);
release_armor_context (afx);
release_progress_context (pfx);
return rc;
}
int
setup_symkey (STRING2KEY **symkey_s2k,DEK **symkey_dek)
{
int canceled;
*symkey_s2k=xmalloc_clear(sizeof(STRING2KEY));
(*symkey_s2k)->mode = opt.s2k_mode;
(*symkey_s2k)->hash_algo = S2K_DIGEST_ALGO;
*symkey_dek=passphrase_to_dek(NULL,0,opt.s2k_cipher_algo,
*symkey_s2k, 4, NULL, &canceled);
if(!*symkey_dek || !(*symkey_dek)->keylen)
{
xfree(*symkey_dek);
xfree(*symkey_s2k);
return gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_BAD_PASSPHRASE);
}
return 0;
}
static int
write_symkey_enc (STRING2KEY *symkey_s2k, DEK *symkey_dek, DEK *dek,
iobuf_t out)
{
int rc, seskeylen = openpgp_cipher_get_algo_keylen (dek->algo);
PKT_symkey_enc *enc;
byte enckey[33];
PACKET pkt;
enc=xmalloc_clear(sizeof(PKT_symkey_enc)+seskeylen+1);
encrypt_seskey(symkey_dek,&dek,enckey);
enc->version = 4;
enc->cipher_algo = opt.s2k_cipher_algo;
enc->s2k = *symkey_s2k;
enc->seskeylen = seskeylen + 1; /* algo id */
memcpy( enc->seskey, enckey, seskeylen + 1 );
pkt.pkttype = PKT_SYMKEY_ENC;
pkt.pkt.symkey_enc = enc;
if ((rc=build_packet(out,&pkt)))
log_error("build symkey_enc packet failed: %s\n",g10_errstr(rc));
xfree(enc);
return rc;
}
/*
* Encrypt the file with the given userids (or ask if none is
* supplied). Either FILENAME or FILEFD must be given, but not both.
* The caller may provide a checked list of public keys in
* PROVIDED_PKS; if not the function builds a list of keys on its own.
*/
int
encrypt_crypt (ctrl_t ctrl, int filefd, const char *filename,
strlist_t remusr, int use_symkey, pk_list_t provided_keys,
int outputfd)
{
iobuf_t inp = NULL;
iobuf_t out = NULL;
PACKET pkt;
PKT_plaintext *pt = NULL;
DEK *symkey_dek = NULL;
STRING2KEY *symkey_s2k = NULL;
int rc = 0, rc2 = 0;
u32 filesize;
cipher_filter_context_t cfx;
armor_filter_context_t *afx = NULL;
compress_filter_context_t zfx;
text_filter_context_t tfx;
progress_filter_context_t *pfx;
PK_LIST pk_list, work_list;
int do_compress;
if (filefd != -1 && filename)
return gpg_error (GPG_ERR_INV_ARG);
do_compress = opt.compress_algo && !RFC1991;
pfx = new_progress_context ();
memset( &cfx, 0, sizeof cfx);
memset( &zfx, 0, sizeof zfx);
memset( &tfx, 0, sizeof tfx);
init_packet(&pkt);
if (use_symkey
&& (rc=setup_symkey(&symkey_s2k,&symkey_dek)))
{
release_progress_context (pfx);
return rc;
}
if (provided_keys)
pk_list = provided_keys;
else
{
if ((rc = build_pk_list (ctrl, remusr, &pk_list, PUBKEY_USAGE_ENC)))
{
release_progress_context (pfx);
return rc;
}
}
if(PGP2)
{
for (work_list=pk_list; work_list; work_list=work_list->next)
if (!(is_RSA (work_list->pk->pubkey_algo)
&& nbits_from_pk (work_list->pk) <= 2048))
{
log_info(_("you can only encrypt to RSA keys of 2048 bits or "
"less in --pgp2 mode\n"));
compliance_failure();
break;
}
}
/* Prepare iobufs. */
inp = iobuf_open_fd_or_name (filefd, filename, "rb");
if (inp)
iobuf_ioctl (inp, IOBUF_IOCTL_NO_CACHE, 1, NULL);
if (inp && is_secured_file (iobuf_get_fd (inp)))
{
iobuf_close (inp);
inp = NULL;
gpg_err_set_errno (EPERM);
}
if (!inp)
{
char xname[64];
rc = gpg_error_from_syserror ();
if (filefd != -1)
snprintf (xname, sizeof xname, "[fd %d]", filefd);
else if (!filename)
strcpy (xname, "[stdin]");
else
*xname = 0;
log_error (_("can't open `%s': %s\n"),
*xname? xname : filename, gpg_strerror (rc) );
goto leave;
}
if (opt.verbose)
log_info (_("reading from `%s'\n"), iobuf_get_fname_nonnull (inp));
handle_progress (pfx, inp, filename);
if (opt.textmode)
iobuf_push_filter (inp, text_filter, &tfx);
rc = open_outfile (outputfd, filename, opt.armor? 1:0, &out);
if (rc)
goto leave;
if (opt.armor)
{
afx = new_armor_context ();
push_armor_filter (afx, out);
}
/* Create a session key. */
cfx.dek = xmalloc_secure_clear (sizeof *cfx.dek);
if (!opt.def_cipher_algo)
{
/* Try to get it from the prefs. */
cfx.dek->algo = select_algo_from_prefs (pk_list, PREFTYPE_SYM, -1, NULL);
/* The only way select_algo_from_prefs can fail here is when
mixing v3 and v4 keys, as v4 keys have an implicit preference
entry for 3DES, and the pk_list cannot be empty. In this
case, use 3DES anyway as it's the safest choice - perhaps the
v3 key is being used in an OpenPGP implementation and we know
that the implementation behind any v4 key can handle 3DES. */
if (cfx.dek->algo == -1)
{
cfx.dek->algo = CIPHER_ALGO_3DES;
if (PGP2)
{
log_info(_("unable to use the IDEA cipher for all of the keys "
"you are encrypting to.\n"));
compliance_failure();
}
}
/* In case 3DES has been selected, print a warning if any key
does not have a preference for AES. This should help to
indentify why encrypting to several recipients falls back to
3DES. */
if (opt.verbose && cfx.dek->algo == CIPHER_ALGO_3DES)
warn_missing_aes_from_pklist (pk_list);
}
else
{
if (!opt.expert
&& (select_algo_from_prefs (pk_list, PREFTYPE_SYM,
opt.def_cipher_algo, NULL)
!= opt.def_cipher_algo))
{
log_info(_("WARNING: forcing symmetric cipher %s (%d)"
" violates recipient preferences\n"),
openpgp_cipher_algo_name (opt.def_cipher_algo),
opt.def_cipher_algo);
}
cfx.dek->algo = opt.def_cipher_algo;
}
cfx.dek->use_mdc = use_mdc (pk_list,cfx.dek->algo);
/* Only do the is-file-already-compressed check if we are using a
MDC. This forces compressed files to be re-compressed if we do
not have a MDC to give some protection against chosen ciphertext
attacks. */
if (do_compress && cfx.dek->use_mdc && is_file_compressed(filename, &rc2))
{
if (opt.verbose)
log_info(_("`%s' already compressed\n"), filename);
do_compress = 0;
}
if (rc2)
{
rc = rc2;
goto leave;
}
make_session_key (cfx.dek);
if (DBG_CIPHER)
log_printhex ("DEK is: ", cfx.dek->key, cfx.dek->keylen );
rc = write_pubkey_enc_from_list (pk_list, cfx.dek, out);
if (rc)
goto leave;
/* We put the passphrase (if any) after any public keys as this
seems to be the most useful on the recipient side - there is no
point in prompting a user for a passphrase if they have the
secret key needed to decrypt. */
if(use_symkey && (rc = write_symkey_enc(symkey_s2k,symkey_dek,cfx.dek,out)))
goto leave;
if (!opt.no_literal)
pt = setup_plaintext_name (filename, inp);
if (filefd != -1
&& !iobuf_is_pipe_filename (filename) && *filename && !opt.textmode )
{
off_t tmpsize;
int overflow;
if ( !(tmpsize = iobuf_get_filelength(inp, &overflow))
&& !overflow && opt.verbose)
log_info(_("WARNING: `%s' is an empty file\n"), filename );
/* We can't encode the length of very large files because
OpenPGP uses only 32 bit for file sizes. So if the the size
of a file is larger than 2^32 minus some bytes for packet
headers, we switch to partial length encoding. */
if (tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
filesize = tmpsize;
else
filesize = 0;
}
else
filesize = opt.set_filesize ? opt.set_filesize : 0; /* stdin */
if (!opt.no_literal)
{
pt->timestamp = make_timestamp();
pt->mode = opt.textmode ? 't' : 'b';
pt->len = filesize;
pt->new_ctb = !pt->len && !RFC1991;
pt->buf = inp;
pkt.pkttype = PKT_PLAINTEXT;
pkt.pkt.plaintext = pt;
cfx.datalen = filesize && !do_compress? calc_packet_length( &pkt ) : 0;
}
else
cfx.datalen = filesize && !do_compress ? filesize : 0;
/* Register the cipher filter. */
iobuf_push_filter (out, cipher_filter, &cfx);
/* Register the compress filter. */
if (do_compress)
{
int compr_algo = opt.compress_algo;
if (compr_algo == -1)
{
compr_algo = select_algo_from_prefs (pk_list, PREFTYPE_ZIP, -1, NULL);
if (compr_algo == -1)
compr_algo = DEFAULT_COMPRESS_ALGO;
/* Theoretically impossible to get here since uncompressed
is implicit. */
}
else if (!opt.expert
&& select_algo_from_prefs(pk_list, PREFTYPE_ZIP,
compr_algo, NULL) != compr_algo)
{
log_info (_("WARNING: forcing compression algorithm %s (%d)"
" violates recipient preferences\n"),
compress_algo_to_string(compr_algo), compr_algo);
}
/* Algo 0 means no compression. */
if (compr_algo)
{
if (cfx.dek && cfx.dek->use_mdc)
zfx.new_ctb = 1;
push_compress_filter (out,&zfx,compr_algo);
}
}
/* Do the work. */
if (!opt.no_literal)
{
if ((rc = build_packet( out, &pkt )))
log_error ("build_packet failed: %s\n", g10_errstr(rc));
}
else
{
/* User requested not to create a literal packet, so we copy the
plain data. */
byte copy_buffer[4096];
int bytes_copied;
while ((bytes_copied = iobuf_read (inp, copy_buffer, 4096)) != -1)
{
rc = iobuf_write (out, copy_buffer, bytes_copied);
if (rc)
{
log_error ("copying input to output failed: %s\n",
gpg_strerror (rc));
break;
}
}
wipememory (copy_buffer, 4096); /* Burn the buffer. */
}
/* Finish the stuff. */
leave:
iobuf_close (inp);
if (rc)
iobuf_cancel (out);
else
{
iobuf_close (out); /* fixme: check returncode */
write_status (STATUS_END_ENCRYPTION);
}
if (pt)
pt->buf = NULL;
free_packet (&pkt);
xfree (cfx.dek);
xfree (symkey_dek);
xfree (symkey_s2k);
if (!provided_keys)
release_pk_list (pk_list);
release_armor_context (afx);
release_progress_context (pfx);
return rc;
}
/*
* Filter to do a complete public key encryption.
*/
int
encrypt_filter (void *opaque, int control,
iobuf_t a, byte *buf, size_t *ret_len)
{
size_t size = *ret_len;
encrypt_filter_context_t *efx = opaque;
int rc = 0;
if (control == IOBUFCTRL_UNDERFLOW) /* decrypt */
{
BUG(); /* not used */
}
else if ( control == IOBUFCTRL_FLUSH ) /* encrypt */
{
if ( !efx->header_okay )
{
efx->cfx.dek = xmalloc_secure_clear ( sizeof *efx->cfx.dek );
if ( !opt.def_cipher_algo )
{
/* Try to get it from the prefs. */
efx->cfx.dek->algo =
select_algo_from_prefs (efx->pk_list, PREFTYPE_SYM, -1, NULL);
if (efx->cfx.dek->algo == -1 )
{
/* Because 3DES is implicitly in the prefs, this can
only happen if we do not have any public keys in
the list. */
efx->cfx.dek->algo = DEFAULT_CIPHER_ALGO;
}
/* In case 3DES has been selected, print a warning if
any key does not have a preference for AES. This
should help to indentify why encrypting to several
recipients falls back to 3DES. */
if (opt.verbose
&& efx->cfx.dek->algo == CIPHER_ALGO_3DES)
warn_missing_aes_from_pklist (efx->pk_list);
}
else
{
if (!opt.expert
&& select_algo_from_prefs (efx->pk_list,PREFTYPE_SYM,
opt.def_cipher_algo,
NULL) != opt.def_cipher_algo)
log_info(_("forcing symmetric cipher %s (%d) "
"violates recipient preferences\n"),
openpgp_cipher_algo_name (opt.def_cipher_algo),
opt.def_cipher_algo);
efx->cfx.dek->algo = opt.def_cipher_algo;
}
efx->cfx.dek->use_mdc = use_mdc (efx->pk_list,efx->cfx.dek->algo);
make_session_key ( efx->cfx.dek );
if (DBG_CIPHER)
log_printhex ("DEK is: ", efx->cfx.dek->key, efx->cfx.dek->keylen);
rc = write_pubkey_enc_from_list (efx->pk_list, efx->cfx.dek, a);
if (rc)
return rc;
if(efx->symkey_s2k && efx->symkey_dek)
{
rc=write_symkey_enc(efx->symkey_s2k,efx->symkey_dek,
efx->cfx.dek,a);
if(rc)
return rc;
}
iobuf_push_filter (a, cipher_filter, &efx->cfx);
efx->header_okay = 1;
}
rc = iobuf_write (a, buf, size);
}
else if (control == IOBUFCTRL_FREE)
{
xfree (efx->symkey_dek);
xfree (efx->symkey_s2k);
}
else if ( control == IOBUFCTRL_DESC )
{
*(char**)buf = "encrypt_filter";
}
return rc;
}
/*
* Write pubkey-enc packets from the list of PKs to OUT.
*/
static int
write_pubkey_enc_from_list (PK_LIST pk_list, DEK *dek, iobuf_t out)
{
PACKET pkt;
PKT_public_key *pk;
PKT_pubkey_enc *enc;
int rc;
for ( ; pk_list; pk_list = pk_list->next )
{
gcry_mpi_t frame;
-
+ byte fp[MAX_FINGERPRINT_LEN];
+ size_t fpn;
+
pk = pk_list->pk;
print_pubkey_algo_note ( pk->pubkey_algo );
enc = xmalloc_clear ( sizeof *enc );
enc->pubkey_algo = pk->pubkey_algo;
keyid_from_pk( pk, enc->keyid );
enc->throw_keyid = (opt.throw_keyid || (pk_list->flags&1));
if (opt.throw_keyid && (PGP2 || PGP6 || PGP7 || PGP8))
{
log_info(_("you may not use %s while in %s mode\n"),
"--throw-keyid",compliance_option_string());
compliance_failure();
}
+ fingerprint_from_pk( pk, fp, &fpn );
+ assert( fpn == 20 );
+
/* Okay, what's going on: We have the session key somewhere in
* the structure DEK and want to encode this session key in an
* integer value of n bits. pubkey_nbits gives us the number of
* bits we have to use. We then encode the session key in some
* way and we get it back in the big intger value FRAME. Then
* we use FRAME, the public key PK->PKEY and the algorithm
* number PK->PUBKEY_ALGO and pass it to pubkey_encrypt which
* returns the encrypted value in the array ENC->DATA. This
* array has a size which depends on the used algorithm (e.g. 2
* for Elgamal). We don't need frame anymore because we have
* everything now in enc->data which is the passed to
* build_packet(). */
- frame = encode_session_key (dek,
+ frame = encode_session_key (pk->pubkey_algo, dek,
pubkey_nbits (pk->pubkey_algo, pk->pkey));
- rc = pk_encrypt (pk->pubkey_algo, enc->data, frame, pk->pkey);
+ rc = pk_encrypt (pk->pubkey_algo, enc->data, frame, fp, pk->pkey);
gcry_mpi_release (frame);
if (rc)
log_error ("pubkey_encrypt failed: %s\n", gpg_strerror (rc) );
else
{
if ( opt.verbose )
{
char *ustr = get_user_id_string_native (enc->keyid);
log_info (_("%s/%s encrypted for: \"%s\"\n"),
gcry_pk_algo_name (enc->pubkey_algo),
openpgp_cipher_algo_name (dek->algo),
ustr );
xfree (ustr);
}
/* And write it. */
init_packet (&pkt);
pkt.pkttype = PKT_PUBKEY_ENC;
pkt.pkt.pubkey_enc = enc;
rc = build_packet (out, &pkt);
if (rc)
log_error ("build_packet(pubkey_enc) failed: %s\n",
g10_errstr (rc));
}
free_pubkey_enc(enc);
if (rc)
return rc;
}
return 0;
}
void
encrypt_crypt_files (ctrl_t ctrl, int nfiles, char **files, strlist_t remusr)
{
int rc = 0;
if (opt.outfile)
{
log_error(_("--output doesn't work for this command\n"));
return;
}
if (!nfiles)
{
char line[2048];
unsigned int lno = 0;
while ( fgets(line, DIM(line), stdin) )
{
lno++;
if (!*line || line[strlen(line)-1] != '\n')
{
log_error("input line %u too long or missing LF\n", lno);
return;
}
line[strlen(line)-1] = '\0';
print_file_status(STATUS_FILE_START, line, 2);
rc = encrypt_crypt (ctrl, -1, line, remusr, 0, NULL, -1);
if (rc)
log_error ("encryption of `%s' failed: %s\n",
print_fname_stdin(line), g10_errstr(rc) );
write_status( STATUS_FILE_DONE );
}
}
else
{
while (nfiles--)
{
print_file_status(STATUS_FILE_START, *files, 2);
if ( (rc = encrypt_crypt (ctrl, -1, *files, remusr, 0, NULL, -1)) )
log_error("encryption of `%s' failed: %s\n",
print_fname_stdin(*files), g10_errstr(rc) );
write_status( STATUS_FILE_DONE );
files++;
}
}
}
diff --git a/g10/export.c b/g10/export.c
index 91c6a73d7..82d97511f 100644
--- a/g10/export.c
+++ b/g10/export.c
@@ -1,1207 +1,1219 @@
/* export.c - Export keys in the OpenPGP defined format.
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
* 2005, 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
* 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
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include
#include "gpg.h"
#include "options.h"
#include "packet.h"
#include "status.h"
#include "keydb.h"
#include "util.h"
#include "main.h"
#include "i18n.h"
#include "trustdb.h"
#include "call-agent.h"
/* An object to keep track of subkeys. */
struct subkey_list_s
{
struct subkey_list_s *next;
u32 kid[2];
};
typedef struct subkey_list_s *subkey_list_t;
static int do_export (ctrl_t ctrl,
strlist_t users, int secret, unsigned int options );
static int do_export_stream (ctrl_t ctrl, iobuf_t out,
strlist_t users, int secret,
kbnode_t *keyblock_out, unsigned int options,
int *any);
static int build_sexp (iobuf_t out, PACKET *pkt, int *indent);
int
parse_export_options(char *str,unsigned int *options,int noisy)
{
struct parse_options export_opts[]=
{
{"export-local-sigs",EXPORT_LOCAL_SIGS,NULL,
N_("export signatures that are marked as local-only")},
{"export-attributes",EXPORT_ATTRIBUTES,NULL,
N_("export attribute user IDs (generally photo IDs)")},
{"export-sensitive-revkeys",EXPORT_SENSITIVE_REVKEYS,NULL,
N_("export revocation keys marked as \"sensitive\"")},
{"export-clean",EXPORT_CLEAN,NULL,
N_("remove unusable parts from key during export")},
{"export-minimal",EXPORT_MINIMAL|EXPORT_CLEAN,NULL,
N_("remove as much as possible from key during export")},
{"export-sexp-format",EXPORT_SEXP_FORMAT, NULL,
N_("export keys in an S-expression based format")},
/* Aliases for backward compatibility */
{"include-local-sigs",EXPORT_LOCAL_SIGS,NULL,NULL},
{"include-attributes",EXPORT_ATTRIBUTES,NULL,NULL},
{"include-sensitive-revkeys",EXPORT_SENSITIVE_REVKEYS,NULL,NULL},
/* dummy */
{"export-unusable-sigs",0,NULL,NULL},
{"export-clean-sigs",0,NULL,NULL},
{"export-clean-uids",0,NULL,NULL},
{NULL,0,NULL,NULL}
/* add tags for include revoked and disabled? */
};
return parse_options(str,options,export_opts,noisy);
}
/****************
* Export the public keys (to standard out or --output).
* Depending on opt.armor the output is armored.
* options are defined in main.h.
* If USERS is NULL, the complete ring will be exported. */
int
export_pubkeys (ctrl_t ctrl, strlist_t users, unsigned int options )
{
return do_export (ctrl, users, 0, options );
}
/****************
* Export to an already opened stream; return -1 if no keys have
* been exported
*/
int
export_pubkeys_stream (ctrl_t ctrl, iobuf_t out, strlist_t users,
kbnode_t *keyblock_out, unsigned int options )
{
int any, rc;
rc = do_export_stream (ctrl, out, users, 0, keyblock_out, options, &any);
if (!rc && !any)
rc = -1;
return rc;
}
int
export_seckeys (ctrl_t ctrl, strlist_t users )
{
/* Use only relevant options for the secret key. */
unsigned int options = (opt.export_options & EXPORT_SEXP_FORMAT);
return do_export (ctrl, users, 1, options);
}
int
export_secsubkeys (ctrl_t ctrl, strlist_t users )
{
/* Use only relevant options for the secret key. */
unsigned int options = (opt.export_options & EXPORT_SEXP_FORMAT);
return do_export (ctrl, users, 2, options);
}
/* Export the keys identified by the list of strings in USERS. If
Secret is false public keys will be exported. With secret true
secret keys will be exported; in this case 1 means the entire
secret keyblock and 2 only the subkeys. OPTIONS are the export
options to apply. */
static int
do_export (ctrl_t ctrl, strlist_t users, int secret, unsigned int options )
{
IOBUF out = NULL;
int any, rc;
armor_filter_context_t *afx = NULL;
compress_filter_context_t zfx;
memset( &zfx, 0, sizeof zfx);
rc = open_outfile (GNUPG_INVALID_FD, NULL, 0, &out );
if (rc)
return rc;
if (!(options & EXPORT_SEXP_FORMAT))
{
if ( opt.armor )
{
afx = new_armor_context ();
afx->what = secret? 5 : 1;
push_armor_filter (afx, out);
}
if ( opt.compress_keys )
push_compress_filter (out,&zfx,default_compress_algo());
}
rc = do_export_stream (ctrl, out, users, secret, NULL, options, &any );
if ( rc || !any )
iobuf_cancel (out);
else
iobuf_close (out);
release_armor_context (afx);
return rc;
}
/* Release an entire subkey list. */
static void
release_subkey_list (subkey_list_t list)
{
while (list)
{
subkey_list_t tmp = list->next;;
xfree (list);
list = tmp;
}
}
/* Returns true if NODE is a subkey and contained in LIST. */
static int
subkey_in_list_p (subkey_list_t list, KBNODE node)
{
if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
|| node->pkt->pkttype == PKT_SECRET_SUBKEY )
{
u32 kid[2];
keyid_from_pk (node->pkt->pkt.public_key, kid);
for (; list; list = list->next)
if (list->kid[0] == kid[0] && list->kid[1] == kid[1])
return 1;
}
return 0;
}
/* Allocate a new subkey list item from NODE. */
static subkey_list_t
new_subkey_list_item (KBNODE node)
{
subkey_list_t list = xcalloc (1, sizeof *list);
if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
|| node->pkt->pkttype == PKT_SECRET_SUBKEY)
keyid_from_pk (node->pkt->pkt.public_key, list->kid);
return list;
}
/* Helper function to check whether the subkey at NODE actually
matches the description at DESC. The function returns true if the
key under question has been specified by an exact specification
(keyID or fingerprint) and does match the one at NODE. It is
assumed that the packet at NODE is either a public or secret
subkey. */
static int
exact_subkey_match_p (KEYDB_SEARCH_DESC *desc, KBNODE node)
{
u32 kid[2];
byte fpr[MAX_FINGERPRINT_LEN];
size_t fprlen;
int result = 0;
switch(desc->mode)
{
case KEYDB_SEARCH_MODE_SHORT_KID:
case KEYDB_SEARCH_MODE_LONG_KID:
keyid_from_pk (node->pkt->pkt.public_key, kid);
break;
case KEYDB_SEARCH_MODE_FPR16:
case KEYDB_SEARCH_MODE_FPR20:
case KEYDB_SEARCH_MODE_FPR:
fingerprint_from_pk (node->pkt->pkt.public_key, fpr,&fprlen);
break;
default:
break;
}
switch(desc->mode)
{
case KEYDB_SEARCH_MODE_SHORT_KID:
if (desc->u.kid[1] == kid[1])
result = 1;
break;
case KEYDB_SEARCH_MODE_LONG_KID:
if (desc->u.kid[0] == kid[0] && desc->u.kid[1] == kid[1])
result = 1;
break;
case KEYDB_SEARCH_MODE_FPR16:
if (!memcmp (desc->u.fpr, fpr, 16))
result = 1;
break;
case KEYDB_SEARCH_MODE_FPR20:
case KEYDB_SEARCH_MODE_FPR:
if (!memcmp (desc->u.fpr, fpr, 20))
result = 1;
break;
default:
break;
}
return result;
}
/* Return a canonicalized public key algoithms. This is used to
compare different flavors of algorithms (e.g. ELG and ELG_E are
considered the same). */
static int
canon_pubkey_algo (int algo)
{
switch (algo)
{
case GCRY_PK_RSA:
case GCRY_PK_RSA_E:
case GCRY_PK_RSA_S: return GCRY_PK_RSA;
case GCRY_PK_ELG:
case GCRY_PK_ELG_E: return GCRY_PK_ELG;
default: return algo;
}
}
/* Use the key transfer format given in S_PGP to create the secinfo
structure in PK and chnage the parameter array in PK to include the
secret parameters. */
static gpg_error_t
transfer_format_to_openpgp (gcry_sexp_t s_pgp, PKT_public_key *pk)
{
gpg_error_t err;
gcry_sexp_t top_list;
gcry_sexp_t list = NULL;
const char *value;
size_t valuelen;
char *string;
int idx;
int is_v4, is_protected;
int pubkey_algo;
int protect_algo = 0;
char iv[16];
int ivlen = 0;
int s2k_mode = 0;
int s2k_algo = 0;
byte s2k_salt[8];
u32 s2k_count = 0;
size_t npkey, nskey;
gcry_mpi_t skey[10]; /* We support up to 9 parameters. */
u16 desired_csum;
int skeyidx = 0;
struct seckey_info *ski;
top_list = gcry_sexp_find_token (s_pgp, "openpgp-private-key", 0);
if (!top_list)
goto bad_seckey;
list = gcry_sexp_find_token (top_list, "version", 0);
if (!list)
goto bad_seckey;
value = gcry_sexp_nth_data (list, 1, &valuelen);
if (!value || valuelen != 1 || !(value[0] == '3' || value[0] == '4'))
goto bad_seckey;
is_v4 = (value[0] == '4');
gcry_sexp_release (list);
list = gcry_sexp_find_token (top_list, "protection", 0);
if (!list)
goto bad_seckey;
value = gcry_sexp_nth_data (list, 1, &valuelen);
if (!value)
goto bad_seckey;
if (valuelen == 4 && !memcmp (value, "sha1", 4))
is_protected = 2;
else if (valuelen == 3 && !memcmp (value, "sum", 3))
is_protected = 1;
else if (valuelen == 4 && !memcmp (value, "none", 4))
is_protected = 0;
else
goto bad_seckey;
if (is_protected)
{
string = gcry_sexp_nth_string (list, 2);
if (!string)
goto bad_seckey;
protect_algo = gcry_cipher_map_name (string);
xfree (string);
value = gcry_sexp_nth_data (list, 3, &valuelen);
if (!value || !valuelen || valuelen > sizeof iv)
goto bad_seckey;
memcpy (iv, value, valuelen);
ivlen = valuelen;
string = gcry_sexp_nth_string (list, 4);
if (!string)
goto bad_seckey;
s2k_mode = strtol (string, NULL, 10);
xfree (string);
string = gcry_sexp_nth_string (list, 5);
if (!string)
goto bad_seckey;
s2k_algo = gcry_md_map_name (string);
xfree (string);
value = gcry_sexp_nth_data (list, 6, &valuelen);
if (!value || !valuelen || valuelen > sizeof s2k_salt)
goto bad_seckey;
memcpy (s2k_salt, value, valuelen);
string = gcry_sexp_nth_string (list, 7);
if (!string)
goto bad_seckey;
s2k_count = strtoul (string, NULL, 10);
xfree (string);
}
gcry_sexp_release (list);
list = gcry_sexp_find_token (top_list, "algo", 0);
if (!list)
goto bad_seckey;
string = gcry_sexp_nth_string (list, 1);
if (!string)
goto bad_seckey;
pubkey_algo = gcry_pk_map_name (string);
xfree (string);
if (gcry_pk_algo_info (pubkey_algo, GCRYCTL_GET_ALGO_NPKEY, NULL, &npkey)
|| gcry_pk_algo_info (pubkey_algo, GCRYCTL_GET_ALGO_NSKEY, NULL, &nskey)
|| !npkey || npkey >= nskey || nskey > PUBKEY_MAX_NSKEY)
goto bad_seckey;
gcry_sexp_release (list);
list = gcry_sexp_find_token (top_list, "skey", 0);
if (!list)
goto bad_seckey;
for (idx=0;;)
{
int is_enc;
value = gcry_sexp_nth_data (list, ++idx, &valuelen);
if (!value && skeyidx >= npkey)
break; /* Ready. */
/* Check for too many parameters. Note that depending on the
protection mode and version number we may see less than NSKEY
(but at least NPKEY+1) parameters. */
if (idx >= 2*nskey)
goto bad_seckey;
if (skeyidx >= DIM (skey)-1)
goto bad_seckey;
if (!value || valuelen != 1 || !(value[0] == '_' || value[0] == 'e'))
goto bad_seckey;
is_enc = (value[0] == 'e');
value = gcry_sexp_nth_data (list, ++idx, &valuelen);
if (!value || !valuelen)
goto bad_seckey;
if (is_enc)
{
void *p = xtrymalloc (valuelen);
if (!p)
goto outofmem;
memcpy (p, value, valuelen);
skey[skeyidx] = gcry_mpi_set_opaque (NULL, p, valuelen*8);
if (!skey[skeyidx])
goto outofmem;
}
else
{
if (gcry_mpi_scan (skey + skeyidx, GCRYMPI_FMT_STD,
value, valuelen, NULL))
goto bad_seckey;
}
skeyidx++;
}
skey[skeyidx++] = NULL;
gcry_sexp_release (list);
list = gcry_sexp_find_token (top_list, "csum", 0);
if (list)
{
string = gcry_sexp_nth_string (list, 1);
if (!string)
goto bad_seckey;
desired_csum = strtoul (string, NULL, 10);
xfree (string);
}
else
desired_csum = 0;
gcry_sexp_release (list); list = NULL;
gcry_sexp_release (top_list); top_list = NULL;
/* log_debug ("XXX is_v4=%d\n", is_v4); */
/* log_debug ("XXX pubkey_algo=%d\n", pubkey_algo); */
/* log_debug ("XXX is_protected=%d\n", is_protected); */
/* log_debug ("XXX protect_algo=%d\n", protect_algo); */
/* log_printhex ("XXX iv", iv, ivlen); */
/* log_debug ("XXX ivlen=%d\n", ivlen); */
/* log_debug ("XXX s2k_mode=%d\n", s2k_mode); */
/* log_debug ("XXX s2k_algo=%d\n", s2k_algo); */
/* log_printhex ("XXX s2k_salt", s2k_salt, sizeof s2k_salt); */
/* log_debug ("XXX s2k_count=%lu\n", (unsigned long)s2k_count); */
/* for (idx=0; skey[idx]; idx++) */
/* { */
/* int is_enc = gcry_mpi_get_flag (skey[idx], GCRYMPI_FLAG_OPAQUE); */
/* log_info ("XXX skey[%d]%s:", idx, is_enc? " (enc)":""); */
/* if (is_enc) */
/* { */
/* void *p; */
/* unsigned int nbits; */
/* p = gcry_mpi_get_opaque (skey[idx], &nbits); */
/* log_printhex (NULL, p, (nbits+7)/8); */
/* } */
/* else */
/* gcry_mpi_dump (skey[idx]); */
/* log_printf ("\n"); */
/* } */
if (!is_v4 || is_protected != 2 )
{
/* We only support the v4 format and a SHA-1 checksum. */
err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
goto leave;
}
/* Do some sanity checks. */
if (s2k_count <= 1024)
{
/* The count must be larger so that encode_s2k_iterations does
not fall into a backward compatibility mode. */
err = gpg_error (GPG_ERR_INV_DATA);
goto leave;
}
if (canon_pubkey_algo (pubkey_algo) != canon_pubkey_algo (pk->pubkey_algo))
{
err = gpg_error (GPG_ERR_PUBKEY_ALGO);
goto leave;
}
err = openpgp_cipher_test_algo (protect_algo);
if (err)
goto leave;
err = openpgp_md_test_algo (s2k_algo);
if (err)
goto leave;
/* Check that the public key parameters match. */
for (idx=0; idx < npkey; idx++)
if (gcry_mpi_get_flag (pk->pkey[idx], GCRYMPI_FLAG_OPAQUE)
|| gcry_mpi_get_flag (skey[idx], GCRYMPI_FLAG_OPAQUE)
|| gcry_mpi_cmp (pk->pkey[idx], skey[idx]))
{
err = gpg_error (GPG_ERR_BAD_PUBKEY);
goto leave;
}
/* Check that the first secret key parameter in SKEY is encrypted
and that there are no more secret key parameters. The latter is
guaranteed by the v4 packet format. */
if (!gcry_mpi_get_flag (skey[npkey], GCRYMPI_FLAG_OPAQUE))
goto bad_seckey;
if (npkey+1 < DIM (skey) && skey[npkey+1])
goto bad_seckey;
/* Check that the secret key parameters in PK are all set to NULL. */
for (idx=npkey; idx < nskey; idx++)
if (pk->pkey[idx])
goto bad_seckey;
/* Now build the protection info. */
pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
if (!ski)
{
err = gpg_error_from_syserror ();
goto leave;
}
ski->is_protected = 1;
ski->sha1chk = 1;
ski->algo = protect_algo;
ski->s2k.mode = s2k_mode;
ski->s2k.hash_algo = s2k_algo;
assert (sizeof ski->s2k.salt == sizeof s2k_salt);
memcpy (ski->s2k.salt, s2k_salt, sizeof s2k_salt);
ski->s2k.count = encode_s2k_iterations (s2k_count);
assert (ivlen <= sizeof ski->iv);
memcpy (ski->iv, iv, ivlen);
ski->ivlen = ivlen;
/* Store the protected secret key parameter. */
pk->pkey[npkey] = skey[npkey];
skey[npkey] = NULL;
/* That's it. */
leave:
gcry_sexp_release (list);
gcry_sexp_release (top_list);
for (idx=0; idx < skeyidx; idx++)
gcry_mpi_release (skey[idx]);
return err;
bad_seckey:
err = gpg_error (GPG_ERR_BAD_SECKEY);
goto leave;
outofmem:
err = gpg_error (GPG_ERR_ENOMEM);
goto leave;
}
/* Export the keys identified by the list of strings in USERS to the
stream OUT. If Secret is false public keys will be exported. With
secret true secret keys will be exported; in this case 1 means the
entire secret keyblock and 2 only the subkeys. OPTIONS are the
export options to apply. If KEYBLOCK_OUT is not NULL, AND the exit
code is zero, a pointer to the first keyblock found and exported
will be stored at this address; no other keyblocks are exported in
this case. The caller must free it the returned keyblock. If any
key has been exported true is stored at ANY. */
static int
do_export_stream (ctrl_t ctrl, iobuf_t out, strlist_t users, int secret,
kbnode_t *keyblock_out, unsigned int options, int *any)
{
gpg_error_t err = 0;
PACKET pkt;
KBNODE keyblock = NULL;
KBNODE kbctx, node;
size_t ndesc, descindex;
KEYDB_SEARCH_DESC *desc = NULL;
subkey_list_t subkey_list = NULL; /* Track already processed subkeys. */
KEYDB_HANDLE kdbhd;
strlist_t sl;
int indent = 0;
gcry_cipher_hd_t cipherhd = NULL;
*any = 0;
init_packet (&pkt);
kdbhd = keydb_new ();
if (!users)
{
ndesc = 1;
desc = xcalloc (ndesc, sizeof *desc);
desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
}
else
{
for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++)
;
desc = xmalloc ( ndesc * sizeof *desc);
for (ndesc=0, sl=users; sl; sl = sl->next)
{
if (!(err=classify_user_id (sl->d, desc+ndesc)))
ndesc++;
else
log_error (_("key \"%s\" not found: %s\n"),
sl->d, gpg_strerror (err));
}
/* It would be nice to see which of the given users did actually
match one in the keyring. To implement this we need to have
a found flag for each entry in desc. To set this flag we
must check all those entries after a match to mark all
matched one - currently we stop at the first match. To do
this we need an extra flag to enable this feature. */
}
#ifdef ENABLE_SELINUX_HACKS
if (secret)
{
log_error (_("exporting secret keys not allowed\n"));
err = gpg_error (GPG_ERR_NOT_SUPPORTED);
goto leave;
}
#endif
/* For secret key export we need to setup a decryption context. */
if (secret)
{
void *kek = NULL;
size_t keklen;
err = agent_keywrap_key (ctrl, 1, &kek, &keklen);
if (err)
{
log_error ("error getting the KEK: %s\n", gpg_strerror (err));
goto leave;
}
/* Prepare a cipher context. */
err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
GCRY_CIPHER_MODE_AESWRAP, 0);
if (!err)
err = gcry_cipher_setkey (cipherhd, kek, keklen);
if (err)
{
log_error ("error setting up an encryption context: %s\n",
gpg_strerror (err));
goto leave;
}
xfree (kek);
kek = NULL;
}
while (!(err = keydb_search2 (kdbhd, desc, ndesc, &descindex)))
{
int skip_until_subkey = 0;
u32 keyid[2];
PKT_public_key *pk;
if (!users)
desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
/* Read the keyblock. */
release_kbnode (keyblock);
keyblock = NULL;
err = keydb_get_keyblock (kdbhd, &keyblock);
if (err)
{
log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
goto leave;
}
node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
if (!node)
{
log_error ("public key packet not found in keyblock - skipped\n");
continue;
}
pk = node->pkt->pkt.public_key;
keyid_from_pk (pk, keyid);
/* If a secret key export is required we need to check whether
we have a secret key at all and if so create the seckey_info
structure. */
if (secret)
{
if (agent_probe_any_secret_key (ctrl, keyblock))
continue; /* No secret key (neither primary nor subkey). */
/* No v3 keys with GNU mode 1001. */
if (secret == 2 && pk->version == 3)
{
log_info (_("key %s: PGP 2.x style key - skipped\n"),
keystr (keyid));
continue;
}
/* The agent does not yet allow to export v3 packets. It is
actually questionable whether we should allow them at
all. */
if (pk->version == 3)
{
log_info ("key %s: PGP 2.x style key (v3) export "
"not yet supported - skipped\n", keystr (keyid));
continue;
}
}
/* Always do the cleaning on the public key part if requested.
Note that we don't yet set this option if we are exporting
secret keys. Note that both export-clean and export-minimal
only apply to UID sigs (0x10, 0x11, 0x12, and 0x13). A
designated revocation is never stripped, even with
export-minimal set. */
if ((options & EXPORT_CLEAN))
clean_key (keyblock, opt.verbose, (options&EXPORT_MINIMAL), NULL, NULL);
/* And write it. */
for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
{
if (skip_until_subkey)
{
if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
skip_until_subkey = 0;
else
continue;
}
/* We used to use comment packets, but not any longer. In
case we still have comments on a key, strip them here
before we call build_packet(). */
if (node->pkt->pkttype == PKT_COMMENT)
continue;
/* Make sure that ring_trust packets never get exported. */
if (node->pkt->pkttype == PKT_RING_TRUST)
continue;
/* If exact is set, then we only export what was requested
(plus the primary key, if the user didn't specifically
request it). */
if (desc[descindex].exact
&& node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
{
if (!exact_subkey_match_p (desc+descindex, node))
{
/* Before skipping this subkey, check whether any
other description wants an exact match on a
subkey and include that subkey into the output
too. Need to add this subkey to a list so that
it won't get processed a second time.
So the first step here is to check that list and
skip in any case if the key is in that list.
We need this whole mess because the import
function of GnuPG < 2.1 is not able to merge
secret keys and thus it is useless to output them
as two separate keys and have import merge them. */
if (subkey_in_list_p (subkey_list, node))
skip_until_subkey = 1; /* Already processed this one. */
else
{
size_t j;
for (j=0; j < ndesc; j++)
if (j != descindex && desc[j].exact
&& exact_subkey_match_p (desc+j, node))
break;
if (!(j < ndesc))
skip_until_subkey = 1; /* No other one matching. */
}
}
if(skip_until_subkey)
continue;
/* Mark this one as processed. */
{
subkey_list_t tmp = new_subkey_list_item (node);
tmp->next = subkey_list;
subkey_list = tmp;
}
}
if (node->pkt->pkttype == PKT_SIGNATURE)
{
/* Do not export packets which are marked as not
exportable. */
if (!(options&EXPORT_LOCAL_SIGS)
&& !node->pkt->pkt.signature->flags.exportable)
continue; /* not exportable */
/* Do not export packets with a "sensitive" revocation
key unless the user wants us to. Note that we do
export these when issuing the actual revocation
(see revoke.c). */
if (!(options&EXPORT_SENSITIVE_REVKEYS)
&& node->pkt->pkt.signature->revkey)
{
int i;
for (i=0;ipkt->pkt.signature->numrevkeys;i++)
if ( (node->pkt->pkt.signature->revkey[i]->class & 0x40))
break;
if (i < node->pkt->pkt.signature->numrevkeys)
continue;
}
}
/* Don't export attribs? */
if (!(options&EXPORT_ATTRIBUTES)
&& node->pkt->pkttype == PKT_USER_ID
&& node->pkt->pkt.user_id->attrib_data )
{
/* Skip until we get to something that is not an attrib
or a signature on an attrib */
while (kbctx->next && kbctx->next->pkt->pkttype==PKT_SIGNATURE)
kbctx = kbctx->next;
continue;
}
if (secret && (node->pkt->pkttype == PKT_PUBLIC_KEY
|| node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
{
u32 subkidbuf[2], *subkid;
char *hexgrip, *serialno;
pk = node->pkt->pkt.public_key;
if (node->pkt->pkttype == PKT_PUBLIC_KEY)
subkid = NULL;
else
{
keyid_from_pk (pk, subkidbuf);
subkid = subkidbuf;
}
if (pk->seckey_info)
{
log_error ("key %s: oops: seckey_info already set"
" - skipped\n", keystr_with_sub (keyid, subkid));
skip_until_subkey = 1;
continue;
}
err = hexkeygrip_from_pk (pk, &hexgrip);
if (err)
{
log_error ("key %s: error computing keygrip: %s"
" - skipped\n", keystr_with_sub (keyid, subkid),
gpg_strerror (err));
skip_until_subkey = 1;
err = 0;
continue;
}
if (secret == 2 && node->pkt->pkttype == PKT_PUBLIC_KEY)
{
/* We are asked not to export the secret parts of
the primary key. Make up an error code to create
the stub. */
err = GPG_ERR_NOT_FOUND;
serialno = NULL;
}
else
err = agent_get_keyinfo (ctrl, hexgrip, &serialno);
if ((!err && serialno)
&& secret == 2 && node->pkt->pkttype == PKT_PUBLIC_KEY)
{
/* It does not make sense to export a key with its
primary key on card using a non-key stub. Thus
we skip those keys when used with
--export-secret-subkeys. */
log_info (_("key %s: key material on-card - skipped\n"),
keystr_with_sub (keyid, subkid));
skip_until_subkey = 1;
}
else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND
|| (!err && serialno))
{
/* Create a key stub. */
struct seckey_info *ski;
const char *s;
pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
if (!ski)
{
err = gpg_error_from_syserror ();
xfree (hexgrip);
goto leave;
}
ski->is_protected = 1;
if (err)
ski->s2k.mode = 1001; /* GNU dummy (no secret key). */
else
{
ski->s2k.mode = 1002; /* GNU-divert-to-card. */
for (s=serialno; sizeof (ski->ivlen) && *s && s[1];
ski->ivlen++, s += 2)
ski->iv[ski->ivlen] = xtoi_2 (s);
}
if ((options&EXPORT_SEXP_FORMAT))
err = build_sexp (out, node->pkt, &indent);
else
err = build_packet (out, node->pkt);
}
else if (!err)
{
/* FIXME: Move this spaghetti code into a separate
function. */
unsigned char *wrappedkey = NULL;
size_t wrappedkeylen;
unsigned char *key = NULL;
size_t keylen, realkeylen;
gcry_sexp_t s_skey;
if (opt.verbose)
log_info ("key %s: asking agent for the secret parts\n",
keystr_with_sub (keyid, subkid));
err = agent_export_key (ctrl, hexgrip, "Key foo", NULL,
&wrappedkey, &wrappedkeylen);
if (err)
goto unwraperror;
if (wrappedkeylen < 24)
{
err = gpg_error (GPG_ERR_INV_LENGTH);
goto unwraperror;
}
keylen = wrappedkeylen - 8;
key = xtrymalloc_secure (keylen);
if (!key)
{
err = gpg_error_from_syserror ();
goto unwraperror;
}
err = gcry_cipher_decrypt (cipherhd, key, keylen,
wrappedkey, wrappedkeylen);
if (err)
goto unwraperror;
realkeylen = gcry_sexp_canon_len (key, keylen, NULL, &err);
if (!realkeylen)
goto unwraperror; /* Invalid csexp. */
err = gcry_sexp_sscan (&s_skey, NULL, key, realkeylen);
xfree (key);
key = NULL;
if (err)
goto unwraperror;
err = transfer_format_to_openpgp (s_skey, pk);
gcry_sexp_release (s_skey);
if (err)
goto unwraperror;
if ((options&EXPORT_SEXP_FORMAT))
err = build_sexp (out, node->pkt, &indent);
else
err = build_packet (out, node->pkt);
goto unwraperror_leave;
unwraperror:
xfree (wrappedkey);
xfree (key);
if (err)
{
log_error ("key %s: error receiving key from agent:"
" %s%s\n",
keystr_with_sub (keyid, subkid),
gpg_strerror (err),
gpg_err_code (err) == GPG_ERR_FULLY_CANCELED?
"":_(" - skipped"));
if (gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
goto leave;
skip_until_subkey = 1;
err = 0;
}
unwraperror_leave:
;
}
else
{
log_error ("key %s: error getting keyinfo from agent: %s"
" - skipped\n", keystr_with_sub (keyid, subkid),
gpg_strerror (err));
skip_until_subkey = 1;
err = 0;
}
xfree (pk->seckey_info);
pk->seckey_info = NULL;
xfree (hexgrip);
}
else
{
if ((options&EXPORT_SEXP_FORMAT))
err = build_sexp (out, node->pkt, &indent);
else
err = build_packet (out, node->pkt);
}
if (err)
{
log_error ("build_packet(%d) failed: %s\n",
node->pkt->pkttype, gpg_strerror (err));
goto leave;
}
if (!skip_until_subkey)
*any = 1;
}
if ((options&EXPORT_SEXP_FORMAT) && indent)
{
for (; indent; indent--)
iobuf_put (out, ')');
iobuf_put (out, '\n');
}
if (keyblock_out)
{
*keyblock_out = keyblock;
break;
}
}
if ((options&EXPORT_SEXP_FORMAT) && indent)
{
for (; indent; indent--)
iobuf_put (out, ')');
iobuf_put (out, '\n');
}
if (err == -1)
err = 0;
leave:
gcry_cipher_close (cipherhd);
release_subkey_list (subkey_list);
xfree(desc);
keydb_release (kdbhd);
if (err || !keyblock_out)
release_kbnode( keyblock );
if( !*any )
log_info(_("WARNING: nothing exported\n"));
return err;
}
/* static int */
/* write_sexp_line (iobuf_t out, int *indent, const char *text) */
/* { */
/* int i; */
/* for (i=0; i < *indent; i++) */
/* iobuf_put (out, ' '); */
/* iobuf_writestr (out, text); */
/* return 0; */
/* } */
/* static int */
/* write_sexp_keyparm (iobuf_t out, int *indent, const char *name, gcry_mpi_t a) */
/* { */
/* int rc; */
/* unsigned char *buffer; */
/* write_sexp_line (out, indent, "("); */
/* iobuf_writestr (out, name); */
/* iobuf_writestr (out, " #"); */
/* rc = gcry_mpi_aprint (GCRYMPI_FMT_HEX, &buffer, NULL, a); */
/* assert (!rc); */
/* iobuf_writestr (out, buffer); */
/* iobuf_writestr (out, "#)"); */
/* gcry_free (buffer); */
/* return 0; */
/* } */
static int
build_sexp_seckey (iobuf_t out, PACKET *pkt, int *indent)
{
(void)out;
(void)pkt;
(void)indent;
/* FIXME: Not yet implemented. */
return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
/* PKT_secret_key *sk = pkt->pkt.secret_key; */
/* char tmpbuf[100]; */
/* if (pkt->pkttype == PKT_SECRET_KEY) */
/* { */
/* iobuf_writestr (out, "(openpgp-key\n"); */
/* (*indent)++; */
/* } */
/* else */
/* { */
/* iobuf_writestr (out, " (subkey\n"); */
/* (*indent)++; */
/* } */
/* (*indent)++; */
/* write_sexp_line (out, indent, "(private-key\n"); */
/* (*indent)++; */
/* if (is_RSA (sk->pubkey_algo) && !sk->is_protected) */
/* { */
/* write_sexp_line (out, indent, "(rsa\n"); */
/* (*indent)++; */
/* write_sexp_keyparm (out, indent, "n", sk->skey[0]); iobuf_put (out,'\n'); */
/* write_sexp_keyparm (out, indent, "e", sk->skey[1]); iobuf_put (out,'\n'); */
/* write_sexp_keyparm (out, indent, "d", sk->skey[2]); iobuf_put (out,'\n'); */
/* write_sexp_keyparm (out, indent, "p", sk->skey[3]); iobuf_put (out,'\n'); */
/* write_sexp_keyparm (out, indent, "q", sk->skey[4]); iobuf_put (out,'\n'); */
/* write_sexp_keyparm (out, indent, "u", sk->skey[5]); */
/* iobuf_put (out,')'); iobuf_put (out,'\n'); */
/* (*indent)--; */
/* } */
/* else if (sk->pubkey_algo == PUBKEY_ALGO_DSA && !sk->is_protected) */
/* { */
/* write_sexp_line (out, indent, "(dsa\n"); */
/* (*indent)++; */
/* write_sexp_keyparm (out, indent, "p", sk->skey[0]); iobuf_put (out,'\n'); */
/* write_sexp_keyparm (out, indent, "q", sk->skey[1]); iobuf_put (out,'\n'); */
/* write_sexp_keyparm (out, indent, "g", sk->skey[2]); iobuf_put (out,'\n'); */
/* write_sexp_keyparm (out, indent, "y", sk->skey[3]); iobuf_put (out,'\n'); */
/* write_sexp_keyparm (out, indent, "x", sk->skey[4]); */
/* iobuf_put (out,')'); iobuf_put (out,'\n'); */
/* (*indent)--; */
/* } */
+/*
+ else if (sk->pubkey_algo == PUBKEY_ALGO_ECDSA && !sk->is_protected)
+ {
+ write_sexp_line (out, indent, "(ecdsa\n");
+ (*indent)++;
+ write_sexp_keyparm (out, indent, "c", sk->skey[0]); iobuf_put (out,'\n');
+ write_sexp_keyparm (out, indent, "q", sk->skey[6]); iobuf_put (out,'\n');
+ write_sexp_keyparm (out, indent, "d", sk->skey[7]);
+ iobuf_put (out,')'); iobuf_put (out,'\n');
+ (*indent)--;
+ }
+*/
/* else if (is_ELGAMAL (sk->pubkey_algo) && !sk->is_protected) */
/* { */
/* write_sexp_line (out, indent, "(elg\n"); */
/* (*indent)++; */
/* write_sexp_keyparm (out, indent, "p", sk->skey[0]); iobuf_put (out,'\n'); */
/* write_sexp_keyparm (out, indent, "g", sk->skey[2]); iobuf_put (out,'\n'); */
/* write_sexp_keyparm (out, indent, "y", sk->skey[3]); iobuf_put (out,'\n'); */
/* write_sexp_keyparm (out, indent, "x", sk->skey[4]); */
/* iobuf_put (out,')'); iobuf_put (out,'\n'); */
/* (*indent)--; */
/* } */
/* write_sexp_line (out, indent, "(attrib\n"); (*indent)++; */
/* sprintf (tmpbuf, "(created \"%lu\"", (unsigned long)sk->timestamp); */
/* write_sexp_line (out, indent, tmpbuf); */
/* iobuf_put (out,')'); (*indent)--; /\* close created *\/ */
/* iobuf_put (out,')'); (*indent)--; /\* close attrib *\/ */
/* iobuf_put (out,')'); (*indent)--; /\* close private-key *\/ */
/* if (pkt->pkttype != PKT_SECRET_KEY) */
/* iobuf_put (out,')'), (*indent)--; /\* close subkey *\/ */
/* iobuf_put (out,'\n'); */
/* return 0; */
}
/* For some packet types we write them in a S-expression format. This
is still EXPERIMENTAL and subject to change. */
static int
build_sexp (iobuf_t out, PACKET *pkt, int *indent)
{
int rc;
switch (pkt->pkttype)
{
case PKT_SECRET_KEY:
case PKT_SECRET_SUBKEY:
rc = build_sexp_seckey (out, pkt, indent);
break;
default:
rc = 0;
break;
}
return rc;
}
diff --git a/g10/getkey.c b/g10/getkey.c
index f114920d2..65f5829dc 100644
--- a/g10/getkey.c
+++ b/g10/getkey.c
@@ -1,3048 +1,3051 @@
/* getkey.c - Get a key from the database
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
* 2007, 2008, 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
* 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
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include
#include "gpg.h"
#include "util.h"
#include "packet.h"
#include "iobuf.h"
#include "keydb.h"
#include "options.h"
#include "main.h"
#include "trustdb.h"
#include "i18n.h"
#include "keyserver-internal.h"
#include "call-agent.h"
#define MAX_PK_CACHE_ENTRIES PK_UID_CACHE_SIZE
#define MAX_UID_CACHE_ENTRIES PK_UID_CACHE_SIZE
#if MAX_PK_CACHE_ENTRIES < 2
#error We need the cache for key creation
#endif
struct getkey_ctx_s
{
int exact;
int want_secret; /* The caller requested only secret keys. */
KBNODE keyblock;
KBPOS kbpos;
KBNODE found_key; /* Pointer into some keyblock. */
strlist_t extra_list; /* Will be freed when releasing the context. */
int last_rc;
int req_usage;
int req_algo;
KEYDB_HANDLE kr_handle;
int not_allocated;
int nitems;
KEYDB_SEARCH_DESC items[1];
};
#if 0
static struct
{
int any;
int okay_count;
int nokey_count;
int error_count;
} lkup_stats[21];
#endif
typedef struct keyid_list
{
struct keyid_list *next;
u32 keyid[2];
} *keyid_list_t;
#if MAX_PK_CACHE_ENTRIES
typedef struct pk_cache_entry
{
struct pk_cache_entry *next;
u32 keyid[2];
PKT_public_key *pk;
} *pk_cache_entry_t;
static pk_cache_entry_t pk_cache;
static int pk_cache_entries; /* Number of entries in pk cache. */
static int pk_cache_disabled;
#endif
#if MAX_UID_CACHE_ENTRIES < 5
#error we really need the userid cache
#endif
typedef struct user_id_db
{
struct user_id_db *next;
keyid_list_t keyids;
int len;
char name[1];
} *user_id_db_t;
static user_id_db_t user_id_db;
static int uid_cache_entries; /* Number of entries in uid cache. */
static void merge_selfsigs (kbnode_t keyblock);
static int lookup (getkey_ctx_t ctx, kbnode_t *ret_keyblock, int want_secret);
#if 0
static void
print_stats ()
{
int i;
for (i = 0; i < DIM (lkup_stats); i++)
{
if (lkup_stats[i].any)
fprintf (stderr,
"lookup stats: mode=%-2d ok=%-6d nokey=%-6d err=%-6d\n",
i,
lkup_stats[i].okay_count,
lkup_stats[i].nokey_count, lkup_stats[i].error_count);
}
}
#endif
void
cache_public_key (PKT_public_key * pk)
{
#if MAX_PK_CACHE_ENTRIES
pk_cache_entry_t ce;
u32 keyid[2];
if (pk_cache_disabled)
return;
if (pk->flags.dont_cache)
return;
if (is_ELGAMAL (pk->pubkey_algo)
- || pk->pubkey_algo == PUBKEY_ALGO_DSA || is_RSA (pk->pubkey_algo))
+ || pk->pubkey_algo == PUBKEY_ALGO_DSA
+ || pk->pubkey_algo == PUBKEY_ALGO_ECDSA
+ || pk->pubkey_algo == PUBKEY_ALGO_ECDH
+ || is_RSA (pk->pubkey_algo))
{
keyid_from_pk (pk, keyid);
}
else
return; /* Don't know how to get the keyid. */
for (ce = pk_cache; ce; ce = ce->next)
if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
{
if (DBG_CACHE)
log_debug ("cache_public_key: already in cache\n");
return;
}
if (pk_cache_entries >= MAX_PK_CACHE_ENTRIES)
{
/* fixme: Use another algorithm to free some cache slots. */
pk_cache_disabled = 1;
if (opt.verbose > 1)
log_info (_("too many entries in pk cache - disabled\n"));
return;
}
pk_cache_entries++;
ce = xmalloc (sizeof *ce);
ce->next = pk_cache;
pk_cache = ce;
ce->pk = copy_public_key (NULL, pk);
ce->keyid[0] = keyid[0];
ce->keyid[1] = keyid[1];
#endif
}
/* Return a const utf-8 string with the text "[User ID not found]".
This function is required so that we don't need to switch gettext's
encoding temporary. */
static const char *
user_id_not_found_utf8 (void)
{
static char *text;
if (!text)
text = native_to_utf8 (_("[User ID not found]"));
return text;
}
/* Return the user ID from the given keyblock.
* We use the primary uid flag which has been set by the merge_selfsigs
* function. The returned value is only valid as long as then given
* keyblock is not changed. */
static const char *
get_primary_uid (KBNODE keyblock, size_t * uidlen)
{
KBNODE k;
const char *s;
for (k = keyblock; k; k = k->next)
{
if (k->pkt->pkttype == PKT_USER_ID
&& !k->pkt->pkt.user_id->attrib_data
&& k->pkt->pkt.user_id->is_primary)
{
*uidlen = k->pkt->pkt.user_id->len;
return k->pkt->pkt.user_id->name;
}
}
s = user_id_not_found_utf8 ();
*uidlen = strlen (s);
return s;
}
static void
release_keyid_list (keyid_list_t k)
{
while (k)
{
keyid_list_t k2 = k->next;
xfree (k);
k = k2;
}
}
/****************
* Store the association of keyid and userid
* Feed only public keys to this function.
*/
static void
cache_user_id (KBNODE keyblock)
{
user_id_db_t r;
const char *uid;
size_t uidlen;
keyid_list_t keyids = NULL;
KBNODE k;
for (k = keyblock; k; k = k->next)
{
if (k->pkt->pkttype == PKT_PUBLIC_KEY
|| k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
{
keyid_list_t a = xmalloc_clear (sizeof *a);
/* Hmmm: For a long list of keyids it might be an advantage
* to append the keys. */
keyid_from_pk (k->pkt->pkt.public_key, a->keyid);
/* First check for duplicates. */
for (r = user_id_db; r; r = r->next)
{
keyid_list_t b = r->keyids;
for (b = r->keyids; b; b = b->next)
{
if (b->keyid[0] == a->keyid[0]
&& b->keyid[1] == a->keyid[1])
{
if (DBG_CACHE)
log_debug ("cache_user_id: already in cache\n");
release_keyid_list (keyids);
xfree (a);
return;
}
}
}
/* Now put it into the cache. */
a->next = keyids;
keyids = a;
}
}
if (!keyids)
BUG (); /* No key no fun. */
uid = get_primary_uid (keyblock, &uidlen);
if (uid_cache_entries >= MAX_UID_CACHE_ENTRIES)
{
/* fixme: use another algorithm to free some cache slots */
r = user_id_db;
user_id_db = r->next;
release_keyid_list (r->keyids);
xfree (r);
uid_cache_entries--;
}
r = xmalloc (sizeof *r + uidlen - 1);
r->keyids = keyids;
r->len = uidlen;
memcpy (r->name, uid, r->len);
r->next = user_id_db;
user_id_db = r;
uid_cache_entries++;
}
void
getkey_disable_caches ()
{
#if MAX_PK_CACHE_ENTRIES
{
pk_cache_entry_t ce, ce2;
for (ce = pk_cache; ce; ce = ce2)
{
ce2 = ce->next;
free_public_key (ce->pk);
xfree (ce);
}
pk_cache_disabled = 1;
pk_cache_entries = 0;
pk_cache = NULL;
}
#endif
/* fixme: disable user id cache ? */
}
static void
pk_from_block (GETKEY_CTX ctx, PKT_public_key * pk, KBNODE keyblock)
{
KBNODE a = ctx->found_key ? ctx->found_key : keyblock;
assert (a->pkt->pkttype == PKT_PUBLIC_KEY
|| a->pkt->pkttype == PKT_PUBLIC_SUBKEY);
copy_public_key (pk, a->pkt->pkt.public_key);
}
/* Get a public key and store it into the allocated pk can be called
* with PK set to NULL to just read it into some internal
* structures. */
int
get_pubkey (PKT_public_key * pk, u32 * keyid)
{
int internal = 0;
int rc = 0;
#if MAX_PK_CACHE_ENTRIES
if (pk)
{
/* Try to get it from the cache. We don't do this when pk is
NULL as it does not guarantee that the user IDs are
cached. */
pk_cache_entry_t ce;
for (ce = pk_cache; ce; ce = ce->next)
{
if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
{
copy_public_key (pk, ce->pk);
return 0;
}
}
}
#endif
/* More init stuff. */
if (!pk)
{
pk = xmalloc_clear (sizeof *pk);
internal++;
}
/* Do a lookup. */
{
struct getkey_ctx_s ctx;
KBNODE kb = NULL;
memset (&ctx, 0, sizeof ctx);
ctx.exact = 1; /* Use the key ID exactly as given. */
ctx.not_allocated = 1;
ctx.kr_handle = keydb_new ();
ctx.nitems = 1;
ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
ctx.items[0].u.kid[0] = keyid[0];
ctx.items[0].u.kid[1] = keyid[1];
ctx.req_algo = pk->req_algo;
ctx.req_usage = pk->req_usage;
rc = lookup (&ctx, &kb, 0);
if (!rc)
{
pk_from_block (&ctx, pk, kb);
}
get_pubkey_end (&ctx);
release_kbnode (kb);
}
if (!rc)
goto leave;
rc = G10ERR_NO_PUBKEY;
leave:
if (!rc)
cache_public_key (pk);
if (internal)
free_public_key (pk);
return rc;
}
/* Get a public key and store it into the allocated pk. This function
differs from get_pubkey() in that it does not do a check of the key
to avoid recursion. It should be used only in very certain cases.
It will only retrieve primary keys. */
int
get_pubkey_fast (PKT_public_key * pk, u32 * keyid)
{
int rc = 0;
KEYDB_HANDLE hd;
KBNODE keyblock;
u32 pkid[2];
assert (pk);
#if MAX_PK_CACHE_ENTRIES
{
/* Try to get it from the cache */
pk_cache_entry_t ce;
for (ce = pk_cache; ce; ce = ce->next)
{
if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
{
if (pk)
copy_public_key (pk, ce->pk);
return 0;
}
}
}
#endif
hd = keydb_new ();
rc = keydb_search_kid (hd, keyid);
if (rc == -1)
{
keydb_release (hd);
return G10ERR_NO_PUBKEY;
}
rc = keydb_get_keyblock (hd, &keyblock);
keydb_release (hd);
if (rc)
{
log_error ("keydb_get_keyblock failed: %s\n", g10_errstr (rc));
return G10ERR_NO_PUBKEY;
}
assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
|| keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY);
keyid_from_pk (keyblock->pkt->pkt.public_key, pkid);
if (keyid[0] == pkid[0] && keyid[1] == pkid[1])
copy_public_key (pk, keyblock->pkt->pkt.public_key);
else
rc = G10ERR_NO_PUBKEY;
release_kbnode (keyblock);
/* Not caching key here since it won't have all of the fields
properly set. */
return rc;
}
KBNODE
get_pubkeyblock (u32 * keyid)
{
struct getkey_ctx_s ctx;
int rc = 0;
KBNODE keyblock = NULL;
memset (&ctx, 0, sizeof ctx);
/* No need to set exact here because we want the entire block. */
ctx.not_allocated = 1;
ctx.kr_handle = keydb_new ();
ctx.nitems = 1;
ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
ctx.items[0].u.kid[0] = keyid[0];
ctx.items[0].u.kid[1] = keyid[1];
rc = lookup (&ctx, &keyblock, 0);
get_pubkey_end (&ctx);
return rc ? NULL : keyblock;
}
/*
* Get a public key and store it into PK. This functions check that a
* corresponding secret key is available. With no secret key it does
* not succeeed.
*/
gpg_error_t
get_seckey (PKT_public_key *pk, u32 *keyid)
{
gpg_error_t err;
struct getkey_ctx_s ctx;
kbnode_t keyblock = NULL;
memset (&ctx, 0, sizeof ctx);
ctx.exact = 1; /* Use the key ID exactly as given. */
ctx.not_allocated = 1;
ctx.kr_handle = keydb_new ();
ctx.nitems = 1;
ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
ctx.items[0].u.kid[0] = keyid[0];
ctx.items[0].u.kid[1] = keyid[1];
ctx.req_algo = pk->req_algo;
ctx.req_usage = pk->req_usage;
err = lookup (&ctx, &keyblock, 1);
if (!err)
{
pk_from_block (&ctx, pk, keyblock);
}
get_pubkey_end (&ctx);
release_kbnode (keyblock);
if (!err)
err = agent_probe_secret_key (/*ctrl*/NULL, pk);
return err;
}
static int
skip_unusable (void *dummy, u32 * keyid, PKT_user_id * uid)
{
int unusable = 0;
KBNODE keyblock;
(void) dummy;
keyblock = get_pubkeyblock (keyid);
if (!keyblock)
{
log_error ("error checking usability status of %s\n", keystr (keyid));
goto leave;
}
/* Is the user ID in question revoked/expired? */
if (uid)
{
KBNODE node;
for (node = keyblock; node; node = node->next)
{
if (node->pkt->pkttype == PKT_USER_ID)
{
if (cmp_user_ids (uid, node->pkt->pkt.user_id) == 0
&& (node->pkt->pkt.user_id->is_revoked
|| node->pkt->pkt.user_id->is_expired))
{
unusable = 1;
break;
}
}
}
}
if (!unusable)
unusable = pk_is_disabled (keyblock->pkt->pkt.public_key);
leave:
release_kbnode (keyblock);
return unusable;
}
/* Try to get the pubkey by the userid. This function looks for the
* first pubkey certificate which has the given name in a user_id. If
* PK has the pubkey algo set, the function will only return a pubkey
* with that algo. If NAMELIST is NULL, the first key is returned.
* The caller should provide storage for the PK or pass NULL if it is
* not needed. If RET_KB is not NULL the function stores the entire
* keyblock at that address. */
static int
key_byname (GETKEY_CTX *retctx, strlist_t namelist,
PKT_public_key *pk,
int want_secret, int include_unusable,
KBNODE * ret_kb, KEYDB_HANDLE * ret_kdbhd)
{
int rc = 0;
int n;
strlist_t r;
GETKEY_CTX ctx;
KBNODE help_kb = NULL;
if (retctx)
{
/* Reset the returned context in case of error. */
assert (!ret_kdbhd); /* Not allowed because the handle is stored
in the context. */
*retctx = NULL;
}
if (ret_kdbhd)
*ret_kdbhd = NULL;
if (!namelist)
{
ctx = xmalloc_clear (sizeof *ctx);
ctx->nitems = 1;
ctx->items[0].mode = KEYDB_SEARCH_MODE_FIRST;
if (!include_unusable)
ctx->items[0].skipfnc = skip_unusable;
}
else
{
/* Build the search context. */
for (n = 0, r = namelist; r; r = r->next)
n++;
ctx = xmalloc_clear (sizeof *ctx + (n - 1) * sizeof ctx->items);
ctx->nitems = n;
for (n = 0, r = namelist; r; r = r->next, n++)
{
gpg_error_t err;
err = classify_user_id (r->d, &ctx->items[n]);
if (ctx->items[n].exact)
ctx->exact = 1;
if (err)
{
xfree (ctx);
return gpg_err_code (err); /* FIXME: remove gpg_err_code. */
}
if (!include_unusable
&& ctx->items[n].mode != KEYDB_SEARCH_MODE_SHORT_KID
&& ctx->items[n].mode != KEYDB_SEARCH_MODE_LONG_KID
&& ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR16
&& ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR20
&& ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR)
ctx->items[n].skipfnc = skip_unusable;
}
}
ctx->want_secret = want_secret;
ctx->kr_handle = keydb_new ();
if (!ret_kb)
ret_kb = &help_kb;
if (pk)
{
ctx->req_algo = pk->req_algo;
ctx->req_usage = pk->req_usage;
}
rc = lookup (ctx, ret_kb, want_secret);
if (!rc && pk)
{
pk_from_block (ctx, pk, *ret_kb);
}
release_kbnode (help_kb);
if (retctx) /* Caller wants the context. */
*retctx = ctx;
else
{
if (ret_kdbhd)
{
*ret_kdbhd = ctx->kr_handle;
ctx->kr_handle = NULL;
}
get_pubkey_end (ctx);
}
return rc;
}
/* Find a public key from NAME and return the keyblock or the key. If
ret_kdb is not NULL, the KEYDB handle used to locate this keyblock
is returned and the caller is responsible for closing it. If a key
was not found (or if local search has been disabled) and NAME is a
valid RFC822 mailbox and --auto-key-locate has been enabled, we try
to import the key via the online mechanisms defined by
--auto-key-locate. */
int
get_pubkey_byname (ctrl_t ctrl, GETKEY_CTX * retctx, PKT_public_key * pk,
const char *name, KBNODE * ret_keyblock,
KEYDB_HANDLE * ret_kdbhd, int include_unusable, int no_akl)
{
int rc;
strlist_t namelist = NULL;
struct akl *akl;
int is_mbox;
int nodefault = 0;
int anylocalfirst = 0;
if (retctx)
*retctx = NULL;
is_mbox = is_valid_mailbox (name);
/* Check whether we the default local search has been disabled.
This is the case if either the "nodefault" or the "local" keyword
are in the list of auto key locate mechanisms.
ANYLOCALFIRST is set if the search order has the local method
before any other or if "local" is used first by default. This
makes sure that if a RETCTX is used it gets only set if a local
search has precedence over the other search methods and only then
a followup call to get_pubkey_next shall succeed. */
if (!no_akl)
{
for (akl = opt.auto_key_locate; akl; akl = akl->next)
if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL)
{
nodefault = 1;
break;
}
for (akl = opt.auto_key_locate; akl; akl = akl->next)
if (akl->type != AKL_NODEFAULT)
{
if (akl->type == AKL_LOCAL)
anylocalfirst = 1;
break;
}
}
if (!nodefault)
anylocalfirst = 1;
if (nodefault && is_mbox)
{
/* Nodefault but a mailbox - let the AKL locate the key. */
rc = G10ERR_NO_PUBKEY;
}
else
{
add_to_strlist (&namelist, name);
rc = key_byname (retctx, namelist, pk, 0,
include_unusable, ret_keyblock, ret_kdbhd);
}
/* If the requested name resembles a valid mailbox and automatic
retrieval has been enabled, we try to import the key. */
if (gpg_err_code (rc) == G10ERR_NO_PUBKEY && !no_akl && is_mbox)
{
for (akl = opt.auto_key_locate; akl; akl = akl->next)
{
unsigned char *fpr = NULL;
size_t fpr_len;
int did_key_byname = 0;
int no_fingerprint = 0;
const char *mechanism = "?";
switch (akl->type)
{
case AKL_NODEFAULT:
/* This is a dummy mechanism. */
mechanism = "None";
rc = G10ERR_NO_PUBKEY;
break;
case AKL_LOCAL:
mechanism = "Local";
did_key_byname = 1;
if (retctx)
{
get_pubkey_end (*retctx);
*retctx = NULL;
}
add_to_strlist (&namelist, name);
rc = key_byname (anylocalfirst ? retctx : NULL,
namelist, pk, 0,
include_unusable, ret_keyblock, ret_kdbhd);
break;
case AKL_CERT:
mechanism = "DNS CERT";
glo_ctrl.in_auto_key_retrieve++;
rc = keyserver_import_cert (ctrl, name, &fpr, &fpr_len);
glo_ctrl.in_auto_key_retrieve--;
break;
case AKL_PKA:
mechanism = "PKA";
glo_ctrl.in_auto_key_retrieve++;
rc = keyserver_import_pka (ctrl, name, &fpr, &fpr_len);
glo_ctrl.in_auto_key_retrieve--;
break;
case AKL_LDAP:
mechanism = "LDAP";
glo_ctrl.in_auto_key_retrieve++;
rc = keyserver_import_ldap (ctrl, name, &fpr, &fpr_len);
glo_ctrl.in_auto_key_retrieve--;
break;
case AKL_KEYSERVER:
/* Strictly speaking, we don't need to only use a valid
mailbox for the getname search, but it helps cut down
on the problem of searching for something like "john"
and getting a whole lot of keys back. */
if (opt.keyserver)
{
mechanism = opt.keyserver->uri;
glo_ctrl.in_auto_key_retrieve++;
rc = keyserver_import_name (ctrl, name, &fpr, &fpr_len,
opt.keyserver);
glo_ctrl.in_auto_key_retrieve--;
}
else
{
mechanism = "Unconfigured keyserver";
rc = G10ERR_NO_PUBKEY;
}
break;
case AKL_SPEC:
{
struct keyserver_spec *keyserver;
mechanism = akl->spec->uri;
keyserver = keyserver_match (akl->spec);
glo_ctrl.in_auto_key_retrieve++;
rc = keyserver_import_name (ctrl,
name, &fpr, &fpr_len, keyserver);
glo_ctrl.in_auto_key_retrieve--;
}
break;
}
/* Use the fingerprint of the key that we actually fetched.
This helps prevent problems where the key that we fetched
doesn't have the same name that we used to fetch it. In
the case of CERT and PKA, this is an actual security
requirement as the URL might point to a key put in by an
attacker. By forcing the use of the fingerprint, we
won't use the attacker's key here. */
if (!rc && fpr)
{
char fpr_string[MAX_FINGERPRINT_LEN * 2 + 1];
assert (fpr_len <= MAX_FINGERPRINT_LEN);
free_strlist (namelist);
namelist = NULL;
bin2hex (fpr, fpr_len, fpr_string);
if (opt.verbose)
log_info ("auto-key-locate found fingerprint %s\n",
fpr_string);
add_to_strlist (&namelist, fpr_string);
}
else if (!rc && !fpr && !did_key_byname)
{
no_fingerprint = 1;
rc = G10ERR_NO_PUBKEY;
}
xfree (fpr);
fpr = NULL;
if (!rc && !did_key_byname)
{
if (retctx)
{
get_pubkey_end (*retctx);
*retctx = NULL;
}
rc = key_byname (anylocalfirst ? retctx : NULL,
namelist, pk, 0,
include_unusable, ret_keyblock, ret_kdbhd);
}
if (!rc)
{
/* Key found. */
log_info (_("automatically retrieved `%s' via %s\n"),
name, mechanism);
break;
}
if (rc != G10ERR_NO_PUBKEY || opt.verbose || no_fingerprint)
log_info (_("error retrieving `%s' via %s: %s\n"),
name, mechanism,
no_fingerprint ? _("No fingerprint") : g10_errstr (rc));
}
}
if (rc && retctx)
{
get_pubkey_end (*retctx);
*retctx = NULL;
}
if (retctx && *retctx)
{
assert (!(*retctx)->extra_list);
(*retctx)->extra_list = namelist;
}
else
free_strlist (namelist);
return rc;
}
int
get_pubkey_bynames (GETKEY_CTX * retctx, PKT_public_key * pk,
strlist_t names, KBNODE * ret_keyblock)
{
return key_byname (retctx, names, pk, 0, 1, ret_keyblock, NULL);
}
int
get_pubkey_next (GETKEY_CTX ctx, PKT_public_key * pk, KBNODE * ret_keyblock)
{
int rc;
rc = lookup (ctx, ret_keyblock, 0);
if (!rc && pk && ret_keyblock)
pk_from_block (ctx, pk, *ret_keyblock);
return rc;
}
void
get_pubkey_end (GETKEY_CTX ctx)
{
if (ctx)
{
memset (&ctx->kbpos, 0, sizeof ctx->kbpos);
keydb_release (ctx->kr_handle);
free_strlist (ctx->extra_list);
if (!ctx->not_allocated)
xfree (ctx);
}
}
/* Search for a key with the given fingerprint.
* FIXME:
* We should replace this with the _byname function. This can be done
* by creating a userID conforming to the unified fingerprint style.
*/
int
get_pubkey_byfprint (PKT_public_key * pk,
const byte * fprint, size_t fprint_len)
{
int rc;
if (fprint_len == 20 || fprint_len == 16)
{
struct getkey_ctx_s ctx;
KBNODE kb = NULL;
memset (&ctx, 0, sizeof ctx);
ctx.exact = 1;
ctx.not_allocated = 1;
ctx.kr_handle = keydb_new ();
ctx.nitems = 1;
ctx.items[0].mode = fprint_len == 16 ? KEYDB_SEARCH_MODE_FPR16
: KEYDB_SEARCH_MODE_FPR20;
memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
rc = lookup (&ctx, &kb, 0);
if (!rc && pk)
pk_from_block (&ctx, pk, kb);
release_kbnode (kb);
get_pubkey_end (&ctx);
}
else
rc = G10ERR_GENERAL; /* Oops */
return rc;
}
/* Get a public key and store it into the allocated pk. This function
differs from get_pubkey_byfprint() in that it does not do a check
of the key to avoid recursion. It should be used only in very
certain cases. PK may be NULL to check just for the existance of
the key. */
int
get_pubkey_byfprint_fast (PKT_public_key * pk,
const byte * fprint, size_t fprint_len)
{
int rc = 0;
KEYDB_HANDLE hd;
KBNODE keyblock;
byte fprbuf[MAX_FINGERPRINT_LEN];
int i;
for (i = 0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
fprbuf[i] = fprint[i];
while (i < MAX_FINGERPRINT_LEN)
fprbuf[i++] = 0;
hd = keydb_new ();
rc = keydb_search_fpr (hd, fprbuf);
if (rc == -1)
{
keydb_release (hd);
return G10ERR_NO_PUBKEY;
}
rc = keydb_get_keyblock (hd, &keyblock);
keydb_release (hd);
if (rc)
{
log_error ("keydb_get_keyblock failed: %s\n", g10_errstr (rc));
return G10ERR_NO_PUBKEY;
}
assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
|| keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY);
if (pk)
copy_public_key (pk, keyblock->pkt->pkt.public_key);
release_kbnode (keyblock);
/* Not caching key here since it won't have all of the fields
properly set. */
return 0;
}
/* Search for a key with the given fingerprint and return the
* complete keyblock which may have more than only this key. */
int
get_keyblock_byfprint (KBNODE * ret_keyblock, const byte * fprint,
size_t fprint_len)
{
int rc;
if (fprint_len == 20 || fprint_len == 16)
{
struct getkey_ctx_s ctx;
memset (&ctx, 0, sizeof ctx);
ctx.not_allocated = 1;
ctx.kr_handle = keydb_new ();
ctx.nitems = 1;
ctx.items[0].mode = (fprint_len == 16
? KEYDB_SEARCH_MODE_FPR16
: KEYDB_SEARCH_MODE_FPR20);
memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
rc = lookup (&ctx, ret_keyblock, 0);
get_pubkey_end (&ctx);
}
else
rc = G10ERR_GENERAL; /* Oops */
return rc;
}
/* Get a secret key by NAME and store it into PK. If NAME is NULL use
* the default key. This functions checks that a corresponding secret
* key is available. With no secret key it does not succeeed. */
gpg_error_t
get_seckey_byname (PKT_public_key *pk, const char *name)
{
gpg_error_t err;
strlist_t namelist = NULL;
int include_unusable = 1;
/* If we have no name, try to use the default secret key. If we
have no default, we'll use the first usable one. */
if (!name && opt.def_secret_key && *opt.def_secret_key)
add_to_strlist (&namelist, opt.def_secret_key);
else if (name)
add_to_strlist (&namelist, name);
else
include_unusable = 0;
err = key_byname (NULL, namelist, pk, 1, include_unusable, NULL, NULL);
free_strlist (namelist);
return err;
}
/* Search for a key with the given fingerprint.
* FIXME:
* We should replace this with the _byname function. This can be done
* by creating a userID conforming to the unified fingerprint style. */
gpg_error_t
get_seckey_byfprint (PKT_public_key *pk, const byte * fprint, size_t fprint_len)
{
gpg_error_t err;
if (fprint_len == 20 || fprint_len == 16)
{
struct getkey_ctx_s ctx;
kbnode_t kb = NULL;
memset (&ctx, 0, sizeof ctx);
ctx.exact = 1;
ctx.not_allocated = 1;
ctx.kr_handle = keydb_new ();
ctx.nitems = 1;
ctx.items[0].mode = fprint_len == 16 ? KEYDB_SEARCH_MODE_FPR16
: KEYDB_SEARCH_MODE_FPR20;
memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
err = lookup (&ctx, &kb, 1);
if (!err && pk)
pk_from_block (&ctx, pk, kb);
release_kbnode (kb);
get_pubkey_end (&ctx);
}
else
err = gpg_error (GPG_ERR_BUG);
return err;
}
/* Search for a secret key with the given fingerprint and return the
complete keyblock which may have more than only this key. Return
an error if no corresponding secret key is available. */
gpg_error_t
get_seckeyblock_byfprint (kbnode_t *ret_keyblock,
const byte *fprint, size_t fprint_len)
{
gpg_error_t err;
struct getkey_ctx_s ctx;
if (fprint_len != 20 && fprint_len == 16)
return gpg_error (GPG_ERR_BUG);
memset (&ctx, 0, sizeof ctx);
ctx.not_allocated = 1;
ctx.kr_handle = keydb_new ();
ctx.nitems = 1;
ctx.items[0].mode = (fprint_len == 16
? KEYDB_SEARCH_MODE_FPR16 : KEYDB_SEARCH_MODE_FPR20);
memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
err = lookup (&ctx, ret_keyblock, 1);
get_pubkey_end (&ctx);
return err;
}
/* The new function to return a key.
FIXME: Document it. */
gpg_error_t
getkey_bynames (getkey_ctx_t *retctx, PKT_public_key *pk,
strlist_t names, int want_secret, kbnode_t *ret_keyblock)
{
return key_byname (retctx, names, pk, want_secret, 1,
ret_keyblock, NULL);
}
/* Get a key by name and store it into PK if that is not NULL. If
* RETCTX is not NULL return the search context which needs to be
* released by the caller using getkey_end. If NAME is NULL use the
* default key (see below). On success and if RET_KEYBLOCK is not
* NULL the found keyblock is stored at this address. WANT_SECRET
* passed as true requires that a secret key is available for the
* selected key.
*
* If WANT_SECRET is true and NAME is NULL and a default key has been
* defined that defined key is used. In all other cases the first
* available key is used.
*
* FIXME: Explain what is up with unusable keys.
*
* FIXME: We also have the get_pubkey_byname function which has a
* different semantic. Should be merged with this one.
*/
gpg_error_t
getkey_byname (getkey_ctx_t *retctx, PKT_public_key *pk,
const char *name, int want_secret, kbnode_t *ret_keyblock)
{
gpg_error_t err;
strlist_t namelist = NULL;
int with_unusable = 1;
if (want_secret && !name && opt.def_secret_key && *opt.def_secret_key)
add_to_strlist (&namelist, opt.def_secret_key);
else if (name)
add_to_strlist (&namelist, name);
else
with_unusable = 0;
err = key_byname (retctx, namelist, pk, want_secret, with_unusable,
ret_keyblock, NULL);
/* FIXME: Check that we really return GPG_ERR_NO_SECKEY if
WANT_SECRET has been used. */
free_strlist (namelist);
return err;
}
/* The new function to return the next key. */
gpg_error_t
getkey_next (getkey_ctx_t ctx, PKT_public_key *pk, kbnode_t *ret_keyblock)
{
int rc; /* Fixme: Make sure this is proper gpg_error */
rc = lookup (ctx, ret_keyblock, ctx->want_secret);
if (!rc && pk && ret_keyblock)
pk_from_block (ctx, pk, *ret_keyblock);
return rc;
}
/* The new function to finish a key listing. */
void
getkey_end (getkey_ctx_t ctx)
{
get_pubkey_end (ctx);
}
/************************************************
************* Merging stuff ********************
************************************************/
/* Merge all self-signatures with the keys. */
void
merge_keys_and_selfsig (KBNODE keyblock)
{
if (!keyblock)
;
else if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
merge_selfsigs (keyblock);
else
log_debug ("FIXME: merging secret key blocks is not anymore available\n");
}
static int
parse_key_usage (PKT_signature * sig)
{
int key_usage = 0;
const byte *p;
size_t n;
byte flags;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_FLAGS, &n);
if (p && n)
{
/* First octet of the keyflags. */
flags = *p;
if (flags & 1)
{
key_usage |= PUBKEY_USAGE_CERT;
flags &= ~1;
}
if (flags & 2)
{
key_usage |= PUBKEY_USAGE_SIG;
flags &= ~2;
}
/* We do not distinguish between encrypting communications and
encrypting storage. */
if (flags & (0x04 | 0x08))
{
key_usage |= PUBKEY_USAGE_ENC;
flags &= ~(0x04 | 0x08);
}
if (flags & 0x20)
{
key_usage |= PUBKEY_USAGE_AUTH;
flags &= ~0x20;
}
if (flags)
key_usage |= PUBKEY_USAGE_UNKNOWN;
}
/* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
capability that we do not handle. This serves to distinguish
between a zero key usage which we handle as the default
capabilities for that algorithm, and a usage that we do not
handle. */
return key_usage;
}
/* Apply information from SIGNODE (which is the valid self-signature
* associated with that UID) to the UIDNODE:
* - wether the UID has been revoked
* - assumed creation date of the UID
* - temporary store the keyflags here
* - temporary store the key expiration time here
* - mark whether the primary user ID flag hat been set.
* - store the preferences
*/
static void
fixup_uidnode (KBNODE uidnode, KBNODE signode, u32 keycreated)
{
PKT_user_id *uid = uidnode->pkt->pkt.user_id;
PKT_signature *sig = signode->pkt->pkt.signature;
const byte *p, *sym, *hash, *zip;
size_t n, nsym, nhash, nzip;
sig->flags.chosen_selfsig = 1;/* We chose this one. */
uid->created = 0; /* Not created == invalid. */
if (IS_UID_REV (sig))
{
uid->is_revoked = 1;
return; /* Has been revoked. */
}
else
uid->is_revoked = 0;
uid->expiredate = sig->expiredate;
if (sig->flags.expired)
{
uid->is_expired = 1;
return; /* Has expired. */
}
else
uid->is_expired = 0;
uid->created = sig->timestamp; /* This one is okay. */
uid->selfsigversion = sig->version;
/* If we got this far, it's not expired :) */
uid->is_expired = 0;
/* Store the key flags in the helper variable for later processing. */
uid->help_key_usage = parse_key_usage (sig);
/* Ditto for the key expiration. */
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
if (p && buffer_to_u32 (p))
uid->help_key_expire = keycreated + buffer_to_u32 (p);
else
uid->help_key_expire = 0;
/* Set the primary user ID flag - we will later wipe out some
* of them to only have one in our keyblock. */
uid->is_primary = 0;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL);
if (p && *p)
uid->is_primary = 2;
/* We could also query this from the unhashed area if it is not in
* the hased area and then later try to decide which is the better
* there should be no security problem with this.
* For now we only look at the hashed one. */
/* Now build the preferences list. These must come from the
hashed section so nobody can modify the ciphers a key is
willing to accept. */
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM, &n);
sym = p;
nsym = p ? n : 0;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH, &n);
hash = p;
nhash = p ? n : 0;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR, &n);
zip = p;
nzip = p ? n : 0;
if (uid->prefs)
xfree (uid->prefs);
n = nsym + nhash + nzip;
if (!n)
uid->prefs = NULL;
else
{
uid->prefs = xmalloc (sizeof (*uid->prefs) * (n + 1));
n = 0;
for (; nsym; nsym--, n++)
{
uid->prefs[n].type = PREFTYPE_SYM;
uid->prefs[n].value = *sym++;
}
for (; nhash; nhash--, n++)
{
uid->prefs[n].type = PREFTYPE_HASH;
uid->prefs[n].value = *hash++;
}
for (; nzip; nzip--, n++)
{
uid->prefs[n].type = PREFTYPE_ZIP;
uid->prefs[n].value = *zip++;
}
uid->prefs[n].type = PREFTYPE_NONE; /* End of list marker */
uid->prefs[n].value = 0;
}
/* See whether we have the MDC feature. */
uid->flags.mdc = 0;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
if (p && n && (p[0] & 0x01))
uid->flags.mdc = 1;
/* And the keyserver modify flag. */
uid->flags.ks_modify = 1;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n);
if (p && n && (p[0] & 0x80))
uid->flags.ks_modify = 0;
}
static void
sig_to_revoke_info (PKT_signature * sig, struct revoke_info *rinfo)
{
rinfo->date = sig->timestamp;
rinfo->algo = sig->pubkey_algo;
rinfo->keyid[0] = sig->keyid[0];
rinfo->keyid[1] = sig->keyid[1];
}
/* Note that R_REVOKED may be set to 0, 1 or 2. */
static void
merge_selfsigs_main (KBNODE keyblock, int *r_revoked,
struct revoke_info *rinfo)
{
PKT_public_key *pk = NULL;
KBNODE k;
u32 kid[2];
u32 sigdate, uiddate, uiddate2;
KBNODE signode, uidnode, uidnode2;
u32 curtime = make_timestamp ();
unsigned int key_usage = 0;
u32 keytimestamp = 0;
u32 key_expire = 0;
int key_expire_seen = 0;
byte sigversion = 0;
*r_revoked = 0;
memset (rinfo, 0, sizeof (*rinfo));
if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
BUG ();
pk = keyblock->pkt->pkt.public_key;
keytimestamp = pk->timestamp;
keyid_from_pk (pk, kid);
pk->main_keyid[0] = kid[0];
pk->main_keyid[1] = kid[1];
if (pk->version < 4)
{
/* Before v4 the key packet itself contains the expiration date
* and there was no way to change it, so we start with the one
* from the key packet. */
key_expire = pk->max_expiredate;
key_expire_seen = 1;
}
/* First pass: Find the latest direct key self-signature. We assume
* that the newest one overrides all others. */
/* In case this key was already merged. */
xfree (pk->revkey);
pk->revkey = NULL;
pk->numrevkeys = 0;
signode = NULL;
sigdate = 0; /* Helper variable to find the latest signature. */
for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
{
if (k->pkt->pkttype == PKT_SIGNATURE)
{
PKT_signature *sig = k->pkt->pkt.signature;
if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
{
if (check_key_signature (keyblock, k, NULL))
; /* Signature did not verify. */
else if (IS_KEY_REV (sig))
{
/* Key has been revoked - there is no way to
* override such a revocation, so we theoretically
* can stop now. We should not cope with expiration
* times for revocations here because we have to
* assume that an attacker can generate all kinds of
* signatures. However due to the fact that the key
* has been revoked it does not harm either and by
* continuing we gather some more info on that
* key. */
*r_revoked = 1;
sig_to_revoke_info (sig, rinfo);
}
else if (IS_KEY_SIG (sig))
{
/* Add any revocation keys onto the pk. This is
particularly interesting since we normally only
get data from the most recent 1F signature, but
you need multiple 1F sigs to properly handle
revocation keys (PGP does it this way, and a
revocation key could be sensitive and hence in a
different signature). */
if (sig->revkey)
{
int i;
pk->revkey =
xrealloc (pk->revkey, sizeof (struct revocation_key) *
(pk->numrevkeys + sig->numrevkeys));
for (i = 0; i < sig->numrevkeys; i++)
memcpy (&pk->revkey[pk->numrevkeys++],
sig->revkey[i],
sizeof (struct revocation_key));
}
if (sig->timestamp >= sigdate)
{
if (sig->flags.expired)
; /* Signature has expired - ignore it. */
else
{
sigdate = sig->timestamp;
signode = k;
if (sig->version > sigversion)
sigversion = sig->version;
}
}
}
}
}
}
/* Remove dupes from the revocation keys. */
if (pk->revkey)
{
int i, j, x, changed = 0;
for (i = 0; i < pk->numrevkeys; i++)
{
for (j = i + 1; j < pk->numrevkeys; j++)
{
if (memcmp (&pk->revkey[i], &pk->revkey[j],
sizeof (struct revocation_key)) == 0)
{
/* remove j */
for (x = j; x < pk->numrevkeys - 1; x++)
pk->revkey[x] = pk->revkey[x + 1];
pk->numrevkeys--;
j--;
changed = 1;
}
}
}
if (changed)
pk->revkey = xrealloc (pk->revkey,
pk->numrevkeys *
sizeof (struct revocation_key));
}
if (signode)
{
/* Some information from a direct key signature take precedence
* over the same information given in UID sigs. */
PKT_signature *sig = signode->pkt->pkt.signature;
const byte *p;
key_usage = parse_key_usage (sig);
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
if (p && buffer_to_u32 (p))
{
key_expire = keytimestamp + buffer_to_u32 (p);
key_expire_seen = 1;
}
/* Mark that key as valid: One direct key signature should
* render a key as valid. */
pk->flags.valid = 1;
}
/* Pass 1.5: Look for key revocation signatures that were not made
by the key (i.e. did a revocation key issue a revocation for
us?). Only bother to do this if there is a revocation key in the
first place and we're not revoked already. */
if (!*r_revoked && pk->revkey)
for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
{
if (k->pkt->pkttype == PKT_SIGNATURE)
{
PKT_signature *sig = k->pkt->pkt.signature;
if (IS_KEY_REV (sig) &&
(sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1]))
{
int rc = check_revocation_keys (pk, sig);
if (rc == 0)
{
*r_revoked = 2;
sig_to_revoke_info (sig, rinfo);
/* Don't continue checking since we can't be any
more revoked than this. */
break;
}
else if (rc == G10ERR_NO_PUBKEY)
pk->flags.maybe_revoked = 1;
/* A failure here means the sig did not verify, was
not issued by a revocation key, or a revocation
key loop was broken. If a revocation key isn't
findable, however, the key might be revoked and
we don't know it. */
/* TODO: In the future handle subkey and cert
revocations? PGP doesn't, but it's in 2440. */
}
}
}
/* Second pass: Look at the self-signature of all user IDs. */
signode = uidnode = NULL;
sigdate = 0; /* Helper variable to find the latest signature in one UID. */
for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
{
if (k->pkt->pkttype == PKT_USER_ID)
{
if (uidnode && signode)
{
fixup_uidnode (uidnode, signode, keytimestamp);
pk->flags.valid = 1;
}
uidnode = k;
signode = NULL;
sigdate = 0;
}
else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
{
PKT_signature *sig = k->pkt->pkt.signature;
if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
{
if (check_key_signature (keyblock, k, NULL))
; /* signature did not verify */
else if ((IS_UID_SIG (sig) || IS_UID_REV (sig))
&& sig->timestamp >= sigdate)
{
/* Note: we allow to invalidate cert revocations
* by a newer signature. An attacker can't use this
* because a key should be revoced with a key revocation.
* The reason why we have to allow for that is that at
* one time an email address may become invalid but later
* the same email address may become valid again (hired,
* fired, hired again). */
sigdate = sig->timestamp;
signode = k;
signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
if (sig->version > sigversion)
sigversion = sig->version;
}
}
}
}
if (uidnode && signode)
{
fixup_uidnode (uidnode, signode, keytimestamp);
pk->flags.valid = 1;
}
/* If the key isn't valid yet, and we have
--allow-non-selfsigned-uid set, then force it valid. */
if (!pk->flags.valid && opt.allow_non_selfsigned_uid)
{
if (opt.verbose)
log_info (_("Invalid key %s made valid by"
" --allow-non-selfsigned-uid\n"), keystr_from_pk (pk));
pk->flags.valid = 1;
}
/* The key STILL isn't valid, so try and find an ultimately
trusted signature. */
if (!pk->flags.valid)
{
uidnode = NULL;
for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
k = k->next)
{
if (k->pkt->pkttype == PKT_USER_ID)
uidnode = k;
else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
{
PKT_signature *sig = k->pkt->pkt.signature;
if (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1])
{
PKT_public_key *ultimate_pk;
ultimate_pk = xmalloc_clear (sizeof (*ultimate_pk));
/* We don't want to use the full get_pubkey to
avoid infinite recursion in certain cases.
There is no reason to check that an ultimately
trusted key is still valid - if it has been
revoked or the user should also renmove the
ultimate trust flag. */
if (get_pubkey_fast (ultimate_pk, sig->keyid) == 0
&& check_key_signature2 (keyblock, k, ultimate_pk,
NULL, NULL, NULL, NULL) == 0
&& get_ownertrust (ultimate_pk) == TRUST_ULTIMATE)
{
free_public_key (ultimate_pk);
pk->flags.valid = 1;
break;
}
free_public_key (ultimate_pk);
}
}
}
}
/* Record the highest selfsig version so we know if this is a v3
key through and through, or a v3 key with a v4 selfsig
somewhere. This is useful in a few places to know if the key
must be treated as PGP2-style or OpenPGP-style. Note that a
selfsig revocation with a higher version number will also raise
this value. This is okay since such a revocation must be
issued by the user (i.e. it cannot be issued by someone else to
modify the key behavior.) */
pk->selfsigversion = sigversion;
/* Now that we had a look at all user IDs we can now get some information
* from those user IDs.
*/
if (!key_usage)
{
/* Find the latest user ID with key flags set. */
uiddate = 0; /* Helper to find the latest user ID. */
for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
k = k->next)
{
if (k->pkt->pkttype == PKT_USER_ID)
{
PKT_user_id *uid = k->pkt->pkt.user_id;
if (uid->help_key_usage && uid->created > uiddate)
{
key_usage = uid->help_key_usage;
uiddate = uid->created;
}
}
}
}
if (!key_usage)
{
/* No key flags at all: get it from the algo. */
key_usage = openpgp_pk_algo_usage (pk->pubkey_algo);
}
else
{
/* Check that the usage matches the usage as given by the algo. */
int x = openpgp_pk_algo_usage (pk->pubkey_algo);
if (x) /* Mask it down to the actual allowed usage. */
key_usage &= x;
}
/* Whatever happens, it's a primary key, so it can certify. */
pk->pubkey_usage = key_usage | PUBKEY_USAGE_CERT;
if (!key_expire_seen)
{
/* Find the latest valid user ID with a key expiration set
* Note, that this may be a different one from the above because
* some user IDs may have no expiration date set. */
uiddate = 0;
for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
k = k->next)
{
if (k->pkt->pkttype == PKT_USER_ID)
{
PKT_user_id *uid = k->pkt->pkt.user_id;
if (uid->help_key_expire && uid->created > uiddate)
{
key_expire = uid->help_key_expire;
uiddate = uid->created;
}
}
}
}
/* Currently only v3 keys have a maximum expiration date, but I'll
bet v5 keys get this feature again. */
if (key_expire == 0
|| (pk->max_expiredate && key_expire > pk->max_expiredate))
key_expire = pk->max_expiredate;
pk->has_expired = key_expire >= curtime ? 0 : key_expire;
pk->expiredate = key_expire;
/* Fixme: we should see how to get rid of the expiretime fields but
* this needs changes at other places too. */
/* And now find the real primary user ID and delete all others. */
uiddate = uiddate2 = 0;
uidnode = uidnode2 = NULL;
for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
{
if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data)
{
PKT_user_id *uid = k->pkt->pkt.user_id;
if (uid->is_primary)
{
if (uid->created > uiddate)
{
uiddate = uid->created;
uidnode = k;
}
else if (uid->created == uiddate && uidnode)
{
/* The dates are equal, so we need to do a
different (and arbitrary) comparison. This
should rarely, if ever, happen. It's good to
try and guarantee that two different GnuPG
users with two different keyrings at least pick
the same primary. */
if (cmp_user_ids (uid, uidnode->pkt->pkt.user_id) > 0)
uidnode = k;
}
}
else
{
if (uid->created > uiddate2)
{
uiddate2 = uid->created;
uidnode2 = k;
}
else if (uid->created == uiddate2 && uidnode2)
{
if (cmp_user_ids (uid, uidnode2->pkt->pkt.user_id) > 0)
uidnode2 = k;
}
}
}
}
if (uidnode)
{
for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
k = k->next)
{
if (k->pkt->pkttype == PKT_USER_ID &&
!k->pkt->pkt.user_id->attrib_data)
{
PKT_user_id *uid = k->pkt->pkt.user_id;
if (k != uidnode)
uid->is_primary = 0;
}
}
}
else if (uidnode2)
{
/* None is flagged primary - use the latest user ID we have,
and disambiguate with the arbitrary packet comparison. */
uidnode2->pkt->pkt.user_id->is_primary = 1;
}
else
{
/* None of our uids were self-signed, so pick the one that
sorts first to be the primary. This is the best we can do
here since there are no self sigs to date the uids. */
uidnode = NULL;
for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
k = k->next)
{
if (k->pkt->pkttype == PKT_USER_ID
&& !k->pkt->pkt.user_id->attrib_data)
{
if (!uidnode)
{
uidnode = k;
uidnode->pkt->pkt.user_id->is_primary = 1;
continue;
}
else
{
if (cmp_user_ids (k->pkt->pkt.user_id,
uidnode->pkt->pkt.user_id) > 0)
{
uidnode->pkt->pkt.user_id->is_primary = 0;
uidnode = k;
uidnode->pkt->pkt.user_id->is_primary = 1;
}
else
k->pkt->pkt.user_id->is_primary = 0; /* just to be
safe */
}
}
}
}
}
/* Convert a buffer to a signature. Useful for 0x19 embedded sigs.
Caller must free the signature when they are done. */
static PKT_signature *
buf_to_sig (const byte * buf, size_t len)
{
PKT_signature *sig = xmalloc_clear (sizeof (PKT_signature));
IOBUF iobuf = iobuf_temp_with_content (buf, len);
int save_mode = set_packet_list_mode (0);
if (parse_signature (iobuf, PKT_SIGNATURE, len, sig) != 0)
{
xfree (sig);
sig = NULL;
}
set_packet_list_mode (save_mode);
iobuf_close (iobuf);
return sig;
}
static void
merge_selfsigs_subkey (KBNODE keyblock, KBNODE subnode)
{
PKT_public_key *mainpk = NULL, *subpk = NULL;
PKT_signature *sig;
KBNODE k;
u32 mainkid[2];
u32 sigdate = 0;
KBNODE signode;
u32 curtime = make_timestamp ();
unsigned int key_usage = 0;
u32 keytimestamp = 0;
u32 key_expire = 0;
const byte *p;
if (subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY)
BUG ();
mainpk = keyblock->pkt->pkt.public_key;
if (mainpk->version < 4)
return;/* (actually this should never happen) */
keyid_from_pk (mainpk, mainkid);
subpk = subnode->pkt->pkt.public_key;
keytimestamp = subpk->timestamp;
subpk->flags.valid = 0;
subpk->main_keyid[0] = mainpk->main_keyid[0];
subpk->main_keyid[1] = mainpk->main_keyid[1];
/* Find the latest key binding self-signature. */
signode = NULL;
sigdate = 0; /* Helper to find the latest signature. */
for (k = subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
k = k->next)
{
if (k->pkt->pkttype == PKT_SIGNATURE)
{
sig = k->pkt->pkt.signature;
if (sig->keyid[0] == mainkid[0] && sig->keyid[1] == mainkid[1])
{
if (check_key_signature (keyblock, k, NULL))
; /* Signature did not verify. */
else if (IS_SUBKEY_REV (sig))
{
/* Note that this means that the date on a
revocation sig does not matter - even if the
binding sig is dated after the revocation sig,
the subkey is still marked as revoked. This
seems ok, as it is just as easy to make new
subkeys rather than re-sign old ones as the
problem is in the distribution. Plus, PGP (7)
does this the same way. */
subpk->flags.revoked = 1;
sig_to_revoke_info (sig, &subpk->revoked);
/* Although we could stop now, we continue to
* figure out other information like the old expiration
* time. */
}
else if (IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate)
{
if (sig->flags.expired)
; /* Signature has expired - ignore it. */
else
{
sigdate = sig->timestamp;
signode = k;
signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
}
}
}
}
}
/* No valid key binding. */
if (!signode)
return;
sig = signode->pkt->pkt.signature;
sig->flags.chosen_selfsig = 1; /* So we know which selfsig we chose later. */
key_usage = parse_key_usage (sig);
if (!key_usage)
{
/* No key flags at all: get it from the algo. */
key_usage = openpgp_pk_algo_usage (subpk->pubkey_algo);
}
else
{
/* Check that the usage matches the usage as given by the algo. */
int x = openpgp_pk_algo_usage (subpk->pubkey_algo);
if (x) /* Mask it down to the actual allowed usage. */
key_usage &= x;
}
subpk->pubkey_usage = key_usage;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
if (p && buffer_to_u32 (p))
key_expire = keytimestamp + buffer_to_u32 (p);
else
key_expire = 0;
subpk->has_expired = key_expire >= curtime ? 0 : key_expire;
subpk->expiredate = key_expire;
/* Algo doesn't exist. */
if (openpgp_pk_test_algo (subpk->pubkey_algo))
return;
subpk->flags.valid = 1;
/* Find the most recent 0x19 embedded signature on our self-sig. */
if (!subpk->flags.backsig)
{
int seq = 0;
size_t n;
PKT_signature *backsig = NULL;
sigdate = 0;
/* We do this while() since there may be other embedded
signatures in the future. We only want 0x19 here. */
while ((p = enum_sig_subpkt (sig->hashed,
SIGSUBPKT_SIGNATURE, &n, &seq, NULL)))
if (n > 3
&& ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
{
PKT_signature *tempsig = buf_to_sig (p, n);
if (tempsig)
{
if (tempsig->timestamp > sigdate)
{
if (backsig)
free_seckey_enc (backsig);
backsig = tempsig;
sigdate = backsig->timestamp;
}
else
free_seckey_enc (tempsig);
}
}
seq = 0;
/* It is safe to have this in the unhashed area since the 0x19
is located on the selfsig for convenience, not security. */
while ((p = enum_sig_subpkt (sig->unhashed, SIGSUBPKT_SIGNATURE,
&n, &seq, NULL)))
if (n > 3
&& ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
{
PKT_signature *tempsig = buf_to_sig (p, n);
if (tempsig)
{
if (tempsig->timestamp > sigdate)
{
if (backsig)
free_seckey_enc (backsig);
backsig = tempsig;
sigdate = backsig->timestamp;
}
else
free_seckey_enc (tempsig);
}
}
if (backsig)
{
/* At ths point, backsig contains the most recent 0x19 sig.
Let's see if it is good. */
/* 2==valid, 1==invalid, 0==didn't check */
if (check_backsig (mainpk, subpk, backsig) == 0)
subpk->flags.backsig = 2;
else
subpk->flags.backsig = 1;
free_seckey_enc (backsig);
}
}
}
/*
* Merge information from the self-signatures with the key, so that
* we can later use them more easy.
* The function works by first applying the self signatures to the
* primary key and the to each subkey.
* Here are the rules we use to decide which inormation from which
* self-signature is used:
* We check all self signatures or validity and ignore all invalid signatures.
* All signatures are then ordered by their creation date ....
* For the primary key:
* FIXME the docs
*/
static void
merge_selfsigs (KBNODE keyblock)
{
KBNODE k;
int revoked;
struct revoke_info rinfo;
PKT_public_key *main_pk;
prefitem_t *prefs;
unsigned int mdc_feature;
if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
{
if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
{
log_error ("expected public key but found secret key "
"- must stop\n");
/* We better exit here because a public key is expected at
other places too. FIXME: Figure this out earlier and
don't get to here at all */
g10_exit (1);
}
BUG ();
}
merge_selfsigs_main (keyblock, &revoked, &rinfo);
/* Now merge in the data from each of the subkeys. */
for (k = keyblock; k; k = k->next)
{
if (k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
{
merge_selfsigs_subkey (keyblock, k);
}
}
main_pk = keyblock->pkt->pkt.public_key;
if (revoked || main_pk->has_expired || !main_pk->flags.valid)
{
/* If the primary key is revoked, expired, or invalid we
* better set the appropriate flags on that key and all
* subkeys. */
for (k = keyblock; k; k = k->next)
{
if (k->pkt->pkttype == PKT_PUBLIC_KEY
|| k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
{
PKT_public_key *pk = k->pkt->pkt.public_key;
if (!main_pk->flags.valid)
pk->flags.valid = 0;
if (revoked && !pk->flags.revoked)
{
pk->flags.revoked = revoked;
memcpy (&pk->revoked, &rinfo, sizeof (rinfo));
}
if (main_pk->has_expired)
pk->has_expired = main_pk->has_expired;
}
}
return;
}
/* Set the preference list of all keys to those of the primary real
* user ID. Note: we use these preferences when we don't know by
* which user ID the key has been selected.
* fixme: we should keep atoms of commonly used preferences or
* use reference counting to optimize the preference lists storage.
* FIXME: it might be better to use the intersection of
* all preferences.
* Do a similar thing for the MDC feature flag. */
prefs = NULL;
mdc_feature = 0;
for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
{
if (k->pkt->pkttype == PKT_USER_ID
&& !k->pkt->pkt.user_id->attrib_data
&& k->pkt->pkt.user_id->is_primary)
{
prefs = k->pkt->pkt.user_id->prefs;
mdc_feature = k->pkt->pkt.user_id->flags.mdc;
break;
}
}
for (k = keyblock; k; k = k->next)
{
if (k->pkt->pkttype == PKT_PUBLIC_KEY
|| k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
{
PKT_public_key *pk = k->pkt->pkt.public_key;
if (pk->prefs)
xfree (pk->prefs);
pk->prefs = copy_prefs (prefs);
pk->flags.mdc = mdc_feature;
}
}
}
/* See whether the key fits our requirements and in case we do not
* request the primary key, select a suitable subkey.
*
* Returns: True when a suitable key has been found.
*
* We have to distinguish four cases: FIXME!
* 1. No usage and no primary key requested
* Examples for this case are that we have a keyID to be used
* for decrytion or verification.
* 2. No usage but primary key requested
* This is the case for all functions which work on an
* entire keyblock, e.g. for editing or listing
* 3. Usage and primary key requested
* FXME
* 4. Usage but no primary key requested
* FIXME
* FIXME: Tell what is going to happen here and something about the rationale
* Note: We don't use this function if no specific usage is requested;
* This way the getkey functions can be used for plain key listings.
*
* CTX ist the keyblock we are investigating, if FOUNDK is not NULL this
* is the key we actually found by looking at the keyid or a fingerprint and
* may either point to the primary or one of the subkeys. */
static int
finish_lookup (GETKEY_CTX ctx)
{
KBNODE keyblock = ctx->keyblock;
KBNODE k;
KBNODE foundk = NULL;
PKT_user_id *foundu = NULL;
#define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
unsigned int req_usage = (ctx->req_usage & USAGE_MASK);
/* Request the primary if we're certifying another key, and also
if signing data while --pgp6 or --pgp7 is on since pgp 6 and 7
do not understand signatures made by a signing subkey. PGP 8
does. */
int req_prim = (ctx->req_usage & PUBKEY_USAGE_CERT) ||
((PGP6 || PGP7) && (ctx->req_usage & PUBKEY_USAGE_SIG));
u32 latest_date;
KBNODE latest_key;
u32 curtime = make_timestamp ();
assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
ctx->found_key = NULL;
if (ctx->exact)
{
for (k = keyblock; k; k = k->next)
{
if ((k->flag & 1))
{
assert (k->pkt->pkttype == PKT_PUBLIC_KEY
|| k->pkt->pkttype == PKT_PUBLIC_SUBKEY);
foundk = k;
break;
}
}
}
for (k = keyblock; k; k = k->next)
{
if ((k->flag & 2))
{
assert (k->pkt->pkttype == PKT_USER_ID);
foundu = k->pkt->pkt.user_id;
break;
}
}
if (DBG_CACHE)
log_debug ("finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
(ulong) keyid_from_pk (keyblock->pkt->pkt.public_key, NULL),
foundk ? "one" : "all", req_usage);
if (!req_usage)
{
latest_key = foundk ? foundk : keyblock;
goto found;
}
latest_date = 0;
latest_key = NULL;
/* Do not look at subkeys if a certification key is requested. */
if ((!foundk || foundk->pkt->pkttype == PKT_PUBLIC_SUBKEY) && !req_prim)
{
KBNODE nextk;
/* Either start a loop or check just this one subkey. */
for (k = foundk ? foundk : keyblock; k; k = nextk)
{
PKT_public_key *pk;
nextk = k->next;
if (k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
continue;
if (foundk)
nextk = NULL; /* what a hack */
pk = k->pkt->pkt.public_key;
if (DBG_CACHE)
log_debug ("\tchecking subkey %08lX\n",
(ulong) keyid_from_pk (pk, NULL));
if (!pk->flags.valid)
{
if (DBG_CACHE)
log_debug ("\tsubkey not valid\n");
continue;
}
if (pk->flags.revoked)
{
if (DBG_CACHE)
log_debug ("\tsubkey has been revoked\n");
continue;
}
if (pk->has_expired)
{
if (DBG_CACHE)
log_debug ("\tsubkey has expired\n");
continue;
}
if (pk->timestamp > curtime && !opt.ignore_valid_from)
{
if (DBG_CACHE)
log_debug ("\tsubkey not yet valid\n");
continue;
}
if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
{
if (DBG_CACHE)
log_debug ("\tusage does not match: want=%x have=%x\n",
req_usage, pk->pubkey_usage);
continue;
}
if (DBG_CACHE)
log_debug ("\tsubkey might be fine\n");
/* In case a key has a timestamp of 0 set, we make sure
that it is used. A better change would be to compare
">=" but that might also change the selected keys and
is as such a more intrusive change. */
if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
{
latest_date = pk->timestamp;
latest_key = k;
}
}
}
/* Okay now try the primary key unless we want an exact
* key ID match on a subkey */
if ((!latest_key && !(ctx->exact && foundk != keyblock)) || req_prim)
{
PKT_public_key *pk;
if (DBG_CACHE && !foundk && !req_prim)
log_debug ("\tno suitable subkeys found - trying primary\n");
pk = keyblock->pkt->pkt.public_key;
if (!pk->flags.valid)
{
if (DBG_CACHE)
log_debug ("\tprimary key not valid\n");
}
else if (pk->flags.revoked)
{
if (DBG_CACHE)
log_debug ("\tprimary key has been revoked\n");
}
else if (pk->has_expired)
{
if (DBG_CACHE)
log_debug ("\tprimary key has expired\n");
}
else if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
{
if (DBG_CACHE)
log_debug ("\tprimary key usage does not match: "
"want=%x have=%x\n", req_usage, pk->pubkey_usage);
}
else /* Okay. */
{
if (DBG_CACHE)
log_debug ("\tprimary key may be used\n");
latest_key = keyblock;
latest_date = pk->timestamp;
}
}
if (!latest_key)
{
if (DBG_CACHE)
log_debug ("\tno suitable key found - giving up\n");
return 0; /* Not found. */
}
found:
if (DBG_CACHE)
log_debug ("\tusing key %08lX\n",
(ulong) keyid_from_pk (latest_key->pkt->pkt.public_key, NULL));
if (latest_key)
{
PKT_public_key *pk = latest_key->pkt->pkt.public_key;
if (pk->user_id)
free_user_id (pk->user_id);
pk->user_id = scopy_user_id (foundu);
}
ctx->found_key = latest_key;
if (latest_key != keyblock && opt.verbose)
{
char *tempkeystr =
xstrdup (keystr_from_pk (latest_key->pkt->pkt.public_key));
log_info (_("using subkey %s instead of primary key %s\n"),
tempkeystr, keystr_from_pk (keyblock->pkt->pkt.public_key));
xfree (tempkeystr);
}
cache_user_id (keyblock);
return 1; /* Found. */
}
/* The main function to lookup a key. On success the found keyblock
is stored at RET_KEYBLOCK and also in CTX. If WANT_SECRET is true
a corresponding secret key is required. */
static int
lookup (getkey_ctx_t ctx, kbnode_t *ret_keyblock, int want_secret)
{
int rc;
int no_suitable_key = 0;
rc = 0;
while (!(rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems)))
{
/* If we are searching for the first key we have to make sure
that the next iteration does not do an implicit reset.
This can be triggered by an empty key ring. */
if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
rc = keydb_get_keyblock (ctx->kr_handle, &ctx->keyblock);
if (rc)
{
log_error ("keydb_get_keyblock failed: %s\n", g10_errstr (rc));
rc = 0;
goto skip;
}
if (want_secret && agent_probe_any_secret_key (NULL, ctx->keyblock))
goto skip; /* No secret key available. */
/* Warning: node flag bits 0 and 1 should be preserved by
* merge_selfsigs. For secret keys, premerge did tranfer the
* keys to the keyblock. */
merge_selfsigs (ctx->keyblock);
if (finish_lookup (ctx))
{
no_suitable_key = 0;
goto found;
}
else
no_suitable_key = 1;
skip:
/* Release resources and continue search. */
release_kbnode (ctx->keyblock);
ctx->keyblock = NULL;
}
found:
if (rc && rc != -1)
log_error ("keydb_search failed: %s\n", g10_errstr (rc));
if (!rc)
{
*ret_keyblock = ctx->keyblock; /* Return the keyblock. */
ctx->keyblock = NULL;
}
else if (rc == -1 && no_suitable_key)
rc = want_secret? G10ERR_UNU_SECKEY : G10ERR_UNU_PUBKEY;
else if (rc == -1)
rc = want_secret? G10ERR_NO_SECKEY : G10ERR_NO_PUBKEY;
release_kbnode (ctx->keyblock);
ctx->keyblock = NULL;
ctx->last_rc = rc;
return rc;
}
/*
* Enumerate certain secret keys. Caller must use these procedure:
* 1) create a void pointer and initialize it to NULL
* 2) pass this void pointer by reference to this function
* and provide space for the secret key (pass a buffer for sk)
* 3) call this function as long as it does not return an error.
* The error code GPG_ERR_EOF indicates the end of the listing.
* 4) Always call this function a last time with SK set to NULL,
* so that can free it's context.
*/
gpg_error_t
enum_secret_keys (void **context, PKT_public_key *sk)
{
gpg_error_t err = 0;
const char *name;
struct
{
int eof;
int state;
strlist_t sl;
kbnode_t keyblock;
kbnode_t node;
} *c = *context;
if (!c)
{
/* Make a new context. */
c = xtrycalloc (1, sizeof *c);
if (!c)
return gpg_error_from_syserror ();
*context = c;
}
if (!sk)
{
/* Free the context. */
release_kbnode (c->keyblock);
xfree (c);
*context = NULL;
return 0;
}
if (c->eof)
return gpg_error (GPG_ERR_EOF);
for (;;)
{
/* Loop until we have a keyblock. */
while (!c->keyblock)
{
/* Loop over the list of secret keys. */
do
{
name = NULL;
switch (c->state)
{
case 0: /* First try to use the --default-key. */
if (opt.def_secret_key && *opt.def_secret_key)
name = opt.def_secret_key;
c->state = 1;
break;
case 1: /* Init list of keys to try. */
c->sl = opt.secret_keys_to_try;
c->state++;
break;
case 2: /* Get next item from list. */
if (c->sl)
{
name = c->sl->d;
c->sl = c->sl->next;
}
else
c->state++;
break;
default: /* No more names to check - stop. */
c->eof = 1;
return gpg_error (GPG_ERR_EOF);
}
}
while (!name || !*name);
err = getkey_byname (NULL, NULL, name, 1, &c->keyblock);
if (err)
{
/* getkey_byname might return a keyblock even in the
error case - I have not checked. Thus better release
it. */
release_kbnode (c->keyblock);
c->keyblock = NULL;
}
else
c->node = c->keyblock;
}
/* Get the next key from the current keyblock. */
for (; c->node; c->node = c->node->next)
{
if (c->node->pkt->pkttype == PKT_PUBLIC_KEY
|| c->node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
{
copy_public_key (sk, c->node->pkt->pkt.public_key);
c->node = c->node->next;
return 0; /* Found. */
}
}
/* Dispose the keyblock and continue. */
release_kbnode (c->keyblock);
c->keyblock = NULL;
}
}
/*********************************************
*********** User ID printing helpers *******
*********************************************/
/* Return a string with a printable representation of the user_id.
* this string must be freed by xfree. */
char *
get_user_id_string (u32 * keyid)
{
user_id_db_t r;
char *p;
int pass = 0;
/* Try it two times; second pass reads from key resources. */
do
{
for (r = user_id_db; r; r = r->next)
{
keyid_list_t a;
for (a = r->keyids; a; a = a->next)
{
if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
{
p = xmalloc (keystrlen () + 1 + r->len + 1);
sprintf (p, "%s %.*s", keystr (keyid), r->len, r->name);
return p;
}
}
}
}
while (++pass < 2 && !get_pubkey (NULL, keyid));
p = xmalloc (keystrlen () + 5);
sprintf (p, "%s [?]", keystr (keyid));
return p;
}
char *
get_user_id_string_native (u32 * keyid)
{
char *p = get_user_id_string (keyid);
char *p2 = utf8_to_native (p, strlen (p), 0);
xfree (p);
return p2;
}
char *
get_long_user_id_string (u32 * keyid)
{
user_id_db_t r;
char *p;
int pass = 0;
/* Try it two times; second pass reads from key resources. */
do
{
for (r = user_id_db; r; r = r->next)
{
keyid_list_t a;
for (a = r->keyids; a; a = a->next)
{
if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
{
p = xmalloc (r->len + 20);
sprintf (p, "%08lX%08lX %.*s",
(ulong) keyid[0], (ulong) keyid[1],
r->len, r->name);
return p;
}
}
}
}
while (++pass < 2 && !get_pubkey (NULL, keyid));
p = xmalloc (25);
sprintf (p, "%08lX%08lX [?]", (ulong) keyid[0], (ulong) keyid[1]);
return p;
}
char *
get_user_id (u32 * keyid, size_t * rn)
{
user_id_db_t r;
char *p;
int pass = 0;
/* Try it two times; second pass reads from key resources. */
do
{
for (r = user_id_db; r; r = r->next)
{
keyid_list_t a;
for (a = r->keyids; a; a = a->next)
{
if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
{
p = xmalloc (r->len);
memcpy (p, r->name, r->len);
*rn = r->len;
return p;
}
}
}
}
while (++pass < 2 && !get_pubkey (NULL, keyid));
p = xstrdup (user_id_not_found_utf8 ());
*rn = strlen (p);
return p;
}
char *
get_user_id_native (u32 * keyid)
{
size_t rn;
char *p = get_user_id (keyid, &rn);
char *p2 = utf8_to_native (p, rn, 0);
xfree (p);
return p2;
}
KEYDB_HANDLE
get_ctx_handle (GETKEY_CTX ctx)
{
return ctx->kr_handle;
}
static void
free_akl (struct akl *akl)
{
if (akl->spec)
free_keyserver_spec (akl->spec);
xfree (akl);
}
void
release_akl (void)
{
while (opt.auto_key_locate)
{
struct akl *akl2 = opt.auto_key_locate;
opt.auto_key_locate = opt.auto_key_locate->next;
free_akl (akl2);
}
}
/* Returns false on error. */
int
parse_auto_key_locate (char *options)
{
char *tok;
while ((tok = optsep (&options)))
{
struct akl *akl, *check, *last = NULL;
int dupe = 0;
if (tok[0] == '\0')
continue;
akl = xmalloc_clear (sizeof (*akl));
if (ascii_strcasecmp (tok, "nodefault") == 0)
akl->type = AKL_NODEFAULT;
else if (ascii_strcasecmp (tok, "local") == 0)
akl->type = AKL_LOCAL;
else if (ascii_strcasecmp (tok, "ldap") == 0)
akl->type = AKL_LDAP;
else if (ascii_strcasecmp (tok, "keyserver") == 0)
akl->type = AKL_KEYSERVER;
#ifdef USE_DNS_CERT
else if (ascii_strcasecmp (tok, "cert") == 0)
akl->type = AKL_CERT;
#endif
#ifdef USE_DNS_PKA
else if (ascii_strcasecmp (tok, "pka") == 0)
akl->type = AKL_PKA;
#endif
else if ((akl->spec = parse_keyserver_uri (tok, 1, NULL, 0)))
akl->type = AKL_SPEC;
else
{
free_akl (akl);
return 0;
}
/* We must maintain the order the user gave us */
for (check = opt.auto_key_locate; check;
last = check, check = check->next)
{
/* Check for duplicates */
if (check->type == akl->type
&& (akl->type != AKL_SPEC
|| (akl->type == AKL_SPEC
&& strcmp (check->spec->uri, akl->spec->uri) == 0)))
{
dupe = 1;
free_akl (akl);
break;
}
}
if (!dupe)
{
if (last)
last->next = akl;
else
opt.auto_key_locate = akl;
}
}
return 1;
}
/* Return true if a secret key or secret subkey is available for one
of the public keys in KEYBLOCK. */
int
have_any_secret_key (ctrl_t ctrl, kbnode_t keyblock)
{
kbnode_t node;
for (node = keyblock; node; node = node->next)
if ((node->pkt->pkttype == PKT_PUBLIC_KEY
|| node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
&& !agent_probe_secret_key (ctrl, node->pkt->pkt.public_key))
return 1;
return 0;
}
/* Return true if a secret key is available for the public key with
* the given KEYID. This is just a fast check and does not tell us
* whether the secret key is valid. It merely tells os whether there
* is some secret key. */
int
have_secret_key_with_kid (u32 *keyid)
{
gpg_error_t err;
KEYDB_HANDLE kdbhd;
KEYDB_SEARCH_DESC desc;
kbnode_t keyblock;
kbnode_t node;
int result = 0;
kdbhd = keydb_new ();
memset (&desc, 0, sizeof desc);
desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
desc.u.kid[0] = keyid[0];
desc.u.kid[1] = keyid[1];
while (!result && !(err = keydb_search (kdbhd, &desc, 1)))
{
desc.mode = KEYDB_SEARCH_MODE_NEXT;
err = keydb_get_keyblock (kdbhd, &keyblock);
if (err)
{
log_error (_("error reading keyblock: %s\n"), g10_errstr (err));
break;
}
for (node = keyblock; node; node = node->next)
{
/* Bit 0 of the flags is set if the search found the key
using that key or subkey. */
if ((node->flag & 1))
{
assert (node->pkt->pkttype == PKT_PUBLIC_KEY
|| node->pkt->pkttype == PKT_PUBLIC_SUBKEY);
if (!agent_probe_secret_key (NULL, node->pkt->pkt.public_key))
{
result = 1;
break;
}
}
}
release_kbnode (keyblock);
}
keydb_release (kdbhd);
return result;
}
#if 0
/*
* Merge the secret keys from secblock into the pubblock thereby
* replacing the public (sub)keys with their secret counterparts Hmmm:
* It might be better to get away from the concept of entire secret
* keys at all and have a way to store just the real secret parts
* from the key.
*
* FIXME: this is not anymore needed but we keep it as example code for the
* new code we need to write for the import/export feature.
*/
static void
merge_public_with_secret (KBNODE pubblock, KBNODE secblock)
{
KBNODE pub;
assert (pubblock->pkt->pkttype == PKT_PUBLIC_KEY);
assert (secblock->pkt->pkttype == PKT_SECRET_KEY);
for (pub = pubblock; pub; pub = pub->next)
{
if (pub->pkt->pkttype == PKT_PUBLIC_KEY)
{
PKT_public_key *pk = pub->pkt->pkt.public_key;
PKT_secret_key *sk = secblock->pkt->pkt.secret_key;
assert (pub == pubblock); /* Only in the first node. */
/* There is nothing to compare in this case, so just replace
* some information. */
copy_public_parts_to_secret_key (pk, sk);
free_public_key (pk);
pub->pkt->pkttype = PKT_SECRET_KEY;
pub->pkt->pkt.secret_key = copy_secret_key (NULL, sk);
}
else if (pub->pkt->pkttype == PKT_PUBLIC_SUBKEY)
{
KBNODE sec;
PKT_public_key *pk = pub->pkt->pkt.public_key;
/* This is more complicated: It may happen that the sequence
* of the subkeys dosn't match, so we have to find the
* appropriate secret key. */
for (sec = secblock->next; sec; sec = sec->next)
{
if (sec->pkt->pkttype == PKT_SECRET_SUBKEY)
{
PKT_secret_key *sk = sec->pkt->pkt.secret_key;
if (!cmp_public_secret_key (pk, sk))
{
copy_public_parts_to_secret_key (pk, sk);
free_public_key (pk);
pub->pkt->pkttype = PKT_SECRET_SUBKEY;
pub->pkt->pkt.secret_key = copy_secret_key (NULL, sk);
break;
}
}
}
if (!sec)
BUG (); /* Already checked in premerge. */
}
}
}
/* This function checks that for every public subkey a corresponding
* secret subkey is available and deletes the public subkey otherwise.
* We need this function because we can't delete it later when we
* actually merge the secret parts into the pubring.
* The function also plays some games with the node flags.
*
* FIXME: this is not anymore needed but we keep it as example code for the
* new code we need to write for the import/export feature.
*/
static void
premerge_public_with_secret (KBNODE pubblock, KBNODE secblock)
{
KBNODE last, pub;
assert (pubblock->pkt->pkttype == PKT_PUBLIC_KEY);
assert (secblock->pkt->pkttype == PKT_SECRET_KEY);
for (pub = pubblock, last = NULL; pub; last = pub, pub = pub->next)
{
pub->flag &= ~3; /* Reset bits 0 and 1. */
if (pub->pkt->pkttype == PKT_PUBLIC_SUBKEY)
{
KBNODE sec;
PKT_public_key *pk = pub->pkt->pkt.public_key;
for (sec = secblock->next; sec; sec = sec->next)
{
if (sec->pkt->pkttype == PKT_SECRET_SUBKEY)
{
PKT_secret_key *sk = sec->pkt->pkt.secret_key;
if (!cmp_public_secret_key (pk, sk))
{
if (sk->protect.s2k.mode == 1001)
{
/* The secret parts are not available so
we can't use that key for signing etc.
Fix the pubkey usage */
pk->pubkey_usage &= ~(PUBKEY_USAGE_SIG
| PUBKEY_USAGE_AUTH);
}
/* Transfer flag bits 0 and 1 to the pubblock. */
pub->flag |= (sec->flag & 3);
break;
}
}
}
if (!sec)
{
KBNODE next, ll;
if (opt.verbose)
log_info (_("no secret subkey"
" for public subkey %s - ignoring\n"),
keystr_from_pk (pk));
/* We have to remove the subkey in this case. */
assert (last);
/* Find the next subkey. */
for (next = pub->next, ll = pub;
next && next->pkt->pkttype != PKT_PUBLIC_SUBKEY;
ll = next, next = next->next)
;
/* Make new link. */
last->next = next;
/* Release this public subkey with all sigs. */
ll->next = NULL;
release_kbnode (pub);
/* Let the loop continue. */
pub = last;
}
}
}
/* We need to copy the found bits (0 and 1) from the secret key to
the public key. This has already been done for the subkeys but
got lost on the primary key - fix it here. */
pubblock->flag |= (secblock->flag & 3);
}
#endif /*0*/
diff --git a/g10/gpg.c b/g10/gpg.c
index 4a17b2905..23b193402 100644
--- a/g10/gpg.c
+++ b/g10/gpg.c
@@ -1,4401 +1,4401 @@
/* gpg.c - The GnuPG utility (main for gpg)
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
* 2006, 2007, 2008, 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
* 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
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#ifdef HAVE_STAT
#include /* for stat() */
#endif
#include
#ifdef HAVE_W32_SYSTEM
#include
#endif
#define INCLUDED_BY_MAIN_MODULE 1
#include "gpg.h"
#include
#include "../common/iobuf.h"
#include "util.h"
#include "packet.h"
#include "main.h"
#include "options.h"
#include "keydb.h"
#include "trustdb.h"
#include "cipher.h"
#include "filter.h"
#include "ttyio.h"
#include "i18n.h"
#include "sysutils.h"
#include "status.h"
#include "keyserver-internal.h"
#include "exec.h"
#include "gc-opt-flags.h"
#include "asshelp.h"
#if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
#define MY_O_BINARY O_BINARY
#ifndef S_IRGRP
# define S_IRGRP 0
# define S_IWGRP 0
#endif
#else
#define MY_O_BINARY 0
#endif
enum cmd_and_opt_values
{
aNull = 0,
oArmor = 'a',
aDetachedSign = 'b',
aSym = 'c',
aDecrypt = 'd',
aEncr = 'e',
oInteractive = 'i',
aListKeys = 'k',
oDryRun = 'n',
oOutput = 'o',
oQuiet = 'q',
oRecipient = 'r',
oHiddenRecipient = 'R',
aSign = 's',
oTextmodeShort= 't',
oLocalUser = 'u',
oVerbose = 'v',
oCompress = 'z',
oSetNotation = 'N',
aListSecretKeys = 'K',
oBatch = 500,
oMaxOutput,
oSigNotation,
oCertNotation,
oShowNotation,
oNoShowNotation,
aEncrFiles,
aEncrSym,
aDecryptFiles,
aClearsign,
aStore,
aKeygen,
aSignEncr,
aSignEncrSym,
aSignSym,
aSignKey,
aLSignKey,
aListConfig,
aGPGConfList,
aGPGConfTest,
aListPackets,
aEditKey,
aDeleteKeys,
aDeleteSecretKeys,
aDeleteSecretAndPublicKeys,
aImport,
aFastImport,
aVerify,
aVerifyFiles,
aListSigs,
aSendKeys,
aRecvKeys,
aLocateKeys,
aSearchKeys,
aRefreshKeys,
aFetchKeys,
aExport,
aExportSecret,
aExportSecretSub,
aCheckKeys,
aGenRevoke,
aDesigRevoke,
aPrimegen,
aPrintMD,
aPrintMDs,
aCheckTrustDB,
aUpdateTrustDB,
aFixTrustDB,
aListTrustDB,
aListTrustPath,
aExportOwnerTrust,
aImportOwnerTrust,
aDeArmor,
aEnArmor,
aGenRandom,
aRebuildKeydbCaches,
aCardStatus,
aCardEdit,
aChangePIN,
aPasswd,
aServer,
oTextmode,
oNoTextmode,
oExpert,
oNoExpert,
oDefSigExpire,
oAskSigExpire,
oNoAskSigExpire,
oDefCertExpire,
oAskCertExpire,
oNoAskCertExpire,
oDefCertLevel,
oMinCertLevel,
oAskCertLevel,
oNoAskCertLevel,
oFingerprint,
oWithFingerprint,
oWithKeygrip,
oAnswerYes,
oAnswerNo,
oKeyring,
oPrimaryKeyring,
oSecretKeyring,
oShowKeyring,
oDefaultKey,
oDefRecipient,
oDefRecipientSelf,
oNoDefRecipient,
oTrySecretKey,
oOptions,
oDebug,
oDebugLevel,
oDebugAll,
oDebugCCIDDriver,
oStatusFD,
oStatusFile,
oAttributeFD,
oAttributeFile,
oEmitVersion,
oNoEmitVersion,
oCompletesNeeded,
oMarginalsNeeded,
oMaxCertDepth,
oLoadExtension,
oGnuPG,
oRFC1991,
oRFC2440,
oRFC4880,
oOpenPGP,
oPGP2,
oPGP6,
oPGP7,
oPGP8,
oRFC2440Text,
oNoRFC2440Text,
oCipherAlgo,
oDigestAlgo,
oCertDigestAlgo,
oCompressAlgo,
oCompressLevel,
oBZ2CompressLevel,
oBZ2DecompressLowmem,
oPassphrase,
oPassphraseFD,
oPassphraseFile,
oPassphraseRepeat,
oCommandFD,
oCommandFile,
oQuickRandom,
oNoVerbose,
oTrustDBName,
oNoSecmemWarn,
oRequireSecmem,
oNoRequireSecmem,
oNoPermissionWarn,
oNoMDCWarn,
oNoArmor,
oNoDefKeyring,
oNoGreeting,
oNoTTY,
oNoOptions,
oNoBatch,
oHomedir,
oWithColons,
oWithKeyData,
oWithSigList,
oWithSigCheck,
oSkipVerify,
oSkipHiddenRecipients,
oNoSkipHiddenRecipients,
oCompressKeys,
oCompressSigs,
oAlwaysTrust,
oTrustModel,
oForceOwnertrust,
oSetFilename,
oForYourEyesOnly,
oNoForYourEyesOnly,
oSetPolicyURL,
oSigPolicyURL,
oCertPolicyURL,
oShowPolicyURL,
oNoShowPolicyURL,
oSigKeyserverURL,
oUseEmbeddedFilename,
oNoUseEmbeddedFilename,
oComment,
oDefaultComment,
oNoComments,
oThrowKeyids,
oNoThrowKeyids,
oShowPhotos,
oNoShowPhotos,
oPhotoViewer,
oForceV3Sigs,
oNoForceV3Sigs,
oForceV4Certs,
oNoForceV4Certs,
oForceMDC,
oNoForceMDC,
oDisableMDC,
oNoDisableMDC,
oS2KMode,
oS2KDigest,
oS2KCipher,
oS2KCount,
oDisplayCharset,
oNotDashEscaped,
oEscapeFrom,
oNoEscapeFrom,
oLockOnce,
oLockMultiple,
oLockNever,
oKeyServer,
oKeyServerOptions,
oImportOptions,
oExportOptions,
oListOptions,
oVerifyOptions,
oTempDir,
oExecPath,
oEncryptTo,
oHiddenEncryptTo,
oNoEncryptTo,
oLoggerFD,
oLoggerFile,
oUtf8Strings,
oNoUtf8Strings,
oDisableCipherAlgo,
oDisablePubkeyAlgo,
oAllowNonSelfsignedUID,
oNoAllowNonSelfsignedUID,
oAllowFreeformUID,
oNoAllowFreeformUID,
oAllowSecretKeyImport,
oEnableSpecialFilenames,
oNoLiteral,
oSetFilesize,
oHonorHttpProxy,
oFastListMode,
oListOnly,
oIgnoreTimeConflict,
oIgnoreValidFrom,
oIgnoreCrcError,
oIgnoreMDCError,
oShowSessionKey,
oOverrideSessionKey,
oNoRandomSeedFile,
oAutoKeyRetrieve,
oNoAutoKeyRetrieve,
oUseAgent,
oNoUseAgent,
oGpgAgentInfo,
oMergeOnly,
oTryAllSecrets,
oTrustedKey,
oNoExpensiveTrustChecks,
oFixedListMode,
oNoSigCache,
oNoSigCreateCheck,
oAutoCheckTrustDB,
oNoAutoCheckTrustDB,
oPreservePermissions,
oDefaultPreferenceList,
oDefaultKeyserverURL,
oPersonalCipherPreferences,
oPersonalDigestPreferences,
oPersonalCompressPreferences,
oAgentProgram,
oDisplay,
oTTYname,
oTTYtype,
oLCctype,
oLCmessages,
oXauthority,
oGroup,
oUnGroup,
oNoGroups,
oStrict,
oNoStrict,
oMangleDosFilenames,
oNoMangleDosFilenames,
oEnableProgressFilter,
oMultifile,
oKeyidFormat,
oExitOnStatusWriteError,
oLimitCardInsertTries,
oRequireCrossCert,
oNoRequireCrossCert,
oAutoKeyLocate,
oNoAutoKeyLocate,
oAllowMultisigVerification,
oEnableDSA2,
oDisableDSA2,
oAllowMultipleMessages,
oNoAllowMultipleMessages,
oFakedSystemTime,
oNoop
};
static ARGPARSE_OPTS opts[] = {
ARGPARSE_group (300, N_("@Commands:\n ")),
ARGPARSE_c (aSign, "sign", N_("make a signature")),
ARGPARSE_c (aClearsign, "clearsign", N_("make a clear text signature")),
ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")),
ARGPARSE_c (aEncr, "encrypt", N_("encrypt data")),
ARGPARSE_c (aEncrFiles, "encrypt-files", "@"),
ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")),
ARGPARSE_c (aStore, "store", "@"),
ARGPARSE_c (aDecrypt, "decrypt", N_("decrypt data (default)")),
ARGPARSE_c (aDecryptFiles, "decrypt-files", "@"),
ARGPARSE_c (aVerify, "verify" , N_("verify a signature")),
ARGPARSE_c (aVerifyFiles, "verify-files" , "@" ),
ARGPARSE_c (aListKeys, "list-keys", N_("list keys")),
ARGPARSE_c (aListKeys, "list-public-keys", "@" ),
ARGPARSE_c (aListSigs, "list-sigs", N_("list keys and signatures")),
ARGPARSE_c (aCheckKeys, "check-sigs",N_("list and check key signatures")),
ARGPARSE_c (oFingerprint, "fingerprint", N_("list keys and fingerprints")),
ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")),
ARGPARSE_c (aKeygen, "gen-key", N_("generate a new key pair")),
ARGPARSE_c (aGenRevoke, "gen-revoke",N_("generate a revocation certificate")),
ARGPARSE_c (aDeleteKeys,"delete-keys",
N_("remove keys from the public keyring")),
ARGPARSE_c (aDeleteSecretKeys, "delete-secret-keys",
N_("remove keys from the secret keyring")),
ARGPARSE_c (aSignKey, "sign-key" ,N_("sign a key")),
ARGPARSE_c (aLSignKey, "lsign-key" ,N_("sign a key locally")),
ARGPARSE_c (aEditKey, "edit-key" ,N_("sign or edit a key")),
ARGPARSE_c (aEditKey, "key-edit" ,"@"),
ARGPARSE_c (aPasswd, "passwd", N_("change a passphrase")),
ARGPARSE_c (aDesigRevoke, "desig-revoke","@" ),
ARGPARSE_c (aExport, "export" , N_("export keys") ),
ARGPARSE_c (aSendKeys, "send-keys" , N_("export keys to a key server") ),
ARGPARSE_c (aRecvKeys, "recv-keys" , N_("import keys from a key server") ),
ARGPARSE_c (aSearchKeys, "search-keys" ,
N_("search for keys on a key server") ),
ARGPARSE_c (aRefreshKeys, "refresh-keys",
N_("update all keys from a keyserver")),
ARGPARSE_c (aLocateKeys, "locate-keys", "@"),
ARGPARSE_c (aFetchKeys, "fetch-keys" , "@" ),
ARGPARSE_c (aExportSecret, "export-secret-keys" , "@" ),
ARGPARSE_c (aExportSecretSub, "export-secret-subkeys" , "@" ),
ARGPARSE_c (aImport, "import", N_("import/merge keys")),
ARGPARSE_c (aFastImport, "fast-import", "@"),
#ifdef ENABLE_CARD_SUPPORT
ARGPARSE_c (aCardStatus, "card-status", N_("print the card status")),
ARGPARSE_c (aCardEdit, "card-edit", N_("change data on a card")),
ARGPARSE_c (aChangePIN, "change-pin", N_("change a card's PIN")),
#endif
ARGPARSE_c (aListConfig, "list-config", "@"),
ARGPARSE_c (aGPGConfList, "gpgconf-list", "@" ),
ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@" ),
ARGPARSE_c (aListPackets, "list-packets","@"),
ARGPARSE_c (aExportOwnerTrust, "export-ownertrust", "@"),
ARGPARSE_c (aImportOwnerTrust, "import-ownertrust", "@"),
ARGPARSE_c (aUpdateTrustDB,"update-trustdb",
N_("update the trust database")),
ARGPARSE_c (aCheckTrustDB, "check-trustdb", "@"),
ARGPARSE_c (aFixTrustDB, "fix-trustdb", "@"),
ARGPARSE_c (aDeArmor, "dearmor", "@"),
ARGPARSE_c (aDeArmor, "dearmour", "@"),
ARGPARSE_c (aEnArmor, "enarmor", "@"),
ARGPARSE_c (aEnArmor, "enarmour", "@"),
ARGPARSE_c (aPrintMD, "print-md", N_("print message digests")),
ARGPARSE_c (aPrimegen, "gen-prime", "@" ),
ARGPARSE_c (aGenRandom,"gen-random", "@" ),
ARGPARSE_c (aServer, "server", N_("run in server mode")),
ARGPARSE_group (301, N_("@\nOptions:\n ")),
ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")),
ARGPARSE_s_n (oArmor, "armour", "@"),
ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")),
ARGPARSE_s_s (oHiddenRecipient, "hidden-recipient", "@"),
ARGPARSE_s_s (oRecipient, "remote-user", "@"), /* (old option name) */
ARGPARSE_s_s (oDefRecipient, "default-recipient", "@"),
ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", "@"),
ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"),
ARGPARSE_s_s (oTempDir, "temp-directory", "@"),
ARGPARSE_s_s (oExecPath, "exec-path", "@"),
ARGPARSE_s_s (oEncryptTo, "encrypt-to", "@"),
ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"),
ARGPARSE_s_s (oHiddenEncryptTo, "hidden-encrypt-to", "@"),
ARGPARSE_s_s (oLocalUser, "local-user",
N_("|USER-ID|use USER-ID to sign or decrypt")),
ARGPARSE_s_s (oTrySecretKey, "try-secret-key", "@"),
ARGPARSE_s_i (oCompress, NULL,
N_("|N|set compress level to N (0 disables)")),
ARGPARSE_s_i (oCompressLevel, "compress-level", "@"),
ARGPARSE_s_i (oBZ2CompressLevel, "bzip2-compress-level", "@"),
ARGPARSE_s_n (oBZ2DecompressLowmem, "bzip2-decompress-lowmem", "@"),
ARGPARSE_s_n (oTextmodeShort, NULL, "@"),
ARGPARSE_s_n (oTextmode, "textmode", N_("use canonical text mode")),
ARGPARSE_s_n (oNoTextmode, "no-textmode", "@"),
ARGPARSE_s_n (oExpert, "expert", "@"),
ARGPARSE_s_n (oNoExpert, "no-expert", "@"),
ARGPARSE_s_s (oDefSigExpire, "default-sig-expire", "@"),
ARGPARSE_s_n (oAskSigExpire, "ask-sig-expire", "@"),
ARGPARSE_s_n (oNoAskSigExpire, "no-ask-sig-expire", "@"),
ARGPARSE_s_s (oDefCertExpire, "default-cert-expire", "@"),
ARGPARSE_s_n (oAskCertExpire, "ask-cert-expire", "@"),
ARGPARSE_s_n (oNoAskCertExpire, "no-ask-cert-expire", "@"),
ARGPARSE_s_i (oDefCertLevel, "default-cert-level", "@"),
ARGPARSE_s_i (oMinCertLevel, "min-cert-level", "@"),
ARGPARSE_s_n (oAskCertLevel, "ask-cert-level", "@"),
ARGPARSE_s_n (oNoAskCertLevel, "no-ask-cert-level", "@"),
ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")),
ARGPARSE_p_u (oMaxOutput, "max-output", "@"),
ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
ARGPARSE_s_n (oQuiet, "quiet", "@"),
ARGPARSE_s_n (oNoTTY, "no-tty", "@"),
ARGPARSE_s_n (oForceV3Sigs, "force-v3-sigs", "@"),
ARGPARSE_s_n (oNoForceV3Sigs, "no-force-v3-sigs", "@"),
ARGPARSE_s_n (oForceV4Certs, "force-v4-certs", "@"),
ARGPARSE_s_n (oNoForceV4Certs, "no-force-v4-certs", "@"),
ARGPARSE_s_n (oForceMDC, "force-mdc", "@"),
ARGPARSE_s_n (oNoForceMDC, "no-force-mdc", "@"),
ARGPARSE_s_n (oDisableMDC, "disable-mdc", "@"),
ARGPARSE_s_n (oNoDisableMDC, "no-disable-mdc", "@"),
ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")),
ARGPARSE_s_n (oInteractive, "interactive", N_("prompt before overwriting")),
ARGPARSE_s_n (oUseAgent, "use-agent", "@"),
ARGPARSE_s_n (oNoUseAgent, "no-use-agent", "@"),
ARGPARSE_s_s (oGpgAgentInfo, "gpg-agent-info", "@"),
ARGPARSE_s_n (oBatch, "batch", "@"),
ARGPARSE_s_n (oAnswerYes, "yes", "@"),
ARGPARSE_s_n (oAnswerNo, "no", "@"),
ARGPARSE_s_s (oKeyring, "keyring", "@"),
ARGPARSE_s_s (oPrimaryKeyring, "primary-keyring", "@"),
ARGPARSE_s_s (oSecretKeyring, "secret-keyring", "@"),
ARGPARSE_s_n (oShowKeyring, "show-keyring", "@"),
ARGPARSE_s_s (oDefaultKey, "default-key", "@"),
ARGPARSE_s_s (oKeyServer, "keyserver", "@"),
ARGPARSE_s_s (oKeyServerOptions, "keyserver-options", "@"),
ARGPARSE_s_s (oImportOptions, "import-options", "@"),
ARGPARSE_s_s (oExportOptions, "export-options", "@"),
ARGPARSE_s_s (oListOptions, "list-options", "@"),
ARGPARSE_s_s (oVerifyOptions, "verify-options", "@"),
ARGPARSE_s_s (oDisplayCharset, "display-charset", "@"),
ARGPARSE_s_s (oDisplayCharset, "charset", "@"),
ARGPARSE_s_s (oOptions, "options", "@"),
ARGPARSE_p_u (oDebug, "debug", "@"),
ARGPARSE_s_s (oDebugLevel, "debug-level", "@"),
ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
ARGPARSE_s_i (oStatusFD, "status-fd", "@"),
ARGPARSE_s_s (oStatusFile, "status-file", "@"),
ARGPARSE_s_i (oAttributeFD, "attribute-fd", "@"),
ARGPARSE_s_s (oAttributeFile, "attribute-file", "@"),
ARGPARSE_s_n (oNoop, "sk-comments", "@"),
ARGPARSE_s_n (oNoop, "no-sk-comments", "@"),
ARGPARSE_s_i (oCompletesNeeded, "completes-needed", "@"),
ARGPARSE_s_i (oMarginalsNeeded, "marginals-needed", "@"),
ARGPARSE_s_i (oMaxCertDepth, "max-cert-depth", "@" ),
ARGPARSE_s_s (oTrustedKey, "trusted-key", "@"),
ARGPARSE_s_s (oLoadExtension, "load-extension", "@"), /* Dummy. */
ARGPARSE_s_n (oGnuPG, "gnupg", "@"),
ARGPARSE_s_n (oGnuPG, "no-pgp2", "@"),
ARGPARSE_s_n (oGnuPG, "no-pgp6", "@"),
ARGPARSE_s_n (oGnuPG, "no-pgp7", "@"),
ARGPARSE_s_n (oGnuPG, "no-pgp8", "@"),
ARGPARSE_s_n (oRFC1991, "rfc1991", "@"),
ARGPARSE_s_n (oRFC2440, "rfc2440", "@"),
ARGPARSE_s_n (oRFC4880, "rfc4880", "@"),
ARGPARSE_s_n (oOpenPGP, "openpgp", N_("use strict OpenPGP behavior")),
ARGPARSE_s_n (oPGP2, "pgp2", "@"),
ARGPARSE_s_n (oPGP6, "pgp6", "@"),
ARGPARSE_s_n (oPGP7, "pgp7", "@"),
ARGPARSE_s_n (oPGP8, "pgp8", "@"),
ARGPARSE_s_n (oRFC2440Text, "rfc2440-text", "@"),
ARGPARSE_s_n (oNoRFC2440Text, "no-rfc2440-text", "@"),
ARGPARSE_s_i (oS2KMode, "s2k-mode", "@"),
ARGPARSE_s_s (oS2KDigest, "s2k-digest-algo", "@"),
ARGPARSE_s_s (oS2KCipher, "s2k-cipher-algo", "@"),
ARGPARSE_s_i (oS2KCount, "s2k-count", "@"),
ARGPARSE_s_s (oCipherAlgo, "cipher-algo", "@"),
ARGPARSE_s_s (oDigestAlgo, "digest-algo", "@"),
ARGPARSE_s_s (oCertDigestAlgo, "cert-digest-algo", "@"),
ARGPARSE_s_s (oCompressAlgo,"compress-algo", "@"),
ARGPARSE_s_s (oCompressAlgo, "compression-algo", "@"), /* Alias */
ARGPARSE_s_n (oThrowKeyids, "throw-keyid", "@"),
ARGPARSE_s_n (oThrowKeyids, "throw-keyids", "@"),
ARGPARSE_s_n (oNoThrowKeyids, "no-throw-keyid", "@"),
ARGPARSE_s_n (oNoThrowKeyids, "no-throw-keyids", "@"),
ARGPARSE_s_n (oShowPhotos, "show-photos", "@"),
ARGPARSE_s_n (oNoShowPhotos, "no-show-photos", "@"),
ARGPARSE_s_s (oPhotoViewer, "photo-viewer", "@"),
ARGPARSE_s_s (oSetNotation, "set-notation", "@"),
ARGPARSE_s_s (oSetNotation, "notation-data", "@"), /* Alias */
ARGPARSE_s_s (oSigNotation, "sig-notation", "@"),
ARGPARSE_s_s (oCertNotation, "cert-notation", "@"),
ARGPARSE_group (302, N_(
"@\n(See the man page for a complete listing of all commands and options)\n"
)),
ARGPARSE_group (303, N_("@\nExamples:\n\n"
" -se -r Bob [file] sign and encrypt for user Bob\n"
" --clearsign [file] make a clear text signature\n"
" --detach-sign [file] make a detached signature\n"
" --list-keys [names] show keys\n"
" --fingerprint [names] show fingerprints\n")),
/* More hidden commands and options. */
ARGPARSE_c (aPrintMDs, "print-mds", "@"), /* old */
ARGPARSE_c (aListTrustDB, "list-trustdb", "@"),
/* Not yet used:
ARGPARSE_c (aListTrustPath, "list-trust-path", "@"), */
ARGPARSE_c (aDeleteSecretAndPublicKeys,
"delete-secret-and-public-keys", "@"),
ARGPARSE_c (aRebuildKeydbCaches, "rebuild-keydb-caches", "@"),
ARGPARSE_s_s (oPassphrase, "passphrase", "@"),
ARGPARSE_s_i (oPassphraseFD, "passphrase-fd", "@"),
ARGPARSE_s_s (oPassphraseFile, "passphrase-file", "@"),
ARGPARSE_s_i (oPassphraseRepeat,"passphrase-repeat", "@"),
ARGPARSE_s_i (oCommandFD, "command-fd", "@"),
ARGPARSE_s_s (oCommandFile, "command-file", "@"),
ARGPARSE_s_n (oQuickRandom, "debug-quick-random", "@"),
ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
ARGPARSE_s_s (oTrustDBName, "trustdb-name", "@"),
ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"),
ARGPARSE_s_n (oRequireSecmem, "require-secmem", "@"),
ARGPARSE_s_n (oNoRequireSecmem, "no-require-secmem", "@"),
ARGPARSE_s_n (oNoPermissionWarn, "no-permission-warning", "@"),
ARGPARSE_s_n (oNoMDCWarn, "no-mdc-warning", "@"),
ARGPARSE_s_n (oNoArmor, "no-armor", "@"),
ARGPARSE_s_n (oNoArmor, "no-armour", "@"),
ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"),
ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
ARGPARSE_s_n (oNoOptions, "no-options", "@"),
ARGPARSE_s_s (oHomedir, "homedir", "@"),
ARGPARSE_s_n (oNoBatch, "no-batch", "@"),
ARGPARSE_s_n (oWithColons, "with-colons", "@"),
ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"),
ARGPARSE_s_n (oWithSigList,"with-sig-list", "@"),
ARGPARSE_s_n (oWithSigCheck,"with-sig-check", "@"),
ARGPARSE_s_n (aListKeys, "list-key", "@"), /* alias */
ARGPARSE_s_n (aListSigs, "list-sig", "@"), /* alias */
ARGPARSE_s_n (aCheckKeys, "check-sig", "@"), /* alias */
ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"),
ARGPARSE_s_n (oSkipHiddenRecipients, "skip-hidden-recipients", "@"),
ARGPARSE_s_n (oNoSkipHiddenRecipients, "no-skip-hidden-recipients", "@"),
ARGPARSE_s_n (oCompressKeys, "compress-keys", "@"),
ARGPARSE_s_n (oCompressSigs, "compress-sigs", "@"),
ARGPARSE_s_i (oDefCertLevel, "default-cert-check-level", "@"), /* old */
ARGPARSE_s_n (oAlwaysTrust, "always-trust", "@"),
ARGPARSE_s_s (oTrustModel, "trust-model", "@"),
ARGPARSE_s_s (oForceOwnertrust, "force-ownertrust", "@"),
ARGPARSE_s_s (oSetFilename, "set-filename", "@"),
ARGPARSE_s_n (oForYourEyesOnly, "for-your-eyes-only", "@"),
ARGPARSE_s_n (oNoForYourEyesOnly, "no-for-your-eyes-only", "@"),
ARGPARSE_s_s (oSetPolicyURL, "set-policy-url", "@"),
ARGPARSE_s_s (oSigPolicyURL, "sig-policy-url", "@"),
ARGPARSE_s_s (oCertPolicyURL, "cert-policy-url", "@"),
ARGPARSE_s_n (oShowPolicyURL, "show-policy-url", "@"),
ARGPARSE_s_n (oNoShowPolicyURL, "no-show-policy-url", "@"),
ARGPARSE_s_s (oSigKeyserverURL, "sig-keyserver-url", "@"),
ARGPARSE_s_n (oShowNotation, "show-notation", "@"),
ARGPARSE_s_n (oNoShowNotation, "no-show-notation", "@"),
ARGPARSE_s_s (oComment, "comment", "@"),
ARGPARSE_s_n (oDefaultComment, "default-comment", "@"),
ARGPARSE_s_n (oNoComments, "no-comments", "@"),
ARGPARSE_s_n (oEmitVersion, "emit-version", "@"),
ARGPARSE_s_n (oNoEmitVersion, "no-emit-version", "@"),
ARGPARSE_s_n (oNoEmitVersion, "no-version", "@"), /* alias */
ARGPARSE_s_n (oNotDashEscaped, "not-dash-escaped", "@"),
ARGPARSE_s_n (oEscapeFrom, "escape-from-lines", "@"),
ARGPARSE_s_n (oNoEscapeFrom, "no-escape-from-lines", "@"),
ARGPARSE_s_n (oLockOnce, "lock-once", "@"),
ARGPARSE_s_n (oLockMultiple, "lock-multiple", "@"),
ARGPARSE_s_n (oLockNever, "lock-never", "@"),
ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"),
ARGPARSE_s_s (oLoggerFile, "log-file", "@"),
ARGPARSE_s_s (oLoggerFile, "logger-file", "@"), /* 1.4 compatibility. */
ARGPARSE_s_n (oUseEmbeddedFilename, "use-embedded-filename", "@"),
ARGPARSE_s_n (oNoUseEmbeddedFilename, "no-use-embedded-filename", "@"),
ARGPARSE_s_n (oUtf8Strings, "utf8-strings", "@"),
ARGPARSE_s_n (oNoUtf8Strings, "no-utf8-strings", "@"),
ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"),
ARGPARSE_s_n (oWithKeygrip, "with-keygrip", "@"),
ARGPARSE_s_s (oDisableCipherAlgo, "disable-cipher-algo", "@"),
ARGPARSE_s_s (oDisablePubkeyAlgo, "disable-pubkey-algo", "@"),
ARGPARSE_s_n (oAllowNonSelfsignedUID, "allow-non-selfsigned-uid", "@"),
ARGPARSE_s_n (oNoAllowNonSelfsignedUID, "no-allow-non-selfsigned-uid", "@"),
ARGPARSE_s_n (oAllowFreeformUID, "allow-freeform-uid", "@"),
ARGPARSE_s_n (oNoAllowFreeformUID, "no-allow-freeform-uid", "@"),
ARGPARSE_s_n (oNoLiteral, "no-literal", "@"),
ARGPARSE_p_u (oSetFilesize, "set-filesize", "@"),
ARGPARSE_s_n (oHonorHttpProxy, "honor-http-proxy", "@"),
ARGPARSE_s_n (oFastListMode, "fast-list-mode", "@"),
ARGPARSE_s_n (oFixedListMode, "fixed-list-mode", "@"),
ARGPARSE_s_n (oListOnly, "list-only", "@"),
ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"),
ARGPARSE_s_n (oIgnoreValidFrom, "ignore-valid-from", "@"),
ARGPARSE_s_n (oIgnoreCrcError, "ignore-crc-error", "@"),
ARGPARSE_s_n (oIgnoreMDCError, "ignore-mdc-error", "@"),
ARGPARSE_s_n (oShowSessionKey, "show-session-key", "@"),
ARGPARSE_s_s (oOverrideSessionKey, "override-session-key", "@"),
ARGPARSE_s_n (oNoRandomSeedFile, "no-random-seed-file", "@"),
ARGPARSE_s_n (oAutoKeyRetrieve, "auto-key-retrieve", "@"),
ARGPARSE_s_n (oNoAutoKeyRetrieve, "no-auto-key-retrieve", "@"),
ARGPARSE_s_n (oNoSigCache, "no-sig-cache", "@"),
ARGPARSE_s_n (oNoSigCreateCheck, "no-sig-create-check", "@"),
ARGPARSE_s_n (oAutoCheckTrustDB, "auto-check-trustdb", "@"),
ARGPARSE_s_n (oNoAutoCheckTrustDB, "no-auto-check-trustdb", "@"),
ARGPARSE_s_n (oMergeOnly, "merge-only", "@" ),
ARGPARSE_s_n (oAllowSecretKeyImport, "allow-secret-key-import", "@"),
ARGPARSE_s_n (oTryAllSecrets, "try-all-secrets", "@"),
ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"),
ARGPARSE_s_n (oNoExpensiveTrustChecks, "no-expensive-trust-checks", "@"),
ARGPARSE_s_n (oPreservePermissions, "preserve-permissions", "@"),
ARGPARSE_s_s (oDefaultPreferenceList, "default-preference-list", "@"),
ARGPARSE_s_s (oDefaultKeyserverURL, "default-keyserver-url", "@"),
ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-preferences","@"),
ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-preferences","@"),
ARGPARSE_s_s (oPersonalCompressPreferences,
"personal-compress-preferences", "@"),
ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
/* Aliases. I constantly mistype these, and assume other people do
as well. */
ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-prefs", "@"),
ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-prefs", "@"),
ARGPARSE_s_s (oPersonalCompressPreferences, "personal-compress-prefs", "@"),
ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
ARGPARSE_s_s (oDisplay, "display", "@"),
ARGPARSE_s_s (oTTYname, "ttyname", "@"),
ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
ARGPARSE_s_s (oLCmessages, "lc-messages","@"),
ARGPARSE_s_s (oXauthority, "xauthority", "@"),
ARGPARSE_s_s (oGroup, "group", "@"),
ARGPARSE_s_s (oUnGroup, "ungroup", "@"),
ARGPARSE_s_n (oNoGroups, "no-groups", "@"),
ARGPARSE_s_n (oStrict, "strict", "@"),
ARGPARSE_s_n (oNoStrict, "no-strict", "@"),
ARGPARSE_s_n (oMangleDosFilenames, "mangle-dos-filenames", "@"),
ARGPARSE_s_n (oNoMangleDosFilenames, "no-mangle-dos-filenames", "@"),
ARGPARSE_s_n (oEnableProgressFilter, "enable-progress-filter", "@"),
ARGPARSE_s_n (oMultifile, "multifile", "@"),
ARGPARSE_s_s (oKeyidFormat, "keyid-format", "@"),
ARGPARSE_s_n (oExitOnStatusWriteError, "exit-on-status-write-error", "@"),
ARGPARSE_s_i (oLimitCardInsertTries, "limit-card-insert-tries", "@"),
ARGPARSE_s_n (oAllowMultisigVerification,
"allow-multisig-verification", "@"),
ARGPARSE_s_n (oEnableDSA2, "enable-dsa2", "@"),
ARGPARSE_s_n (oDisableDSA2, "disable-dsa2", "@"),
ARGPARSE_s_n (oAllowMultipleMessages, "allow-multiple-messages", "@"),
ARGPARSE_s_n (oNoAllowMultipleMessages, "no-allow-multiple-messages", "@"),
/* These two are aliases to help users of the PGP command line
product use gpg with minimal pain. Many commands are common
already as they seem to have borrowed commands from us. Now I'm
returning the favor. */
ARGPARSE_s_s (oLocalUser, "sign-with", "@"),
ARGPARSE_s_s (oRecipient, "user", "@"),
ARGPARSE_s_n (oRequireCrossCert, "require-backsigs", "@"),
ARGPARSE_s_n (oRequireCrossCert, "require-cross-certification", "@"),
ARGPARSE_s_n (oNoRequireCrossCert, "no-require-backsigs", "@"),
ARGPARSE_s_n (oNoRequireCrossCert, "no-require-cross-certification", "@"),
/* New options. Fixme: Should go more to the top. */
ARGPARSE_s_s (oAutoKeyLocate, "auto-key-locate", "@"),
ARGPARSE_s_n (oNoAutoKeyLocate, "no-auto-key-locate", "@"),
ARGPARSE_end ()
};
#ifdef ENABLE_SELINUX_HACKS
#define ALWAYS_ADD_KEYRINGS 1
#else
#define ALWAYS_ADD_KEYRINGS 0
#endif
int g10_errors_seen = 0;
static int utf8_strings = 0;
static int maybe_setuid = 1;
static char *build_list( const char *text, char letter,
const char *(*mapf)(int), int (*chkf)(int) );
static void set_cmd( enum cmd_and_opt_values *ret_cmd,
enum cmd_and_opt_values new_cmd );
static void print_mds( const char *fname, int algo );
static void add_notation_data( const char *string, int which );
static void add_policy_url( const char *string, int which );
static void add_keyserver_url( const char *string, int which );
static void emergency_cleanup (void);
static char *
make_libversion (const char *libname, const char *(*getfnc)(const char*))
{
const char *s;
char *result;
if (maybe_setuid)
{
gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
maybe_setuid = 0;
}
s = getfnc (NULL);
result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
strcpy (stpcpy (stpcpy (result, libname), " "), s);
return result;
}
static const char *
my_strusage( int level )
{
static char *digests, *pubkeys, *ciphers, *zips, *ver_gcry;
const char *p;
switch( level ) {
- case 11: p = "gpg (GnuPG)";
+ case 11: p = "gpg (GnuPG) ecc";
break;
case 13: p = VERSION; break;
case 17: p = PRINTABLE_OS_NAME; break;
case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
case 20:
if (!ver_gcry)
ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
p = ver_gcry;
break;
#ifdef IS_DEVELOPMENT_VERSION
case 25:
p="NOTE: THIS IS A DEVELOPMENT VERSION!";
break;
case 26:
p="It is only intended for test purposes and should NOT be";
break;
case 27:
p="used in a production environment or with production keys!";
break;
#endif
case 1:
case 40: p =
_("Usage: gpg [options] [files] (-h for help)");
break;
case 41: p =
_("Syntax: gpg [options] [files]\n"
"sign, check, encrypt or decrypt\n"
"default operation depends on the input data\n");
break;
case 31: p = "\nHome: "; break;
#ifndef __riscos__
case 32: p = opt.homedir; break;
#else /* __riscos__ */
case 32: p = make_filename(opt.homedir, NULL); break;
#endif /* __riscos__ */
case 33: p = _("\nSupported algorithms:\n"); break;
case 34:
if (!pubkeys)
pubkeys = build_list (_("Pubkey: "), 0,
- gcry_pk_algo_name,
+ openpgp_pk_algo_name,
openpgp_pk_test_algo );
p = pubkeys;
break;
case 35:
if( !ciphers )
ciphers = build_list(_("Cipher: "), 'S',
openpgp_cipher_algo_name,
openpgp_cipher_test_algo );
p = ciphers;
break;
case 36:
if( !digests )
digests = build_list(_("Hash: "), 'H',
gcry_md_algo_name,
openpgp_md_test_algo );
p = digests;
break;
case 37:
if( !zips )
zips = build_list(_("Compression: "),'Z',
compress_algo_to_string,
check_compress_algo);
p = zips;
break;
default: p = NULL;
}
return p;
}
static char *
build_list( const char *text, char letter,
const char * (*mapf)(int), int (*chkf)(int) )
{
int i;
const char *s;
size_t n=strlen(text)+2;
char *list, *p, *line=NULL;
if (maybe_setuid)
gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
for(i=0; i <= 110; i++ )
if( !chkf(i) && (s=mapf(i)) )
n += strlen(s) + 7 + 2;
list = xmalloc( 21 + n ); *list = 0;
for(p=NULL, i=0; i <= 110; i++ ) {
if( !chkf(i) && (s=mapf(i)) ) {
if( !p ) {
p = stpcpy( list, text );
line=p;
}
else
p = stpcpy( p, ", ");
if(strlen(line)>60) {
int spaces=strlen(text);
list=xrealloc(list,n+spaces+1);
/* realloc could move the block, so find the end again */
p=list;
while(*p)
p++;
p=stpcpy(p, "\n");
line=p;
for(;spaces;spaces--)
p=stpcpy(p, " ");
}
p = stpcpy(p, s );
if(opt.verbose && letter)
{
char num[8];
sprintf(num," (%c%d)",letter,i);
p = stpcpy(p,num);
}
}
}
if( p )
p = stpcpy(p, "\n" );
return list;
}
static void
wrong_args( const char *text)
{
fputs(_("usage: gpg [options] "),stderr);
fputs(text,stderr);
putc('\n',stderr);
g10_exit(2);
}
static char *
make_username( const char *string )
{
char *p;
if( utf8_strings )
p = xstrdup(string);
else
p = native_to_utf8( string );
return p;
}
static void
set_opt_session_env (const char *name, const char *value)
{
gpg_error_t err;
err = session_env_setenv (opt.session_env, name, value);
if (err)
log_fatal ("error setting session environment: %s\n",
gpg_strerror (err));
}
/* Setup the debugging. With a LEVEL of NULL only the active debug
flags are propagated to the subsystems. With LEVEL set, a specific
set of debug flags is set; thus overriding all flags already
set. */
static void
set_debug (const char *level)
{
int numok = (level && digitp (level));
int numlvl = numok? atoi (level) : 0;
if (!level)
;
else if (!strcmp (level, "none") || (numok && numlvl < 1))
opt.debug = 0;
else if (!strcmp (level, "basic") || (numok && numlvl <= 2))
opt.debug = DBG_MEMSTAT_VALUE;
else if (!strcmp (level, "advanced") || (numok && numlvl <= 5))
opt.debug = DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE;
else if (!strcmp (level, "expert") || (numok && numlvl <= 8))
opt.debug = (DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE
|DBG_CACHE_VALUE|DBG_FILTER_VALUE|DBG_PACKET_VALUE);
else if (!strcmp (level, "guru") || numok)
{
opt.debug = ~0;
/* Unless the "guru" string has been used we don't want to allow
hashing debugging. The rationale is that people tend to
select the highest debug value and would then clutter their
disk with debug files which may reveal confidential data. */
if (numok)
opt.debug &= ~(DBG_HASHING_VALUE);
}
else
{
log_error (_("invalid debug-level `%s' given\n"), level);
g10_exit (2);
}
if (opt.debug & DBG_MEMORY_VALUE )
memory_debug_mode = 1;
if (opt.debug & DBG_MEMSTAT_VALUE )
memory_stat_debug_mode = 1;
if (opt.debug & DBG_MPI_VALUE)
gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
if (opt.debug & DBG_CIPHER_VALUE )
gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
if (opt.debug & DBG_IOBUF_VALUE )
iobuf_debug_mode = 1;
gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
if (opt.debug)
log_info ("enabled debug flags:%s%s%s%s%s%s%s%s%s%s%s%s%s\n",
(opt.debug & DBG_PACKET_VALUE )? " packet":"",
(opt.debug & DBG_MPI_VALUE )? " mpi":"",
(opt.debug & DBG_CIPHER_VALUE )? " cipher":"",
(opt.debug & DBG_FILTER_VALUE )? " filter":"",
(opt.debug & DBG_IOBUF_VALUE )? " iobuf":"",
(opt.debug & DBG_MEMORY_VALUE )? " memory":"",
(opt.debug & DBG_CACHE_VALUE )? " cache":"",
(opt.debug & DBG_MEMSTAT_VALUE)? " memstat":"",
(opt.debug & DBG_TRUST_VALUE )? " trust":"",
(opt.debug & DBG_HASHING_VALUE)? " hashing":"",
(opt.debug & DBG_EXTPROG_VALUE)? " extprog":"",
(opt.debug & DBG_CARD_IO_VALUE)? " cardio":"",
(opt.debug & DBG_ASSUAN_VALUE )? " assuan":"");
}
/* We need the home directory also in some other directories, so make
sure that both variables are always in sync. */
static void
set_homedir (const char *dir)
{
if (!dir)
dir = "";
opt.homedir = dir;
}
/* We set the screen dimensions for UI purposes. Do not allow screens
smaller than 80x24 for the sake of simplicity. */
static void
set_screen_dimensions(void)
{
#ifndef HAVE_W32_SYSTEM
char *str;
str=getenv("COLUMNS");
if(str)
opt.screen_columns=atoi(str);
str=getenv("LINES");
if(str)
opt.screen_lines=atoi(str);
#endif
if(opt.screen_columns<80 || opt.screen_columns>255)
opt.screen_columns=80;
if(opt.screen_lines<24 || opt.screen_lines>255)
opt.screen_lines=24;
}
/* Helper to open a file FNAME either for reading or writing to be
used with --status-file etc functions. Not generally useful but it
avoids the riscos specific functions and well some Windows people
might like it too. Prints an error message and returns -1 on
error. On success the file descriptor is returned. */
static int
open_info_file (const char *fname, int for_write, int binary)
{
#ifdef __riscos__
return riscos_fdopenfile (fname, for_write);
#elif defined (ENABLE_SELINUX_HACKS)
/* We can't allow these even when testing for a secured filename
because files to be secured might not yet been secured. This is
similar to the option file but in that case it is unlikely that
sensitive information may be retrieved by means of error
messages. */
(void)fname;
(void)for_write;
(void)binary;
return -1;
#else
int fd;
if (binary)
binary = MY_O_BINARY;
/* if (is_secured_filename (fname)) */
/* { */
/* fd = -1; */
/* gpg_err_set_errno (EPERM); */
/* } */
/* else */
/* { */
do
{
if (for_write)
fd = open (fname, O_CREAT | O_TRUNC | O_WRONLY | binary,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
else
fd = open (fname, O_RDONLY | binary);
}
while (fd == -1 && errno == EINTR);
/* } */
if ( fd == -1)
log_error ( for_write? _("can't create `%s': %s\n")
: _("can't open `%s': %s\n"), fname, strerror(errno));
return fd;
#endif
}
static void
set_cmd( enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd )
{
enum cmd_and_opt_values cmd = *ret_cmd;
if( !cmd || cmd == new_cmd )
cmd = new_cmd;
else if( cmd == aSign && new_cmd == aEncr )
cmd = aSignEncr;
else if( cmd == aEncr && new_cmd == aSign )
cmd = aSignEncr;
else if( cmd == aSign && new_cmd == aSym )
cmd = aSignSym;
else if( cmd == aSym && new_cmd == aSign )
cmd = aSignSym;
else if( cmd == aSym && new_cmd == aEncr )
cmd = aEncrSym;
else if( cmd == aEncr && new_cmd == aSym )
cmd = aEncrSym;
else if (cmd == aSignEncr && new_cmd == aSym)
cmd = aSignEncrSym;
else if (cmd == aSignSym && new_cmd == aEncr)
cmd = aSignEncrSym;
else if (cmd == aEncrSym && new_cmd == aSign)
cmd = aSignEncrSym;
else if( ( cmd == aSign && new_cmd == aClearsign )
|| ( cmd == aClearsign && new_cmd == aSign ) )
cmd = aClearsign;
else {
log_error(_("conflicting commands\n"));
g10_exit(2);
}
*ret_cmd = cmd;
}
static void
add_group(char *string)
{
char *name,*value;
struct groupitem *item;
/* Break off the group name */
name=strsep(&string,"=");
if(string==NULL)
{
log_error(_("no = sign found in group definition `%s'\n"),name);
return;
}
trim_trailing_ws(name,strlen(name));
/* Does this group already exist? */
for(item=opt.grouplist;item;item=item->next)
if(strcasecmp(item->name,name)==0)
break;
if(!item)
{
item=xmalloc(sizeof(struct groupitem));
item->name=name;
item->next=opt.grouplist;
item->values=NULL;
opt.grouplist=item;
}
/* Break apart the values */
while ((value= strsep(&string," \t")))
{
if (*value)
add_to_strlist2(&item->values,value,utf8_strings);
}
}
static void
rm_group(char *name)
{
struct groupitem *item,*last=NULL;
trim_trailing_ws(name,strlen(name));
for(item=opt.grouplist;item;last=item,item=item->next)
{
if(strcasecmp(item->name,name)==0)
{
if(last)
last->next=item->next;
else
opt.grouplist=item->next;
free_strlist(item->values);
xfree(item);
break;
}
}
}
/* We need to check three things.
0) The homedir. It must be x00, a directory, and owned by the
user.
1) The options/gpg.conf file. Okay unless it or its containing
directory is group or other writable or not owned by us. Disable
exec in this case.
2) Extensions. Same as #1.
Returns true if the item is unsafe. */
static int
check_permissions (const char *path, int item)
{
#if defined(HAVE_STAT) && !defined(HAVE_DOSISH_SYSTEM)
static int homedir_cache=-1;
char *tmppath,*dir;
struct stat statbuf,dirbuf;
int homedir=0,ret=0,checkonly=0;
int perm=0,own=0,enc_dir_perm=0,enc_dir_own=0;
if(opt.no_perm_warn)
return 0;
assert(item==0 || item==1 || item==2);
/* extensions may attach a path */
if(item==2 && path[0]!=DIRSEP_C)
{
if(strchr(path,DIRSEP_C))
tmppath=make_filename(path,NULL);
else
tmppath=make_filename(gnupg_libdir (),path,NULL);
}
else
tmppath=xstrdup(path);
/* If the item is located in the homedir, but isn't the homedir,
don't continue if we already checked the homedir itself. This is
to avoid user confusion with an extra options file warning which
could be rectified if the homedir itself had proper
permissions. */
if(item!=0 && homedir_cache>-1
&& ascii_strncasecmp(opt.homedir,tmppath,strlen(opt.homedir))==0)
{
ret=homedir_cache;
goto end;
}
/* It's okay if the file or directory doesn't exist */
if(stat(tmppath,&statbuf)!=0)
{
ret=0;
goto end;
}
/* Now check the enclosing directory. Theoretically, we could walk
this test up to the root directory /, but for the sake of sanity,
I'm stopping at one level down. */
dir=make_dirname(tmppath);
if(stat(dir,&dirbuf)!=0 || !S_ISDIR(dirbuf.st_mode))
{
/* Weird error */
ret=1;
goto end;
}
xfree(dir);
/* Assume failure */
ret=1;
if(item==0)
{
/* The homedir must be x00, a directory, and owned by the user. */
if(S_ISDIR(statbuf.st_mode))
{
if(statbuf.st_uid==getuid())
{
if((statbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
ret=0;
else
perm=1;
}
else
own=1;
homedir_cache=ret;
}
}
else if(item==1 || item==2)
{
/* The options or extension file. Okay unless it or its
containing directory is group or other writable or not owned
by us or root. */
if(S_ISREG(statbuf.st_mode))
{
if(statbuf.st_uid==getuid() || statbuf.st_uid==0)
{
if((statbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
{
/* it's not writable, so make sure the enclosing
directory is also not writable */
if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
{
if((dirbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
ret=0;
else
enc_dir_perm=1;
}
else
enc_dir_own=1;
}
else
{
/* it's writable, so the enclosing directory had
better not let people get to it. */
if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
{
if((dirbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
ret=0;
else
perm=enc_dir_perm=1; /* unclear which one to fix! */
}
else
enc_dir_own=1;
}
}
else
own=1;
}
}
else
BUG();
if(!checkonly)
{
if(own)
{
if(item==0)
log_info(_("WARNING: unsafe ownership on"
" homedir `%s'\n"),tmppath);
else if(item==1)
log_info(_("WARNING: unsafe ownership on"
" configuration file `%s'\n"),tmppath);
else
log_info(_("WARNING: unsafe ownership on"
" extension `%s'\n"),tmppath);
}
if(perm)
{
if(item==0)
log_info(_("WARNING: unsafe permissions on"
" homedir `%s'\n"),tmppath);
else if(item==1)
log_info(_("WARNING: unsafe permissions on"
" configuration file `%s'\n"),tmppath);
else
log_info(_("WARNING: unsafe permissions on"
" extension `%s'\n"),tmppath);
}
if(enc_dir_own)
{
if(item==0)
log_info(_("WARNING: unsafe enclosing directory ownership on"
" homedir `%s'\n"),tmppath);
else if(item==1)
log_info(_("WARNING: unsafe enclosing directory ownership on"
" configuration file `%s'\n"),tmppath);
else
log_info(_("WARNING: unsafe enclosing directory ownership on"
" extension `%s'\n"),tmppath);
}
if(enc_dir_perm)
{
if(item==0)
log_info(_("WARNING: unsafe enclosing directory permissions on"
" homedir `%s'\n"),tmppath);
else if(item==1)
log_info(_("WARNING: unsafe enclosing directory permissions on"
" configuration file `%s'\n"),tmppath);
else
log_info(_("WARNING: unsafe enclosing directory permissions on"
" extension `%s'\n"),tmppath);
}
}
end:
xfree(tmppath);
if(homedir)
homedir_cache=ret;
return ret;
#else /*!(HAVE_STAT && !HAVE_DOSISH_SYSTEM)*/
(void)path;
(void)item;
return 0;
#endif /*!(HAVE_STAT && !HAVE_DOSISH_SYSTEM)*/
}
/* Print the OpenPGP defined algo numbers. */
static void
print_algo_numbers(int (*checker)(int))
{
int i,first=1;
for(i=0;i<=110;i++)
{
if(!checker(i))
{
if(first)
first=0;
else
es_printf (";");
es_printf ("%d",i);
}
}
}
static void
print_algo_names(int (*checker)(int),const char *(*mapper)(int))
{
int i,first=1;
for(i=0;i<=110;i++)
{
if(!checker(i))
{
if(first)
first=0;
else
es_printf (";");
es_printf ("%s",mapper(i));
}
}
}
/* In the future, we can do all sorts of interesting configuration
output here. For now, just give "group" as the Enigmail folks need
it, and pubkey, cipher, hash, and compress as they may be useful
for frontends. */
static void
list_config(char *items)
{
int show_all=(items==NULL);
char *name=NULL;
if(!opt.with_colons)
return;
while(show_all || (name=strsep(&items," ")))
{
int any=0;
if(show_all || ascii_strcasecmp(name,"group")==0)
{
struct groupitem *iter;
for(iter=opt.grouplist;iter;iter=iter->next)
{
strlist_t sl;
es_fprintf (es_stdout, "cfg:group:");
es_write_sanitized (es_stdout, iter->name, strlen(iter->name),
":", NULL);
es_putc (':', es_stdout);
for(sl=iter->values;sl;sl=sl->next)
{
print_sanitized_string2 (stdout, sl->d, ':',';');
if(sl->next)
es_printf(";");
}
es_printf("\n");
}
any=1;
}
if(show_all || ascii_strcasecmp(name,"version")==0)
{
es_printf("cfg:version:");
es_write_sanitized (es_stdout, VERSION, strlen(VERSION), ":", NULL);
es_printf ("\n");
any=1;
}
if(show_all || ascii_strcasecmp(name,"pubkey")==0)
{
es_printf ("cfg:pubkey:");
print_algo_numbers (openpgp_pk_test_algo);
es_printf ("\n");
any=1;
}
if(show_all || ascii_strcasecmp(name,"cipher")==0)
{
es_printf ("cfg:cipher:");
print_algo_numbers(openpgp_cipher_test_algo);
es_printf ("\n");
any=1;
}
if (show_all || !ascii_strcasecmp (name,"ciphername"))
{
es_printf ("cfg:ciphername:");
print_algo_names (openpgp_cipher_test_algo,openpgp_cipher_algo_name);
es_printf ("\n");
any = 1;
}
if(show_all
|| ascii_strcasecmp(name,"digest")==0
|| ascii_strcasecmp(name,"hash")==0)
{
es_printf ("cfg:digest:");
print_algo_numbers(openpgp_md_test_algo);
es_printf ("\n");
any=1;
}
if (show_all
|| !ascii_strcasecmp(name,"digestname")
|| !ascii_strcasecmp(name,"hashname"))
{
es_printf ("cfg:digestname:");
print_algo_names (openpgp_md_test_algo, gcry_md_algo_name);
es_printf ("\n");
any=1;
}
if(show_all || ascii_strcasecmp(name,"compress")==0)
{
es_printf ("cfg:compress:");
print_algo_numbers(check_compress_algo);
es_printf ("\n");
any=1;
}
if(show_all || ascii_strcasecmp(name,"ccid-reader-id")==0)
{
#if defined(ENABLE_CARD_SUPPORT) && defined(HAVE_LIBUSB) \
&& GNUPG_MAJOR_VERSION == 1
char *p, *p2, *list = ccid_get_reader_list ();
for (p=list; p && (p2 = strchr (p, '\n')); p = p2+1)
{
*p2 = 0;
es_printf ("cfg:ccid-reader-id:%s\n", p);
}
free (list);
#endif
any=1;
}
if(show_all)
break;
if(!any)
log_error(_("unknown configuration item `%s'\n"),name);
}
}
/* List options and default values in the GPG Conf format. This is a
new tool distributed with gnupg 1.9.x but we also want some limited
support in older gpg versions. The output is the name of the
configuration file and a list of options available for editing by
gpgconf. */
static void
gpgconf_list (const char *configfile)
{
char *configfile_esc = percent_escape (configfile, NULL);
es_printf ("gpgconf-gpg.conf:%lu:\"%s\n",
GC_OPT_FLAG_DEFAULT,
configfile_esc ? configfile_esc : "/dev/null");
es_printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
es_printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
es_printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
es_printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE);
es_printf ("default-key:%lu:\n", GC_OPT_FLAG_NONE);
es_printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_NONE);
es_printf ("try-secret-key:%lu:\n", GC_OPT_FLAG_NONE);
es_printf ("auto-key-locate:%lu:\n", GC_OPT_FLAG_NONE);
es_printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE);
es_printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
es_printf ("group:%lu:\n", GC_OPT_FLAG_NONE);
/* The next one is an info only item and should match the macros at
the top of keygen.c */
es_printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
"RSA-2048");
xfree (configfile_esc);
}
static int
parse_subpacket_list(char *list)
{
char *tok;
byte subpackets[128],i;
int count=0;
if(!list)
{
/* No arguments means all subpackets */
memset(subpackets+1,1,sizeof(subpackets)-1);
count=127;
}
else
{
memset(subpackets,0,sizeof(subpackets));
/* Merge with earlier copy */
if(opt.show_subpackets)
{
byte *in;
for(in=opt.show_subpackets;*in;in++)
{
if(*in>127 || *in<1)
BUG();
if(!subpackets[*in])
count++;
subpackets[*in]=1;
}
}
while((tok=strsep(&list," ,")))
{
if(!*tok)
continue;
i=atoi(tok);
if(i>127 || i<1)
return 0;
if(!subpackets[i])
count++;
subpackets[i]=1;
}
}
xfree(opt.show_subpackets);
opt.show_subpackets=xmalloc(count+1);
opt.show_subpackets[count--]=0;
for(i=1;i<128 && count>=0;i++)
if(subpackets[i])
opt.show_subpackets[count--]=i;
return 1;
}
static int
parse_list_options(char *str)
{
char *subpackets=""; /* something that isn't NULL */
struct parse_options lopts[]=
{
{"show-photos",LIST_SHOW_PHOTOS,NULL,
N_("display photo IDs during key listings")},
{"show-policy-urls",LIST_SHOW_POLICY_URLS,NULL,
N_("show policy URLs during signature listings")},
{"show-notations",LIST_SHOW_NOTATIONS,NULL,
N_("show all notations during signature listings")},
{"show-std-notations",LIST_SHOW_STD_NOTATIONS,NULL,
N_("show IETF standard notations during signature listings")},
{"show-standard-notations",LIST_SHOW_STD_NOTATIONS,NULL,
NULL},
{"show-user-notations",LIST_SHOW_USER_NOTATIONS,NULL,
N_("show user-supplied notations during signature listings")},
{"show-keyserver-urls",LIST_SHOW_KEYSERVER_URLS,NULL,
N_("show preferred keyserver URLs during signature listings")},
{"show-uid-validity",LIST_SHOW_UID_VALIDITY,NULL,
N_("show user ID validity during key listings")},
{"show-unusable-uids",LIST_SHOW_UNUSABLE_UIDS,NULL,
N_("show revoked and expired user IDs in key listings")},
{"show-unusable-subkeys",LIST_SHOW_UNUSABLE_SUBKEYS,NULL,
N_("show revoked and expired subkeys in key listings")},
{"show-keyring",LIST_SHOW_KEYRING,NULL,
N_("show the keyring name in key listings")},
{"show-sig-expire",LIST_SHOW_SIG_EXPIRE,NULL,
N_("show expiration dates during signature listings")},
{"show-sig-subpackets",LIST_SHOW_SIG_SUBPACKETS,NULL,
NULL},
{NULL,0,NULL,NULL}
};
/* C99 allows for non-constant initializers, but we'd like to
compile everywhere, so fill in the show-sig-subpackets argument
here. Note that if the parse_options array changes, we'll have
to change the subscript here. */
lopts[12].value=&subpackets;
if(parse_options(str,&opt.list_options,lopts,1))
{
if(opt.list_options&LIST_SHOW_SIG_SUBPACKETS)
{
/* Unset so users can pass multiple lists in. */
opt.list_options&=~LIST_SHOW_SIG_SUBPACKETS;
if(!parse_subpacket_list(subpackets))
return 0;
}
else if(subpackets==NULL && opt.show_subpackets)
{
/* User did 'no-show-subpackets' */
xfree(opt.show_subpackets);
opt.show_subpackets=NULL;
}
return 1;
}
else
return 0;
}
/* Collapses argc/argv into a single string that must be freed */
static char *
collapse_args(int argc,char *argv[])
{
char *str=NULL;
int i,first=1,len=0;
for(i=0;iflags=2;
break;
case oShowKeyring:
deprecated_warning(configname,configlineno,"--show-keyring",
"--list-options ","show-keyring");
opt.list_options|=LIST_SHOW_KEYRING;
break;
case oDebug: opt.debug |= pargs.r.ret_ulong; break;
case oDebugAll: opt.debug = ~0; break;
case oDebugLevel: debug_level = pargs.r.ret_str; break;
case oStatusFD:
set_status_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
break;
case oStatusFile:
set_status_fd ( open_info_file (pargs.r.ret_str, 1, 0) );
break;
case oAttributeFD:
set_attrib_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
break;
case oAttributeFile:
set_attrib_fd ( open_info_file (pargs.r.ret_str, 1, 1) );
break;
case oLoggerFD:
log_set_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1));
break;
case oLoggerFile:
logfile = pargs.r.ret_str;
break;
case oWithFingerprint:
opt.with_fingerprint = 1;
opt.fingerprint++;
break;
case oFingerprint:
opt.fingerprint++;
fpr_maybe_cmd = 1;
break;
case oWithKeygrip:
opt.with_keygrip = 1;
break;
case oSecretKeyring:
/* Ignore this old option. */
break;
case oOptions:
/* config files may not be nested (silently ignore them) */
if( !configfp ) {
xfree(configname);
configname = xstrdup(pargs.r.ret_str);
goto next_pass;
}
break;
case oNoArmor: opt.no_armor=1; opt.armor=0; break;
case oNoDefKeyring: default_keyring = 0; break;
case oNoGreeting: nogreeting = 1; break;
case oNoVerbose:
opt.verbose = 0;
gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
opt.list_sigs=0;
break;
case oQuickRandom:
gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
break;
case oEmitVersion: opt.no_version=0; break;
case oNoEmitVersion: opt.no_version=1; break;
case oCompletesNeeded: opt.completes_needed = pargs.r.ret_int; break;
case oMarginalsNeeded: opt.marginals_needed = pargs.r.ret_int; break;
case oMaxCertDepth: opt.max_cert_depth = pargs.r.ret_int; break;
case oTrustDBName: trustdb_name = pargs.r.ret_str; break;
case oDefaultKey: opt.def_secret_key = pargs.r.ret_str; break;
case oDefRecipient:
if( *pargs.r.ret_str )
opt.def_recipient = make_username(pargs.r.ret_str);
break;
case oDefRecipientSelf:
xfree(opt.def_recipient); opt.def_recipient = NULL;
opt.def_recipient_self = 1;
break;
case oNoDefRecipient:
xfree(opt.def_recipient); opt.def_recipient = NULL;
opt.def_recipient_self = 0;
break;
case oNoOptions: opt.no_homedir_creation = 1; break; /* no-options */
case oHomedir: break;
case oNoBatch: opt.batch = 0; break;
case oWithKeyData: opt.with_key_data=1; /*FALLTHRU*/
case oWithColons: opt.with_colons=':'; break;
case oWithSigCheck: opt.check_sigs = 1; /*FALLTHRU*/
case oWithSigList: opt.list_sigs = 1; break;
case oSkipVerify: opt.skip_verify=1; break;
case oSkipHiddenRecipients: opt.skip_hidden_recipients = 1; break;
case oNoSkipHiddenRecipients: opt.skip_hidden_recipients = 0; break;
case oCompressKeys: opt.compress_keys = 1; break;
case aListSecretKeys: set_cmd( &cmd, aListSecretKeys); break;
/* There are many programs (like mutt) that call gpg with
--always-trust so keep this option around for a long
time. */
case oAlwaysTrust: opt.trust_model=TM_ALWAYS; break;
case oTrustModel:
parse_trust_model(pargs.r.ret_str);
break;
case oForceOwnertrust:
log_info(_("NOTE: %s is not for normal use!\n"),
"--force-ownertrust");
opt.force_ownertrust=string_to_trust_value(pargs.r.ret_str);
if(opt.force_ownertrust==-1)
{
log_error("invalid ownertrust `%s'\n",pargs.r.ret_str);
opt.force_ownertrust=0;
}
break;
case oLoadExtension:
/* Dummy so that gpg 1.4 conf files can work. Should
eventually be removed. */
break;
case oRFC1991:
opt.compliance = CO_RFC1991;
opt.force_v4_certs = 0;
opt.escape_from = 1;
break;
case oOpenPGP:
case oRFC4880:
/* This is effectively the same as RFC2440, but with
"--enable-dsa2 --no-rfc2440-text --escape-from-lines
--require-cross-certification". */
opt.compliance = CO_RFC4880;
opt.flags.dsa2 = 1;
opt.flags.require_cross_cert = 1;
opt.rfc2440_text = 0;
opt.allow_non_selfsigned_uid = 1;
opt.allow_freeform_uid = 1;
opt.pgp2_workarounds = 0;
opt.escape_from = 1;
opt.force_v3_sigs = 0;
opt.compress_keys = 0; /* not mandated, but we do it */
opt.compress_sigs = 0; /* ditto. */
opt.not_dash_escaped = 0;
opt.def_cipher_algo = 0;
opt.def_digest_algo = 0;
opt.cert_digest_algo = 0;
opt.compress_algo = -1;
opt.s2k_mode = 3; /* iterated+salted */
opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
break;
case oRFC2440:
opt.compliance = CO_RFC2440;
opt.flags.dsa2 = 0;
opt.rfc2440_text = 1;
opt.allow_non_selfsigned_uid = 1;
opt.allow_freeform_uid = 1;
opt.pgp2_workarounds = 0;
opt.escape_from = 0;
opt.force_v3_sigs = 0;
opt.compress_keys = 0; /* not mandated, but we do it */
opt.compress_sigs = 0; /* ditto. */
opt.not_dash_escaped = 0;
opt.def_cipher_algo = 0;
opt.def_digest_algo = 0;
opt.cert_digest_algo = 0;
opt.compress_algo = -1;
opt.s2k_mode = 3; /* iterated+salted */
opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
break;
case oPGP2: opt.compliance = CO_PGP2; break;
case oPGP6: opt.compliance = CO_PGP6; break;
case oPGP7: opt.compliance = CO_PGP7; break;
case oPGP8: opt.compliance = CO_PGP8; break;
case oGnuPG: opt.compliance = CO_GNUPG; break;
case oCompressSigs: opt.compress_sigs = 1; break;
case oRFC2440Text: opt.rfc2440_text=1; break;
case oNoRFC2440Text: opt.rfc2440_text=0; break;
case oSetFilename:
if(utf8_strings)
opt.set_filename = pargs.r.ret_str;
else
opt.set_filename = native_to_utf8(pargs.r.ret_str);
break;
case oForYourEyesOnly: eyes_only = 1; break;
case oNoForYourEyesOnly: eyes_only = 0; break;
case oSetPolicyURL:
add_policy_url(pargs.r.ret_str,0);
add_policy_url(pargs.r.ret_str,1);
break;
case oSigPolicyURL: add_policy_url(pargs.r.ret_str,0); break;
case oCertPolicyURL: add_policy_url(pargs.r.ret_str,1); break;
case oShowPolicyURL:
deprecated_warning(configname,configlineno,"--show-policy-url",
"--list-options ","show-policy-urls");
deprecated_warning(configname,configlineno,"--show-policy-url",
"--verify-options ","show-policy-urls");
opt.list_options|=LIST_SHOW_POLICY_URLS;
opt.verify_options|=VERIFY_SHOW_POLICY_URLS;
break;
case oNoShowPolicyURL:
deprecated_warning(configname,configlineno,"--no-show-policy-url",
"--list-options ","no-show-policy-urls");
deprecated_warning(configname,configlineno,"--no-show-policy-url",
"--verify-options ","no-show-policy-urls");
opt.list_options&=~LIST_SHOW_POLICY_URLS;
opt.verify_options&=~VERIFY_SHOW_POLICY_URLS;
break;
case oSigKeyserverURL: add_keyserver_url(pargs.r.ret_str,0); break;
case oUseEmbeddedFilename:
opt.flags.use_embedded_filename=1;
break;
case oNoUseEmbeddedFilename:
opt.flags.use_embedded_filename=0;
break;
case oComment:
if(pargs.r.ret_str[0])
append_to_strlist(&opt.comments,pargs.r.ret_str);
break;
case oDefaultComment:
deprecated_warning(configname,configlineno,
"--default-comment","--no-comments","");
/* fall through */
case oNoComments:
free_strlist(opt.comments);
opt.comments=NULL;
break;
case oThrowKeyids: opt.throw_keyid = 1; break;
case oNoThrowKeyids: opt.throw_keyid = 0; break;
case oShowPhotos:
deprecated_warning(configname,configlineno,"--show-photos",
"--list-options ","show-photos");
deprecated_warning(configname,configlineno,"--show-photos",
"--verify-options ","show-photos");
opt.list_options|=LIST_SHOW_PHOTOS;
opt.verify_options|=VERIFY_SHOW_PHOTOS;
break;
case oNoShowPhotos:
deprecated_warning(configname,configlineno,"--no-show-photos",
"--list-options ","no-show-photos");
deprecated_warning(configname,configlineno,"--no-show-photos",
"--verify-options ","no-show-photos");
opt.list_options&=~LIST_SHOW_PHOTOS;
opt.verify_options&=~VERIFY_SHOW_PHOTOS;
break;
case oPhotoViewer: opt.photo_viewer = pargs.r.ret_str; break;
case oForceV3Sigs: opt.force_v3_sigs = 1; break;
case oNoForceV3Sigs: opt.force_v3_sigs = 0; break;
case oForceV4Certs: opt.force_v4_certs = 1; break;
case oNoForceV4Certs: opt.force_v4_certs = 0; break;
case oForceMDC: opt.force_mdc = 1; break;
case oNoForceMDC: opt.force_mdc = 0; break;
case oDisableMDC: opt.disable_mdc = 1; break;
case oNoDisableMDC: opt.disable_mdc = 0; break;
case oS2KMode: opt.s2k_mode = pargs.r.ret_int; break;
case oS2KDigest: s2k_digest_string = xstrdup(pargs.r.ret_str); break;
case oS2KCipher: s2k_cipher_string = xstrdup(pargs.r.ret_str); break;
case oS2KCount:
if (pargs.r.ret_int)
opt.s2k_count = encode_s2k_iterations (pargs.r.ret_int);
else
opt.s2k_count = 0; /* Auto-calibrate when needed. */
break;
case oNoEncryptTo: opt.no_encrypt_to = 1; break;
case oEncryptTo: /* store the recipient in the second list */
sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
sl->flags = 1;
break;
case oHiddenEncryptTo: /* store the recipient in the second list */
sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
sl->flags = 1|2;
break;
case oRecipient: /* store the recipient */
add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
any_explicit_recipient = 1;
break;
case oHiddenRecipient: /* store the recipient with a flag */
sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
sl->flags = 2;
any_explicit_recipient = 1;
break;
case oTrySecretKey:
add_to_strlist2 (&opt.secret_keys_to_try,
pargs.r.ret_str, utf8_strings);
break;
case oTextmodeShort: opt.textmode = 2; break;
case oTextmode: opt.textmode=1; break;
case oNoTextmode: opt.textmode=0; break;
case oExpert: opt.expert = 1; break;
case oNoExpert: opt.expert = 0; break;
case oDefSigExpire:
if(*pargs.r.ret_str!='\0')
{
if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
log_error(_("`%s' is not a valid signature expiration\n"),
pargs.r.ret_str);
else
opt.def_sig_expire=pargs.r.ret_str;
}
break;
case oAskSigExpire: opt.ask_sig_expire = 1; break;
case oNoAskSigExpire: opt.ask_sig_expire = 0; break;
case oDefCertExpire:
if(*pargs.r.ret_str!='\0')
{
if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
log_error(_("`%s' is not a valid signature expiration\n"),
pargs.r.ret_str);
else
opt.def_cert_expire=pargs.r.ret_str;
}
break;
case oAskCertExpire: opt.ask_cert_expire = 1; break;
case oNoAskCertExpire: opt.ask_cert_expire = 0; break;
case oDefCertLevel: opt.def_cert_level=pargs.r.ret_int; break;
case oMinCertLevel: opt.min_cert_level=pargs.r.ret_int; break;
case oAskCertLevel: opt.ask_cert_level = 1; break;
case oNoAskCertLevel: opt.ask_cert_level = 0; break;
case oLocalUser: /* store the local users */
add_to_strlist2( &locusr, pargs.r.ret_str, utf8_strings );
break;
case oCompress:
/* this is the -z command line option */
opt.compress_level = opt.bz2_compress_level = pargs.r.ret_int;
break;
case oCompressLevel: opt.compress_level = pargs.r.ret_int; break;
case oBZ2CompressLevel: opt.bz2_compress_level = pargs.r.ret_int; break;
case oBZ2DecompressLowmem: opt.bz2_decompress_lowmem=1; break;
case oPassphrase:
set_passphrase_from_string(pargs.r.ret_str);
break;
case oPassphraseFD:
pwfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
break;
case oPassphraseFile:
pwfd = open_info_file (pargs.r.ret_str, 0, 1);
break;
case oPassphraseRepeat: opt.passphrase_repeat=pargs.r.ret_int; break;
case oCommandFD:
opt.command_fd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
break;
case oCommandFile:
opt.command_fd = open_info_file (pargs.r.ret_str, 0, 1);
break;
case oCipherAlgo:
def_cipher_string = xstrdup(pargs.r.ret_str);
break;
case oDigestAlgo:
def_digest_string = xstrdup(pargs.r.ret_str);
break;
case oCompressAlgo:
/* If it is all digits, stick a Z in front of it for
later. This is for backwards compatibility with
versions that took the compress algorithm number. */
{
char *pt=pargs.r.ret_str;
while(*pt)
{
if (!isascii (*pt) || !isdigit (*pt))
break;
pt++;
}
if(*pt=='\0')
{
compress_algo_string=xmalloc(strlen(pargs.r.ret_str)+2);
strcpy(compress_algo_string,"Z");
strcat(compress_algo_string,pargs.r.ret_str);
}
else
compress_algo_string = xstrdup(pargs.r.ret_str);
}
break;
case oCertDigestAlgo:
cert_digest_string = xstrdup(pargs.r.ret_str);
break;
case oNoSecmemWarn:
gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
break;
case oRequireSecmem: require_secmem=1; break;
case oNoRequireSecmem: require_secmem=0; break;
case oNoPermissionWarn: opt.no_perm_warn=1; break;
case oNoMDCWarn: opt.no_mdc_warn=1; break;
case oDisplayCharset:
if( set_native_charset( pargs.r.ret_str ) )
log_error(_("`%s' is not a valid character set\n"),
pargs.r.ret_str);
break;
case oNotDashEscaped: opt.not_dash_escaped = 1; break;
case oEscapeFrom: opt.escape_from = 1; break;
case oNoEscapeFrom: opt.escape_from = 0; break;
case oLockOnce: opt.lock_once = 1; break;
case oLockNever:
disable_dotlock ();
break;
case oLockMultiple:
#ifndef __riscos__
opt.lock_once = 0;
#else /* __riscos__ */
riscos_not_implemented("lock-multiple");
#endif /* __riscos__ */
break;
case oKeyServer:
{
struct keyserver_spec *keyserver;
keyserver=parse_keyserver_uri(pargs.r.ret_str,0,
configname,configlineno);
if(!keyserver)
log_error(_("could not parse keyserver URL\n"));
else
{
keyserver->next=opt.keyserver;
opt.keyserver=keyserver;
}
}
break;
case oKeyServerOptions:
if(!parse_keyserver_options(pargs.r.ret_str))
{
if(configname)
log_error(_("%s:%d: invalid keyserver options\n"),
configname,configlineno);
else
log_error(_("invalid keyserver options\n"));
}
break;
case oImportOptions:
if(!parse_import_options(pargs.r.ret_str,&opt.import_options,1))
{
if(configname)
log_error(_("%s:%d: invalid import options\n"),
configname,configlineno);
else
log_error(_("invalid import options\n"));
}
break;
case oExportOptions:
if(!parse_export_options(pargs.r.ret_str,&opt.export_options,1))
{
if(configname)
log_error(_("%s:%d: invalid export options\n"),
configname,configlineno);
else
log_error(_("invalid export options\n"));
}
break;
case oListOptions:
if(!parse_list_options(pargs.r.ret_str))
{
if(configname)
log_error(_("%s:%d: invalid list options\n"),
configname,configlineno);
else
log_error(_("invalid list options\n"));
}
break;
case oVerifyOptions:
{
struct parse_options vopts[]=
{
{"show-photos",VERIFY_SHOW_PHOTOS,NULL,
N_("display photo IDs during signature verification")},
{"show-policy-urls",VERIFY_SHOW_POLICY_URLS,NULL,
N_("show policy URLs during signature verification")},
{"show-notations",VERIFY_SHOW_NOTATIONS,NULL,
N_("show all notations during signature verification")},
{"show-std-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
N_("show IETF standard notations during signature verification")},
{"show-standard-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
NULL},
{"show-user-notations",VERIFY_SHOW_USER_NOTATIONS,NULL,
N_("show user-supplied notations during signature verification")},
{"show-keyserver-urls",VERIFY_SHOW_KEYSERVER_URLS,NULL,
N_("show preferred keyserver URLs during signature verification")},
{"show-uid-validity",VERIFY_SHOW_UID_VALIDITY,NULL,
N_("show user ID validity during signature verification")},
{"show-unusable-uids",VERIFY_SHOW_UNUSABLE_UIDS,NULL,
N_("show revoked and expired user IDs in signature verification")},
{"show-primary-uid-only",VERIFY_SHOW_PRIMARY_UID_ONLY,NULL,
N_("show only the primary user ID in signature verification")},
{"pka-lookups",VERIFY_PKA_LOOKUPS,NULL,
N_("validate signatures with PKA data")},
{"pka-trust-increase",VERIFY_PKA_TRUST_INCREASE,NULL,
N_("elevate the trust of signatures with valid PKA data")},
{NULL,0,NULL,NULL}
};
if(!parse_options(pargs.r.ret_str,&opt.verify_options,vopts,1))
{
if(configname)
log_error(_("%s:%d: invalid verify options\n"),
configname,configlineno);
else
log_error(_("invalid verify options\n"));
}
}
break;
case oTempDir: opt.temp_dir=pargs.r.ret_str; break;
case oExecPath:
if(set_exec_path(pargs.r.ret_str))
log_error(_("unable to set exec-path to %s\n"),pargs.r.ret_str);
else
opt.exec_path_set=1;
break;
case oSetNotation:
add_notation_data( pargs.r.ret_str, 0 );
add_notation_data( pargs.r.ret_str, 1 );
break;
case oSigNotation: add_notation_data( pargs.r.ret_str, 0 ); break;
case oCertNotation: add_notation_data( pargs.r.ret_str, 1 ); break;
case oShowNotation:
deprecated_warning(configname,configlineno,"--show-notation",
"--list-options ","show-notations");
deprecated_warning(configname,configlineno,"--show-notation",
"--verify-options ","show-notations");
opt.list_options|=LIST_SHOW_NOTATIONS;
opt.verify_options|=VERIFY_SHOW_NOTATIONS;
break;
case oNoShowNotation:
deprecated_warning(configname,configlineno,"--no-show-notation",
"--list-options ","no-show-notations");
deprecated_warning(configname,configlineno,"--no-show-notation",
"--verify-options ","no-show-notations");
opt.list_options&=~LIST_SHOW_NOTATIONS;
opt.verify_options&=~VERIFY_SHOW_NOTATIONS;
break;
case oUtf8Strings: utf8_strings = 1; break;
case oNoUtf8Strings: utf8_strings = 0; break;
case oDisableCipherAlgo:
{
int algo = string_to_cipher_algo (pargs.r.ret_str);
gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
}
break;
case oDisablePubkeyAlgo:
{
int algo = gcry_pk_map_name (pargs.r.ret_str);
gcry_pk_ctl (GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
}
break;
case oNoSigCache: opt.no_sig_cache = 1; break;
case oNoSigCreateCheck: opt.no_sig_create_check = 1; break;
case oAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid = 1; break;
case oNoAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid=0; break;
case oAllowFreeformUID: opt.allow_freeform_uid = 1; break;
case oNoAllowFreeformUID: opt.allow_freeform_uid = 0; break;
case oNoLiteral: opt.no_literal = 1; break;
case oSetFilesize: opt.set_filesize = pargs.r.ret_ulong; break;
case oHonorHttpProxy:
add_to_strlist(&opt.keyserver_options.other,"http-proxy");
deprecated_warning(configname,configlineno,
"--honor-http-proxy",
"--keyserver-options ","http-proxy");
break;
case oFastListMode: opt.fast_list_mode = 1; break;
case oFixedListMode: /* Dummy */ break;
case oListOnly: opt.list_only=1; break;
case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
case oIgnoreValidFrom: opt.ignore_valid_from = 1; break;
case oIgnoreCrcError: opt.ignore_crc_error = 1; break;
case oIgnoreMDCError: opt.ignore_mdc_error = 1; break;
case oNoRandomSeedFile: use_random_seed = 0; break;
case oAutoKeyRetrieve:
case oNoAutoKeyRetrieve:
if(pargs.r_opt==oAutoKeyRetrieve)
opt.keyserver_options.options|=KEYSERVER_AUTO_KEY_RETRIEVE;
else
opt.keyserver_options.options&=~KEYSERVER_AUTO_KEY_RETRIEVE;
deprecated_warning(configname,configlineno,
pargs.r_opt==oAutoKeyRetrieve?"--auto-key-retrieve":
"--no-auto-key-retrieve","--keyserver-options ",
pargs.r_opt==oAutoKeyRetrieve?"auto-key-retrieve":
"no-auto-key-retrieve");
break;
case oShowSessionKey: opt.show_session_key = 1; break;
case oOverrideSessionKey:
opt.override_session_key = pargs.r.ret_str;
break;
case oMergeOnly:
deprecated_warning(configname,configlineno,"--merge-only",
"--import-options ","merge-only");
opt.import_options|=IMPORT_MERGE_ONLY;
break;
case oAllowSecretKeyImport: /* obsolete */ break;
case oTryAllSecrets: opt.try_all_secrets = 1; break;
case oTrustedKey: register_trusted_key( pargs.r.ret_str ); break;
case oEnableSpecialFilenames:
iobuf_enable_special_filenames (1);
break;
case oNoExpensiveTrustChecks: opt.no_expensive_trust_checks=1; break;
case oAutoCheckTrustDB: opt.no_auto_check_trustdb=0; break;
case oNoAutoCheckTrustDB: opt.no_auto_check_trustdb=1; break;
case oPreservePermissions: opt.preserve_permissions=1; break;
case oDefaultPreferenceList:
opt.def_preference_list = pargs.r.ret_str;
break;
case oDefaultKeyserverURL:
{
struct keyserver_spec *keyserver;
keyserver=parse_keyserver_uri(pargs.r.ret_str,1,
configname,configlineno);
if(!keyserver)
log_error(_("could not parse keyserver URL\n"));
else
free_keyserver_spec(keyserver);
opt.def_keyserver_url = pargs.r.ret_str;
}
break;
case oPersonalCipherPreferences:
pers_cipher_list=pargs.r.ret_str;
break;
case oPersonalDigestPreferences:
pers_digest_list=pargs.r.ret_str;
break;
case oPersonalCompressPreferences:
pers_compress_list=pargs.r.ret_str;
break;
case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
case oDisplay:
set_opt_session_env ("DISPLAY", pargs.r.ret_str);
break;
case oTTYname:
set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
break;
case oTTYtype:
set_opt_session_env ("TERM", pargs.r.ret_str);
break;
case oXauthority:
set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
break;
case oLCctype: opt.lc_ctype = pargs.r.ret_str; break;
case oLCmessages: opt.lc_messages = pargs.r.ret_str; break;
case oGroup: add_group(pargs.r.ret_str); break;
case oUnGroup: rm_group(pargs.r.ret_str); break;
case oNoGroups:
while(opt.grouplist)
{
struct groupitem *iter=opt.grouplist;
free_strlist(iter->values);
opt.grouplist=opt.grouplist->next;
xfree(iter);
}
break;
case oStrict:
case oNoStrict:
/* Not used */
break;
case oMangleDosFilenames: opt.mangle_dos_filenames = 1; break;
case oNoMangleDosFilenames: opt.mangle_dos_filenames = 0; break;
case oEnableProgressFilter: opt.enable_progress_filter = 1; break;
case oMultifile: multifile=1; break;
case oKeyidFormat:
if(ascii_strcasecmp(pargs.r.ret_str,"short")==0)
opt.keyid_format=KF_SHORT;
else if(ascii_strcasecmp(pargs.r.ret_str,"long")==0)
opt.keyid_format=KF_LONG;
else if(ascii_strcasecmp(pargs.r.ret_str,"0xshort")==0)
opt.keyid_format=KF_0xSHORT;
else if(ascii_strcasecmp(pargs.r.ret_str,"0xlong")==0)
opt.keyid_format=KF_0xLONG;
else
log_error("unknown keyid-format `%s'\n",pargs.r.ret_str);
break;
case oExitOnStatusWriteError:
opt.exit_on_status_write_error = 1;
break;
case oLimitCardInsertTries:
opt.limit_card_insert_tries = pargs.r.ret_int;
break;
case oRequireCrossCert: opt.flags.require_cross_cert=1; break;
case oNoRequireCrossCert: opt.flags.require_cross_cert=0; break;
case oAutoKeyLocate:
if(!parse_auto_key_locate(pargs.r.ret_str))
{
if(configname)
log_error(_("%s:%d: invalid auto-key-locate list\n"),
configname,configlineno);
else
log_error(_("invalid auto-key-locate list\n"));
}
break;
case oNoAutoKeyLocate:
release_akl();
break;
case oEnableDSA2: opt.flags.dsa2=1; break;
case oDisableDSA2: opt.flags.dsa2=0; break;
case oAllowMultisigVerification:
case oAllowMultipleMessages:
opt.flags.allow_multiple_messages=1;
break;
case oNoAllowMultipleMessages:
opt.flags.allow_multiple_messages=0;
break;
case oFakedSystemTime:
{
time_t faked_time = isotime2epoch (pargs.r.ret_str);
if (faked_time == (time_t)(-1))
faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
gnupg_set_time (faked_time, 0);
}
break;
case oNoop: break;
default:
pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
break;
}
}
if (configfp)
{
fclose( configfp );
configfp = NULL;
/* Remember the first config file name. */
if (!save_configname)
save_configname = configname;
else
xfree(configname);
configname = NULL;
goto next_pass;
}
xfree(configname); configname = NULL;
if (log_get_errorcount (0))
g10_exit(2);
/* The command --gpgconf-list is pretty simple and may be called
directly after the option parsing. */
if (cmd == aGPGConfList)
{
gpgconf_list (save_configname ? save_configname : default_configname);
g10_exit (0);
}
xfree (save_configname);
xfree (default_configname);
if( nogreeting )
greeting = 0;
if( greeting )
{
es_fprintf (es_stderr, "%s %s; %s\n",
strusage(11), strusage(13), strusage(14) );
es_fprintf (es_stderr, "%s\n", strusage(15) );
}
#ifdef IS_DEVELOPMENT_VERSION
if (!opt.batch)
{
const char *s;
if((s=strusage(25)))
log_info("%s\n",s);
if((s=strusage(26)))
log_info("%s\n",s);
if((s=strusage(27)))
log_info("%s\n",s);
}
#endif
/* FIXME: We should use logging to a file only in server mode;
however we have not yet implemetyed that. Thus we try to get
away with --batch as indication for logging to file
required. */
if (logfile && opt.batch)
{
log_set_file (logfile);
log_set_prefix (NULL, 1|2|4);
}
/* Older Libgcrypts fail with an assertion during DSA key
generation. Better disable DSA2 entirely. */
if (opt.flags.dsa2 && !gcry_check_version ("1.4.0") )
{
log_info ("WARNING: "
"DSA2 is only available with Libgcrypt 1.4 and later\n");
opt.flags.dsa2 = 0;
}
if (opt.verbose > 2)
log_info ("using character set `%s'\n", get_native_charset ());
if( may_coredump && !opt.quiet )
log_info(_("WARNING: program may create a core file!\n"));
if (eyes_only) {
if (opt.set_filename)
log_info(_("WARNING: %s overrides %s\n"),
"--for-your-eyes-only","--set-filename");
opt.set_filename="_CONSOLE";
}
if (opt.no_literal) {
log_info(_("NOTE: %s is not for normal use!\n"), "--no-literal");
if (opt.textmode)
log_error(_("%s not allowed with %s!\n"),
"--textmode", "--no-literal" );
if (opt.set_filename)
log_error(_("%s makes no sense with %s!\n"),
eyes_only?"--for-your-eyes-only":"--set-filename",
"--no-literal" );
}
if (opt.set_filesize)
log_info(_("NOTE: %s is not for normal use!\n"), "--set-filesize");
if( opt.batch )
tty_batchmode( 1 );
if (gnupg_faked_time_p ())
{
gnupg_isotime_t tbuf;
log_info (_("WARNING: running with faked system time: "));
gnupg_get_isotime (tbuf);
dump_isotime (tbuf);
log_printf ("\n");
}
gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
if(require_secmem && !got_secmem)
{
log_info(_("will not run with insecure memory due to %s\n"),
"--require-secmem");
g10_exit(2);
}
set_debug (debug_level);
/* Do these after the switch(), so they can override settings. */
if(PGP2)
{
int unusable=0;
if(cmd==aSign && !detached_sig)
{
log_info(_("you can only make detached or clear signatures "
"while in --pgp2 mode\n"));
unusable=1;
}
else if(cmd==aSignEncr || cmd==aSignSym)
{
log_info(_("you can't sign and encrypt at the "
"same time while in --pgp2 mode\n"));
unusable=1;
}
else if(argc==0 && (cmd==aSign || cmd==aEncr || cmd==aSym))
{
log_info(_("you must use files (and not a pipe) when "
"working with --pgp2 enabled.\n"));
unusable=1;
}
else if(cmd==aEncr || cmd==aSym)
{
/* Everything else should work without IDEA (except using
a secret key encrypted with IDEA and setting an IDEA
preference, but those have their own error
messages). */
if (openpgp_cipher_test_algo(CIPHER_ALGO_IDEA))
{
log_info(_("encrypting a message in --pgp2 mode requires "
"the IDEA cipher\n"));
idea_cipher_warn(1);
unusable=1;
}
else if(cmd==aSym)
{
/* This only sets IDEA for symmetric encryption
since it is set via select_algo_from_prefs for
pk encryption. */
xfree(def_cipher_string);
def_cipher_string = xstrdup("idea");
}
/* PGP2 can't handle the output from the textmode
filter, so we disable it for anything that could
create a literal packet (only encryption and
symmetric encryption, since we disable signing
above). */
if(!unusable)
opt.textmode=0;
}
if(unusable)
compliance_failure();
else
{
opt.force_v4_certs = 0;
opt.escape_from = 1;
opt.force_v3_sigs = 1;
opt.pgp2_workarounds = 1;
opt.ask_sig_expire = 0;
opt.ask_cert_expire = 0;
xfree(def_digest_string);
def_digest_string = xstrdup("md5");
xfree(s2k_digest_string);
s2k_digest_string = xstrdup("md5");
opt.compress_algo = COMPRESS_ALGO_ZIP;
}
}
else if(PGP6)
{
opt.disable_mdc=1;
opt.escape_from=1;
opt.force_v3_sigs=1;
opt.ask_sig_expire=0;
}
else if(PGP7)
{
opt.escape_from=1;
opt.force_v3_sigs=1;
opt.ask_sig_expire=0;
}
else if(PGP8)
{
opt.escape_from=1;
}
if( def_cipher_string ) {
opt.def_cipher_algo = string_to_cipher_algo (def_cipher_string);
if(opt.def_cipher_algo==0 &&
(ascii_strcasecmp(def_cipher_string,"idea")==0
|| ascii_strcasecmp(def_cipher_string,"s1")==0))
idea_cipher_warn(1);
xfree(def_cipher_string); def_cipher_string = NULL;
if ( openpgp_cipher_test_algo (opt.def_cipher_algo) )
log_error(_("selected cipher algorithm is invalid\n"));
}
if( def_digest_string ) {
opt.def_digest_algo = string_to_digest_algo (def_digest_string);
xfree(def_digest_string); def_digest_string = NULL;
if ( openpgp_md_test_algo (opt.def_digest_algo) )
log_error(_("selected digest algorithm is invalid\n"));
}
if( compress_algo_string ) {
opt.compress_algo = string_to_compress_algo(compress_algo_string);
xfree(compress_algo_string); compress_algo_string = NULL;
if( check_compress_algo(opt.compress_algo) )
log_error(_("selected compression algorithm is invalid\n"));
}
if( cert_digest_string ) {
opt.cert_digest_algo = string_to_digest_algo (cert_digest_string);
xfree(cert_digest_string); cert_digest_string = NULL;
if (openpgp_md_test_algo(opt.cert_digest_algo))
log_error(_("selected certification digest algorithm is invalid\n"));
}
if( s2k_cipher_string ) {
opt.s2k_cipher_algo = string_to_cipher_algo (s2k_cipher_string);
xfree(s2k_cipher_string); s2k_cipher_string = NULL;
if (openpgp_cipher_test_algo (opt.s2k_cipher_algo))
log_error(_("selected cipher algorithm is invalid\n"));
}
if( s2k_digest_string ) {
opt.s2k_digest_algo = string_to_digest_algo (s2k_digest_string);
xfree(s2k_digest_string); s2k_digest_string = NULL;
if (openpgp_md_test_algo(opt.s2k_digest_algo))
log_error(_("selected digest algorithm is invalid\n"));
}
if( opt.completes_needed < 1 )
log_error(_("completes-needed must be greater than 0\n"));
if( opt.marginals_needed < 2 )
log_error(_("marginals-needed must be greater than 1\n"));
if( opt.max_cert_depth < 1 || opt.max_cert_depth > 255 )
log_error(_("max-cert-depth must be in the range from 1 to 255\n"));
if(opt.def_cert_level<0 || opt.def_cert_level>3)
log_error(_("invalid default-cert-level; must be 0, 1, 2, or 3\n"));
if( opt.min_cert_level < 1 || opt.min_cert_level > 3 )
log_error(_("invalid min-cert-level; must be 1, 2, or 3\n"));
switch( opt.s2k_mode ) {
case 0:
log_info(_("NOTE: simple S2K mode (0) is strongly discouraged\n"));
break;
case 1: case 3: break;
default:
log_error(_("invalid S2K mode; must be 0, 1 or 3\n"));
}
/* This isn't actually needed, but does serve to error out if the
string is invalid. */
if(opt.def_preference_list &&
keygen_set_std_prefs(opt.def_preference_list,0))
log_error(_("invalid default preferences\n"));
if(pers_cipher_list &&
keygen_set_std_prefs(pers_cipher_list,PREFTYPE_SYM))
log_error(_("invalid personal cipher preferences\n"));
if(pers_digest_list &&
keygen_set_std_prefs(pers_digest_list,PREFTYPE_HASH))
log_error(_("invalid personal digest preferences\n"));
if(pers_compress_list &&
keygen_set_std_prefs(pers_compress_list,PREFTYPE_ZIP))
log_error(_("invalid personal compress preferences\n"));
/* We don't support all possible commands with multifile yet */
if(multifile)
{
char *cmdname;
switch(cmd)
{
case aSign:
cmdname="--sign";
break;
case aClearsign:
cmdname="--clearsign";
break;
case aDetachedSign:
cmdname="--detach-sign";
break;
case aSym:
cmdname="--symmetric";
break;
case aEncrSym:
cmdname="--symmetric --encrypt";
break;
case aStore:
cmdname="--store";
break;
default:
cmdname=NULL;
break;
}
if(cmdname)
log_error(_("%s does not yet work with %s\n"),cmdname,"--multifile");
}
if( log_get_errorcount(0) )
g10_exit(2);
if(opt.compress_level==0)
opt.compress_algo=COMPRESS_ALGO_NONE;
/* Check our chosen algorithms against the list of legal
algorithms. */
if(!GNUPG)
{
const char *badalg=NULL;
preftype_t badtype=PREFTYPE_NONE;
if(opt.def_cipher_algo
&& !algo_available(PREFTYPE_SYM,opt.def_cipher_algo,NULL))
{
badalg = openpgp_cipher_algo_name (opt.def_cipher_algo);
badtype = PREFTYPE_SYM;
}
else if(opt.def_digest_algo
&& !algo_available(PREFTYPE_HASH,opt.def_digest_algo,NULL))
{
badalg = gcry_md_algo_name (opt.def_digest_algo);
badtype = PREFTYPE_HASH;
}
else if(opt.cert_digest_algo
&& !algo_available(PREFTYPE_HASH,opt.cert_digest_algo,NULL))
{
badalg = gcry_md_algo_name (opt.cert_digest_algo);
badtype = PREFTYPE_HASH;
}
else if(opt.compress_algo!=-1
&& !algo_available(PREFTYPE_ZIP,opt.compress_algo,NULL))
{
badalg = compress_algo_to_string(opt.compress_algo);
badtype = PREFTYPE_ZIP;
}
if(badalg)
{
switch(badtype)
{
case PREFTYPE_SYM:
log_info(_("you may not use cipher algorithm `%s'"
" while in %s mode\n"),
badalg,compliance_option_string());
break;
case PREFTYPE_HASH:
log_info(_("you may not use digest algorithm `%s'"
" while in %s mode\n"),
badalg,compliance_option_string());
break;
case PREFTYPE_ZIP:
log_info(_("you may not use compression algorithm `%s'"
" while in %s mode\n"),
badalg,compliance_option_string());
break;
default:
BUG();
}
compliance_failure();
}
}
/* Set the random seed file. */
if( use_random_seed ) {
char *p = make_filename(opt.homedir, "random_seed", NULL );
gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
if (!access (p, F_OK))
register_secured_file (p);
xfree(p);
}
/* If there is no command but the --fingerprint is given, default
to the --list-keys command. */
if (!cmd && fpr_maybe_cmd)
{
set_cmd (&cmd, aListKeys);
}
if( opt.verbose > 1 )
set_packet_list_mode(1);
/* Add the keyrings, but not for some special commands. Also
avoid adding the secret keyring for a couple of commands to
avoid unneeded access in case the secrings are stored on a
floppy.
We always need to add the keyrings if we are running under
SELinux, this is so that the rings are added to the list of
secured files. */
if( ALWAYS_ADD_KEYRINGS
|| (cmd != aDeArmor && cmd != aEnArmor && cmd != aGPGConfTest) )
{
if (!nrings || default_keyring) /* Add default ring. */
keydb_add_resource ("pubring" EXTSEP_S "gpg", 4);
for (sl = nrings; sl; sl = sl->next )
keydb_add_resource (sl->d, sl->flags);
}
FREE_STRLIST(nrings);
if (cmd == aGPGConfTest)
g10_exit(0);
if( pwfd != -1 ) /* Read the passphrase now. */
read_passphrase_from_fd( pwfd );
fname = argc? *argv : NULL;
if(fname && utf8_strings)
opt.flags.utf8_filename=1;
ctrl = xcalloc (1, sizeof *ctrl);
gpg_init_default_ctrl (ctrl);
switch( cmd ) {
case aPrimegen:
case aPrintMD:
case aPrintMDs:
case aGenRandom:
case aDeArmor:
case aEnArmor:
break;
case aFixTrustDB:
case aExportOwnerTrust: rc = setup_trustdb( 0, trustdb_name ); break;
case aListTrustDB: rc = setup_trustdb( argc? 1:0, trustdb_name ); break;
default: rc = setup_trustdb(1, trustdb_name ); break;
}
if( rc )
log_error(_("failed to initialize the TrustDB: %s\n"), g10_errstr(rc));
switch (cmd)
{
case aStore:
case aSym:
case aSign:
case aSignSym:
case aClearsign:
if (!opt.quiet && any_explicit_recipient)
log_info (_("WARNING: recipients (-r) given "
"without using public key encryption\n"));
break;
default:
break;
}
switch( cmd )
{
case aServer:
gpg_server (ctrl);
break;
case aStore: /* only store the file */
if( argc > 1 )
wrong_args(_("--store [filename]"));
if( (rc = encrypt_store(fname)) )
log_error ("storing `%s' failed: %s\n",
print_fname_stdin(fname),g10_errstr(rc) );
break;
case aSym: /* encrypt the given file only with the symmetric cipher */
if( argc > 1 )
wrong_args(_("--symmetric [filename]"));
if( (rc = encrypt_symmetric(fname)) )
log_error (_("symmetric encryption of `%s' failed: %s\n"),
print_fname_stdin(fname),g10_errstr(rc) );
break;
case aEncr: /* encrypt the given file */
if(multifile)
encrypt_crypt_files (ctrl, argc, argv, remusr);
else
{
if( argc > 1 )
wrong_args(_("--encrypt [filename]"));
if( (rc = encrypt_crypt (ctrl, -1, fname, remusr, 0, NULL, -1)) )
log_error("%s: encryption failed: %s\n",
print_fname_stdin(fname), g10_errstr(rc) );
}
break;
case aEncrSym:
/* This works with PGP 8 in the sense that it acts just like a
symmetric message. It doesn't work at all with 2 or 6. It
might work with 7, but alas, I don't have a copy to test
with right now. */
if( argc > 1 )
wrong_args(_("--symmetric --encrypt [filename]"));
else if(opt.s2k_mode==0)
log_error(_("you cannot use --symmetric --encrypt"
" with --s2k-mode 0\n"));
else if(PGP2 || PGP6 || PGP7 || RFC1991)
log_error(_("you cannot use --symmetric --encrypt"
" while in %s mode\n"),compliance_option_string());
else
{
if( (rc = encrypt_crypt (ctrl, -1, fname, remusr, 1, NULL, -1)) )
log_error("%s: encryption failed: %s\n",
print_fname_stdin(fname), g10_errstr(rc) );
}
break;
case aSign: /* sign the given file */
sl = NULL;
if( detached_sig ) { /* sign all files */
for( ; argc; argc--, argv++ )
add_to_strlist( &sl, *argv );
}
else {
if( argc > 1 )
wrong_args(_("--sign [filename]"));
if( argc ) {
sl = xmalloc_clear( sizeof *sl + strlen(fname));
strcpy(sl->d, fname);
}
}
if( (rc = sign_file (ctrl, sl, detached_sig, locusr, 0, NULL, NULL)) )
log_error("signing failed: %s\n", g10_errstr(rc) );
free_strlist(sl);
break;
case aSignEncr: /* sign and encrypt the given file */
if( argc > 1 )
wrong_args(_("--sign --encrypt [filename]"));
if( argc ) {
sl = xmalloc_clear( sizeof *sl + strlen(fname));
strcpy(sl->d, fname);
}
else
sl = NULL;
if ((rc = sign_file (ctrl, sl, detached_sig, locusr, 1, remusr, NULL)))
log_error("%s: sign+encrypt failed: %s\n",
print_fname_stdin(fname), g10_errstr(rc) );
free_strlist(sl);
break;
case aSignEncrSym: /* sign and encrypt the given file */
if( argc > 1 )
wrong_args(_("--symmetric --sign --encrypt [filename]"));
else if(opt.s2k_mode==0)
log_error(_("you cannot use --symmetric --sign --encrypt"
" with --s2k-mode 0\n"));
else if(PGP2 || PGP6 || PGP7 || RFC1991)
log_error(_("you cannot use --symmetric --sign --encrypt"
" while in %s mode\n"),compliance_option_string());
else
{
if( argc )
{
sl = xmalloc_clear( sizeof *sl + strlen(fname));
strcpy(sl->d, fname);
}
else
sl = NULL;
if ((rc = sign_file (ctrl, sl, detached_sig, locusr,
2, remusr, NULL)))
log_error("%s: symmetric+sign+encrypt failed: %s\n",
print_fname_stdin(fname), g10_errstr(rc) );
free_strlist(sl);
}
break;
case aSignSym: /* sign and conventionally encrypt the given file */
if (argc > 1)
wrong_args(_("--sign --symmetric [filename]"));
rc = sign_symencrypt_file (fname, locusr);
if (rc)
log_error("%s: sign+symmetric failed: %s\n",
print_fname_stdin(fname), g10_errstr(rc) );
break;
case aClearsign: /* make a clearsig */
if( argc > 1 )
wrong_args(_("--clearsign [filename]"));
if( (rc = clearsign_file(fname, locusr, NULL)) )
log_error("%s: clearsign failed: %s\n",
print_fname_stdin(fname), g10_errstr(rc) );
break;
case aVerify:
if (multifile)
{
if ((rc = verify_files (ctrl, argc, argv)))
log_error("verify files failed: %s\n", g10_errstr(rc) );
}
else
{
if ((rc = verify_signatures (ctrl, argc, argv)))
log_error("verify signatures failed: %s\n", g10_errstr(rc) );
}
break;
case aDecrypt:
if (multifile)
decrypt_messages (ctrl, argc, argv);
else
{
if( argc > 1 )
wrong_args(_("--decrypt [filename]"));
if( (rc = decrypt_message (ctrl, fname) ))
log_error("decrypt_message failed: %s\n", g10_errstr(rc) );
}
break;
case aSignKey:
if( argc != 1 )
wrong_args(_("--sign-key user-id"));
/* fall through */
case aLSignKey:
if( argc != 1 )
wrong_args(_("--lsign-key user-id"));
/* fall through */
sl=NULL;
if(cmd==aSignKey)
append_to_strlist(&sl,"sign");
else if(cmd==aLSignKey)
append_to_strlist(&sl,"lsign");
else
BUG();
append_to_strlist( &sl, "save" );
username = make_username( fname );
keyedit_menu (ctrl, username, locusr, sl, 0, 0 );
xfree(username);
free_strlist(sl);
break;
case aEditKey: /* Edit a key signature */
if( !argc )
wrong_args(_("--edit-key user-id [commands]"));
username = make_username( fname );
if( argc > 1 ) {
sl = NULL;
for( argc--, argv++ ; argc; argc--, argv++ )
append_to_strlist( &sl, *argv );
keyedit_menu (ctrl, username, locusr, sl, 0, 1 );
free_strlist(sl);
}
else
keyedit_menu (ctrl, username, locusr, NULL, 0, 1 );
xfree(username);
break;
case aPasswd:
if (argc != 1)
wrong_args (_("--passwd "));
else
{
username = make_username (fname);
keyedit_passwd (ctrl, username);
xfree (username);
}
break;
case aDeleteKeys:
case aDeleteSecretKeys:
case aDeleteSecretAndPublicKeys:
sl = NULL;
/* I'm adding these in reverse order as add_to_strlist2
reverses them again, and it's easier to understand in the
proper order :) */
for( ; argc; argc-- )
add_to_strlist2( &sl, argv[argc-1], utf8_strings );
delete_keys(sl,cmd==aDeleteSecretKeys,cmd==aDeleteSecretAndPublicKeys);
free_strlist(sl);
break;
case aCheckKeys:
opt.check_sigs = 1;
case aListSigs:
opt.list_sigs = 1;
case aListKeys:
sl = NULL;
for( ; argc; argc--, argv++ )
add_to_strlist2( &sl, *argv, utf8_strings );
public_key_list (ctrl, sl, 0);
free_strlist(sl);
break;
case aListSecretKeys:
sl = NULL;
for( ; argc; argc--, argv++ )
add_to_strlist2( &sl, *argv, utf8_strings );
secret_key_list (ctrl, sl);
free_strlist(sl);
break;
case aLocateKeys:
sl = NULL;
for (; argc; argc--, argv++)
add_to_strlist2( &sl, *argv, utf8_strings );
public_key_list (ctrl, sl, 1);
free_strlist (sl);
break;
case aKeygen: /* generate a key */
if( opt.batch ) {
if( argc > 1 )
wrong_args("--gen-key [parameterfile]");
generate_keypair (argc? *argv : NULL, NULL, 0);
}
else {
if( argc )
wrong_args("--gen-key");
generate_keypair (NULL, NULL, 0);
}
break;
case aFastImport:
opt.import_options |= IMPORT_FAST;
case aImport:
import_keys (ctrl, argc? argv:NULL, argc, NULL, opt.import_options);
break;
/* TODO: There are a number of command that use this same
"make strlist, call function, report error, free strlist"
pattern. Join them together here and avoid all that
duplicated code. */
case aExport:
case aSendKeys:
case aRecvKeys:
sl = NULL;
for( ; argc; argc--, argv++ )
append_to_strlist2( &sl, *argv, utf8_strings );
if( cmd == aSendKeys )
rc = keyserver_export (ctrl, sl );
else if( cmd == aRecvKeys )
rc = keyserver_import (ctrl, sl );
else
rc = export_pubkeys (ctrl, sl, opt.export_options);
if(rc)
{
if(cmd==aSendKeys)
log_error(_("keyserver send failed: %s\n"),g10_errstr(rc));
else if(cmd==aRecvKeys)
log_error(_("keyserver receive failed: %s\n"),g10_errstr(rc));
else
log_error(_("key export failed: %s\n"),g10_errstr(rc));
}
free_strlist(sl);
break;
case aSearchKeys:
sl = NULL;
for( ; argc; argc--, argv++ )
append_to_strlist2( &sl, *argv, utf8_strings );
rc = keyserver_search (ctrl, sl);
if(rc)
log_error(_("keyserver search failed: %s\n"),g10_errstr(rc));
free_strlist(sl);
break;
case aRefreshKeys:
sl = NULL;
for( ; argc; argc--, argv++ )
append_to_strlist2( &sl, *argv, utf8_strings );
rc = keyserver_refresh (ctrl, sl);
if(rc)
log_error(_("keyserver refresh failed: %s\n"),g10_errstr(rc));
free_strlist(sl);
break;
case aFetchKeys:
sl = NULL;
for( ; argc; argc--, argv++ )
append_to_strlist2( &sl, *argv, utf8_strings );
rc = keyserver_fetch (ctrl, sl);
if(rc)
log_error("key fetch failed: %s\n",g10_errstr(rc));
free_strlist(sl);
break;
case aExportSecret:
sl = NULL;
for( ; argc; argc--, argv++ )
add_to_strlist2( &sl, *argv, utf8_strings );
export_seckeys (ctrl, sl);
free_strlist(sl);
break;
case aExportSecretSub:
sl = NULL;
for( ; argc; argc--, argv++ )
add_to_strlist2( &sl, *argv, utf8_strings );
export_secsubkeys (ctrl, sl);
free_strlist(sl);
break;
case aGenRevoke:
if( argc != 1 )
wrong_args("--gen-revoke user-id");
username = make_username(*argv);
gen_revoke( username );
xfree( username );
break;
case aDesigRevoke:
if( argc != 1 )
wrong_args("--desig-revoke user-id");
username = make_username(*argv);
gen_desig_revoke( username, locusr );
xfree( username );
break;
case aDeArmor:
if( argc > 1 )
wrong_args("--dearmor [file]");
rc = dearmor_file( argc? *argv: NULL );
if( rc )
log_error(_("dearmoring failed: %s\n"), g10_errstr(rc));
break;
case aEnArmor:
if( argc > 1 )
wrong_args("--enarmor [file]");
rc = enarmor_file( argc? *argv: NULL );
if( rc )
log_error(_("enarmoring failed: %s\n"), g10_errstr(rc));
break;
case aPrimegen:
#if 0 /*FIXME*/
{ int mode = argc < 2 ? 0 : atoi(*argv);
if( mode == 1 && argc == 2 ) {
mpi_print (es_stdout,
generate_public_prime( atoi(argv[1]) ), 1);
}
else if( mode == 2 && argc == 3 ) {
mpi_print (es_stdout, generate_elg_prime(
0, atoi(argv[1]),
atoi(argv[2]), NULL,NULL ), 1);
}
else if( mode == 3 && argc == 3 ) {
MPI *factors;
mpi_print (es_stdout, generate_elg_prime(
1, atoi(argv[1]),
atoi(argv[2]), NULL,&factors ), 1);
putchar('\n');
mpi_print (es_stdout, factors[0], 1 ); /* print q */
}
else if( mode == 4 && argc == 3 ) {
MPI g = mpi_alloc(1);
mpi_print (es_stdout, generate_elg_prime(
0, atoi(argv[1]),
atoi(argv[2]), g, NULL ), 1);
putchar('\n');
mpi_print (es_stdout, g, 1 );
mpi_free (g);
}
else
wrong_args("--gen-prime mode bits [qbits] ");
putchar('\n');
}
#endif
wrong_args("--gen-prime not yet supported ");
break;
case aGenRandom:
{
int level = argc ? atoi(*argv):0;
int count = argc > 1 ? atoi(argv[1]): 0;
int endless = !count;
if( argc < 1 || argc > 2 || level < 0 || level > 2 || count < 0 )
wrong_args("--gen-random 0|1|2 [count]");
while( endless || count ) {
byte *p;
/* Wee need a multiple of 3, so that in case of
armored output we get a correct string. No
linefolding is done, as it is best to levae this to
other tools */
size_t n = !endless && count < 99? count : 99;
p = gcry_random_bytes (n, level);
#ifdef HAVE_DOSISH_SYSTEM
setmode ( fileno(stdout), O_BINARY );
#endif
if (opt.armor) {
char *tmp = make_radix64_string (p, n);
fputs (tmp, stdout);
xfree (tmp);
if (n%3 == 1)
putchar ('=');
if (n%3)
putchar ('=');
} else {
fwrite( p, n, 1, stdout );
}
xfree(p);
if( !endless )
count -= n;
}
if (opt.armor)
putchar ('\n');
}
break;
case aPrintMD:
if( argc < 1)
wrong_args("--print-md algo [files]");
{
int all_algos = (**argv=='*' && !(*argv)[1]);
int algo = all_algos? 0 : gcry_md_map_name (*argv);
if( !algo && !all_algos )
log_error(_("invalid hash algorithm `%s'\n"), *argv );
else {
argc--; argv++;
if( !argc )
print_mds(NULL, algo);
else {
for(; argc; argc--, argv++ )
print_mds(*argv, algo);
}
}
}
break;
case aPrintMDs: /* old option */
if( !argc )
print_mds(NULL,0);
else {
for(; argc; argc--, argv++ )
print_mds(*argv,0);
}
break;
case aListTrustDB:
if( !argc )
list_trustdb(NULL);
else {
for( ; argc; argc--, argv++ )
list_trustdb( *argv );
}
break;
case aUpdateTrustDB:
if( argc )
wrong_args("--update-trustdb");
update_trustdb();
break;
case aCheckTrustDB:
/* Old versions allowed for arguments - ignore them */
check_trustdb();
break;
case aFixTrustDB:
how_to_fix_the_trustdb ();
break;
case aListTrustPath:
if( !argc )
wrong_args("--list-trust-path ");
for( ; argc; argc--, argv++ ) {
username = make_username( *argv );
list_trust_path( username );
xfree(username);
}
break;
case aExportOwnerTrust:
if( argc )
wrong_args("--export-ownertrust");
export_ownertrust();
break;
case aImportOwnerTrust:
if( argc > 1 )
wrong_args("--import-ownertrust [file]");
import_ownertrust( argc? *argv:NULL );
break;
case aRebuildKeydbCaches:
if (argc)
wrong_args ("--rebuild-keydb-caches");
keydb_rebuild_caches (1);
break;
#ifdef ENABLE_CARD_SUPPORT
case aCardStatus:
if (argc)
wrong_args ("--card-status");
card_status (es_stdout, NULL, 0);
break;
case aCardEdit:
if (argc) {
sl = NULL;
for (argc--, argv++ ; argc; argc--, argv++)
append_to_strlist (&sl, *argv);
card_edit (ctrl, sl);
free_strlist (sl);
}
else
card_edit (ctrl, NULL);
break;
case aChangePIN:
if (!argc)
change_pin (0,1);
else if (argc == 1)
change_pin (atoi (*argv),1);
else
wrong_args ("--change-pin [no]");
break;
#endif /* ENABLE_CARD_SUPPORT*/
case aListConfig:
{
char *str=collapse_args(argc,argv);
list_config(str);
xfree(str);
}
break;
case aListPackets:
opt.list_packets=2;
default:
if( argc > 1 )
wrong_args(_("[filename]"));
/* Issue some output for the unix newbie */
if (!fname && !opt.outfile
&& gnupg_isatty (fileno (stdin))
&& gnupg_isatty (fileno (stdout))
&& gnupg_isatty (fileno (stderr)))
log_info(_("Go ahead and type your message ...\n"));
a = iobuf_open(fname);
if (a && is_secured_file (iobuf_get_fd (a)))
{
iobuf_close (a);
a = NULL;
gpg_err_set_errno (EPERM);
}
if( !a )
log_error(_("can't open `%s'\n"), print_fname_stdin(fname));
else {
if( !opt.no_armor ) {
if( use_armor_filter( a ) ) {
afx = new_armor_context ();
push_armor_filter (afx, a);
}
}
if( cmd == aListPackets ) {
set_packet_list_mode(1);
opt.list_packets=1;
}
rc = proc_packets (ctrl, NULL, a );
if( rc )
log_error("processing message failed: %s\n", g10_errstr(rc) );
iobuf_close(a);
}
break;
}
/* cleanup */
gpg_deinit_default_ctrl (ctrl);
xfree (ctrl);
release_armor_context (afx);
FREE_STRLIST(remusr);
FREE_STRLIST(locusr);
g10_exit(0);
return 8; /*NEVER REACHED*/
}
/* Note: This function is used by signal handlers!. */
static void
emergency_cleanup (void)
{
gcry_control (GCRYCTL_TERM_SECMEM );
}
void
g10_exit( int rc )
{
gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
if ( (opt.debug & DBG_MEMSTAT_VALUE) )
{
gcry_control (GCRYCTL_DUMP_MEMORY_STATS);
gcry_control (GCRYCTL_DUMP_RANDOM_STATS);
}
if (opt.debug)
gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
emergency_cleanup ();
rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0;
exit (rc);
}
/* Pretty-print hex hashes. This assumes at least an 80-character
display, but there are a few other similar assumptions in the
display code. */
static void
print_hex (gcry_md_hd_t md, int algo, const char *fname)
{
int i,n,count,indent=0;
const byte *p;
if (fname)
indent = es_printf("%s: ",fname);
if (indent>40)
{
printf("\n");
indent=0;
}
if (algo==DIGEST_ALGO_RMD160)
indent += es_printf("RMD160 = ");
else if (algo>0)
indent += es_printf("%6s = ", gcry_md_algo_name (algo));
else
algo = abs(algo);
count = indent;
p = gcry_md_read (md, algo);
n = gcry_md_get_algo_dlen (algo);
count += es_printf ("%02X",*p++);
for(i=1;i79)
{
es_printf ("\n%*s",indent," ");
count = indent;
}
else
count += es_printf(" ");
if (!(i%8))
count += es_printf(" ");
}
else if (n==20)
{
if(!(i%2))
{
if(count+4>79)
{
es_printf ("\n%*s",indent," ");
count=indent;
}
else
count += es_printf(" ");
}
if (!(i%10))
count += es_printf(" ");
}
else
{
if(!(i%4))
{
if (count+8>79)
{
es_printf ("\n%*s",indent," ");
count=indent;
}
else
count += es_printf(" ");
}
}
count += es_printf("%02X",*p);
}
es_printf ("\n");
}
static void
print_hashline( gcry_md_hd_t md, int algo, const char *fname )
{
int i, n;
const byte *p;
if ( fname )
{
for (p = fname; *p; p++ )
{
if ( *p <= 32 || *p > 127 || *p == ':' || *p == '%' )
es_printf ("%%%02X", *p );
else
es_putc (*p, es_stdout);
}
}
es_putc (':', es_stdout);
es_printf ("%d:", algo);
p = gcry_md_read (md, algo);
n = gcry_md_get_algo_dlen (algo);
for(i=0; i < n ; i++, p++ )
es_printf ("%02X", *p);
es_fputs (":\n", es_stdout);
}
static void
print_mds( const char *fname, int algo )
{
FILE *fp;
char buf[1024];
size_t n;
gcry_md_hd_t md;
if( !fname ) {
fp = stdin;
#ifdef HAVE_DOSISH_SYSTEM
setmode ( fileno(fp) , O_BINARY );
#endif
}
else {
fp = fopen( fname, "rb" );
if (fp && is_secured_file (fileno (fp)))
{
fclose (fp);
fp = NULL;
gpg_err_set_errno (EPERM);
}
}
if( !fp ) {
log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
return;
}
gcry_md_open (&md, 0, 0);
if( algo )
gcry_md_enable (md, algo);
else {
gcry_md_enable (md, GCRY_MD_MD5);
gcry_md_enable (md, GCRY_MD_SHA1);
gcry_md_enable (md, GCRY_MD_RMD160);
if (!openpgp_md_test_algo (GCRY_MD_SHA224))
gcry_md_enable (md, GCRY_MD_SHA224);
if (!openpgp_md_test_algo (GCRY_MD_SHA256))
gcry_md_enable (md, GCRY_MD_SHA256);
if (!openpgp_md_test_algo (GCRY_MD_SHA384))
gcry_md_enable (md, GCRY_MD_SHA384);
if (!openpgp_md_test_algo (GCRY_MD_SHA512))
gcry_md_enable (md, GCRY_MD_SHA512);
}
while( (n=fread( buf, 1, DIM(buf), fp )) )
gcry_md_write (md, buf, n);
if( ferror(fp) )
log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
else {
gcry_md_final (md);
if ( opt.with_colons ) {
if ( algo )
print_hashline( md, algo, fname );
else {
print_hashline( md, GCRY_MD_MD5, fname );
print_hashline( md, GCRY_MD_SHA1, fname );
if (!gcry_md_test_algo (GCRY_MD_RMD160))
print_hashline( md, GCRY_MD_RMD160, fname );
if (!gcry_md_test_algo (GCRY_MD_SHA224))
print_hashline (md, GCRY_MD_SHA224, fname);
if (!gcry_md_test_algo (GCRY_MD_SHA256))
print_hashline( md, GCRY_MD_SHA256, fname );
if (!gcry_md_test_algo (GCRY_MD_SHA384))
print_hashline ( md, GCRY_MD_SHA384, fname );
if (!gcry_md_test_algo (GCRY_MD_SHA512))
print_hashline ( md, GCRY_MD_SHA512, fname );
}
}
else {
if( algo )
print_hex(md,-algo,fname);
else {
print_hex( md, GCRY_MD_MD5, fname );
print_hex( md, GCRY_MD_SHA1, fname );
if (!gcry_md_test_algo (GCRY_MD_RMD160))
print_hex( md, GCRY_MD_RMD160, fname );
if (!gcry_md_test_algo (GCRY_MD_SHA224))
print_hex (md, GCRY_MD_SHA224, fname);
if (!gcry_md_test_algo (GCRY_MD_SHA256))
print_hex( md, GCRY_MD_SHA256, fname );
if (!gcry_md_test_algo (GCRY_MD_SHA384))
print_hex( md, GCRY_MD_SHA384, fname );
if (!gcry_md_test_algo (GCRY_MD_SHA512))
print_hex( md, GCRY_MD_SHA512, fname );
}
}
}
gcry_md_close(md);
if( fp != stdin )
fclose(fp);
}
/****************
* Check the supplied name,value string and add it to the notation
* data to be used for signatures. which==0 for sig notations, and 1
* for cert notations.
*/
static void
add_notation_data( const char *string, int which )
{
struct notation *notation;
notation=string_to_notation(string,utf8_strings);
if(notation)
{
if(which)
{
notation->next=opt.cert_notations;
opt.cert_notations=notation;
}
else
{
notation->next=opt.sig_notations;
opt.sig_notations=notation;
}
}
}
static void
add_policy_url( const char *string, int which )
{
unsigned int i,critical=0;
strlist_t sl;
if(*string=='!')
{
string++;
critical=1;
}
for(i=0;iflags |= 1;
}
static void
add_keyserver_url( const char *string, int which )
{
unsigned int i,critical=0;
strlist_t sl;
if(*string=='!')
{
string++;
critical=1;
}
for(i=0;iflags |= 1;
}
diff --git a/g10/keygen.c b/g10/keygen.c
index ec7e7e79c..f7f152659 100644
--- a/g10/keygen.c
+++ b/g10/keygen.c
@@ -1,3963 +1,4186 @@
/* keygen.c - generate a key pair
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
* 2006, 2007, 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
* 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
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "gpg.h"
#include "util.h"
#include "main.h"
#include "packet.h"
#include "cipher.h"
#include "ttyio.h"
#include "options.h"
#include "keydb.h"
#include "trustdb.h"
#include "status.h"
#include "i18n.h"
#include "keyserver-internal.h"
#include "call-agent.h"
+#include "pkglue.h"
+#include "gcrypt.h"
/* The default algorithms. If you change them remember to change them
also in gpg.c:gpgconf_list. You should also check that the value
is inside the bounds enforced by ask_keysize and gen_xxx. */
#define DEFAULT_STD_ALGO GCRY_PK_RSA
#define DEFAULT_STD_KEYSIZE 2048
-#define KEYGEN_FLAG_NO_PROTECTION 1
-#define KEYGEN_FLAG_TRANSIENT_KEY 2
-
-
#define MAX_PREFS 30
enum para_name {
pKEYTYPE,
pKEYLENGTH,
pKEYUSAGE,
pSUBKEYTYPE,
pSUBKEYLENGTH,
pSUBKEYUSAGE,
pAUTHKEYTYPE,
pNAMEREAL,
pNAMEEMAIL,
pNAMECOMMENT,
pPREFERENCES,
pREVOKER,
pUSERID,
pCREATIONDATE,
pKEYCREATIONDATE, /* Same in seconds since epoch. */
pEXPIREDATE,
pKEYEXPIRE, /* in n seconds */
pSUBKEYEXPIRE, /* in n seconds */
pPASSPHRASE,
pPASSPHRASE_DEK,
pPASSPHRASE_S2K,
pSERIALNO,
pCARDBACKUPKEY,
pHANDLE,
pKEYSERVER
};
struct para_data_s {
struct para_data_s *next;
int lnr;
enum para_name key;
union {
DEK *dek;
STRING2KEY *s2k;
u32 expire;
u32 creation;
unsigned int usage;
struct revocation_key revkey;
char value[1];
} u;
};
struct output_control_s
{
int lnr;
int dryrun;
int ask_passphrase;
unsigned int keygen_flags;
int use_files;
struct {
char *fname;
char *newfname;
IOBUF stream;
armor_filter_context_t *afx;
} pub;
};
struct opaque_data_usage_and_pk {
unsigned int usage;
PKT_public_key *pk;
};
static int prefs_initialized = 0;
static byte sym_prefs[MAX_PREFS];
static int nsym_prefs;
static byte hash_prefs[MAX_PREFS];
static int nhash_prefs;
static byte zip_prefs[MAX_PREFS];
static int nzip_prefs;
static int mdc_available,ks_modify;
static void do_generate_keypair( struct para_data_s *para,
struct output_control_s *outctrl, int card );
static int write_keyblock (iobuf_t out, kbnode_t node);
static gpg_error_t gen_card_key (int algo, int keyno, int is_primary,
kbnode_t pub_root,
u32 *timestamp, u32 expireval);
static int gen_card_key_with_backup (int algo, int keyno, int is_primary,
kbnode_t pub_root, u32 timestamp,
u32 expireval, struct para_data_s *para);
static void
print_status_key_created (int letter, PKT_public_key *pk, const char *handle)
{
byte array[MAX_FINGERPRINT_LEN], *s;
char *buf, *p;
size_t i, n;
if (!handle)
handle = "";
buf = xmalloc (MAX_FINGERPRINT_LEN*2+31 + strlen (handle) + 1);
p = buf;
if (letter || pk)
{
*p++ = letter;
*p++ = ' ';
fingerprint_from_pk (pk, array, &n);
s = array;
for (i=0; i < n ; i++, s++, p += 2)
sprintf (p, "%02X", *s);
}
if (*handle)
{
*p++ = ' ';
for (i=0; handle[i] && i < 100; i++)
*p++ = isspace ((unsigned int)handle[i])? '_':handle[i];
}
*p = 0;
write_status_text ((letter || pk)?STATUS_KEY_CREATED:STATUS_KEY_NOT_CREATED,
buf);
xfree (buf);
}
static void
print_status_key_not_created (const char *handle)
{
print_status_key_created (0, NULL, handle);
}
static void
write_uid( KBNODE root, const char *s )
{
PACKET *pkt = xmalloc_clear(sizeof *pkt );
size_t n = strlen(s);
pkt->pkttype = PKT_USER_ID;
pkt->pkt.user_id = xmalloc_clear( sizeof *pkt->pkt.user_id + n - 1 );
pkt->pkt.user_id->len = n;
pkt->pkt.user_id->ref = 1;
strcpy(pkt->pkt.user_id->name, s);
add_kbnode( root, new_kbnode( pkt ) );
}
static void
do_add_key_flags (PKT_signature *sig, unsigned int use)
{
byte buf[1];
buf[0] = 0;
/* The spec says that all primary keys MUST be able to certify. */
if(sig->sig_class!=0x18)
buf[0] |= 0x01;
if (use & PUBKEY_USAGE_SIG)
buf[0] |= 0x02;
if (use & PUBKEY_USAGE_ENC)
buf[0] |= 0x04 | 0x08;
if (use & PUBKEY_USAGE_AUTH)
buf[0] |= 0x20;
if (!buf[0])
return;
build_sig_subpkt (sig, SIGSUBPKT_KEY_FLAGS, buf, 1);
}
int
keygen_add_key_expire (PKT_signature *sig, void *opaque)
{
PKT_public_key *pk = opaque;
byte buf[8];
u32 u;
if (pk->expiredate)
{
if (pk->expiredate > pk->timestamp)
u = pk->expiredate - pk->timestamp;
else
u = 1;
buf[0] = (u >> 24) & 0xff;
buf[1] = (u >> 16) & 0xff;
buf[2] = (u >> 8) & 0xff;
buf[3] = u & 0xff;
build_sig_subpkt (sig, SIGSUBPKT_KEY_EXPIRE, buf, 4);
}
else
{
/* Make sure we don't leave a key expiration subpacket lying
around */
delete_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE);
}
return 0;
}
static int
keygen_add_key_flags_and_expire (PKT_signature *sig, void *opaque)
{
struct opaque_data_usage_and_pk *oduap = opaque;
do_add_key_flags (sig, oduap->usage);
return keygen_add_key_expire (sig, oduap->pk);
}
static int
set_one_pref (int val, int type, const char *item, byte *buf, int *nbuf)
{
int i;
for (i=0; i < *nbuf; i++ )
if (buf[i] == val)
{
log_info (_("preference `%s' duplicated\n"), item);
return -1;
}
if (*nbuf >= MAX_PREFS)
{
if(type==1)
log_info(_("too many cipher preferences\n"));
else if(type==2)
log_info(_("too many digest preferences\n"));
else if(type==3)
log_info(_("too many compression preferences\n"));
else
BUG();
return -1;
}
buf[(*nbuf)++] = val;
return 0;
}
/*
* Parse the supplied string and use it to set the standard
* preferences. The string may be in a form like the one printed by
* "pref" (something like: "S10 S3 H3 H2 Z2 Z1") or the actual
* cipher/hash/compress names. Use NULL to set the default
* preferences. Returns: 0 = okay
*/
int
keygen_set_std_prefs (const char *string,int personal)
{
byte sym[MAX_PREFS], hash[MAX_PREFS], zip[MAX_PREFS];
int nsym=0, nhash=0, nzip=0, val, rc=0;
int mdc=1, modify=0; /* mdc defaults on, modify defaults off. */
char dummy_string[20*4+1]; /* Enough for 20 items. */
if (!string || !ascii_strcasecmp (string, "default"))
{
if (opt.def_preference_list)
string=opt.def_preference_list;
else
{
int any_compress = 0;
dummy_string[0]='\0';
/* The rationale why we use the order AES256,192,128 is
for compatibility reasons with PGP. If gpg would
define AES128 first, we would get the somewhat
confusing situation:
gpg -r pgpkey -r gpgkey ---gives--> AES256
gpg -r gpgkey -r pgpkey ---gives--> AES
Note that by using --personal-cipher-preferences it is
possible to prefer AES128.
*/
/* Make sure we do not add more than 15 items here, as we
could overflow the size of dummy_string. We currently
have at most 12. */
if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES256) )
strcat(dummy_string,"S9 ");
if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES192) )
strcat(dummy_string,"S8 ");
if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES) )
strcat(dummy_string,"S7 ");
if ( !openpgp_cipher_test_algo (CIPHER_ALGO_CAST5) )
strcat(dummy_string,"S3 ");
strcat(dummy_string,"S2 "); /* 3DES */
/* If we have it, IDEA goes *after* 3DES so it won't be
used unless we're encrypting along with a V3 key.
Ideally, we would only put the S1 preference in if the
key was RSA and <=2048 bits, as that is what won't
break PGP2, but that is difficult with the current
code, and not really worth checking as a non-RSA <=2048
bit key wouldn't be usable by PGP2 anyway. -dms */
if ( !openpgp_cipher_test_algo (CIPHER_ALGO_IDEA) )
strcat(dummy_string,"S1 ");
/* The default hash algo order is:
SHA-256, SHA-1, SHA-384, SHA-512, SHA-224.
Ordering SHA-1 before SHA-384 might be viewed as a bit
strange; it is done because we expect that soon enough
SHA-3 will be available and at that point there should
be no more need for SHA-384 etc. Anyway this order is
just a default and can easily be changed by a config
option. */
if (!openpgp_md_test_algo (DIGEST_ALGO_SHA256))
strcat (dummy_string, "H8 ");
strcat (dummy_string, "H2 "); /* SHA-1 */
if (!openpgp_md_test_algo (DIGEST_ALGO_SHA384))
strcat (dummy_string, "H9 ");
if (!openpgp_md_test_algo (DIGEST_ALGO_SHA512))
strcat (dummy_string, "H10 ");
if (!openpgp_md_test_algo (DIGEST_ALGO_SHA224))
strcat (dummy_string, "H11 ");
if(!check_compress_algo(COMPRESS_ALGO_ZLIB))
{
strcat(dummy_string,"Z2 ");
any_compress = 1;
}
if(!check_compress_algo(COMPRESS_ALGO_BZIP2))
{
strcat(dummy_string,"Z3 ");
any_compress = 1;
}
if(!check_compress_algo(COMPRESS_ALGO_ZIP))
{
strcat(dummy_string,"Z1 ");
any_compress = 1;
}
/* In case we have no compress algo at all, declare that
we prefer no compresssion. */
if (!any_compress)
strcat(dummy_string,"Z0 ");
/* Remove the trailing space. */
if (*dummy_string && dummy_string[strlen (dummy_string)-1] == ' ')
dummy_string[strlen (dummy_string)-1] = 0;
string=dummy_string;
}
}
else if (!ascii_strcasecmp (string, "none"))
string = "";
if(strlen(string))
{
char *tok,*prefstring;
prefstring=xstrdup(string); /* need a writable string! */
while((tok=strsep(&prefstring," ,")))
{
if((val=string_to_cipher_algo (tok)))
{
if(set_one_pref(val,1,tok,sym,&nsym))
rc=-1;
}
else if((val=string_to_digest_algo (tok)))
{
if(set_one_pref(val,2,tok,hash,&nhash))
rc=-1;
}
else if((val=string_to_compress_algo(tok))>-1)
{
if(set_one_pref(val,3,tok,zip,&nzip))
rc=-1;
}
else if (ascii_strcasecmp(tok,"mdc")==0)
mdc=1;
else if (ascii_strcasecmp(tok,"no-mdc")==0)
mdc=0;
else if (ascii_strcasecmp(tok,"ks-modify")==0)
modify=1;
else if (ascii_strcasecmp(tok,"no-ks-modify")==0)
modify=0;
else
{
log_info (_("invalid item `%s' in preference string\n"),tok);
/* Complain if IDEA is not available. */
if(ascii_strcasecmp(tok,"s1")==0
|| ascii_strcasecmp(tok,"idea")==0)
idea_cipher_warn(1);
rc=-1;
}
}
xfree(prefstring);
}
if(!rc)
{
if(personal)
{
if(personal==PREFTYPE_SYM)
{
xfree(opt.personal_cipher_prefs);
if(nsym==0)
opt.personal_cipher_prefs=NULL;
else
{
int i;
opt.personal_cipher_prefs=
xmalloc(sizeof(prefitem_t *)*(nsym+1));
for (i=0; iref=1;
uid->prefs=xmalloc((sizeof(prefitem_t *)*
(nsym_prefs+nhash_prefs+nzip_prefs+1)));
for(i=0;iprefs[j].type=PREFTYPE_SYM;
uid->prefs[j].value=sym_prefs[i];
}
for(i=0;iprefs[j].type=PREFTYPE_HASH;
uid->prefs[j].value=hash_prefs[i];
}
for(i=0;iprefs[j].type=PREFTYPE_ZIP;
uid->prefs[j].value=zip_prefs[i];
}
uid->prefs[j].type=PREFTYPE_NONE;
uid->prefs[j].value=0;
uid->flags.mdc=mdc_available;
uid->flags.ks_modify=ks_modify;
return uid;
}
static void
add_feature_mdc (PKT_signature *sig,int enabled)
{
const byte *s;
size_t n;
int i;
char *buf;
s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n );
/* Already set or cleared */
if (s && n &&
((enabled && (s[0] & 0x01)) || (!enabled && !(s[0] & 0x01))))
return;
if (!s || !n) { /* create a new one */
n = 1;
buf = xmalloc_clear (n);
}
else {
buf = xmalloc (n);
memcpy (buf, s, n);
}
if(enabled)
buf[0] |= 0x01; /* MDC feature */
else
buf[0] &= ~0x01;
/* Are there any bits set? */
for(i=0;ihashed, SIGSUBPKT_FEATURES);
else
build_sig_subpkt (sig, SIGSUBPKT_FEATURES, buf, n);
xfree (buf);
}
static void
add_keyserver_modify (PKT_signature *sig,int enabled)
{
const byte *s;
size_t n;
int i;
char *buf;
/* The keyserver modify flag is a negative flag (i.e. no-modify) */
enabled=!enabled;
s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n );
/* Already set or cleared */
if (s && n &&
((enabled && (s[0] & 0x80)) || (!enabled && !(s[0] & 0x80))))
return;
if (!s || !n) { /* create a new one */
n = 1;
buf = xmalloc_clear (n);
}
else {
buf = xmalloc (n);
memcpy (buf, s, n);
}
if(enabled)
buf[0] |= 0x80; /* no-modify flag */
else
buf[0] &= ~0x80;
/* Are there any bits set? */
for(i=0;ihashed, SIGSUBPKT_KS_FLAGS);
else
build_sig_subpkt (sig, SIGSUBPKT_KS_FLAGS, buf, n);
xfree (buf);
}
int
keygen_upd_std_prefs (PKT_signature *sig, void *opaque)
{
(void)opaque;
if (!prefs_initialized)
keygen_set_std_prefs (NULL, 0);
if (nsym_prefs)
build_sig_subpkt (sig, SIGSUBPKT_PREF_SYM, sym_prefs, nsym_prefs);
else
{
delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM);
delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_SYM);
}
if (nhash_prefs)
build_sig_subpkt (sig, SIGSUBPKT_PREF_HASH, hash_prefs, nhash_prefs);
else
{
delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH);
delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_HASH);
}
if (nzip_prefs)
build_sig_subpkt (sig, SIGSUBPKT_PREF_COMPR, zip_prefs, nzip_prefs);
else
{
delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR);
delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_COMPR);
}
/* Make sure that the MDC feature flag is set if needed. */
add_feature_mdc (sig,mdc_available);
add_keyserver_modify (sig,ks_modify);
keygen_add_keyserver_url(sig,NULL);
return 0;
}
/****************
* Add preference to the self signature packet.
* This is only called for packets with version > 3.
*/
int
keygen_add_std_prefs (PKT_signature *sig, void *opaque)
{
PKT_public_key *pk = opaque;
do_add_key_flags (sig, pk->pubkey_usage);
keygen_add_key_expire (sig, opaque );
keygen_upd_std_prefs (sig, opaque);
keygen_add_keyserver_url (sig,NULL);
return 0;
}
int
keygen_add_keyserver_url(PKT_signature *sig, void *opaque)
{
const char *url=opaque;
if(!url)
url=opt.def_keyserver_url;
if(url)
build_sig_subpkt(sig,SIGSUBPKT_PREF_KS,url,strlen(url));
else
delete_sig_subpkt (sig->hashed,SIGSUBPKT_PREF_KS);
return 0;
}
int
keygen_add_notations(PKT_signature *sig,void *opaque)
{
struct notation *notation;
/* We always start clean */
delete_sig_subpkt(sig->hashed,SIGSUBPKT_NOTATION);
delete_sig_subpkt(sig->unhashed,SIGSUBPKT_NOTATION);
sig->flags.notation=0;
for(notation=opaque;notation;notation=notation->next)
if(!notation->flags.ignore)
{
unsigned char *buf;
unsigned int n1,n2;
n1=strlen(notation->name);
if(notation->altvalue)
n2=strlen(notation->altvalue);
else if(notation->bdat)
n2=notation->blen;
else
n2=strlen(notation->value);
buf = xmalloc( 8 + n1 + n2 );
/* human readable or not */
buf[0] = notation->bdat?0:0x80;
buf[1] = buf[2] = buf[3] = 0;
buf[4] = n1 >> 8;
buf[5] = n1;
buf[6] = n2 >> 8;
buf[7] = n2;
memcpy(buf+8, notation->name, n1 );
if(notation->altvalue)
memcpy(buf+8+n1, notation->altvalue, n2 );
else if(notation->bdat)
memcpy(buf+8+n1, notation->bdat, n2 );
else
memcpy(buf+8+n1, notation->value, n2 );
build_sig_subpkt( sig, SIGSUBPKT_NOTATION |
(notation->flags.critical?SIGSUBPKT_FLAG_CRITICAL:0),
buf, 8+n1+n2 );
xfree(buf);
}
return 0;
}
int
keygen_add_revkey (PKT_signature *sig, void *opaque)
{
struct revocation_key *revkey = opaque;
byte buf[2+MAX_FINGERPRINT_LEN];
buf[0] = revkey->class;
buf[1] = revkey->algid;
memcpy (&buf[2], revkey->fpr, MAX_FINGERPRINT_LEN);
build_sig_subpkt (sig, SIGSUBPKT_REV_KEY, buf, 2+MAX_FINGERPRINT_LEN);
/* All sigs with revocation keys set are nonrevocable. */
sig->flags.revocable = 0;
buf[0] = 0;
build_sig_subpkt (sig, SIGSUBPKT_REVOCABLE, buf, 1);
parse_revkeys (sig);
return 0;
}
/* Create a back-signature. If TIMESTAMP is not NULL, use it for the
signature creation time. */
gpg_error_t
make_backsig (PKT_signature *sig, PKT_public_key *pk,
PKT_public_key *sub_pk, PKT_public_key *sub_psk,
u32 timestamp, const char *cache_nonce)
{
gpg_error_t err;
PKT_signature *backsig;
cache_public_key (sub_pk);
err = make_keysig_packet (&backsig, pk, NULL, sub_pk, sub_psk, 0x19,
0, 0, timestamp, 0, NULL, NULL, cache_nonce);
if (err)
log_error ("make_keysig_packet failed for backsig: %s\n", g10_errstr(err));
else
{
/* Get it into a binary packed form. */
IOBUF backsig_out = iobuf_temp();
PACKET backsig_pkt;
init_packet (&backsig_pkt);
backsig_pkt.pkttype = PKT_SIGNATURE;
backsig_pkt.pkt.signature = backsig;
err = build_packet (backsig_out, &backsig_pkt);
free_packet (&backsig_pkt);
if (err)
log_error ("build_packet failed for backsig: %s\n", g10_errstr(err));
else
{
size_t pktlen = 0;
byte *buf = iobuf_get_temp_buffer (backsig_out);
/* Remove the packet header. */
if(buf[0]&0x40)
{
if (buf[1] < 192)
{
pktlen = buf[1];
buf += 2;
}
else if(buf[1] < 224)
{
pktlen = (buf[1]-192)*256;
pktlen += buf[2]+192;
buf += 3;
}
else if (buf[1] == 255)
{
pktlen = buf[2] << 24;
pktlen |= buf[3] << 16;
pktlen |= buf[4] << 8;
pktlen |= buf[5];
buf += 6;
}
else
BUG ();
}
else
{
int mark = 1;
switch (buf[0]&3)
{
case 3:
BUG ();
break;
case 2:
pktlen = buf[mark++] << 24;
pktlen |= buf[mark++] << 16;
case 1:
pktlen |= buf[mark++] << 8;
case 0:
pktlen |= buf[mark++];
}
buf += mark;
}
/* Now make the binary blob into a subpacket. */
build_sig_subpkt (sig, SIGSUBPKT_SIGNATURE, buf, pktlen);
iobuf_close (backsig_out);
}
}
return err;
}
/* Write a direct key signature to the first key in ROOT using the key
PSK. REVKEY is describes the direct key signature and TIMESTAMP is
the timestamp to set on the signature. */
static gpg_error_t
write_direct_sig (KBNODE root, PKT_public_key *psk,
struct revocation_key *revkey, u32 timestamp,
const char *cache_nonce)
{
gpg_error_t err;
PACKET *pkt;
PKT_signature *sig;
KBNODE node;
PKT_public_key *pk;
if (opt.verbose)
log_info (_("writing direct signature\n"));
/* Get the pk packet from the pub_tree. */
node = find_kbnode (root, PKT_PUBLIC_KEY);
if (!node)
BUG ();
pk = node->pkt->pkt.public_key;
/* We have to cache the key, so that the verification of the
signature creation is able to retrieve the public key. */
cache_public_key (pk);
/* Make the signature. */
err = make_keysig_packet (&sig, pk, NULL,NULL, psk, 0x1F,
0, 0, timestamp, 0,
keygen_add_revkey, revkey, cache_nonce);
if (err)
{
log_error ("make_keysig_packet failed: %s\n", g10_errstr (err) );
return err;
}
pkt = xmalloc_clear (sizeof *pkt);
pkt->pkttype = PKT_SIGNATURE;
pkt->pkt.signature = sig;
add_kbnode (root, new_kbnode (pkt));
return err;
}
/* Write a self-signature to the first user id in ROOT using the key
PSK. USE and TIMESTAMP give the extra data we need for the
signature. */
static gpg_error_t
write_selfsigs (KBNODE root, PKT_public_key *psk,
unsigned int use, u32 timestamp, const char *cache_nonce)
{
gpg_error_t err;
PACKET *pkt;
PKT_signature *sig;
PKT_user_id *uid;
KBNODE node;
PKT_public_key *pk;
if (opt.verbose)
log_info (_("writing self signature\n"));
/* Get the uid packet from the list. */
node = find_kbnode (root, PKT_USER_ID);
if (!node)
BUG(); /* No user id packet in tree. */
uid = node->pkt->pkt.user_id;
/* Get the pk packet from the pub_tree. */
node = find_kbnode (root, PKT_PUBLIC_KEY);
if (!node)
BUG();
pk = node->pkt->pkt.public_key;
/* The usage has not yet been set - do it now. */
pk->pubkey_usage = use;
/* We have to cache the key, so that the verification of the
signature creation is able to retrieve the public key. */
cache_public_key (pk);
/* Make the signature. */
err = make_keysig_packet (&sig, pk, uid, NULL, psk, 0x13,
0, 0, timestamp, 0,
keygen_add_std_prefs, pk, cache_nonce);
if (err)
{
log_error ("make_keysig_packet failed: %s\n", g10_errstr (err));
return err;
}
pkt = xmalloc_clear (sizeof *pkt);
pkt->pkttype = PKT_SIGNATURE;
pkt->pkt.signature = sig;
add_kbnode (root, new_kbnode (pkt));
return err;
}
/* Write the key binding signature. If TIMESTAMP is not NULL use the
signature creation time. PRI_PSK is the key use for signing.
SUB_PSK is a key used to create a back-signature; that one is only
used if USE has the PUBKEY_USAGE_SIG capability. */
static int
write_keybinding (KBNODE root, PKT_public_key *pri_psk, PKT_public_key *sub_psk,
unsigned int use, u32 timestamp, const char *cache_nonce)
{
gpg_error_t err;
PACKET *pkt;
PKT_signature *sig;
KBNODE node;
PKT_public_key *pri_pk, *sub_pk;
struct opaque_data_usage_and_pk oduap;
if (opt.verbose)
log_info(_("writing key binding signature\n"));
/* Get the primary pk packet from the tree. */
node = find_kbnode (root, PKT_PUBLIC_KEY);
if (!node)
BUG();
pri_pk = node->pkt->pkt.public_key;
/* We have to cache the key, so that the verification of the
* signature creation is able to retrieve the public key. */
cache_public_key (pri_pk);
/* Find the last subkey. */
sub_pk = NULL;
for (node = root; node; node = node->next )
{
if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
sub_pk = node->pkt->pkt.public_key;
}
if (!sub_pk)
BUG();
/* Make the signature. */
oduap.usage = use;
oduap.pk = sub_pk;
err = make_keysig_packet (&sig, pri_pk, NULL, sub_pk, pri_psk, 0x18,
0, 0, timestamp, 0,
keygen_add_key_flags_and_expire, &oduap,
cache_nonce);
if (err)
{
log_error ("make_keysig_packet failed: %s\n", g10_errstr (err));
return err;
}
/* Make a backsig. */
if (use & PUBKEY_USAGE_SIG)
{
err = make_backsig (sig, pri_pk, sub_pk, sub_psk, timestamp, cache_nonce);
if (err)
return err;
}
pkt = xmalloc_clear ( sizeof *pkt );
pkt->pkttype = PKT_SIGNATURE;
pkt->pkt.signature = sig;
add_kbnode (root, new_kbnode (pkt) );
return err;
}
static int
key_from_sexp (gcry_mpi_t *array, gcry_sexp_t sexp,
const char *topname, const char *elems)
{
gcry_sexp_t list, l2;
const char *s;
int i, idx;
int rc = 0;
list = gcry_sexp_find_token (sexp, topname, 0);
if (!list)
return gpg_error (GPG_ERR_INV_OBJ);
l2 = gcry_sexp_cadr (list);
gcry_sexp_release (list);
list = l2;
if (!list)
return gpg_error (GPG_ERR_NO_OBJ);
for (idx=0,s=elems; *s; s++, idx++)
{
l2 = gcry_sexp_find_token (list, s, 1);
if (!l2)
{
rc = gpg_error (GPG_ERR_NO_OBJ); /* required parameter not found */
goto leave;
}
array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
gcry_sexp_release (l2);
if (!array[idx])
{
rc = gpg_error (GPG_ERR_INV_OBJ); /* required parameter invalid */
goto leave;
}
}
gcry_sexp_release (list);
leave:
if (rc)
{
for (i=0; itimestamp = timestamp;
pk->version = 4;
- if (expireval)
- pk->expiredate = pk->timestamp + expireval;
pk->pubkey_algo = algo;
err = key_from_sexp (pk->pkey, s_key, "public-key", algoelem);
if (err)
{
log_error ("key_from_sexp failed: %s\n", gpg_strerror (err) );
gcry_sexp_release (s_key);
free_public_key (pk);
return err;
}
gcry_sexp_release (s_key);
- pkt = xtrycalloc (1, sizeof *pkt);
- if (!pkt)
- {
- err = gpg_error_from_syserror ();
- free_public_key (pk);
- return err;
- }
-
- pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
- pkt->pkt.public_key = pk;
- add_kbnode (pub_root, new_kbnode (pkt));
+ *pk_out = pk;
return 0;
}
+/* Common code for the key generation fucntion gen_xxx. */
+static int
+common_gen (const char *keyparms, int algo, const char *algoelem,
+ kbnode_t pub_root, u32 timestamp, u32 expireval, int is_subkey,
+ int keygen_flags, char **cache_nonce_addr)
+{
+ PKT_public_key *pk;
+ int err;
+
+ err = common_key_gen( keyparms, algo, algoelem, keygen_flags, cache_nonce_addr, &pk );
+
+ if( !err ) {
+ PACKET *pkt;
+
+ pk->timestamp = timestamp;
+ if (expireval)
+ pk->expiredate = pk->timestamp + expireval;
+
+ pkt = xtrycalloc (1, sizeof *pkt);
+ if (!pkt)
+ {
+ err = gpg_error_from_syserror ();
+ free_public_key (pk);
+ return err;
+ }
+
+ pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
+ pkt->pkt.public_key = pk;
+
+ add_kbnode (pub_root, new_kbnode (pkt));
+ }
+
+ return err;
+}
/*
* Generate an Elgamal key.
*/
static int
gen_elg (int algo, unsigned int nbits, KBNODE pub_root,
u32 timestamp, u32 expireval, int is_subkey,
int keygen_flags, char **cache_nonce_addr)
{
int err;
char *keyparms;
char nbitsstr[35];
assert (is_ELGAMAL (algo));
if (nbits < 512)
{
nbits = 1024;
log_info (_("keysize invalid; using %u bits\n"), nbits );
}
if ((nbits % 32))
{
nbits = ((nbits + 31) / 32) * 32;
log_info (_("keysize rounded up to %u bits\n"), nbits );
}
/* Note that we use transient-key only if no-protection has also
been enabled. */
snprintf (nbitsstr, sizeof nbitsstr, "%u", nbits);
keyparms = xtryasprintf ("(genkey(%s(nbits %zu:%s)%s))",
algo == GCRY_PK_ELG_E ? "openpgp-elg" :
algo == GCRY_PK_ELG ? "elg" : "x-oops" ,
strlen (nbitsstr), nbitsstr,
((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
&& (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
"(transient-key)" : "" );
if (!keyparms)
err = gpg_error_from_syserror ();
else
{
err = common_gen (keyparms, algo, "pgy",
pub_root, timestamp, expireval, is_subkey,
keygen_flags, cache_nonce_addr);
xfree (keyparms);
}
return err;
}
/*
* Generate an DSA key
*/
static gpg_error_t
gen_dsa (unsigned int nbits, KBNODE pub_root,
u32 timestamp, u32 expireval, int is_subkey,
int keygen_flags, char **cache_nonce_addr)
{
int err;
unsigned int qbits;
char *keyparms;
char nbitsstr[35];
char qbitsstr[35];
if ( nbits < 512)
{
nbits = 1024;
log_info(_("keysize invalid; using %u bits\n"), nbits );
}
else if ( nbits > 3072 )
{
nbits = 3072;
log_info(_("keysize invalid; using %u bits\n"), nbits );
}
if( (nbits % 64) )
{
nbits = ((nbits + 63) / 64) * 64;
log_info(_("keysize rounded up to %u bits\n"), nbits );
}
/* To comply with FIPS rules we round up to the next value unless in
expert mode. */
if (!opt.expert && nbits > 1024 && (nbits % 1024))
{
nbits = ((nbits + 1023) / 1024) * 1024;
log_info(_("keysize rounded up to %u bits\n"), nbits );
}
/*
Figure out a q size based on the key size. FIPS 180-3 says:
L = 1024, N = 160
L = 2048, N = 224
L = 2048, N = 256
L = 3072, N = 256
2048/256 is an odd pair since there is also a 2048/224 and
3072/256. Matching sizes is not a very exact science.
We'll do 256 qbits for nbits over 2047, 224 for nbits over 1024
but less than 2048, and 160 for 1024 (DSA1).
*/
if (nbits > 2047)
qbits = 256;
else if ( nbits > 1024)
qbits = 224;
else
qbits = 160;
if (qbits != 160 )
log_info (_("WARNING: some OpenPGP programs can't"
" handle a DSA key with this digest size\n"));
snprintf (nbitsstr, sizeof nbitsstr, "%u", nbits);
snprintf (qbitsstr, sizeof qbitsstr, "%u", qbits);
keyparms = xtryasprintf ("(genkey(dsa(nbits %zu:%s)(qbits %zu:%s)%s))",
strlen (nbitsstr), nbitsstr,
strlen (qbitsstr), qbitsstr,
((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
&& (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
"(transient-key)" : "" );
if (!keyparms)
err = gpg_error_from_syserror ();
else
{
err = common_gen (keyparms, PUBKEY_ALGO_DSA, "pqgy",
pub_root, timestamp, expireval, is_subkey,
keygen_flags, cache_nonce_addr);
xfree (keyparms);
}
return err;
}
+/* Returns allocated ECC key generation S-explression
+ call gcry_sexp_release ( out ) to free it.
+ */
+static int
+delme__pk_ecc_build_sexp( int qbits, int algo, int is_long_term, gcry_sexp_t *out ) {
+ gcry_mpi_t kek_params;
+ char *kek_params_s;
+ int rc;
+
+ if( is_long_term && algo == PUBKEY_ALGO_ECDH )
+ kek_params = pk_ecdh_default_params_to_mpi( qbits );
+ else
+ kek_params = NULL;
+
+ if( kek_params ) {
+ kek_params_s = mpi2hex( kek_params );
+ mpi_release( kek_params );
+ }
+
+ rc = gcry_sexp_build (out, NULL,
+ algo == PUBKEY_ALGO_ECDSA ?
+ "(genkey(ecdsa(nbits %d)(qbits %d)))" :
+ "(genkey(ecdh(nbits %d)(qbits %d)(transient-key %d)(kek-params %s)))",
+ (int)qbits, (int)qbits, (int)(is_long_term==0), kek_params_s);
+ xfree( kek_params_s );
+ if (rc) {
+ log_debug("ec gen gcry_sexp_build failed: %s\n", gpg_strerror (rc));
+ return rc;
+ }
+ return 0;
+}
+
+static char *
+pk_ecc_build_key_params( int qbits, int algo, int transient ) {
+ byte *kek_params = NULL;
+ size_t kek_params_size;
+ char nbitsstr[35];
+ char qbitsstr[35];
+ char *keyparms;
+ int n;
+
+ /* KEK parameters are only needed for long term key generation */
+ if( !transient && algo == PUBKEY_ALGO_ECDH )
+ kek_params = pk_ecdh_default_params( qbits, &kek_params_size );
+ else
+ kek_params = NULL;
+
+ snprintf (nbitsstr, sizeof nbitsstr, "%u", qbits);
+ snprintf (qbitsstr, sizeof qbitsstr, "%u", qbits);
+ if( algo == PUBKEY_ALGO_ECDSA || kek_params == NULL )
+ keyparms = xtryasprintf (
+ "(genkey(%s(nbits %zu:%s)(qbits %zu:%s)(transient-key 1:%d)))",
+ algo == PUBKEY_ALGO_ECDSA ? "ecdsa" : "ecdh",
+ strlen (nbitsstr), nbitsstr,
+ strlen (qbitsstr), qbitsstr,
+ transient );
+ else {
+ assert( kek_params != NULL );
+ keyparms = xtryasprintf (
+ "(genkey(ecdh(nbits %zu:%s)(qbits %zu:%s)(transient-key 1:%d)(kek-params %u:",
+ strlen (nbitsstr), nbitsstr,
+ strlen (qbitsstr), qbitsstr,
+ transient,
+ (unsigned)kek_params_size );
+ if( keyparms != NULL ) {
+ n = strlen(keyparms);
+ keyparms = xtryrealloc( keyparms, n + kek_params_size + 4 );
+ }
+ if( keyparms == NULL ) {
+ xfree( kek_params );
+ return NULL;
+ }
+ memcpy( keyparms+n, kek_params, kek_params_size );
+ xfree( kek_params );
+ memcpy( keyparms+n+kek_params_size, ")))", 4 );
+ }
+ return keyparms;
+}
+
+/* This common function is used in this file and also to generate ephemeral keys for ECDH.
+ * Caller must call free_public_key and free_secret_key */
+int
+pk_ecc_keypair_gen( PKT_public_key **pk_out, int algo, int keygen_flags, char **cache_nonce_addr, unsigned nbits) {
+ int err;
+ unsigned int qbits;
+ char *keyparms;
+ // PUBKEY_ALGO_ECDH, PUBKEY_ALGO_ECDSA
+ static const char * const ec_pub_params[2] = { "cqp", "cq" };
+ //static const char * const ec_priv_params[2] = { "cqpd", "cqd" };
+
+ assert( algo == PUBKEY_ALGO_ECDSA || algo == PUBKEY_ALGO_ECDH );
+ assert( PUBKEY_ALGO_ECDSA == PUBKEY_ALGO_ECDH + 1 );
+
+ *pk_out = NULL;
+
+ if( pubkey_get_npkey (PUBKEY_ALGO_ECDSA) != 2 || pubkey_get_nskey (PUBKEY_ALGO_ECDSA) != 3 ||
+ pubkey_get_npkey (PUBKEY_ALGO_ECDH) != 3 || pubkey_get_nskey (PUBKEY_ALGO_ECDH) != 4 )
+ {
+ log_info(_("incompatible version of gcrypt library (expect named curve logic for ECC)\n") );
+ return GPG_ERR_EPROGMISMATCH;
+ }
+
+ if ( nbits != 256 && nbits != 384 && nbits != 521 )
+ {
+ log_info(_("keysize invalid; using 256 bits instead of passed in %d\n"), nbits );
+ }
+
+ /*
+ Figure out a q size based on the key size. See gen_dsa for more details.
+ Due to 8-bit rounding we may get 528 here instead of 521
+ */
+ nbits = qbits = (nbits < 521 ? nbits : 521 );
+
+ keyparms = pk_ecc_build_key_params(qbits, algo, !!((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY) && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION)) );
+ if (!keyparms) {
+ err = gpg_error_from_syserror ();
+ log_error ("ec pk_ecc_build_key_params failed: %s\n", gpg_strerror (err) );
+ }
+ else
+ {
+ err = common_key_gen (keyparms, algo, ec_pub_params[algo-PUBKEY_ALGO_ECDH],
+ keygen_flags, cache_nonce_addr, pk_out);
+ xfree (keyparms);
+ }
+
+#if 0
+ /* always allocase seckey_info for EC keys. TODO: is this needed? */
+ if( *pk_out ) {
+ struct seckey_info *ski;
+
+ (*pk_out)->seckey_info = ski = xtrycalloc (1, sizeof *ski);
+ if (!(*pk_out)->seckey_info) {
+ free_public_key(*pk_out);
+ *pk_out = NULL;
+ return gpg_error_from_syserror ();
+ }
+
+ ski->is_protected = 0;
+ ski->algo = 0;
+ }
+#endif
+
+ return err;
+}
+
+
+/****************
+ * Generate an ECC OpenPGP key
+ */
+static gpg_error_t
+gen_ecc (int algo, unsigned int nbits, KBNODE pub_root,
+ u32 timestamp, u32 expireval, int is_subkey,
+ int keygen_flags, char **cache_nonce_addr)
+{
+ int rc;
+ PACKET *pkt;
+ PKT_public_key *pk;
+
+ rc = pk_ecc_keypair_gen( &pk, algo, keygen_flags, cache_nonce_addr, nbits );
+ if( rc )
+ return rc;
+
+ /* the rest is very similar to common_gen */
+
+ pk->timestamp = timestamp;
+ if (expireval)
+ pk->expiredate = pk->timestamp + expireval;
+
+ //assert( pk->seckey_info != NULL );
+ /// TODO: the new agent-based model doesn't return private portion here (the pkey array is allocated, but private MPIs are NULL, so this will cause a crash... )
+ ///pk->seckey_info->csum = checksum_mpi ( pk->pkey[algo==PUBKEY_ALGO_ECDSA ? 2 : 3] ); /* corresponds to 'd' in 'cqd' or 'cqpd' */
+
+ pkt = xmalloc_clear(sizeof *pkt);
+ pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
+ pkt->pkt.public_key = pk;
+ add_kbnode(pub_root, new_kbnode( pkt ));
+
+ return 0;
+}
+
/*
* Generate an RSA key.
*/
static int
gen_rsa (int algo, unsigned int nbits, KBNODE pub_root,
u32 timestamp, u32 expireval, int is_subkey,
int keygen_flags, char **cache_nonce_addr)
{
int err;
char *keyparms;
char nbitsstr[35];
assert (is_RSA(algo));
if (!nbits)
nbits = DEFAULT_STD_KEYSIZE;
if (nbits < 1024)
{
nbits = 1024;
log_info (_("keysize invalid; using %u bits\n"), nbits );
}
if ((nbits % 32))
{
nbits = ((nbits + 31) / 32) * 32;
log_info (_("keysize rounded up to %u bits\n"), nbits );
}
snprintf (nbitsstr, sizeof nbitsstr, "%u", nbits);
keyparms = xtryasprintf ("(genkey(rsa(nbits %zu:%s)%s))",
strlen (nbitsstr), nbitsstr,
((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
&& (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
"(transient-key)" : "" );
if (!keyparms)
err = gpg_error_from_syserror ();
else
{
err = common_gen (keyparms, algo, "ne",
pub_root, timestamp, expireval, is_subkey,
keygen_flags, cache_nonce_addr);
xfree (keyparms);
}
return err;
}
/****************
* check valid days:
* return 0 on error or the multiplier
*/
static int
check_valid_days( const char *s )
{
if( !digitp(s) )
return 0;
for( s++; *s; s++)
if( !digitp(s) )
break;
if( !*s )
return 1;
if( s[1] )
return 0; /* e.g. "2323wc" */
if( *s == 'd' || *s == 'D' )
return 1;
if( *s == 'w' || *s == 'W' )
return 7;
if( *s == 'm' || *s == 'M' )
return 30;
if( *s == 'y' || *s == 'Y' )
return 365;
return 0;
}
static void
print_key_flags(int flags)
{
if(flags&PUBKEY_USAGE_SIG)
tty_printf("%s ",_("Sign"));
if(flags&PUBKEY_USAGE_CERT)
tty_printf("%s ",_("Certify"));
if(flags&PUBKEY_USAGE_ENC)
tty_printf("%s ",_("Encrypt"));
if(flags&PUBKEY_USAGE_AUTH)
tty_printf("%s ",_("Authenticate"));
}
/* Returns the key flags */
static unsigned int
ask_key_flags(int algo,int subkey)
{
/* TRANSLATORS: Please use only plain ASCII characters for the
translation. If this is not possible use single digits. The
string needs to 8 bytes long. Here is a description of the
functions:
s = Toggle signing capability
e = Toggle encryption capability
a = Toggle authentication capability
q = Finish
*/
const char *togglers=_("SsEeAaQq");
char *answer=NULL;
unsigned int current=0;
unsigned int possible=openpgp_pk_algo_usage(algo);
if ( strlen(togglers) != 8 )
{
tty_printf ("NOTE: Bad translation at %s:%d. "
"Please report.\n", __FILE__, __LINE__);
togglers = "11223300";
}
/* Only primary keys may certify. */
if(subkey)
possible&=~PUBKEY_USAGE_CERT;
/* Preload the current set with the possible set, minus
authentication, since nobody really uses auth yet. */
current=possible&~PUBKEY_USAGE_AUTH;
for(;;)
{
tty_printf("\n");
tty_printf(_("Possible actions for a %s key: "),
gcry_pk_algo_name (algo));
print_key_flags(possible);
tty_printf("\n");
tty_printf(_("Current allowed actions: "));
print_key_flags(current);
tty_printf("\n\n");
if(possible&PUBKEY_USAGE_SIG)
tty_printf(_(" (%c) Toggle the sign capability\n"),
togglers[0]);
if(possible&PUBKEY_USAGE_ENC)
tty_printf(_(" (%c) Toggle the encrypt capability\n"),
togglers[2]);
if(possible&PUBKEY_USAGE_AUTH)
tty_printf(_(" (%c) Toggle the authenticate capability\n"),
togglers[4]);
tty_printf(_(" (%c) Finished\n"),togglers[6]);
tty_printf("\n");
xfree(answer);
answer = cpr_get("keygen.flags",_("Your selection? "));
cpr_kill_prompt();
if(strlen(answer)>1)
tty_printf(_("Invalid selection.\n"));
else if(*answer=='\0' || *answer==togglers[6] || *answer==togglers[7])
break;
else if((*answer==togglers[0] || *answer==togglers[1])
&& possible&PUBKEY_USAGE_SIG)
{
if(current&PUBKEY_USAGE_SIG)
current&=~PUBKEY_USAGE_SIG;
else
current|=PUBKEY_USAGE_SIG;
}
else if((*answer==togglers[2] || *answer==togglers[3])
&& possible&PUBKEY_USAGE_ENC)
{
if(current&PUBKEY_USAGE_ENC)
current&=~PUBKEY_USAGE_ENC;
else
current|=PUBKEY_USAGE_ENC;
}
else if((*answer==togglers[4] || *answer==togglers[5])
&& possible&PUBKEY_USAGE_AUTH)
{
if(current&PUBKEY_USAGE_AUTH)
current&=~PUBKEY_USAGE_AUTH;
else
current|=PUBKEY_USAGE_AUTH;
}
else
tty_printf(_("Invalid selection.\n"));
}
xfree(answer);
return current;
}
/* Ask for an algorithm. The function returns the algorithm id to
* create. If ADDMODE is false the function won't show an option to
* create the primary and subkey combined and won't set R_USAGE
* either. If a combined algorithm has been selected, the subkey
* algorithm is stored at R_SUBKEY_ALGO. */
static int
ask_algo (int addmode, int *r_subkey_algo, unsigned int *r_usage)
{
char *answer;
int algo;
int dummy_algo;
if (!r_subkey_algo)
r_subkey_algo = &dummy_algo;
tty_printf (_("Please select what kind of key you want:\n"));
if (!addmode)
tty_printf (_(" (%d) RSA and RSA (default)\n"), 1 );
if (!addmode)
tty_printf (_(" (%d) DSA and Elgamal\n"), 2 );
tty_printf (_(" (%d) DSA (sign only)\n"), 3 );
tty_printf (_(" (%d) RSA (sign only)\n"), 4 );
if (addmode)
{
tty_printf (_(" (%d) Elgamal (encrypt only)\n"), 5 );
tty_printf (_(" (%d) RSA (encrypt only)\n"), 6 );
}
if (opt.expert)
{
tty_printf (_(" (%d) DSA (set your own capabilities)\n"), 7 );
tty_printf (_(" (%d) RSA (set your own capabilities)\n"), 8 );
}
+ tty_printf (_(" (%d) ECDSA and ECDH\n"), 9 );
+
for(;;)
{
*r_usage = 0;
*r_subkey_algo = 0;
answer = cpr_get ("keygen.algo", _("Your selection? "));
cpr_kill_prompt ();
algo = *answer? atoi (answer) : 1;
xfree(answer);
if (algo == 1 && !addmode)
{
algo = PUBKEY_ALGO_RSA;
*r_subkey_algo = PUBKEY_ALGO_RSA;
break;
}
else if (algo == 2 && !addmode)
{
algo = PUBKEY_ALGO_DSA;
*r_subkey_algo = PUBKEY_ALGO_ELGAMAL_E;
break;
}
else if (algo == 3)
{
algo = PUBKEY_ALGO_DSA;
*r_usage = PUBKEY_USAGE_SIG;
break;
}
else if (algo == 4)
{
algo = PUBKEY_ALGO_RSA;
*r_usage = PUBKEY_USAGE_SIG;
break;
}
else if (algo == 5 && addmode)
{
algo = PUBKEY_ALGO_ELGAMAL_E;
*r_usage = PUBKEY_USAGE_ENC;
break;
}
else if (algo == 6 && addmode)
{
algo = PUBKEY_ALGO_RSA;
*r_usage = PUBKEY_USAGE_ENC;
break;
}
else if (algo == 7 && opt.expert)
{
algo = PUBKEY_ALGO_DSA;
*r_usage = ask_key_flags (algo, addmode);
break;
}
else if (algo == 8 && opt.expert)
{
algo = PUBKEY_ALGO_RSA;
*r_usage = ask_key_flags (algo, addmode);
break;
}
+ else if (algo == 9)
+ {
+ algo = PUBKEY_ALGO_ECDSA;
+ *r_subkey_algo = PUBKEY_ALGO_ECDH;
+ break;
+ }
else
tty_printf (_("Invalid selection.\n"));
}
return algo;
}
/* Ask for the key size. ALGO is the algorithm. If PRIMARY_KEYSIZE
is not 0, the function asks for the size of the encryption
subkey. */
static unsigned
ask_keysize (int algo, unsigned int primary_keysize)
{
unsigned int nbits, min, def = DEFAULT_STD_KEYSIZE, max=4096;
int for_subkey = !!primary_keysize;
int autocomp = 0;
if(opt.expert)
min=512;
else
min=1024;
if (primary_keysize && !opt.expert)
{
/* Deduce the subkey size from the primary key size. */
if (algo == PUBKEY_ALGO_DSA && primary_keysize > 3072)
nbits = 3072; /* For performance reasons we don't support more
than 3072 bit DSA. However we won't see this
case anyway because DSA can't be used as an
encryption subkey ;-). */
else
nbits = primary_keysize;
autocomp = 1;
goto leave;
}
switch(algo)
{
case PUBKEY_ALGO_DSA:
def=2048;
max=3072;
break;
+ case PUBKEY_ALGO_ECDSA:
+ case PUBKEY_ALGO_ECDH:
+ min=256;
+ def=256;
+ max=521;
+ break;
+
case PUBKEY_ALGO_RSA:
min=1024;
break;
}
tty_printf(_("%s keys may be between %u and %u bits long.\n"),
- gcry_pk_algo_name (algo), min, max);
+ openpgp_pk_algo_name (algo), min, max);
for(;;)
{
char *prompt, *answer;
if (for_subkey)
prompt = xasprintf (_("What keysize do you want "
"for the subkey? (%u) "), def);
else
prompt = xasprintf (_("What keysize do you want? (%u) "), def);
answer = cpr_get ("keygen.size", prompt);
cpr_kill_prompt ();
nbits = *answer? atoi (answer): def;
xfree(prompt);
xfree(answer);
if(nbitsmax)
tty_printf(_("%s keysizes must be in the range %u-%u\n"),
- gcry_pk_algo_name (algo), min, max);
+ openpgp_pk_algo_name (algo), min, max);
else
break;
}
tty_printf(_("Requested keysize is %u bits\n"), nbits );
leave:
if( algo == PUBKEY_ALGO_DSA && (nbits % 64) )
{
- nbits = ((nbits + 63) / 64) * 64;
- if (!autocomp)
- tty_printf(_("rounded up to %u bits\n"), nbits );
+ if( !(algo == PUBKEY_ALGO_ECDSA && nbits==521) ) {
+ nbits = ((nbits + 63) / 64) * 64;
+ if (!autocomp)
+ tty_printf(_("rounded up to %u bits\n"), nbits );
+ }
}
+ else if( algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA ) {
+ if( nbits != 256 && nbits != 384 && nbits != 521 ) {
+ nbits = min;
+ tty_printf(_("unsupported ECDH value, corrected to the minimum %u bits\n"), nbits );
+ }
+ }
else if( (nbits % 32) )
{
nbits = ((nbits + 31) / 32) * 32;
if (!autocomp)
tty_printf(_("rounded up to %u bits\n"), nbits );
}
return nbits;
}
/****************
* Parse an expire string and return its value in seconds.
* Returns (u32)-1 on error.
* This isn't perfect since scan_isodatestr returns unix time, and
* OpenPGP actually allows a 32-bit time *plus* a 32-bit offset.
* Because of this, we only permit setting expirations up to 2106, but
* OpenPGP could theoretically allow up to 2242. I think we'll all
* just cope for the next few years until we get a 64-bit time_t or
* similar.
*/
u32
parse_expire_string( const char *string )
{
int mult;
u32 seconds;
u32 abs_date = 0;
u32 curtime = make_timestamp ();
time_t tt;
if (!*string)
seconds = 0;
else if (!strncmp (string, "seconds=", 8))
seconds = atoi (string+8);
else if ((abs_date = scan_isodatestr(string))
&& (abs_date+86400/2) > curtime)
seconds = (abs_date+86400/2) - curtime;
else if ((tt = isotime2epoch (string)) != (time_t)(-1))
seconds = (u32)tt - curtime;
else if ((mult = check_valid_days (string)))
seconds = atoi (string) * 86400L * mult;
else
seconds = (u32)(-1);
return seconds;
}
/* Parsean Creation-Date string which is either "1986-04-26" or
"19860426T042640". Returns 0 on error. */
static u32
parse_creation_string (const char *string)
{
u32 seconds;
if (!*string)
seconds = 0;
else if ( !strncmp (string, "seconds=", 8) )
seconds = atoi (string+8);
else if ( !(seconds = scan_isodatestr (string)))
{
time_t tmp = isotime2epoch (string);
seconds = (tmp == (time_t)(-1))? 0 : tmp;
}
return seconds;
}
/* object == 0 for a key, and 1 for a sig */
u32
ask_expire_interval(int object,const char *def_expire)
{
u32 interval;
char *answer;
switch(object)
{
case 0:
if(def_expire)
BUG();
tty_printf(_("Please specify how long the key should be valid.\n"
" 0 = key does not expire\n"
" = key expires in n days\n"
" w = key expires in n weeks\n"
" m = key expires in n months\n"
" y = key expires in n years\n"));
break;
case 1:
if(!def_expire)
BUG();
tty_printf(_("Please specify how long the signature should be valid.\n"
" 0 = signature does not expire\n"
" = signature expires in n days\n"
" w = signature expires in n weeks\n"
" m = signature expires in n months\n"
" y = signature expires in n years\n"));
break;
default:
BUG();
}
/* Note: The elgamal subkey for DSA has no expiration date because
* it must be signed with the DSA key and this one has the expiration
* date */
answer = NULL;
for(;;)
{
u32 curtime=make_timestamp();
xfree(answer);
if(object==0)
answer = cpr_get("keygen.valid",_("Key is valid for? (0) "));
else
{
char *prompt;
#define PROMPTSTRING _("Signature is valid for? (%s) ")
/* This will actually end up larger than necessary because
of the 2 bytes for '%s' */
prompt=xmalloc(strlen(PROMPTSTRING)+strlen(def_expire)+1);
sprintf(prompt,PROMPTSTRING,def_expire);
#undef PROMPTSTRING
answer = cpr_get("siggen.valid",prompt);
xfree(prompt);
if(*answer=='\0')
answer=xstrdup(def_expire);
}
cpr_kill_prompt();
trim_spaces(answer);
interval = parse_expire_string( answer );
if( interval == (u32)-1 )
{
tty_printf(_("invalid value\n"));
continue;
}
if( !interval )
{
tty_printf((object==0)
? _("Key does not expire at all\n")
: _("Signature does not expire at all\n"));
}
else
{
tty_printf(object==0
? _("Key expires at %s\n")
: _("Signature expires at %s\n"),
asctimestamp((ulong)(curtime + interval) ) );
#if SIZEOF_TIME_T <= 4 && !defined (HAVE_UNSIGNED_TIME_T)
if ( (time_t)((ulong)(curtime+interval)) < 0 )
tty_printf (_("Your system can't display dates beyond 2038.\n"
"However, it will be correctly handled up to"
" 2106.\n"));
else
#endif /*SIZEOF_TIME_T*/
if ( (time_t)((unsigned long)(curtime+interval)) < curtime )
{
tty_printf (_("invalid value\n"));
continue;
}
}
if( cpr_enabled() || cpr_get_answer_is_yes("keygen.valid.okay",
_("Is this correct? (y/N) ")) )
break;
}
xfree(answer);
return interval;
}
u32
ask_expiredate()
{
u32 x = ask_expire_interval(0,NULL);
return x? make_timestamp() + x : 0;
}
static PKT_user_id *
uid_from_string (const char *string)
{
size_t n;
PKT_user_id *uid;
n = strlen (string);
uid = xmalloc_clear (sizeof *uid + n);
uid->len = n;
strcpy (uid->name, string);
uid->ref = 1;
return uid;
}
/* Ask for a user ID. With a MODE of 1 an extra help prompt is
printed for use during a new key creation. If KEYBLOCK is not NULL
the function prevents the creation of an already existing user
ID. */
static char *
ask_user_id (int mode, KBNODE keyblock)
{
char *answer;
char *aname, *acomment, *amail, *uid;
if ( !mode )
{
/* TRANSLATORS: This is the new string telling the user what
gpg is now going to do (i.e. ask for the parts of the user
ID). Note that if you do not tyranslated this string, a
different string will be used used, which might still have
a correct transaltion. */
const char *s1 =
N_("\n"
"GnuPG needs to construct a user ID to identify your key.\n"
"\n");
const char *s2 = _(s1);
if (!strcmp (s1, s2))
{
/* There is no translation for the string thus we to use
the old info text. gettext has no way to tell whether
a translation is actually available, thus we need to
to compare again. */
/* TRANSLATORS: This string is in general not anymore used
but you should keep your existing translation. In case
the new string is not translated this old string will
be used. */
const char *s3 = N_("\n"
"You need a user ID to identify your key; "
"the software constructs the user ID\n"
"from the Real Name, Comment and Email Address in this form:\n"
" \"Heinrich Heine (Der Dichter) \"\n\n");
const char *s4 = _(s3);
if (strcmp (s3, s4))
s2 = s3; /* A translation exists - use it. */
}
tty_printf ("%s", s2) ;
}
uid = aname = acomment = amail = NULL;
for(;;) {
char *p;
int fail=0;
if( !aname ) {
for(;;) {
xfree(aname);
aname = cpr_get("keygen.name",_("Real name: "));
trim_spaces(aname);
cpr_kill_prompt();
if( opt.allow_freeform_uid )
break;
if( strpbrk( aname, "<>" ) )
tty_printf(_("Invalid character in name\n"));
else if( digitp(aname) )
tty_printf(_("Name may not start with a digit\n"));
else if( strlen(aname) < 5 )
tty_printf(_("Name must be at least 5 characters long\n"));
else
break;
}
}
if( !amail ) {
for(;;) {
xfree(amail);
amail = cpr_get("keygen.email",_("Email address: "));
trim_spaces(amail);
cpr_kill_prompt();
if( !*amail || opt.allow_freeform_uid )
break; /* no email address is okay */
else if ( !is_valid_mailbox (amail) )
tty_printf(_("Not a valid email address\n"));
else
break;
}
}
if( !acomment ) {
for(;;) {
xfree(acomment);
acomment = cpr_get("keygen.comment",_("Comment: "));
trim_spaces(acomment);
cpr_kill_prompt();
if( !*acomment )
break; /* no comment is okay */
else if( strpbrk( acomment, "()" ) )
tty_printf(_("Invalid character in comment\n"));
else
break;
}
}
xfree(uid);
uid = p = xmalloc(strlen(aname)+strlen(amail)+strlen(acomment)+12+10);
p = stpcpy(p, aname );
if( *acomment )
p = stpcpy(stpcpy(stpcpy(p," ("), acomment),")");
if( *amail )
p = stpcpy(stpcpy(stpcpy(p," <"), amail),">");
/* Append a warning if the RNG is switched into fake mode. */
if ( random_is_faked () )
strcpy(p, " (insecure!)" );
/* print a note in case that UTF8 mapping has to be done */
for(p=uid; *p; p++ ) {
if( *p & 0x80 ) {
tty_printf(_("You are using the `%s' character set.\n"),
get_native_charset() );
break;
}
}
tty_printf(_("You selected this USER-ID:\n \"%s\"\n\n"), uid);
if( !*amail && !opt.allow_freeform_uid
&& (strchr( aname, '@' ) || strchr( acomment, '@'))) {
fail = 1;
tty_printf(_("Please don't put the email address "
"into the real name or the comment\n") );
}
if (!fail && keyblock)
{
PKT_user_id *uidpkt = uid_from_string (uid);
KBNODE node;
for (node=keyblock; node && !fail; node=node->next)
if (!is_deleted_kbnode (node)
&& node->pkt->pkttype == PKT_USER_ID
&& !cmp_user_ids (uidpkt, node->pkt->pkt.user_id))
fail = 1;
if (fail)
tty_printf (_("Such a user ID already exists on this key!\n"));
free_user_id (uidpkt);
}
for(;;) {
/* TRANSLATORS: These are the allowed answers in
lower and uppercase. Below you will find the matching
string which should be translated accordingly and the
letter changed to match the one in the answer string.
n = Change name
c = Change comment
e = Change email
o = Okay (ready, continue)
q = Quit
*/
const char *ansstr = _("NnCcEeOoQq");
if( strlen(ansstr) != 10 )
BUG();
if( cpr_enabled() ) {
answer = xstrdup (ansstr + (fail?8:6));
answer[1] = 0;
}
else {
answer = cpr_get("keygen.userid.cmd", fail?
_("Change (N)ame, (C)omment, (E)mail or (Q)uit? ") :
_("Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? "));
cpr_kill_prompt();
}
if( strlen(answer) > 1 )
;
else if( *answer == ansstr[0] || *answer == ansstr[1] ) {
xfree(aname); aname = NULL;
break;
}
else if( *answer == ansstr[2] || *answer == ansstr[3] ) {
xfree(acomment); acomment = NULL;
break;
}
else if( *answer == ansstr[4] || *answer == ansstr[5] ) {
xfree(amail); amail = NULL;
break;
}
else if( *answer == ansstr[6] || *answer == ansstr[7] ) {
if( fail ) {
tty_printf(_("Please correct the error first\n"));
}
else {
xfree(aname); aname = NULL;
xfree(acomment); acomment = NULL;
xfree(amail); amail = NULL;
break;
}
}
else if( *answer == ansstr[8] || *answer == ansstr[9] ) {
xfree(aname); aname = NULL;
xfree(acomment); acomment = NULL;
xfree(amail); amail = NULL;
xfree(uid); uid = NULL;
break;
}
xfree(answer);
}
xfree(answer);
if( !amail && !acomment && !amail )
break;
xfree(uid); uid = NULL;
}
if( uid ) {
char *p = native_to_utf8( uid );
xfree( uid );
uid = p;
}
return uid;
}
/* MODE 0 - standard
1 - Ask for passphrase of the card backup key. */
static DEK *
do_ask_passphrase (STRING2KEY **ret_s2k, int mode, int *r_canceled)
{
DEK *dek = NULL;
STRING2KEY *s2k;
const char *errtext = NULL;
const char *custdesc = NULL;
tty_printf(_("You need a Passphrase to protect your secret key.\n\n") );
if (mode == 1)
custdesc = _("Please enter a passphrase to protect the off-card "
"backup of the new encryption key.");
s2k = xmalloc_secure( sizeof *s2k );
for(;;) {
s2k->mode = opt.s2k_mode;
s2k->hash_algo = S2K_DIGEST_ALGO;
dek = passphrase_to_dek_ext (NULL, 0, opt.s2k_cipher_algo, s2k, 2,
errtext, custdesc, NULL, r_canceled);
if (!dek && *r_canceled) {
xfree(dek); dek = NULL;
xfree(s2k); s2k = NULL;
break;
}
else if( !dek ) {
errtext = N_("passphrase not correctly repeated; try again");
tty_printf(_("%s.\n"), _(errtext));
}
else if( !dek->keylen ) {
xfree(dek); dek = NULL;
xfree(s2k); s2k = NULL;
tty_printf(_(
"You don't want a passphrase - this is probably a *bad* idea!\n"
"I will do it anyway. You can change your passphrase at any time,\n"
"using this program with the option \"--edit-key\".\n\n"));
break;
}
else
break; /* okay */
}
*ret_s2k = s2k;
return dek;
}
/* Basic key generation. Here we divert to the actual generation
routines based on the requested algorithm. */
static int
do_create (int algo, unsigned int nbits, KBNODE pub_root,
u32 timestamp, u32 expiredate, int is_subkey,
int keygen_flags, char **cache_nonce_addr)
{
gpg_error_t err;
/* Fixme: The entropy collecting message should be moved to a
libgcrypt progress handler. */
if (!opt.batch)
tty_printf (_(
"We need to generate a lot of random bytes. It is a good idea to perform\n"
"some other action (type on the keyboard, move the mouse, utilize the\n"
"disks) during the prime generation; this gives the random number\n"
"generator a better chance to gain enough entropy.\n") );
if (algo == PUBKEY_ALGO_ELGAMAL_E)
err = gen_elg (algo, nbits, pub_root, timestamp, expiredate, is_subkey,
keygen_flags, cache_nonce_addr);
else if (algo == PUBKEY_ALGO_DSA)
err = gen_dsa (nbits, pub_root, timestamp, expiredate, is_subkey,
keygen_flags, cache_nonce_addr);
+ else if( algo == PUBKEY_ALGO_ECDSA || algo == PUBKEY_ALGO_ECDH )
+ err = gen_ecc (algo, nbits, pub_root, timestamp, expiredate, is_subkey,
+ keygen_flags, cache_nonce_addr);
else if (algo == PUBKEY_ALGO_RSA)
err = gen_rsa (algo, nbits, pub_root, timestamp, expiredate, is_subkey,
keygen_flags, cache_nonce_addr);
else
BUG();
return err;
}
/* Generate a new user id packet or return NULL if canceled. If
KEYBLOCK is not NULL the function prevents the creation of an
already existing user ID. */
PKT_user_id *
generate_user_id (KBNODE keyblock)
{
char *p;
p = ask_user_id (1, keyblock);
if (!p)
return NULL; /* Canceled. */
return uid_from_string (p);
}
static void
release_parameter_list (struct para_data_s *r)
{
struct para_data_s *r2;
for (; r ; r = r2)
{
r2 = r->next;
if (r->key == pPASSPHRASE_DEK)
xfree (r->u.dek);
else if (r->key == pPASSPHRASE_S2K )
xfree (r->u.s2k);
xfree (r);
}
}
static struct para_data_s *
get_parameter( struct para_data_s *para, enum para_name key )
{
struct para_data_s *r;
for( r = para; r && r->key != key; r = r->next )
;
return r;
}
static const char *
get_parameter_value( struct para_data_s *para, enum para_name key )
{
struct para_data_s *r = get_parameter( para, key );
return (r && *r->u.value)? r->u.value : NULL;
}
static int
get_parameter_algo( struct para_data_s *para, enum para_name key,
int *r_default)
{
int i;
struct para_data_s *r = get_parameter( para, key );
if (r_default)
*r_default = 0;
if (!r)
return -1;
if (!ascii_strcasecmp (r->u.value, "default"))
{
/* Note: If you change this default algo, remember to change it
also in gpg.c:gpgconf_list. */
i = DEFAULT_STD_ALGO;
if (r_default)
*r_default = 1;
}
else if (digitp (r->u.value))
i = atoi( r->u.value );
else if (!strcmp (r->u.value, "ELG-E")
|| !strcmp (r->u.value, "ELG"))
i = GCRY_PK_ELG_E;
else
i = gcry_pk_map_name (r->u.value);
if (i == PUBKEY_ALGO_RSA_E || i == PUBKEY_ALGO_RSA_S)
i = 0; /* we don't want to allow generation of these algorithms */
return i;
}
/*
* Parse the usage parameter and set the keyflags. Returns -1 on
* error, 0 for no usage given or 1 for usage available.
*/
static int
parse_parameter_usage (const char *fname,
struct para_data_s *para, enum para_name key)
{
struct para_data_s *r = get_parameter( para, key );
char *p, *pn;
unsigned int use;
if( !r )
return 0; /* none (this is an optional parameter)*/
use = 0;
pn = r->u.value;
while ( (p = strsep (&pn, " \t,")) ) {
if ( !*p)
;
else if ( !ascii_strcasecmp (p, "sign") )
use |= PUBKEY_USAGE_SIG;
else if ( !ascii_strcasecmp (p, "encrypt") )
use |= PUBKEY_USAGE_ENC;
else if ( !ascii_strcasecmp (p, "auth") )
use |= PUBKEY_USAGE_AUTH;
else {
log_error("%s:%d: invalid usage list\n", fname, r->lnr );
return -1; /* error */
}
}
r->u.usage = use;
return 1;
}
static int
parse_revocation_key (const char *fname,
struct para_data_s *para, enum para_name key)
{
struct para_data_s *r = get_parameter( para, key );
struct revocation_key revkey;
char *pn;
int i;
if( !r )
return 0; /* none (this is an optional parameter) */
pn = r->u.value;
revkey.class=0x80;
revkey.algid=atoi(pn);
if(!revkey.algid)
goto fail;
/* Skip to the fpr */
while(*pn && *pn!=':')
pn++;
if(*pn!=':')
goto fail;
pn++;
for(i=0;iu.revkey,&revkey,sizeof(struct revocation_key));
return 0;
fail:
log_error("%s:%d: invalid revocation key\n", fname, r->lnr );
return -1; /* error */
}
static u32
get_parameter_u32( struct para_data_s *para, enum para_name key )
{
struct para_data_s *r = get_parameter( para, key );
if( !r )
return 0;
if( r->key == pKEYCREATIONDATE )
return r->u.creation;
if( r->key == pKEYEXPIRE || r->key == pSUBKEYEXPIRE )
return r->u.expire;
if( r->key == pKEYUSAGE || r->key == pSUBKEYUSAGE )
return r->u.usage;
return (unsigned int)strtoul( r->u.value, NULL, 10 );
}
static unsigned int
get_parameter_uint( struct para_data_s *para, enum para_name key )
{
return get_parameter_u32( para, key );
}
static struct revocation_key *
get_parameter_revkey( struct para_data_s *para, enum para_name key )
{
struct para_data_s *r = get_parameter( para, key );
return r? &r->u.revkey : NULL;
}
static int
proc_parameter_file( struct para_data_s *para, const char *fname,
struct output_control_s *outctrl, int card )
{
struct para_data_s *r;
const char *s1, *s2, *s3;
size_t n;
char *p;
int is_default = 0;
int have_user_id = 0;
int err, algo;
/* Check that we have all required parameters. */
r = get_parameter( para, pKEYTYPE );
if(r)
{
algo = get_parameter_algo (para, pKEYTYPE, &is_default);
if (openpgp_pk_test_algo2 (algo, PUBKEY_USAGE_SIG))
{
log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
return -1;
}
}
else
{
log_error ("%s: no Key-Type specified\n",fname);
return -1;
}
err = parse_parameter_usage (fname, para, pKEYUSAGE);
if (!err)
{
/* Default to algo capabilities if key-usage is not provided and
no default algorithm has been requested. */
r = xmalloc_clear(sizeof(*r));
r->key = pKEYUSAGE;
r->u.usage = (is_default
? (PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG)
: openpgp_pk_algo_usage(algo));
r->next = para;
para = r;
}
else if (err == -1)
return -1;
else
{
r = get_parameter (para, pKEYUSAGE);
if (r && (r->u.usage & ~openpgp_pk_algo_usage (algo)))
{
log_error ("%s:%d: specified Key-Usage not allowed for algo %d\n",
fname, r->lnr, algo);
return -1;
}
}
is_default = 0;
r = get_parameter( para, pSUBKEYTYPE );
if(r)
{
algo = get_parameter_algo (para, pSUBKEYTYPE, &is_default);
if (openpgp_pk_test_algo (algo))
{
log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
return -1;
}
err = parse_parameter_usage (fname, para, pSUBKEYUSAGE);
if (!err)
{
/* Default to algo capabilities if subkey-usage is not
provided */
r = xmalloc_clear (sizeof(*r));
r->key = pSUBKEYUSAGE;
r->u.usage = (is_default
? PUBKEY_USAGE_ENC
: openpgp_pk_algo_usage (algo));
r->next = para;
para = r;
}
else if (err == -1)
return -1;
else
{
r = get_parameter (para, pSUBKEYUSAGE);
if (r && (r->u.usage & ~openpgp_pk_algo_usage (algo)))
{
log_error ("%s:%d: specified Subkey-Usage not allowed"
" for algo %d\n", fname, r->lnr, algo);
return -1;
}
}
}
if( get_parameter_value( para, pUSERID ) )
have_user_id=1;
else
{
/* create the formatted user ID */
s1 = get_parameter_value( para, pNAMEREAL );
s2 = get_parameter_value( para, pNAMECOMMENT );
s3 = get_parameter_value( para, pNAMEEMAIL );
if( s1 || s2 || s3 )
{
n = (s1?strlen(s1):0) + (s2?strlen(s2):0) + (s3?strlen(s3):0);
r = xmalloc_clear( sizeof *r + n + 20 );
r->key = pUSERID;
p = r->u.value;
if( s1 )
p = stpcpy(p, s1 );
if( s2 )
p = stpcpy(stpcpy(stpcpy(p," ("), s2 ),")");
if( s3 )
p = stpcpy(stpcpy(stpcpy(p," <"), s3 ),">");
r->next = para;
para = r;
have_user_id=1;
}
}
if(!have_user_id)
{
log_error("%s: no User-ID specified\n",fname);
return -1;
}
/* Set preferences, if any. */
keygen_set_std_prefs(get_parameter_value( para, pPREFERENCES ), 0);
/* Set keyserver, if any. */
s1=get_parameter_value( para, pKEYSERVER );
if(s1)
{
struct keyserver_spec *spec;
spec=parse_keyserver_uri(s1,1,NULL,0);
if(spec)
{
free_keyserver_spec(spec);
opt.def_keyserver_url=s1;
}
else
{
log_error("%s:%d: invalid keyserver url\n", fname, r->lnr );
return -1;
}
}
/* Set revoker, if any. */
if (parse_revocation_key (fname, para, pREVOKER))
return -1;
/* Make DEK and S2K from the Passphrase. */
if (outctrl->ask_passphrase)
{
/* %ask-passphrase is active - ignore pPASSPRASE and ask. This
feature is required so that GUIs are able to do a key
creation but have gpg-agent ask for the passphrase. */
int canceled = 0;
STRING2KEY *s2k;
DEK *dek;
dek = do_ask_passphrase (&s2k, 0, &canceled);
if (dek)
{
r = xmalloc_clear( sizeof *r );
r->key = pPASSPHRASE_DEK;
r->u.dek = dek;
r->next = para;
para = r;
r = xmalloc_clear( sizeof *r );
r->key = pPASSPHRASE_S2K;
r->u.s2k = s2k;
r->next = para;
para = r;
}
if (canceled)
{
log_error ("%s:%d: key generation canceled\n", fname, r->lnr );
return -1;
}
}
else
{
r = get_parameter( para, pPASSPHRASE );
if ( r && *r->u.value )
{
/* We have a plain text passphrase - create a DEK from it.
* It is a little bit ridiculous to keep it in secure memory
* but because we do this always, why not here. */
STRING2KEY *s2k;
DEK *dek;
s2k = xmalloc_secure ( sizeof *s2k );
s2k->mode = opt.s2k_mode;
s2k->hash_algo = S2K_DIGEST_ALGO;
set_next_passphrase ( r->u.value );
dek = passphrase_to_dek (NULL, 0, opt.s2k_cipher_algo, s2k, 2,
NULL, NULL);
set_next_passphrase (NULL );
assert (dek);
memset (r->u.value, 0, strlen(r->u.value));
r = xmalloc_clear (sizeof *r);
r->key = pPASSPHRASE_S2K;
r->u.s2k = s2k;
r->next = para;
para = r;
r = xmalloc_clear (sizeof *r);
r->key = pPASSPHRASE_DEK;
r->u.dek = dek;
r->next = para;
para = r;
}
}
/* Make KEYCREATIONDATE from Creation-Date. */
r = get_parameter (para, pCREATIONDATE);
if (r && *r->u.value)
{
u32 seconds;
seconds = parse_creation_string (r->u.value);
if (!seconds)
{
log_error ("%s:%d: invalid creation date\n", fname, r->lnr );
return -1;
}
r->u.creation = seconds;
r->key = pKEYCREATIONDATE; /* Change that entry. */
}
/* Make KEYEXPIRE from Expire-Date. */
r = get_parameter( para, pEXPIREDATE );
if( r && *r->u.value )
{
u32 seconds;
seconds = parse_expire_string( r->u.value );
if( seconds == (u32)-1 )
{
log_error("%s:%d: invalid expire date\n", fname, r->lnr );
return -1;
}
r->u.expire = seconds;
r->key = pKEYEXPIRE; /* change hat entry */
/* also set it for the subkey */
r = xmalloc_clear( sizeof *r + 20 );
r->key = pSUBKEYEXPIRE;
r->u.expire = seconds;
r->next = para;
para = r;
}
do_generate_keypair( para, outctrl, card );
return 0;
}
/****************
* Kludge to allow non interactive key generation controlled
* by a parameter file.
* Note, that string parameters are expected to be in UTF-8
*/
static void
read_parameter_file( const char *fname )
{
static struct { const char *name;
enum para_name key;
} keywords[] = {
{ "Key-Type", pKEYTYPE},
{ "Key-Length", pKEYLENGTH },
{ "Key-Usage", pKEYUSAGE },
{ "Subkey-Type", pSUBKEYTYPE },
{ "Subkey-Length", pSUBKEYLENGTH },
{ "Subkey-Usage", pSUBKEYUSAGE },
{ "Name-Real", pNAMEREAL },
{ "Name-Email", pNAMEEMAIL },
{ "Name-Comment", pNAMECOMMENT },
{ "Expire-Date", pEXPIREDATE },
{ "Creation-Date", pCREATIONDATE },
{ "Passphrase", pPASSPHRASE },
{ "Preferences", pPREFERENCES },
{ "Revoker", pREVOKER },
{ "Handle", pHANDLE },
{ "Keyserver", pKEYSERVER },
{ NULL, 0 }
};
IOBUF fp;
byte *line;
unsigned int maxlen, nline;
char *p;
int lnr;
const char *err = NULL;
struct para_data_s *para, *r;
int i;
struct output_control_s outctrl;
memset( &outctrl, 0, sizeof( outctrl ) );
outctrl.pub.afx = new_armor_context ();
if( !fname || !*fname)
fname = "-";
fp = iobuf_open (fname);
if (fp && is_secured_file (iobuf_get_fd (fp)))
{
iobuf_close (fp);
fp = NULL;
gpg_err_set_errno (EPERM);
}
if (!fp) {
log_error (_("can't open `%s': %s\n"), fname, strerror(errno) );
return;
}
iobuf_ioctl (fp, IOBUF_IOCTL_NO_CACHE, 1, NULL);
lnr = 0;
err = NULL;
para = NULL;
maxlen = 1024;
line = NULL;
while ( iobuf_read_line (fp, &line, &nline, &maxlen) ) {
char *keyword, *value;
lnr++;
if( !maxlen ) {
err = "line too long";
break;
}
for( p = line; isspace(*(byte*)p); p++ )
;
if( !*p || *p == '#' )
continue;
keyword = p;
if( *keyword == '%' ) {
for( ; !isspace(*(byte*)p); p++ )
;
if( *p )
*p++ = 0;
for( ; isspace(*(byte*)p); p++ )
;
value = p;
trim_trailing_ws( value, strlen(value) );
if( !ascii_strcasecmp( keyword, "%echo" ) )
log_info("%s\n", value );
else if( !ascii_strcasecmp( keyword, "%dry-run" ) )
outctrl.dryrun = 1;
else if( !ascii_strcasecmp( keyword, "%ask-passphrase" ) )
outctrl.ask_passphrase = 1;
else if( !ascii_strcasecmp( keyword, "%no-ask-passphrase" ) )
outctrl.ask_passphrase = 0;
else if( !ascii_strcasecmp( keyword, "%no-protection" ) )
outctrl.keygen_flags |= KEYGEN_FLAG_NO_PROTECTION;
else if( !ascii_strcasecmp( keyword, "%transient-key" ) )
outctrl.keygen_flags |= KEYGEN_FLAG_TRANSIENT_KEY;
else if( !ascii_strcasecmp( keyword, "%commit" ) ) {
outctrl.lnr = lnr;
if (proc_parameter_file( para, fname, &outctrl, 0 ))
print_status_key_not_created
(get_parameter_value (para, pHANDLE));
release_parameter_list( para );
para = NULL;
}
else if( !ascii_strcasecmp( keyword, "%pubring" ) ) {
if( outctrl.pub.fname && !strcmp( outctrl.pub.fname, value ) )
; /* still the same file - ignore it */
else {
xfree( outctrl.pub.newfname );
outctrl.pub.newfname = xstrdup( value );
outctrl.use_files = 1;
}
}
else if( !ascii_strcasecmp( keyword, "%secring" ) ) {
/* Ignore this command. */
}
else
log_info("skipping control `%s' (%s)\n", keyword, value );
continue;
}
if( !(p = strchr( p, ':' )) || p == keyword ) {
err = "missing colon";
break;
}
if( *p )
*p++ = 0;
for( ; isspace(*(byte*)p); p++ )
;
if( !*p ) {
err = "missing argument";
break;
}
value = p;
trim_trailing_ws( value, strlen(value) );
for(i=0; keywords[i].name; i++ ) {
if( !ascii_strcasecmp( keywords[i].name, keyword ) )
break;
}
if( !keywords[i].name ) {
err = "unknown keyword";
break;
}
if( keywords[i].key != pKEYTYPE && !para ) {
err = "parameter block does not start with \"Key-Type\"";
break;
}
if( keywords[i].key == pKEYTYPE && para ) {
outctrl.lnr = lnr;
if (proc_parameter_file( para, fname, &outctrl, 0 ))
print_status_key_not_created
(get_parameter_value (para, pHANDLE));
release_parameter_list( para );
para = NULL;
}
else {
for( r = para; r; r = r->next ) {
if( r->key == keywords[i].key )
break;
}
if( r ) {
err = "duplicate keyword";
break;
}
}
r = xmalloc_clear( sizeof *r + strlen( value ) );
r->lnr = lnr;
r->key = keywords[i].key;
strcpy( r->u.value, value );
r->next = para;
para = r;
}
if( err )
log_error("%s:%d: %s\n", fname, lnr, err );
else if( iobuf_error (fp) ) {
log_error("%s:%d: read error\n", fname, lnr);
}
else if( para ) {
outctrl.lnr = lnr;
if (proc_parameter_file( para, fname, &outctrl, 0 ))
print_status_key_not_created (get_parameter_value (para, pHANDLE));
}
if( outctrl.use_files ) { /* close open streams */
iobuf_close( outctrl.pub.stream );
/* Must invalidate that ugly cache to actually close it. */
if (outctrl.pub.fname)
iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE,
0, (char*)outctrl.pub.fname);
xfree( outctrl.pub.fname );
xfree( outctrl.pub.newfname );
}
release_parameter_list( para );
iobuf_close (fp);
release_armor_context (outctrl.pub.afx);
}
/*
* Generate a keypair (fname is only used in batch mode) If
* CARD_SERIALNO is not NULL the function will create the keys on an
* OpenPGP Card. If CARD_BACKUP_KEY has been set and CARD_SERIALNO is
* NOT NULL, the encryption key for the card is generated on the host,
* imported to the card and a backup file created by gpg-agent.
*/
void
generate_keypair (const char *fname, const char *card_serialno,
int card_backup_key)
{
unsigned int nbits;
char *uid = NULL;
int algo;
unsigned int use;
int both = 0;
u32 expire;
struct para_data_s *para = NULL;
struct para_data_s *r;
struct output_control_s outctrl;
memset( &outctrl, 0, sizeof( outctrl ) );
if (opt.batch && card_serialno)
{
/* We don't yet support unattended key generation. */
log_error (_("can't do this in batch mode\n"));
return;
}
if (opt.batch)
{
read_parameter_file( fname );
return;
}
if (card_serialno)
{
#ifdef ENABLE_CARD_SUPPORT
r = xcalloc (1, sizeof *r + strlen (card_serialno) );
r->key = pSERIALNO;
strcpy( r->u.value, card_serialno);
r->next = para;
para = r;
algo = PUBKEY_ALGO_RSA;
r = xcalloc (1, sizeof *r + 20 );
r->key = pKEYTYPE;
sprintf( r->u.value, "%d", algo );
r->next = para;
para = r;
r = xcalloc (1, sizeof *r + 20 );
r->key = pKEYUSAGE;
strcpy (r->u.value, "sign");
r->next = para;
para = r;
r = xcalloc (1, sizeof *r + 20 );
r->key = pSUBKEYTYPE;
sprintf( r->u.value, "%d", algo );
r->next = para;
para = r;
r = xcalloc (1, sizeof *r + 20 );
r->key = pSUBKEYUSAGE;
strcpy (r->u.value, "encrypt");
r->next = para;
para = r;
r = xcalloc (1, sizeof *r + 20 );
r->key = pAUTHKEYTYPE;
sprintf( r->u.value, "%d", algo );
r->next = para;
para = r;
if (card_backup_key)
{
r = xcalloc (1, sizeof *r + 1);
r->key = pCARDBACKUPKEY;
strcpy (r->u.value, "1");
r->next = para;
para = r;
}
#endif /*ENABLE_CARD_SUPPORT*/
}
else
{
int subkey_algo;
algo = ask_algo (0, &subkey_algo, &use);
if (subkey_algo)
{
/* Create primary and subkey at once. */
both = 1;
r = xmalloc_clear( sizeof *r + 20 );
r->key = pKEYTYPE;
sprintf( r->u.value, "%d", algo );
r->next = para;
para = r;
nbits = ask_keysize (algo, 0);
r = xmalloc_clear( sizeof *r + 20 );
r->key = pKEYLENGTH;
sprintf( r->u.value, "%u", nbits);
r->next = para;
para = r;
r = xmalloc_clear( sizeof *r + 20 );
r->key = pKEYUSAGE;
strcpy( r->u.value, "sign" );
r->next = para;
para = r;
r = xmalloc_clear( sizeof *r + 20 );
r->key = pSUBKEYTYPE;
sprintf( r->u.value, "%d", subkey_algo);
r->next = para;
para = r;
r = xmalloc_clear( sizeof *r + 20 );
r->key = pSUBKEYUSAGE;
strcpy( r->u.value, "encrypt" );
r->next = para;
para = r;
}
else
{
r = xmalloc_clear( sizeof *r + 20 );
r->key = pKEYTYPE;
sprintf( r->u.value, "%d", algo );
r->next = para;
para = r;
if (use)
{
r = xmalloc_clear( sizeof *r + 25 );
r->key = pKEYUSAGE;
sprintf( r->u.value, "%s%s%s",
(use & PUBKEY_USAGE_SIG)? "sign ":"",
(use & PUBKEY_USAGE_ENC)? "encrypt ":"",
(use & PUBKEY_USAGE_AUTH)? "auth":"" );
r->next = para;
para = r;
}
nbits = 0;
}
nbits = ask_keysize (both? subkey_algo : algo, nbits);
r = xmalloc_clear( sizeof *r + 20 );
r->key = both? pSUBKEYLENGTH : pKEYLENGTH;
sprintf( r->u.value, "%u", nbits);
r->next = para;
para = r;
}
expire = ask_expire_interval(0,NULL);
r = xmalloc_clear( sizeof *r + 20 );
r->key = pKEYEXPIRE;
r->u.expire = expire;
r->next = para;
para = r;
r = xmalloc_clear( sizeof *r + 20 );
r->key = pSUBKEYEXPIRE;
r->u.expire = expire;
r->next = para;
para = r;
uid = ask_user_id (0, NULL);
if( !uid )
{
log_error(_("Key generation canceled.\n"));
release_parameter_list( para );
return;
}
r = xmalloc_clear( sizeof *r + strlen(uid) );
r->key = pUSERID;
strcpy( r->u.value, uid );
r->next = para;
para = r;
proc_parameter_file( para, "[internal]", &outctrl, !!card_serialno);
release_parameter_list( para );
}
#if 0 /* not required */
/* Generate a raw key and return it as a secret key packet. The
function will ask for the passphrase and return a protected as well
as an unprotected copy of a new secret key packet. 0 is returned
on success and the caller must then free the returned values. */
static int
generate_raw_key (int algo, unsigned int nbits, u32 created_at,
PKT_secret_key **r_sk_unprotected,
PKT_secret_key **r_sk_protected)
{
int rc;
DEK *dek = NULL;
STRING2KEY *s2k = NULL;
PKT_secret_key *sk = NULL;
int i;
size_t nskey, npkey;
gcry_sexp_t s_parms, s_key;
int canceled;
npkey = pubkey_get_npkey (algo);
nskey = pubkey_get_nskey (algo);
assert (nskey <= PUBKEY_MAX_NSKEY && npkey < nskey);
if (nbits < 512)
{
nbits = 512;
log_info (_("keysize invalid; using %u bits\n"), nbits );
}
if ((nbits % 32))
{
nbits = ((nbits + 31) / 32) * 32;
log_info(_("keysize rounded up to %u bits\n"), nbits );
}
dek = do_ask_passphrase (&s2k, 1, &canceled);
if (canceled)
{
rc = gpg_error (GPG_ERR_CANCELED);
goto leave;
}
sk = xmalloc_clear (sizeof *sk);
sk->timestamp = created_at;
sk->version = 4;
sk->pubkey_algo = algo;
if ( !is_RSA (algo) )
{
log_error ("only RSA is supported for offline generated keys\n");
rc = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
goto leave;
}
rc = gcry_sexp_build (&s_parms, NULL,
"(genkey(rsa(nbits %d)))",
(int)nbits);
if (rc)
log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
rc = gcry_pk_genkey (&s_key, s_parms);
gcry_sexp_release (s_parms);
if (rc)
{
log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
goto leave;
}
rc = key_from_sexp (sk->skey, s_key, "private-key", "nedpqu");
gcry_sexp_release (s_key);
if (rc)
{
log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
goto leave;
}
for (i=npkey; i < nskey; i++)
sk->csum += checksum_mpi (sk->skey[i]);
if (r_sk_unprotected)
*r_sk_unprotected = copy_secret_key (NULL, sk);
rc = genhelp_protect (dek, s2k, sk);
if (rc)
goto leave;
if (r_sk_protected)
{
*r_sk_protected = sk;
sk = NULL;
}
leave:
if (sk)
free_secret_key (sk);
xfree (dek);
xfree (s2k);
return rc;
}
#endif /* ENABLE_CARD_SUPPORT */
/* Create and delete a dummy packet to start off a list of kbnodes. */
static void
start_tree(KBNODE *tree)
{
PACKET *pkt;
pkt=xmalloc_clear(sizeof(*pkt));
pkt->pkttype=PKT_NONE;
*tree=new_kbnode(pkt);
delete_kbnode(*tree);
}
static void
do_generate_keypair (struct para_data_s *para,
struct output_control_s *outctrl, int card)
{
gpg_error_t err;
KBNODE pub_root = NULL;
const char *s;
PKT_public_key *pri_psk = NULL;
PKT_public_key *sub_psk = NULL;
struct revocation_key *revkey;
int did_sub = 0;
u32 timestamp;
char *cache_nonce = NULL;
if (outctrl->dryrun)
{
log_info("dry-run mode - key generation skipped\n");
return;
}
if ( outctrl->use_files )
{
if ( outctrl->pub.newfname )
{
iobuf_close(outctrl->pub.stream);
outctrl->pub.stream = NULL;
if (outctrl->pub.fname)
iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE,
0, (char*)outctrl->pub.fname);
xfree( outctrl->pub.fname );
outctrl->pub.fname = outctrl->pub.newfname;
outctrl->pub.newfname = NULL;
if (is_secured_filename (outctrl->pub.fname) )
{
outctrl->pub.stream = NULL;
gpg_err_set_errno (EPERM);
}
else
outctrl->pub.stream = iobuf_create( outctrl->pub.fname );
if (!outctrl->pub.stream)
{
log_error(_("can't create `%s': %s\n"), outctrl->pub.newfname,
strerror(errno) );
return;
}
if (opt.armor)
{
outctrl->pub.afx->what = 1;
push_armor_filter (outctrl->pub.afx, outctrl->pub.stream);
}
}
assert( outctrl->pub.stream );
if (opt.verbose)
log_info (_("writing public key to `%s'\n"), outctrl->pub.fname );
}
/* We create the packets as a tree of kbnodes. Because the
structure we create is known in advance we simply generate a
linked list. The first packet is a dummy packet which we flag as
deleted. The very first packet must always be a KEY packet. */
start_tree (&pub_root);
timestamp = get_parameter_u32 (para, pKEYCREATIONDATE);
if (!timestamp)
timestamp = make_timestamp ();
/* Note that, depending on the backend (i.e. the used scdaemon
version), the card key generation may update TIMESTAMP for each
key. Thus we need to pass TIMESTAMP to all signing function to
make sure that the binding signature is done using the timestamp
of the corresponding (sub)key and not that of the primary key.
An alternative implementation could tell the signing function the
node of the subkey but that is more work than just to pass the
current timestamp. */
if (!card)
err = do_create (get_parameter_algo( para, pKEYTYPE, NULL ),
get_parameter_uint( para, pKEYLENGTH ),
pub_root,
timestamp,
get_parameter_u32( para, pKEYEXPIRE ), 0,
outctrl->keygen_flags, &cache_nonce);
else
err = gen_card_key (PUBKEY_ALGO_RSA, 1, 1, pub_root,
×tamp,
get_parameter_u32 (para, pKEYEXPIRE));
/* Get the pointer to the generated public key packet. */
if (!err)
{
pri_psk = pub_root->next->pkt->pkt.public_key;
assert (pri_psk);
}
if (!err && (revkey = get_parameter_revkey (para, pREVOKER)))
err = write_direct_sig (pub_root, pri_psk, revkey, timestamp, cache_nonce);
if (!err && (s = get_parameter_value (para, pUSERID)))
{
write_uid (pub_root, s );
err = write_selfsigs (pub_root, pri_psk,
get_parameter_uint (para, pKEYUSAGE), timestamp,
cache_nonce);
}
/* Write the auth key to the card before the encryption key. This
is a partial workaround for a PGP bug (as of this writing, all
versions including 8.1), that causes it to try and encrypt to
the most recent subkey regardless of whether that subkey is
actually an encryption type. In this case, the auth key is an
RSA key so it succeeds. */
if (!err && card && get_parameter (para, pAUTHKEYTYPE))
{
err = gen_card_key (PUBKEY_ALGO_RSA, 3, 0, pub_root,
×tamp,
get_parameter_u32 (para, pKEYEXPIRE));
if (!err)
err = write_keybinding (pub_root, pri_psk, NULL,
PUBKEY_USAGE_AUTH, timestamp, cache_nonce);
}
if (!err && get_parameter (para, pSUBKEYTYPE))
{
sub_psk = NULL;
if (!card)
{
err = do_create (get_parameter_algo (para, pSUBKEYTYPE, NULL),
get_parameter_uint (para, pSUBKEYLENGTH),
pub_root,
timestamp,
get_parameter_u32 (para, pSUBKEYEXPIRE), 1,
outctrl->keygen_flags, &cache_nonce);
/* Get the pointer to the generated public subkey packet. */
if (!err)
{
kbnode_t node;
for (node = pub_root; node; node = node->next)
if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
sub_psk = node->pkt->pkt.public_key;
assert (sub_psk);
}
}
else
{
if ((s = get_parameter_value (para, pCARDBACKUPKEY)))
{
/* A backup of the encryption key has been requested.
Generate the key in software and import it then to
the card. Write a backup file. */
err = gen_card_key_with_backup
(PUBKEY_ALGO_RSA, 2, 0, pub_root, timestamp,
get_parameter_u32 (para, pKEYEXPIRE), para);
}
else
{
err = gen_card_key (PUBKEY_ALGO_RSA, 2, 0, pub_root,
×tamp,
get_parameter_u32 (para, pKEYEXPIRE));
}
}
if (!err)
err = write_keybinding (pub_root, pri_psk, sub_psk,
get_parameter_uint (para, pSUBKEYUSAGE),
timestamp, cache_nonce);
did_sub = 1;
}
if (!err && outctrl->use_files) /* Direct write to specified files. */
{
err = write_keyblock (outctrl->pub.stream, pub_root);
if (err)
log_error ("can't write public key: %s\n", g10_errstr (err));
}
else if (!err) /* Write to the standard keyrings. */
{
KEYDB_HANDLE pub_hd = keydb_new ();
err = keydb_locate_writable (pub_hd, NULL);
if (err)
log_error (_("no writable public keyring found: %s\n"),
g10_errstr (err));
if (!err && opt.verbose)
{
log_info (_("writing public key to `%s'\n"),
keydb_get_resource_name (pub_hd));
}
if (!err)
{
err = keydb_insert_keyblock (pub_hd, pub_root);
if (err)
log_error (_("error writing public keyring `%s': %s\n"),
keydb_get_resource_name (pub_hd), g10_errstr(err));
}
keydb_release (pub_hd);
if (!err)
{
int no_enc_rsa;
PKT_public_key *pk;
no_enc_rsa = ((get_parameter_algo (para, pKEYTYPE, NULL)
== PUBKEY_ALGO_RSA)
&& get_parameter_uint (para, pKEYUSAGE)
&& !((get_parameter_uint (para, pKEYUSAGE)
& PUBKEY_USAGE_ENC)) );
pk = find_kbnode (pub_root, PKT_PUBLIC_KEY)->pkt->pkt.public_key;
keyid_from_pk (pk, pk->main_keyid);
register_trusted_keyid (pk->main_keyid);
update_ownertrust (pk, ((get_ownertrust (pk) & ~TRUST_MASK)
| TRUST_ULTIMATE ));
if (!opt.batch)
{
tty_printf (_("public and secret key created and signed.\n") );
tty_printf ("\n");
list_keyblock (pub_root, 0, 1, NULL);
}
if (!opt.batch
&& (get_parameter_algo (para, pKEYTYPE, NULL) == PUBKEY_ALGO_DSA
|| no_enc_rsa )
&& !get_parameter (para, pSUBKEYTYPE) )
{
tty_printf(_("Note that this key cannot be used for "
"encryption. You may want to use\n"
"the command \"--edit-key\" to generate a "
"subkey for this purpose.\n") );
}
}
}
if (err)
{
if (opt.batch)
log_error ("key generation failed: %s\n", g10_errstr(err) );
else
tty_printf (_("Key generation failed: %s\n"), g10_errstr(err) );
write_status_error (card? "card_key_generate":"key_generate", err);
print_status_key_not_created ( get_parameter_value (para, pHANDLE) );
}
else
{
PKT_public_key *pk = find_kbnode (pub_root,
PKT_PUBLIC_KEY)->pkt->pkt.public_key;
print_status_key_created (did_sub? 'B':'P', pk,
get_parameter_value (para, pHANDLE));
}
release_kbnode (pub_root);
xfree (cache_nonce);
}
/* Add a new subkey to an existing key. Returns 0 if a new key has
been generated and put into the keyblocks. */
gpg_error_t
generate_subkeypair (KBNODE keyblock)
{
gpg_error_t err = 0;
kbnode_t node;
PKT_public_key *pri_psk = NULL;
PKT_public_key *sub_psk = NULL;
int algo;
unsigned int use;
u32 expire;
unsigned int nbits;
u32 cur_time;
char *hexgrip = NULL;
char *serialno = NULL;
/* Break out the primary key. */
node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
if (!node)
{
log_error ("Oops; primary key missing in keyblock!\n");
err = gpg_error (GPG_ERR_BUG);
goto leave;
}
pri_psk = node->pkt->pkt.public_key;
cur_time = make_timestamp ();
if (pri_psk->timestamp > cur_time)
{
ulong d = pri_psk->timestamp - cur_time;
log_info ( d==1 ? _("key has been created %lu second "
"in future (time warp or clock problem)\n")
: _("key has been created %lu seconds "
"in future (time warp or clock problem)\n"), d );
if (!opt.ignore_time_conflict)
{
err = gpg_error (GPG_ERR_TIME_CONFLICT);
goto leave;
}
}
if (pri_psk->version < 4)
{
log_info (_("NOTE: creating subkeys for v3 keys "
"is not OpenPGP compliant\n"));
err = gpg_error (GPG_ERR_CONFLICT);
goto leave;
}
err = hexkeygrip_from_pk (pri_psk, &hexgrip);
if (err)
goto leave;
if (agent_get_keyinfo (NULL, hexgrip, &serialno))
{
tty_printf (_("Secret parts of primary key are not available.\n"));
goto leave;
}
if (serialno)
tty_printf (_("Secret parts of primary key are stored on-card.\n"));
algo = ask_algo (1, NULL, &use);
assert (algo);
nbits = ask_keysize (algo, 0);
expire = ask_expire_interval (0, NULL);
if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.sub.okay",
_("Really create? (y/N) ")))
{
err = gpg_error (GPG_ERR_CANCELED);
goto leave;
}
err = do_create (algo, nbits, keyblock, cur_time, expire, 1, 0, NULL);
if (err)
goto leave;
/* Get the pointer to the generated public subkey packet. */
for (node = keyblock; node; node = node->next)
if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
sub_psk = node->pkt->pkt.public_key;
/* Write the binding signature. */
err = write_keybinding (keyblock, pri_psk, sub_psk, use, cur_time, NULL);
if (err)
goto leave;
write_status_text (STATUS_KEY_CREATED, "S");
leave:
xfree (hexgrip);
xfree (serialno);
if (err)
log_error (_("Key generation failed: %s\n"), g10_errstr (err) );
return err;
}
#ifdef ENABLE_CARD_SUPPORT
/* Generate a subkey on a card. */
gpg_error_t
generate_card_subkeypair (kbnode_t pub_keyblock,
int keyno, const char *serialno)
{
gpg_error_t err = 0;
kbnode_t node;
PKT_public_key *pri_pk = NULL;
int algo;
unsigned int use;
u32 expire;
u32 cur_time;
struct para_data_s *para = NULL;
assert (keyno >= 1 && keyno <= 3);
para = xtrycalloc (1, sizeof *para + strlen (serialno) );
if (!para)
{
err = gpg_error_from_syserror ();
goto leave;
}
para->key = pSERIALNO;
strcpy (para->u.value, serialno);
/* Break out the primary secret key */
node = find_kbnode (pub_keyblock, PKT_PUBLIC_KEY);
if (!node)
{
log_error ("Oops; publkic key lost!\n");
err = gpg_error (GPG_ERR_INTERNAL);
goto leave;
}
pri_pk = node->pkt->pkt.public_key;
cur_time = make_timestamp();
if (pri_pk->timestamp > cur_time)
{
ulong d = pri_pk->timestamp - cur_time;
log_info (d==1 ? _("key has been created %lu second "
"in future (time warp or clock problem)\n")
: _("key has been created %lu seconds "
"in future (time warp or clock problem)\n"), d );
if (!opt.ignore_time_conflict)
{
err = gpg_error (GPG_ERR_TIME_CONFLICT);
goto leave;
}
}
if (pri_pk->version < 4)
{
log_info (_("NOTE: creating subkeys for v3 keys "
"is not OpenPGP compliant\n"));
err = gpg_error (GPG_ERR_NOT_SUPPORTED);
goto leave;
}
algo = PUBKEY_ALGO_RSA;
expire = ask_expire_interval (0, NULL);
if (keyno == 1)
use = PUBKEY_USAGE_SIG;
else if (keyno == 2)
use = PUBKEY_USAGE_ENC;
else
use = PUBKEY_USAGE_AUTH;
if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.cardsub.okay",
_("Really create? (y/N) ")))
{
err = gpg_error (GPG_ERR_CANCELED);
goto leave;
}
/* Note, that depending on the backend, the card key generation may
update CUR_TIME. */
err = gen_card_key (algo, keyno, 0, pub_keyblock, &cur_time, expire);
/* Get the pointer to the generated public subkey packet. */
if (!err)
{
PKT_public_key *sub_pk = NULL;
for (node = pub_keyblock; node; node = node->next)
if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
sub_pk = node->pkt->pkt.public_key;
assert (sub_pk);
err = write_keybinding (pub_keyblock, pri_pk, sub_pk,
use, cur_time, NULL);
}
leave:
if (err)
log_error (_("Key generation failed: %s\n"), g10_errstr(err) );
else
write_status_text (STATUS_KEY_CREATED, "S");
release_parameter_list (para);
return err;
}
#endif /* !ENABLE_CARD_SUPPORT */
/*
* Write a keyblock to an output stream
*/
static int
write_keyblock( IOBUF out, KBNODE node )
{
for( ; node ; node = node->next )
{
if(!is_deleted_kbnode(node))
{
int rc = build_packet( out, node->pkt );
if( rc )
{
log_error("build_packet(%d) failed: %s\n",
node->pkt->pkttype, g10_errstr(rc) );
return rc;
}
}
}
return 0;
}
/* Note that timestamp is an in/out arg. */
static gpg_error_t
gen_card_key (int algo, int keyno, int is_primary, kbnode_t pub_root,
u32 *timestamp, u32 expireval)
{
#ifdef ENABLE_CARD_SUPPORT
gpg_error_t err;
struct agent_card_genkey_s info;
PACKET *pkt;
PKT_public_key *pk;
if (algo != PUBKEY_ALGO_RSA)
return gpg_error (GPG_ERR_PUBKEY_ALGO);
pk = xtrycalloc (1, sizeof *pk );
if (!pk)
return gpg_error_from_syserror ();
pkt = xtrycalloc (1, sizeof *pkt);
if (!pkt)
{
xfree (pk);
return gpg_error_from_syserror ();
}
/* Note: SCD knows the serialnumber, thus there is no point in passing it. */
err = agent_scd_genkey (&info, keyno, 1, NULL, *timestamp);
/* The code below is not used because we force creation of
* the a card key (3rd arg).
* if (gpg_err_code (rc) == GPG_ERR_EEXIST)
* {
* tty_printf ("\n");
* log_error ("WARNING: key does already exists!\n");
* tty_printf ("\n");
* if ( cpr_get_answer_is_yes( "keygen.card.replace_key",
* _("Replace existing key? ")))
* rc = agent_scd_genkey (&info, keyno, 1);
* }
*/
if (!err && (!info.n || !info.e))
{
log_error ("communication error with SCD\n");
gcry_mpi_release (info.n);
gcry_mpi_release (info.e);
err = gpg_error (GPG_ERR_GENERAL);
}
if (err)
{
log_error ("key generation failed: %s\n", gpg_strerror (err));
xfree (pkt);
xfree (pk);
return err;
}
if (*timestamp != info.created_at)
log_info ("NOTE: the key does not use the suggested creation date\n");
*timestamp = info.created_at;
pk->timestamp = info.created_at;
pk->version = 4;
if (expireval)
pk->expiredate = pk->timestamp + expireval;
pk->pubkey_algo = algo;
pk->pkey[0] = info.n;
pk->pkey[1] = info.e;
pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
pkt->pkt.public_key = pk;
add_kbnode (pub_root, new_kbnode (pkt));
return 0;
#else
return gpg_error (GPG_ERR_NOT_SUPPORTED);
#endif /*!ENABLE_CARD_SUPPORT*/
}
static int
gen_card_key_with_backup (int algo, int keyno, int is_primary,
KBNODE pub_root, u32 timestamp,
u32 expireval, struct para_data_s *para)
{
#if 0 /* FIXME: Move this to gpg-agent. */
int rc;
const char *s;
PACKET *pkt;
PKT_secret_key *sk, *sk_unprotected = NULL, *sk_protected = NULL;
PKT_public_key *pk;
size_t n;
int i;
unsigned int nbits;
/* Get the size of the key directly from the card. */
{
struct agent_card_info_s info;
memset (&info, 0, sizeof info);
if (!agent_scd_getattr ("KEY-ATTR", &info)
&& info.key_attr[1].algo)
nbits = info.key_attr[1].nbits;
else
nbits = 1024; /* All pre-v2.0 cards. */
agent_release_card_info (&info);
}
/* Create a key of this size in memory. */
rc = generate_raw_key (algo, nbits, timestamp,
&sk_unprotected, &sk_protected);
if (rc)
return rc;
/* Store the key to the card. */
rc = save_unprotected_key_to_card (sk_unprotected, keyno);
if (rc)
{
log_error (_("storing key onto card failed: %s\n"), g10_errstr (rc));
free_secret_key (sk_unprotected);
free_secret_key (sk_protected);
write_status_errcode ("save_key_to_card", rc);
return rc;
}
/* Get rid of the secret key parameters and store the serial numer. */
sk = sk_unprotected;
n = pubkey_get_nskey (sk->pubkey_algo);
for (i=pubkey_get_npkey (sk->pubkey_algo); i < n; i++)
{
gcry_mpi_release (sk->skey[i]);
sk->skey[i] = NULL;
}
i = pubkey_get_npkey (sk->pubkey_algo);
sk->skey[i] = gcry_mpi_set_opaque (NULL, xstrdup ("dummydata"), 10*8);
sk->is_protected = 1;
sk->protect.s2k.mode = 1002;
s = get_parameter_value (para, pSERIALNO);
assert (s);
for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
sk->protect.ivlen++, s += 2)
sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
/* Now write the *protected* secret key to the file. */
{
char name_buffer[50];
char *fname;
IOBUF fp;
mode_t oldmask;
keyid_from_sk (sk, NULL);
snprintf (name_buffer, sizeof name_buffer, "sk_%08lX%08lX.gpg",
(ulong)sk->keyid[0], (ulong)sk->keyid[1]);
fname = make_filename (backup_dir, name_buffer, NULL);
oldmask = umask (077);
if (is_secured_filename (fname))
{
fp = NULL;
gpg_err_set_errno (EPERM);
}
else
fp = iobuf_create (fname);
umask (oldmask);
if (!fp)
{
rc = gpg_error_from_syserror ();
log_error (_("can't create backup file `%s': %s\n"),
fname, strerror(errno) );
xfree (fname);
free_secret_key (sk_unprotected);
free_secret_key (sk_protected);
return rc;
}
pkt = xcalloc (1, sizeof *pkt);
pkt->pkttype = PKT_SECRET_KEY;
pkt->pkt.secret_key = sk_protected;
sk_protected = NULL;
rc = build_packet (fp, pkt);
if (rc)
{
log_error("build packet failed: %s\n", g10_errstr(rc) );
iobuf_cancel (fp);
}
else
{
unsigned char array[MAX_FINGERPRINT_LEN];
char *fprbuf, *p;
iobuf_close (fp);
iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
log_info (_("NOTE: backup of card key saved to `%s'\n"), fname);
fingerprint_from_sk (sk, array, &n);
p = fprbuf = xmalloc (MAX_FINGERPRINT_LEN*2 + 1 + 1);
for (i=0; i < n ; i++, p += 2)
sprintf (p, "%02X", array[i]);
*p++ = ' ';
*p = 0;
write_status_text_and_buffer (STATUS_BACKUP_KEY_CREATED,
fprbuf,
fname, strlen (fname),
0);
xfree (fprbuf);
}
free_packet (pkt);
xfree (pkt);
xfree (fname);
if (rc)
{
free_secret_key (sk_unprotected);
return rc;
}
}
/* Create the public key from the secret key. */
pk = xcalloc (1, sizeof *pk );
pk->timestamp = sk->timestamp;
pk->version = sk->version;
if (expireval)
pk->expiredate = sk->expiredate = sk->timestamp + expireval;
pk->pubkey_algo = sk->pubkey_algo;
n = pubkey_get_npkey (sk->pubkey_algo);
for (i=0; i < n; i++)
pk->pkey[i] = mpi_copy (sk->skey[i]);
/* Build packets and add them to the node lists. */
pkt = xcalloc (1,sizeof *pkt);
pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
pkt->pkt.public_key = pk;
add_kbnode(pub_root, new_kbnode( pkt ));
pkt = xcalloc (1,sizeof *pkt);
pkt->pkttype = is_primary ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
pkt->pkt.secret_key = sk;
add_kbnode(sec_root, new_kbnode( pkt ));
return 0;
#else
return gpg_error (GPG_ERR_NOT_SUPPORTED);
#endif /*!ENABLE_CARD_SUPPORT*/
}
#if 0
int
save_unprotected_key_to_card (PKT_public_key *sk, int keyno)
{
int rc;
unsigned char *rsa_n = NULL;
unsigned char *rsa_e = NULL;
unsigned char *rsa_p = NULL;
unsigned char *rsa_q = NULL;
size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
unsigned char *sexp = NULL;
unsigned char *p;
char numbuf[55], numbuf2[50];
assert (is_RSA (sk->pubkey_algo));
assert (!sk->is_protected);
/* Copy the parameters into straight buffers. */
gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_n, &rsa_n_len, sk->skey[0]);
gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_e, &rsa_e_len, sk->skey[1]);
gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_p, &rsa_p_len, sk->skey[3]);
gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_q, &rsa_q_len, sk->skey[4]);
if (!rsa_n || !rsa_e || !rsa_p || !rsa_q)
{
rc = G10ERR_INV_ARG;
goto leave;
}
/* Put the key into an S-expression. */
sexp = p = xmalloc_secure (30
+ rsa_n_len + rsa_e_len + rsa_p_len + rsa_q_len
+ 4*sizeof (numbuf) + 25 + sizeof(numbuf) + 20);
p = stpcpy (p,"(11:private-key(3:rsa(1:n");
sprintf (numbuf, "%u:", (unsigned int)rsa_n_len);
p = stpcpy (p, numbuf);
memcpy (p, rsa_n, rsa_n_len);
p += rsa_n_len;
sprintf (numbuf, ")(1:e%u:", (unsigned int)rsa_e_len);
p = stpcpy (p, numbuf);
memcpy (p, rsa_e, rsa_e_len);
p += rsa_e_len;
sprintf (numbuf, ")(1:p%u:", (unsigned int)rsa_p_len);
p = stpcpy (p, numbuf);
memcpy (p, rsa_p, rsa_p_len);
p += rsa_p_len;
sprintf (numbuf, ")(1:q%u:", (unsigned int)rsa_q_len);
p = stpcpy (p, numbuf);
memcpy (p, rsa_q, rsa_q_len);
p += rsa_q_len;
p = stpcpy (p,"))(10:created-at");
sprintf (numbuf2, "%lu", (unsigned long)sk->timestamp);
sprintf (numbuf, "%lu:", (unsigned long)strlen (numbuf2));
p = stpcpy (stpcpy (stpcpy (p, numbuf), numbuf2), "))");
/* Fixme: Unfortunately we don't have the serialnumber available -
thus we can't pass it down to the agent. */
rc = agent_scd_writekey (keyno, NULL, sexp, p - sexp);
leave:
xfree (sexp);
xfree (rsa_n);
xfree (rsa_e);
xfree (rsa_p);
xfree (rsa_q);
return rc;
}
#endif /*ENABLE_CARD_SUPPORT*/
diff --git a/g10/keyid.c b/g10/keyid.c
index 62ce03685..2a9bd1988 100644
--- a/g10/keyid.c
+++ b/g10/keyid.c
@@ -1,763 +1,783 @@
/* keyid.c - key ID and fingerprint handling
* Copyright (C) 1998, 1999, 2000, 2001, 2003,
* 2004, 2006, 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
* 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
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include "gpg.h"
#include "util.h"
#include "main.h"
#include "packet.h"
#include "options.h"
#include "keydb.h"
#include "i18n.h"
#include "rmd160.h"
#define KEYID_STR_SIZE 19
#ifdef HAVE_UNSIGNED_TIME_T
# define IS_INVALID_TIME_T(a) ((a) == (time_t)(-1))
#else
/* Error or 32 bit time_t and value after 2038-01-19. */
# define IS_INVALID_TIME_T(a) ((a) < 0)
#endif
/* Return a letter describing the public key algorithms. */
int
pubkey_letter( int algo )
{
switch (algo)
{
case PUBKEY_ALGO_RSA: return 'R' ;
case PUBKEY_ALGO_RSA_E: return 'r' ;
case PUBKEY_ALGO_RSA_S: return 's' ;
case PUBKEY_ALGO_ELGAMAL_E: return 'g';
case PUBKEY_ALGO_ELGAMAL: return 'G' ;
case PUBKEY_ALGO_DSA: return 'D' ;
+ case PUBKEY_ALGO_ECDSA: return 'E' ; // ECC DSA (sign only)
+ case PUBKEY_ALGO_ECDH: return 'e' ; // ECC DH (encrypt only)
default: return '?';
}
}
/* Hash a public key. This function is useful for v4 fingerprints and
for v3 or v4 key signing. */
void
hash_public_key (gcry_md_hd_t md, PKT_public_key *pk)
{
unsigned int n = 6;
unsigned int nn[PUBKEY_MAX_NPKEY];
byte *pp[PUBKEY_MAX_NPKEY];
int i;
unsigned int nbits;
size_t nbytes;
int npkey = pubkey_get_npkey (pk->pubkey_algo);
+ /* name OID, MPI of public point, [for ECDH only: KEK params] */
+ enum gcry_mpi_format ecc_pub_format[3] = {GCRYMPI_FMT_USG, GCRYMPI_FMT_PGP, GCRYMPI_FMT_USG};
/* Two extra bytes for the expiration date in v3 */
if(pk->version<4)
n+=2;
if (npkey==0 && pk->pkey[0]
&& gcry_mpi_get_flag (pk->pkey[0], GCRYMPI_FLAG_OPAQUE))
{
pp[0] = gcry_mpi_get_opaque (pk->pkey[0], &nbits);
nn[0] = (nbits+7)/8;
n+=nn[0];
}
else
{
for(i=0; i < npkey; i++ )
{
- if (gcry_mpi_print (GCRYMPI_FMT_PGP, NULL, 0, &nbytes, pk->pkey[i]))
+ const enum gcry_mpi_format fmt =
+ ((pk->pubkey_algo==PUBKEY_ALGO_ECDSA || pk->pubkey_algo==PUBKEY_ALGO_ECDH) ? ecc_pub_format[i] : GCRYMPI_FMT_PGP);
+
+ if (gcry_mpi_print (fmt, NULL, 0, &nbytes, pk->pkey[i]))
BUG ();
pp[i] = xmalloc (nbytes);
- if (gcry_mpi_print (GCRYMPI_FMT_PGP, pp[i], nbytes,
- &nbytes, pk->pkey[i]))
+ if (gcry_mpi_print (fmt, pp[i], nbytes, &nbytes, pk->pkey[i]))
BUG ();
nn[i] = nbytes;
n += nn[i];
}
}
gcry_md_putc ( md, 0x99 ); /* ctb */
/* What does it mean if n is greater than than 0xFFFF ? */
gcry_md_putc ( md, n >> 8 ); /* 2 byte length header */
gcry_md_putc ( md, n );
gcry_md_putc ( md, pk->version );
gcry_md_putc ( md, pk->timestamp >> 24 );
gcry_md_putc ( md, pk->timestamp >> 16 );
gcry_md_putc ( md, pk->timestamp >> 8 );
gcry_md_putc ( md, pk->timestamp );
if(pk->version<4)
{
u16 days=0;
if(pk->expiredate)
days=(u16)((pk->expiredate - pk->timestamp) / 86400L);
gcry_md_putc ( md, days >> 8 );
gcry_md_putc ( md, days );
}
gcry_md_putc ( md, pk->pubkey_algo );
if(npkey==0 && pk->pkey[0]
&& gcry_mpi_get_flag (pk->pkey[0], GCRYMPI_FLAG_OPAQUE))
{
gcry_md_write (md, pp[0], nn[0]);
}
else
for(i=0; i < npkey; i++ )
{
gcry_md_write ( md, pp[i], nn[i] );
xfree(pp[i]);
}
}
static gcry_md_hd_t
do_fingerprint_md( PKT_public_key *pk )
{
gcry_md_hd_t md;
if (gcry_md_open (&md, DIGEST_ALGO_SHA1, 0))
BUG ();
hash_public_key(md,pk);
gcry_md_final( md );
return md;
}
/* fixme: Check whether we can replace this function or if not
describe why we need it. */
u32
v3_keyid (gcry_mpi_t a, u32 *ki)
{
byte *buffer, *p;
size_t nbytes;
if (gcry_mpi_print (GCRYMPI_FMT_USG, NULL, 0, &nbytes, a ))
BUG ();
/* fixme: allocate it on the stack */
buffer = xmalloc (nbytes);
if (gcry_mpi_print( GCRYMPI_FMT_USG, buffer, nbytes, NULL, a ))
BUG ();
if (nbytes < 8) /* oops */
ki[0] = ki[1] = 0;
else
{
p = buffer + nbytes - 8;
ki[0] = (p[0] << 24) | (p[1] <<16) | (p[2] << 8) | p[3];
p += 4;
ki[1] = (p[0] << 24) | (p[1] <<16) | (p[2] << 8) | p[3];
}
xfree (buffer);
return ki[1];
}
size_t
keystrlen(void)
{
switch(opt.keyid_format)
{
case KF_SHORT:
return 8;
case KF_LONG:
return 16;
case KF_0xSHORT:
return 10;
case KF_0xLONG:
return 18;
default:
BUG();
}
}
const char *
keystr (u32 *keyid)
{
static char keyid_str[KEYID_STR_SIZE];
switch (opt.keyid_format)
{
case KF_SHORT:
snprintf (keyid_str, sizeof keyid_str, "%08lX", (ulong)keyid[1]);
break;
case KF_LONG:
if (keyid[0])
snprintf (keyid_str, sizeof keyid_str, "%08lX%08lX",
(ulong)keyid[0], (ulong)keyid[1]);
else
snprintf (keyid_str, sizeof keyid_str, "%08lX", (ulong)keyid[1]);
break;
case KF_0xSHORT:
snprintf (keyid_str, sizeof keyid_str, "0x%08lX", (ulong)keyid[1]);
break;
case KF_0xLONG:
if(keyid[0])
snprintf (keyid_str, sizeof keyid_str, "0x%08lX%08lX",
(ulong)keyid[0],(ulong)keyid[1]);
else
snprintf (keyid_str, sizeof keyid_str, "0x%08lX", (ulong)keyid[1]);
break;
default:
BUG();
}
return keyid_str;
}
const char *
keystr_with_sub (u32 *main_kid, u32 *sub_kid)
{
static char buffer[KEYID_STR_SIZE+1+KEYID_STR_SIZE];
char *p;
mem2str (buffer, keystr (main_kid), KEYID_STR_SIZE);
if (sub_kid)
{
p = buffer + strlen (buffer);
*p++ = '/';
mem2str (p, keystr (sub_kid), KEYID_STR_SIZE);
}
return buffer;
}
const char *
keystr_from_pk(PKT_public_key *pk)
{
keyid_from_pk(pk,NULL);
return keystr(pk->keyid);
}
const char *
keystr_from_pk_with_sub (PKT_public_key *main_pk, PKT_public_key *sub_pk)
{
keyid_from_pk (main_pk, NULL);
if (sub_pk)
keyid_from_pk (sub_pk, NULL);
return keystr_with_sub (main_pk->keyid, sub_pk? sub_pk->keyid:NULL);
}
const char *
keystr_from_desc(KEYDB_SEARCH_DESC *desc)
{
switch(desc->mode)
{
case KEYDB_SEARCH_MODE_LONG_KID:
case KEYDB_SEARCH_MODE_SHORT_KID:
return keystr(desc->u.kid);
case KEYDB_SEARCH_MODE_FPR20:
{
u32 keyid[2];
keyid[0] = ((unsigned char)desc->u.fpr[12] << 24
| (unsigned char)desc->u.fpr[13] << 16
| (unsigned char)desc->u.fpr[14] << 8
| (unsigned char)desc->u.fpr[15]);
keyid[1] = ((unsigned char)desc->u.fpr[16] << 24
| (unsigned char)desc->u.fpr[17] << 16
| (unsigned char)desc->u.fpr[18] << 8
| (unsigned char)desc->u.fpr[19]);
return keystr(keyid);
}
case KEYDB_SEARCH_MODE_FPR16:
return "?v3 fpr?";
default:
BUG();
}
}
/*
* Get the keyid from the public key and put it into keyid
* if this is not NULL. Return the 32 low bits of the keyid.
*/
u32
keyid_from_pk (PKT_public_key *pk, u32 *keyid)
{
u32 lowbits;
u32 dummy_keyid[2];
if (!keyid)
keyid = dummy_keyid;
if( pk->keyid[0] || pk->keyid[1] )
{
keyid[0] = pk->keyid[0];
keyid[1] = pk->keyid[1];
lowbits = keyid[1];
}
else if( pk->version < 4 )
{
if( is_RSA(pk->pubkey_algo) )
{
lowbits = (pubkey_get_npkey (pk->pubkey_algo) ?
v3_keyid ( pk->pkey[0], keyid ) : 0); /* From n. */
pk->keyid[0] = keyid[0];
pk->keyid[1] = keyid[1];
}
else
pk->keyid[0]=pk->keyid[1]=keyid[0]=keyid[1]=lowbits=0xFFFFFFFF;
}
else
{
const byte *dp;
gcry_md_hd_t md;
md = do_fingerprint_md(pk);
if(md)
{
dp = gcry_md_read ( md, 0 );
keyid[0] = dp[12] << 24 | dp[13] << 16 | dp[14] << 8 | dp[15] ;
keyid[1] = dp[16] << 24 | dp[17] << 16 | dp[18] << 8 | dp[19] ;
lowbits = keyid[1];
gcry_md_close (md);
pk->keyid[0] = keyid[0];
pk->keyid[1] = keyid[1];
}
else
pk->keyid[0]=pk->keyid[1]=keyid[0]=keyid[1]=lowbits=0xFFFFFFFF;
}
return lowbits;
}
/*
* Get the keyid from the fingerprint. This function is simple for most
* keys, but has to do a keylookup for old stayle keys.
*/
u32
keyid_from_fingerprint( const byte *fprint, size_t fprint_len, u32 *keyid )
{
u32 dummy_keyid[2];
if( !keyid )
keyid = dummy_keyid;
if (fprint_len != 20)
{
/* This is special as we have to lookup the key first. */
PKT_public_key pk;
int rc;
memset (&pk, 0, sizeof pk);
rc = get_pubkey_byfprint (&pk, fprint, fprint_len);
if( rc )
{
log_error("Oops: keyid_from_fingerprint: no pubkey\n");
keyid[0] = 0;
keyid[1] = 0;
}
else
keyid_from_pk (&pk, keyid);
}
else
{
const byte *dp = fprint;
keyid[0] = dp[12] << 24 | dp[13] << 16 | dp[14] << 8 | dp[15] ;
keyid[1] = dp[16] << 24 | dp[17] << 16 | dp[18] << 8 | dp[19] ;
}
return keyid[1];
}
u32
keyid_from_sig (PKT_signature *sig, u32 *keyid)
{
if( keyid )
{
keyid[0] = sig->keyid[0];
keyid[1] = sig->keyid[1];
}
return sig->keyid[1];
}
byte *
namehash_from_uid (PKT_user_id *uid)
{
if (!uid->namehash)
{
uid->namehash = xmalloc (20);
if (uid->attrib_data)
rmd160_hash_buffer (uid->namehash, uid->attrib_data, uid->attrib_len);
else
rmd160_hash_buffer (uid->namehash, uid->name, uid->len);
}
return uid->namehash;
}
/*
* Return the number of bits used in PK.
*/
unsigned int
nbits_from_pk (PKT_public_key *pk)
{
return pubkey_nbits (pk->pubkey_algo, pk->pkey);
}
static const char *
mk_datestr (char *buffer, time_t atime)
{
struct tm *tp;
if (IS_INVALID_TIME_T (atime))
strcpy (buffer, "????" "-??" "-??"); /* Mark this as invalid. */
else
{
tp = gmtime (&atime);
sprintf (buffer,"%04d-%02d-%02d",
1900+tp->tm_year, tp->tm_mon+1, tp->tm_mday );
}
return buffer;
}
/*
* return a string with the creation date of the pk
* Note: this is alloced in a static buffer.
* Format is: yyyy-mm-dd
*/
const char *
datestr_from_pk (PKT_public_key *pk)
{
static char buffer[11+5];
time_t atime = pk->timestamp;
return mk_datestr (buffer, atime);
}
const char *
datestr_from_sig (PKT_signature *sig )
{
static char buffer[11+5];
time_t atime = sig->timestamp;
return mk_datestr (buffer, atime);
}
const char *
expirestr_from_pk (PKT_public_key *pk)
{
static char buffer[11+5];
time_t atime;
if (!pk->expiredate)
return _("never ");
atime = pk->expiredate;
return mk_datestr (buffer, atime);
}
const char *
expirestr_from_sig (PKT_signature *sig)
{
static char buffer[11+5];
time_t atime;
if (!sig->expiredate)
return _("never ");
atime=sig->expiredate;
return mk_datestr (buffer, atime);
}
const char *
revokestr_from_pk( PKT_public_key *pk )
{
static char buffer[11+5];
time_t atime;
if(!pk->revoked.date)
return _("never ");
atime=pk->revoked.date;
return mk_datestr (buffer, atime);
}
const char *
usagestr_from_pk( PKT_public_key *pk )
{
static char buffer[10];
int i = 0;
unsigned int use = pk->pubkey_usage;
if ( use & PUBKEY_USAGE_SIG )
buffer[i++] = 'S';
if ( use & PUBKEY_USAGE_CERT )
buffer[i++] = 'C';
if ( use & PUBKEY_USAGE_ENC )
buffer[i++] = 'E';
if ( (use & PUBKEY_USAGE_AUTH) )
buffer[i++] = 'A';
while (i < 4)
buffer[i++] = ' ';
buffer[i] = 0;
return buffer;
}
const char *
colon_strtime (u32 t)
{
static char buf[20];
if (!t)
return "";
snprintf (buf, sizeof buf, "%lu", (ulong)t);
return buf;
}
const char *
colon_datestr_from_pk (PKT_public_key *pk)
{
static char buf[20];
snprintf (buf, sizeof buf, "%lu", (ulong)pk->timestamp);
return buf;
}
const char *
colon_datestr_from_sig (PKT_signature *sig)
{
static char buf[20];
snprintf (buf, sizeof buf, "%lu", (ulong)sig->timestamp);
return buf;
}
const char *
colon_expirestr_from_sig (PKT_signature *sig)
{
static char buf[20];
if (!sig->expiredate)
return "";
snprintf (buf, sizeof buf,"%lu", (ulong)sig->expiredate);
return buf;
}
/*
* Return a byte array with the fingerprint for the given PK/SK
* The length of the array is returned in ret_len. Caller must free
* the array or provide an array of length MAX_FINGERPRINT_LEN.
*/
byte *
fingerprint_from_pk (PKT_public_key *pk, byte *array, size_t *ret_len)
{
byte *buf;
const byte *dp;
size_t len, nbytes;
int i;
if ( pk->version < 4 )
{
if ( is_RSA(pk->pubkey_algo) )
{
/* RSA in version 3 packets is special. */
gcry_md_hd_t md;
if (gcry_md_open (&md, DIGEST_ALGO_MD5, 0))
BUG ();
if ( pubkey_get_npkey (pk->pubkey_algo) > 1 )
{
for (i=0; i < 2; i++)
{
if (gcry_mpi_print (GCRYMPI_FMT_USG, NULL, 0,
&nbytes, pk->pkey[i]))
BUG ();
/* fixme: Better allocate BUF on the stack */
buf = xmalloc (nbytes);
if (gcry_mpi_print (GCRYMPI_FMT_USG, buf, nbytes,
NULL, pk->pkey[i]))
BUG ();
gcry_md_write (md, buf, nbytes);
xfree (buf);
}
}
gcry_md_final (md);
if (!array)
array = xmalloc (16);
len = 16;
memcpy (array, gcry_md_read (md, DIGEST_ALGO_MD5), 16);
gcry_md_close(md);
}
else
{
if (!array)
array = xmalloc(16);
len = 16;
memset (array,0,16);
}
}
else
{
gcry_md_hd_t md;
md = do_fingerprint_md(pk);
dp = gcry_md_read( md, 0 );
len = gcry_md_get_algo_dlen (gcry_md_get_algo (md));
assert( len <= MAX_FINGERPRINT_LEN );
if (!array)
array = xmalloc ( len );
memcpy (array, dp, len );
pk->keyid[0] = dp[12] << 24 | dp[13] << 16 | dp[14] << 8 | dp[15] ;
pk->keyid[1] = dp[16] << 24 | dp[17] << 16 | dp[18] << 8 | dp[19] ;
gcry_md_close( md);
}
*ret_len = len;
return array;
}
/* Return the so called KEYGRIP which is the SHA-1 hash of the public
key parameters expressed as an canoncial encoded S-Exp. ARRAY must
be 20 bytes long. Returns 0 on sucess or an error code. */
gpg_error_t
keygrip_from_pk (PKT_public_key *pk, unsigned char *array)
{
gpg_error_t err;
gcry_sexp_t s_pkey;
if (DBG_PACKET)
log_debug ("get_keygrip for public key\n");
switch (pk->pubkey_algo)
{
case GCRY_PK_DSA:
err = gcry_sexp_build (&s_pkey, NULL,
"(public-key(dsa(p%m)(q%m)(g%m)(y%m)))",
pk->pkey[0], pk->pkey[1],
pk->pkey[2], pk->pkey[3]);
break;
case GCRY_PK_ELG:
case GCRY_PK_ELG_E:
err = gcry_sexp_build (&s_pkey, NULL,
"(public-key(elg(p%m)(g%m)(y%m)))",
pk->pkey[0], pk->pkey[1], pk->pkey[2]);
break;
case GCRY_PK_RSA:
case GCRY_PK_RSA_S:
case GCRY_PK_RSA_E:
err = gcry_sexp_build (&s_pkey, NULL,
"(public-key(rsa(n%m)(e%m)))",
pk->pkey[0], pk->pkey[1]);
break;
+ case PUBKEY_ALGO_ECDSA:
+ case PUBKEY_ALGO_ECDH:
+ err = gcry_sexp_build (&s_pkey, NULL,
+ "(public-key(ecc(c%m)(q%m)))",
+ pk->pkey[0], pk->pkey[1]);
+ break;
+/*
+ case PUBKEY_ALGO_ECDH:
+ err = gcry_sexp_build (&s_pkey, NULL,
+ "(public-key(ecdh(c%m)(q%m)(p%m)))",
+ pk->pkey[0], pk->pkey[1], pk->pkey[2]);
+ break;
+*/
+
default:
err = gpg_error (GPG_ERR_PUBKEY_ALGO);
break;
}
if (err)
return err;
if (!gcry_pk_get_keygrip (s_pkey, array))
{
log_error ("error computing keygrip\n");
err = gpg_error (GPG_ERR_GENERAL);
}
else
{
if (DBG_PACKET)
log_printhex ("keygrip=", array, 20);
/* FIXME: Save the keygrip in PK. */
}
gcry_sexp_release (s_pkey);
return 0;
}
/* Store an allocated buffer with the keygrip of PK encoded as a
hexstring at r_GRIP. Returns 0 on success. */
gpg_error_t
hexkeygrip_from_pk (PKT_public_key *pk, char **r_grip)
{
gpg_error_t err;
unsigned char grip[20];
*r_grip = NULL;
err = keygrip_from_pk (pk, grip);
if (!err)
{
char * buf = xtrymalloc (20*2+1);
if (!buf)
err = gpg_error_from_syserror ();
else
{
bin2hex (grip, 20, buf);
*r_grip = buf;
}
}
return err;
}
diff --git a/g10/main.h b/g10/main.h
index b673cf559..e336e5ce6 100644
--- a/g10/main.h
+++ b/g10/main.h
@@ -1,357 +1,366 @@
/* main.h
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
* 2008, 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
* 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
* along with this program; if not, see .
*/
#ifndef G10_MAIN_H
#define G10_MAIN_H
#include "types.h"
#include "iobuf.h"
#include "cipher.h"
#include "keydb.h"
#include "util.h"
/* It could be argued that the default cipher should be 3DES rather
than CAST5, and the default compression should be 0
(i.e. uncompressed) rather than 1 (zip). However, the real world
issues of speed and size come into play here. */
#define DEFAULT_CIPHER_ALGO CIPHER_ALGO_CAST5
#define DEFAULT_DIGEST_ALGO DIGEST_ALGO_SHA1
#define DEFAULT_S2K_DIGEST_ALGO DIGEST_ALGO_SHA1
#ifdef HAVE_ZIP
# define DEFAULT_COMPRESS_ALGO COMPRESS_ALGO_ZIP
#else
# define DEFAULT_COMPRESS_ALGO COMPRESS_ALGO_NONE
#endif
#define S2K_DIGEST_ALGO (opt.s2k_digest_algo?opt.s2k_digest_algo:DEFAULT_S2K_DIGEST_ALGO)
typedef struct
{
int header_okay;
PK_LIST pk_list;
DEK *symkey_dek;
STRING2KEY *symkey_s2k;
cipher_filter_context_t cfx;
} encrypt_filter_context_t;
struct groupitem
{
char *name;
strlist_t values;
struct groupitem *next;
};
/*-- gpg.c --*/
extern int g10_errors_seen;
#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 5 )
void g10_exit(int rc) __attribute__ ((noreturn));
#else
void g10_exit(int rc);
#endif
void print_pubkey_algo_note( int algo );
void print_cipher_algo_note( int algo );
void print_digest_algo_note( int algo );
/*-- armor.c --*/
char *make_radix64_string( const byte *data, size_t len );
/*-- misc.c --*/
void trap_unaligned(void);
int disable_core_dumps(void);
void register_secured_file (const char *fname);
void unregister_secured_file (const char *fname);
int is_secured_file (int fd);
int is_secured_filename (const char *fname);
u16 checksum_u16( unsigned n );
u16 checksum( byte *p, unsigned n );
u16 checksum_mpi( gcry_mpi_t a );
u32 buffer_to_u32( const byte *buffer );
const byte *get_session_marker( size_t *rlen );
int map_cipher_openpgp_to_gcry (int algo);
#define openpgp_cipher_open(_a,_b,_c,_d) gcry_cipher_open((_a),map_cipher_openpgp_to_gcry((_b)),(_c),(_d))
#define openpgp_cipher_get_algo_keylen(_a) gcry_cipher_get_algo_keylen(map_cipher_openpgp_to_gcry((_a)))
#define openpgp_cipher_get_algo_blklen(_a) gcry_cipher_get_algo_blklen(map_cipher_openpgp_to_gcry((_a)))
int openpgp_cipher_blocklen (int algo);
int openpgp_cipher_test_algo( int algo );
const char *openpgp_cipher_algo_name (int algo);
+int map_pk_openpgp_to_gcry (int algo);
int openpgp_pk_test_algo( int algo );
int openpgp_pk_test_algo2 ( int algo, unsigned int use );
int openpgp_pk_algo_usage ( int algo );
-const char *openpgp_pk_algo_name (int algo);
int openpgp_md_test_algo( int algo );
+const char *openpgp_pk_algo_name (int algo);
const char *openpgp_md_algo_name (int algo);
#ifdef USE_IDEA
void idea_cipher_warn( int show );
#else
#define idea_cipher_warn(a) do { } while (0)
#endif
struct expando_args
{
PKT_public_key *pk;
PKT_public_key *pksk;
byte imagetype;
int validity_info;
const char *validity_string;
};
char *pct_expando(const char *string,struct expando_args *args);
void deprecated_warning(const char *configname,unsigned int configlineno,
const char *option,const char *repl1,const char *repl2);
void deprecated_command (const char *name);
void obsolete_option (const char *configname, unsigned int configlineno,
const char *name);
int string_to_cipher_algo (const char *string);
int string_to_digest_algo (const char *string);
const char *compress_algo_to_string(int algo);
int string_to_compress_algo(const char *string);
int check_compress_algo(int algo);
int default_cipher_algo(void);
int default_compress_algo(void);
const char *compliance_option_string(void);
void compliance_failure(void);
struct parse_options
{
char *name;
unsigned int bit;
char **value;
char *help;
};
char *optsep(char **stringp);
char *argsplit(char *string);
int parse_options(char *str,unsigned int *options,
struct parse_options *opts,int noisy);
int has_invalid_email_chars (const char *s);
int is_valid_mailbox (const char *name);
const char *get_libexecdir (void);
int path_access(const char *file,int mode);
/* Temporary helpers. */
int pubkey_get_npkey( int algo );
int pubkey_get_nskey( int algo );
int pubkey_get_nsig( int algo );
int pubkey_get_nenc( int algo );
unsigned int pubkey_nbits( int algo, gcry_mpi_t *pkey );
int mpi_print (estream_t stream, gcry_mpi_t a, int mode);
+int iobuf_write_size_body_mpi (iobuf_t out, gcry_mpi_t a);
+int iobuf_read_size_body(iobuf_t inp, byte *body, int body_max_size, int pktlen, gcry_mpi_t *out);
+
+int ecdsa_qbits_from_Q( int qbits );
/*-- status.c --*/
void set_status_fd ( int fd );
int is_status_enabled ( void );
void write_status ( int no );
void write_status_error (const char *where, gpg_error_t err);
void write_status_errcode (const char *where, int errcode);
void write_status_text ( int no, const char *text );
void write_status_buffer ( int no,
const char *buffer, size_t len, int wrap );
void write_status_text_and_buffer ( int no, const char *text,
const char *buffer, size_t len, int wrap );
void write_status_begin_signing (gcry_md_hd_t md);
int cpr_enabled(void);
char *cpr_get( const char *keyword, const char *prompt );
char *cpr_get_no_help( const char *keyword, const char *prompt );
char *cpr_get_utf8( const char *keyword, const char *prompt );
char *cpr_get_hidden( const char *keyword, const char *prompt );
void cpr_kill_prompt(void);
int cpr_get_answer_is_yes( const char *keyword, const char *prompt );
int cpr_get_answer_yes_no_quit( const char *keyword, const char *prompt );
int cpr_get_answer_okay_cancel (const char *keyword,
const char *prompt,
int def_answer);
/*-- helptext.c --*/
void display_online_help( const char *keyword );
/*-- encode.c --*/
int setup_symkey (STRING2KEY **symkey_s2k,DEK **symkey_dek);
int encrypt_symmetric (const char *filename );
int encrypt_store (const char *filename );
int encrypt_crypt (ctrl_t ctrl, int filefd, const char *filename,
strlist_t remusr, int use_symkey, pk_list_t provided_keys,
int outputfd);
void encrypt_crypt_files (ctrl_t ctrl,
int nfiles, char **files, strlist_t remusr);
int encrypt_filter (void *opaque, int control,
iobuf_t a, byte *buf, size_t *ret_len);
/*-- sign.c --*/
int complete_sig (PKT_signature *sig, PKT_public_key *pksk, gcry_md_hd_t md,
const char *cache_nonce);
int sign_file (ctrl_t ctrl, strlist_t filenames, int detached, strlist_t locusr,
int do_encrypt, strlist_t remusr, const char *outfile );
int clearsign_file( const char *fname, strlist_t locusr, const char *outfile );
int sign_symencrypt_file (const char *fname, strlist_t locusr);
/*-- sig-check.c --*/
int check_revocation_keys (PKT_public_key *pk, PKT_signature *sig);
int check_backsig(PKT_public_key *main_pk,PKT_public_key *sub_pk,
PKT_signature *backsig);
int check_key_signature( KBNODE root, KBNODE node, int *is_selfsig );
int check_key_signature2( KBNODE root, KBNODE node, PKT_public_key *check_pk,
PKT_public_key *ret_pk, int *is_selfsig,
u32 *r_expiredate, int *r_expired );
/*-- delkey.c --*/
int delete_keys( strlist_t names, int secret, int allow_both );
/*-- keyedit.c --*/
void keyedit_menu (ctrl_t ctrl, const char *username, strlist_t locusr,
strlist_t commands, int quiet, int seckey_check );
void keyedit_passwd (ctrl_t ctrl, const char *username);
void show_basic_key_info (KBNODE keyblock);
/*-- keygen.c --*/
u32 parse_expire_string(const char *string);
u32 ask_expire_interval(int object,const char *def_expire);
u32 ask_expiredate(void);
void generate_keypair (const char *fname, const char *card_serialno,
int card_backup_key);
int keygen_set_std_prefs (const char *string,int personal);
PKT_user_id *keygen_get_std_prefs (void);
int keygen_add_key_expire( PKT_signature *sig, void *opaque );
int keygen_add_std_prefs( PKT_signature *sig, void *opaque );
int keygen_upd_std_prefs( PKT_signature *sig, void *opaque );
int keygen_add_keyserver_url(PKT_signature *sig, void *opaque);
int keygen_add_notations(PKT_signature *sig,void *opaque);
int keygen_add_revkey(PKT_signature *sig, void *opaque);
gpg_error_t make_backsig (PKT_signature *sig, PKT_public_key *pk,
PKT_public_key *sub_pk, PKT_public_key *sub_psk,
u32 timestamp, const char *cache_nonce);
gpg_error_t generate_subkeypair (kbnode_t pub_keyblock);
#ifdef ENABLE_CARD_SUPPORT
gpg_error_t generate_card_subkeypair (kbnode_t pub_keyblock,
int keyno, const char *serialno);
int save_unprotected_key_to_card (PKT_public_key *sk, int keyno);
#endif
+#define KEYGEN_FLAG_NO_PROTECTION 1
+#define KEYGEN_FLAG_TRANSIENT_KEY 2
+int pk_ecc_keypair_gen( PKT_public_key **pk_out, int algo, int keygen_flags, char **cache_nonce_addr, unsigned nbits);
+
/*-- openfile.c --*/
int overwrite_filep( const char *fname );
char *make_outfile_name( const char *iname );
char *ask_outfile_name( const char *name, size_t namelen );
int open_outfile (int inp_fd, const char *iname, int mode, iobuf_t *a);
iobuf_t open_sigfile( const char *iname, progress_filter_context_t *pfx );
void try_make_homedir( const char *fname );
/*-- seskey.c --*/
void make_session_key( DEK *dek );
-gcry_mpi_t encode_session_key( DEK *dek, unsigned nbits );
+gcry_mpi_t encode_session_key( int openpgp_pk_algo, DEK *dek, unsigned nbits );
gcry_mpi_t encode_md_value (PKT_public_key *pk,
gcry_md_hd_t md, int hash_algo );
/*-- import.c --*/
int parse_import_options(char *str,unsigned int *options,int noisy);
void import_keys (ctrl_t ctrl, char **fnames, int nnames,
void *stats_hd, unsigned int options);
int import_keys_stream (ctrl_t ctrl, iobuf_t inp, void *stats_hd,
unsigned char **fpr,
size_t *fpr_len, unsigned int options);
void *import_new_stats_handle (void);
void import_release_stats_handle (void *p);
void import_print_stats (void *hd);
int collapse_uids( KBNODE *keyblock );
/*-- export.c --*/
int parse_export_options(char *str,unsigned int *options,int noisy);
int export_pubkeys (ctrl_t ctrl, strlist_t users, unsigned int options );
int export_pubkeys_stream (ctrl_t ctrl, iobuf_t out, strlist_t users,
kbnode_t *keyblock_out, unsigned int options );
int export_seckeys (ctrl_t ctrl, strlist_t users);
int export_secsubkeys (ctrl_t ctrl, strlist_t users);
/* dearmor.c --*/
int dearmor_file( const char *fname );
int enarmor_file( const char *fname );
/*-- revoke.c --*/
struct revocation_reason_info;
int gen_revoke( const char *uname );
int gen_desig_revoke( const char *uname, strlist_t locusr);
int revocation_reason_build_cb( PKT_signature *sig, void *opaque );
struct revocation_reason_info *
ask_revocation_reason( int key_rev, int cert_rev, int hint );
void release_revocation_reason_info( struct revocation_reason_info *reason );
/*-- keylist.c --*/
void public_key_list (ctrl_t ctrl, strlist_t list, int locate_mode );
void secret_key_list (ctrl_t ctrl, strlist_t list );
void print_subpackets_colon(PKT_signature *sig);
void reorder_keyblock (KBNODE keyblock);
void list_keyblock( KBNODE keyblock, int secret, int fpr, void *opaque );
void print_fingerprint (PKT_public_key *pk, int mode);
void print_revokers(PKT_public_key *pk);
void show_policy_url(PKT_signature *sig,int indent,int mode);
void show_keyserver_url(PKT_signature *sig,int indent,int mode);
void show_notation(PKT_signature *sig,int indent,int mode,int which);
void dump_attribs (const PKT_user_id *uid, PKT_public_key *pk);
void set_attrib_fd(int fd);
void print_seckey_info (PKT_public_key *pk);
void print_pubkey_info (estream_t fp, PKT_public_key *pk);
void print_card_key_info (estream_t fp, KBNODE keyblock);
/*-- verify.c --*/
void print_file_status( int status, const char *name, int what );
int verify_signatures (ctrl_t ctrl, int nfiles, char **files );
int verify_files (ctrl_t ctrl, int nfiles, char **files );
int gpg_verify (ctrl_t ctrl, int sig_fd, int data_fd, estream_t out_fp);
/*-- decrypt.c --*/
int decrypt_message (ctrl_t ctrl, const char *filename );
gpg_error_t decrypt_message_fd (ctrl_t ctrl, int input_fd, int output_fd);
void decrypt_messages (ctrl_t ctrl, int nfiles, char *files[]);
/*-- plaintext.c --*/
int hash_datafiles( gcry_md_hd_t md, gcry_md_hd_t md2,
strlist_t files, const char *sigfilename, int textmode );
int hash_datafile_by_fd ( gcry_md_hd_t md, gcry_md_hd_t md2, int data_fd,
int textmode );
PKT_plaintext *setup_plaintext_name(const char *filename,IOBUF iobuf);
/*-- signal.c --*/
void init_signals(void);
void block_all_signals(void);
void unblock_all_signals(void);
/*-- server.c --*/
int gpg_server (ctrl_t);
#ifdef ENABLE_CARD_SUPPORT
/*-- card-util.c --*/
void change_pin (int no, int allow_admin);
void card_status (estream_t fp, char *serialno, size_t serialnobuflen);
void card_edit (ctrl_t ctrl, strlist_t commands);
gpg_error_t card_generate_subkey (KBNODE pub_keyblock);
int card_store_subkey (KBNODE node, int use);
#endif
#define S2K_DECODE_COUNT(_val) ((16ul + ((_val) & 15)) << (((_val) >> 4) + 6))
#endif /*G10_MAIN_H*/
diff --git a/g10/mainproc.c b/g10/mainproc.c
index 72cefce43..dcbc4b45a 100644
--- a/g10/mainproc.c
+++ b/g10/mainproc.c
@@ -1,2208 +1,2210 @@
/* mainproc.c - handle packets
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
* 2008, 2009 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
* 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
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include
#include "gpg.h"
#include "util.h"
#include "packet.h"
#include "iobuf.h"
#include "options.h"
#include "cipher.h"
#include "keydb.h"
#include "filter.h"
#include "main.h"
#include "status.h"
#include "i18n.h"
#include "trustdb.h"
#include "keyserver-internal.h"
#include "photoid.h"
#include "pka.h"
struct kidlist_item {
struct kidlist_item *next;
u32 kid[2];
int pubkey_algo;
int reason;
};
/****************
* Structure to hold the context
*/
typedef struct mainproc_context *CTX;
struct mainproc_context
{
ctrl_t ctrl;
struct mainproc_context *anchor; /* May be useful in the future. */
PKT_public_key *last_pubkey;
PKT_user_id *last_user_id;
md_filter_context_t mfx;
int sigs_only; /* Process only signatures and reject all other stuff. */
int encrypt_only; /* Process only encryption messages. */
/* Name of the file with the complete signature or the file with the
detached signature. This is currently only used to deduce the
file name of the data file if that has not been given. */
const char *sigfilename;
/* A structure to describe the signed data in case of a detached
signature. */
struct
{
/* A file descriptor of the the signed data. Only used if not -1. */
int data_fd;
/* A list of filenames with the data files or NULL. This is only
used if DATA_FD is -1. */
strlist_t data_names;
/* Flag to indicated that either one of the next previous fields
is used. This is only needed for better readability. */
int used;
} signed_data;
DEK *dek;
int last_was_session_key;
KBNODE list; /* The current list of packets. */
int have_data;
IOBUF iobuf; /* Used to get the filename etc. */
int trustletter; /* Temporary usage in list_node. */
ulong symkeys;
struct kidlist_item *pkenc_list; /* List of encryption packets. */
int any_sig_seen; /* Set to true if a signature packet has been seen. */
};
static int do_proc_packets( CTX c, IOBUF a );
static void list_node( CTX c, KBNODE node );
static void proc_tree( CTX c, KBNODE node );
static int literals_seen;
void
reset_literals_seen(void)
{
literals_seen=0;
}
static void
release_list( CTX c )
{
if( !c->list )
return;
proc_tree(c, c->list );
release_kbnode( c->list );
while( c->pkenc_list ) {
struct kidlist_item *tmp = c->pkenc_list->next;
xfree( c->pkenc_list );
c->pkenc_list = tmp;
}
c->pkenc_list = NULL;
c->list = NULL;
c->have_data = 0;
c->last_was_session_key = 0;
xfree(c->dek); c->dek = NULL;
}
static int
add_onepass_sig( CTX c, PACKET *pkt )
{
KBNODE node;
if ( c->list ) /* add another packet */
add_kbnode( c->list, new_kbnode( pkt ));
else /* insert the first one */
c->list = node = new_kbnode( pkt );
return 1;
}
static int
add_gpg_control( CTX c, PACKET *pkt )
{
if ( pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START ) {
/* New clear text signature.
* Process the last one and reset everything */
release_list(c);
}
if( c->list ) /* add another packet */
add_kbnode( c->list, new_kbnode( pkt ));
else /* insert the first one */
c->list = new_kbnode( pkt );
return 1;
}
static int
add_user_id( CTX c, PACKET *pkt )
{
if( !c->list ) {
log_error("orphaned user ID\n" );
return 0;
}
add_kbnode( c->list, new_kbnode( pkt ) );
return 1;
}
static int
add_subkey( CTX c, PACKET *pkt )
{
if( !c->list ) {
log_error("subkey w/o mainkey\n" );
return 0;
}
add_kbnode( c->list, new_kbnode( pkt ) );
return 1;
}
static int
add_ring_trust( CTX c, PACKET *pkt )
{
if( !c->list ) {
log_error("ring trust w/o key\n" );
return 0;
}
add_kbnode( c->list, new_kbnode( pkt ) );
return 1;
}
static int
add_signature( CTX c, PACKET *pkt )
{
KBNODE node;
c->any_sig_seen = 1;
if( pkt->pkttype == PKT_SIGNATURE && !c->list ) {
/* This is the first signature for the following datafile.
* GPG does not write such packets; instead it always uses
* onepass-sig packets. The drawback of PGP's method
* of prepending the signature to the data is
* that it is not possible to make a signature from data read
* from stdin. (GPG is able to read PGP stuff anyway.) */
node = new_kbnode( pkt );
c->list = node;
return 1;
}
else if( !c->list )
return 0; /* oops (invalid packet sequence)*/
else if( !c->list->pkt )
BUG(); /* so nicht */
/* add a new signature node id at the end */
node = new_kbnode( pkt );
add_kbnode( c->list, node );
return 1;
}
static int
symkey_decrypt_seskey( DEK *dek, byte *seskey, size_t slen )
{
gcry_cipher_hd_t hd;
if(slen < 17 || slen > 33)
{
log_error ( _("weird size for an encrypted session key (%d)\n"),
(int)slen);
return G10ERR_BAD_KEY;
}
if (openpgp_cipher_open (&hd, dek->algo, GCRY_CIPHER_MODE_CFB, 1))
BUG ();
if (gcry_cipher_setkey ( hd, dek->key, dek->keylen ))
BUG ();
gcry_cipher_setiv ( hd, NULL, 0 );
gcry_cipher_decrypt ( hd, seskey, slen, NULL, 0 );
gcry_cipher_close ( hd );
/* Now we replace the dek components with the real session key to
decrypt the contents of the sequencing packet. */
dek->keylen=slen-1;
dek->algo=seskey[0];
if(dek->keylen > DIM(dek->key))
BUG ();
/* This is not completely accurate, since a bad passphrase may have
resulted in a garbage algorithm byte, but it's close enough since
a bogus byte here will fail later. */
if(dek->algo==CIPHER_ALGO_IDEA)
idea_cipher_warn(0);
memcpy(dek->key, seskey + 1, dek->keylen);
/*log_hexdump( "thekey", dek->key, dek->keylen );*/
return 0;
}
static void
proc_symkey_enc( CTX c, PACKET *pkt )
{
PKT_symkey_enc *enc;
enc = pkt->pkt.symkey_enc;
if (!enc)
log_error ("invalid symkey encrypted packet\n");
else if(!c->dek)
{
int algo = enc->cipher_algo;
const char *s = openpgp_cipher_algo_name (algo);
if (!openpgp_cipher_test_algo (algo))
{
if(!opt.quiet)
{
if(enc->seskeylen)
log_info(_("%s encrypted session key\n"), s );
else
log_info(_("%s encrypted data\n"), s );
}
}
else
log_error(_("encrypted with unknown algorithm %d\n"), algo );
if(openpgp_md_test_algo (enc->s2k.hash_algo))
{
log_error(_("passphrase generated with unknown digest"
" algorithm %d\n"),enc->s2k.hash_algo);
s=NULL;
}
c->last_was_session_key = 2;
if(!s || opt.list_only)
goto leave;
if(opt.override_session_key)
{
c->dek = xmalloc_clear( sizeof *c->dek );
if(get_override_session_key(c->dek, opt.override_session_key))
{
xfree(c->dek);
c->dek = NULL;
}
}
else
{
c->dek = passphrase_to_dek (NULL, 0, algo, &enc->s2k, 3,
NULL, NULL);
if(c->dek)
{
c->dek->symmetric=1;
/* FIXME: This doesn't work perfectly if a symmetric
key comes before a public key in the message - if
the user doesn't know the passphrase, then there is
a chance that the "decrypted" algorithm will happen
to be a valid one, which will make the returned dek
appear valid, so we won't try any public keys that
come later. */
if(enc->seskeylen)
{
if(symkey_decrypt_seskey(c->dek, enc->seskey,
enc->seskeylen))
{
xfree(c->dek);
c->dek=NULL;
}
}
else
c->dek->algo_info_printed = 1;
}
}
}
leave:
c->symkeys++;
free_packet(pkt);
}
static void
proc_pubkey_enc( CTX c, PACKET *pkt )
{
PKT_pubkey_enc *enc;
int result = 0;
/* check whether the secret key is available and store in this case */
c->last_was_session_key = 1;
enc = pkt->pkt.pubkey_enc;
/*printf("enc: encrypted by a pubkey with keyid %08lX\n", enc->keyid[1] );*/
/* Hmmm: why do I have this algo check here - anyway there is
* function to check it. */
if( opt.verbose )
log_info(_("public key is %s\n"), keystr(enc->keyid) );
if( is_status_enabled() ) {
char buf[50];
/* FIXME: For ECC support we need to map the OpenPGP algo
number to the Libgcrypt definef one. This is due a
chicken-egg problem: We need to have code in libgcrypt for
a new algorithm so to implement a proposed new algorithm
before the IANA will finally assign an OpenPGP
indentifier. */
snprintf (buf, sizeof buf, "%08lX%08lX %d 0",
(ulong)enc->keyid[0], (ulong)enc->keyid[1], enc->pubkey_algo );
write_status_text( STATUS_ENC_TO, buf );
}
if( !opt.list_only && opt.override_session_key ) {
/* It does not make much sense to store the session key in
* secure memory because it has already been passed on the
* command line and the GCHQ knows about it. */
c->dek = xmalloc_clear( sizeof *c->dek );
result = get_override_session_key ( c->dek, opt.override_session_key );
if ( result ) {
xfree(c->dek); c->dek = NULL;
}
}
else if( is_ELGAMAL(enc->pubkey_algo)
|| enc->pubkey_algo == PUBKEY_ALGO_DSA
+ || enc->pubkey_algo == PUBKEY_ALGO_ECDSA
+ || enc->pubkey_algo == PUBKEY_ALGO_ECDH
|| is_RSA(enc->pubkey_algo)
|| enc->pubkey_algo == PUBKEY_ALGO_ELGAMAL) {
/* Note that we also allow type 20 Elgamal keys for decryption.
There are still a couple of those keys in active use as a
subkey. */
/* FIXME: Store this all in a list and process it later so that
we can prioritize what key to use. This gives a better user
experience if wildcard keyids are used. */
if ( !c->dek && ((!enc->keyid[0] && !enc->keyid[1])
|| opt.try_all_secrets
|| have_secret_key_with_kid (enc->keyid)) ) {
if( opt.list_only )
result = -1;
else {
c->dek = xmalloc_secure_clear( sizeof *c->dek );
if( (result = get_session_key( enc, c->dek )) ) {
/* error: delete the DEK */
xfree(c->dek); c->dek = NULL;
}
}
}
else
result = G10ERR_NO_SECKEY;
}
else
result = G10ERR_PUBKEY_ALGO;
if( result == -1 )
;
else
{
/* store it for later display */
struct kidlist_item *x = xmalloc( sizeof *x );
x->kid[0] = enc->keyid[0];
x->kid[1] = enc->keyid[1];
x->pubkey_algo = enc->pubkey_algo;
x->reason = result;
x->next = c->pkenc_list;
c->pkenc_list = x;
if( !result && opt.verbose > 1 )
log_info( _("public key encrypted data: good DEK\n") );
}
free_packet(pkt);
}
/****************
* Print the list of public key encrypted packets which we could
* not decrypt.
*/
static void
print_pkenc_list( struct kidlist_item *list, int failed )
{
for( ; list; list = list->next ) {
PKT_public_key *pk;
const char *algstr;
if ( failed && !list->reason )
continue;
if ( !failed && list->reason )
continue;
- algstr = gcry_pk_algo_name ( list->pubkey_algo );
+ algstr = openpgp_pk_algo_name ( list->pubkey_algo );
pk = xmalloc_clear( sizeof *pk );
if( !algstr )
algstr = "[?]";
pk->pubkey_algo = list->pubkey_algo;
if( !get_pubkey( pk, list->kid ) )
{
char *p;
log_info( _("encrypted with %u-bit %s key, ID %s, created %s\n"),
nbits_from_pk( pk ), algstr, keystr_from_pk(pk),
strtimestamp(pk->timestamp) );
p=get_user_id_native(list->kid);
log_printf (_(" \"%s\"\n"),p);
xfree(p);
}
else
log_info(_("encrypted with %s key, ID %s\n"),
algstr,keystr(list->kid));
free_public_key( pk );
if( list->reason == G10ERR_NO_SECKEY ) {
if( is_status_enabled() ) {
char buf[20];
snprintf (buf, sizeof buf, "%08lX%08lX",
(ulong)list->kid[0], (ulong)list->kid[1]);
write_status_text( STATUS_NO_SECKEY, buf );
}
}
else if (list->reason)
{
log_info(_("public key decryption failed: %s\n"),
g10_errstr(list->reason));
write_status_error ("pkdecrypt_failed", list->reason);
}
}
}
static void
proc_encrypted( CTX c, PACKET *pkt )
{
int result = 0;
if (!opt.quiet)
{
if(c->symkeys>1)
log_info(_("encrypted with %lu passphrases\n"),c->symkeys);
else if(c->symkeys==1)
log_info(_("encrypted with 1 passphrase\n"));
print_pkenc_list ( c->pkenc_list, 1 );
print_pkenc_list ( c->pkenc_list, 0 );
}
/* FIXME: Figure out the session key by looking at all pkenc packets. */
write_status( STATUS_BEGIN_DECRYPTION );
/*log_debug("dat: %sencrypted data\n", c->dek?"":"conventional ");*/
if( opt.list_only )
result = -1;
else if( !c->dek && !c->last_was_session_key ) {
int algo;
STRING2KEY s2kbuf, *s2k = NULL;
if(opt.override_session_key)
{
c->dek = xmalloc_clear( sizeof *c->dek );
result=get_override_session_key(c->dek, opt.override_session_key);
if(result)
{
xfree(c->dek);
c->dek = NULL;
}
}
else
{
/* Assume this is old style conventional encrypted data. */
algo = opt.def_cipher_algo;
if ( algo )
log_info (_("assuming %s encrypted data\n"),
openpgp_cipher_algo_name (algo));
else if ( openpgp_cipher_test_algo (CIPHER_ALGO_IDEA) )
{
algo = opt.def_cipher_algo;
if (!algo)
algo = opt.s2k_cipher_algo;
idea_cipher_warn(1);
log_info (_("IDEA cipher unavailable, "
"optimistically attempting to use %s instead\n"),
openpgp_cipher_algo_name (algo));
}
else
{
algo = CIPHER_ALGO_IDEA;
if (!opt.s2k_digest_algo)
{
/* If no digest is given we assume MD5 */
s2kbuf.mode = 0;
s2kbuf.hash_algo = DIGEST_ALGO_MD5;
s2k = &s2kbuf;
}
log_info (_("assuming %s encrypted data\n"), "IDEA");
}
c->dek = passphrase_to_dek ( NULL, 0, algo, s2k, 3, NULL, NULL );
if (c->dek)
c->dek->algo_info_printed = 1;
}
}
else if( !c->dek )
result = G10ERR_NO_SECKEY;
if (!result)
result = decrypt_data (c->ctrl, c, pkt->pkt.encrypted, c->dek );
if( result == -1 )
;
else if( !result || (gpg_err_code (result) == GPG_ERR_BAD_SIGNATURE
&& opt.ignore_mdc_error)) {
write_status( STATUS_DECRYPTION_OKAY );
if( opt.verbose > 1 )
log_info(_("decryption okay\n"));
if( pkt->pkt.encrypted->mdc_method && !result )
write_status( STATUS_GOODMDC );
else if(!opt.no_mdc_warn)
log_info (_("WARNING: message was not integrity protected\n"));
if(opt.show_session_key)
{
int i;
char *buf = xmalloc ( c->dek->keylen*2 + 20 );
sprintf ( buf, "%d:", c->dek->algo );
for(i=0; i < c->dek->keylen; i++ )
sprintf(buf+strlen(buf), "%02X", c->dek->key[i] );
log_info( "session key: `%s'\n", buf );
write_status_text ( STATUS_SESSION_KEY, buf );
}
}
else if( result == G10ERR_BAD_SIGN ) {
glo_ctrl.lasterr = result;
log_error(_("WARNING: encrypted message has been manipulated!\n"));
write_status( STATUS_BADMDC );
write_status( STATUS_DECRYPTION_FAILED );
}
else {
if (gpg_err_code (result) == GPG_ERR_BAD_KEY
&& *c->dek->s2k_cacheid != '\0')
{
log_debug(_("cleared passphrase cached with ID: %s\n"),
c->dek->s2k_cacheid);
passphrase_clear_cache (NULL, c->dek->s2k_cacheid, 0);
}
glo_ctrl.lasterr = result;
write_status( STATUS_DECRYPTION_FAILED );
log_error(_("decryption failed: %s\n"), g10_errstr(result));
/* Hmmm: does this work when we have encrypted using multiple
* ways to specify the session key (symmmetric and PK)*/
}
xfree(c->dek); c->dek = NULL;
free_packet(pkt);
c->last_was_session_key = 0;
write_status( STATUS_END_DECRYPTION );
}
static void
proc_plaintext( CTX c, PACKET *pkt )
{
PKT_plaintext *pt = pkt->pkt.plaintext;
int any, clearsig, only_md5, rc;
KBNODE n;
literals_seen++;
if( pt->namelen == 8 && !memcmp( pt->name, "_CONSOLE", 8 ) )
log_info(_("NOTE: sender requested \"for-your-eyes-only\"\n"));
else if( opt.verbose )
log_info(_("original file name='%.*s'\n"), pt->namelen, pt->name);
free_md_filter_context( &c->mfx );
if (gcry_md_open (&c->mfx.md, 0, 0))
BUG ();
/* fixme: we may need to push the textfilter if we have sigclass 1
* and no armoring - Not yet tested
* Hmmm, why don't we need it at all if we have sigclass 1
* Should we assume that plaintext in mode 't' has always sigclass 1??
* See: Russ Allbery's mail 1999-02-09
*/
any = clearsig = only_md5 = 0;
for(n=c->list; n; n = n->next )
{
if( n->pkt->pkttype == PKT_ONEPASS_SIG )
{
/* For the onepass signature case */
if( n->pkt->pkt.onepass_sig->digest_algo )
{
gcry_md_enable (c->mfx.md,
n->pkt->pkt.onepass_sig->digest_algo);
if( !any && n->pkt->pkt.onepass_sig->digest_algo
== DIGEST_ALGO_MD5 )
only_md5 = 1;
else
only_md5 = 0;
any = 1;
}
if( n->pkt->pkt.onepass_sig->sig_class != 0x01 )
only_md5 = 0;
}
else if( n->pkt->pkttype == PKT_GPG_CONTROL
&& n->pkt->pkt.gpg_control->control
== CTRLPKT_CLEARSIGN_START )
{
/* For the clearsigned message case */
size_t datalen = n->pkt->pkt.gpg_control->datalen;
const byte *data = n->pkt->pkt.gpg_control->data;
/* check that we have at least the sigclass and one hash */
if ( datalen < 2 )
log_fatal("invalid control packet CTRLPKT_CLEARSIGN_START\n");
/* Note that we don't set the clearsig flag for not-dash-escaped
* documents */
clearsig = (*data == 0x01);
for( data++, datalen--; datalen; datalen--, data++ )
gcry_md_enable (c->mfx.md, *data);
any = 1;
break; /* Stop here as one-pass signature packets are not
expected. */
}
else if(n->pkt->pkttype==PKT_SIGNATURE)
{
/* For the SIG+LITERAL case that PGP used to use. */
gcry_md_enable ( c->mfx.md, n->pkt->pkt.signature->digest_algo );
any=1;
}
}
if( !any && !opt.skip_verify )
{
/* This is for the old GPG LITERAL+SIG case. It's not legal
according to 2440, so hopefully it won't come up that
often. There is no good way to specify what algorithms to
use in that case, so these three are the historical
answer. */
gcry_md_enable( c->mfx.md, DIGEST_ALGO_RMD160 );
gcry_md_enable( c->mfx.md, DIGEST_ALGO_SHA1 );
gcry_md_enable( c->mfx.md, DIGEST_ALGO_MD5 );
}
if( opt.pgp2_workarounds && only_md5 && !opt.skip_verify ) {
/* This is a kludge to work around a bug in pgp2. It does only
* catch those mails which are armored. To catch the non-armored
* pgp mails we could see whether there is the signature packet
* in front of the plaintext. If someone needs this, send me a patch.
*/
if ( gcry_md_open (&c->mfx.md2, DIGEST_ALGO_MD5, 0) )
BUG ();
}
if ( DBG_HASHING ) {
gcry_md_start_debug ( c->mfx.md, "verify" );
if ( c->mfx.md2 )
gcry_md_start_debug ( c->mfx.md2, "verify2" );
}
rc=0;
if (literals_seen>1)
{
log_info (_("WARNING: multiple plaintexts seen\n"));
if (!opt.flags.allow_multiple_messages)
{
write_status_text (STATUS_ERROR, "proc_pkt.plaintext 89_BAD_DATA");
log_inc_errorcount ();
rc = gpg_error (GPG_ERR_UNEXPECTED);
}
}
if(!rc)
{
rc = handle_plaintext( pt, &c->mfx, c->sigs_only, clearsig );
if ( gpg_err_code (rc) == GPG_ERR_EACCES && !c->sigs_only )
{
/* Can't write output but we hash it anyway to check the
signature. */
rc = handle_plaintext( pt, &c->mfx, 1, clearsig );
}
}
if( rc )
log_error( "handle plaintext failed: %s\n", g10_errstr(rc));
free_packet(pkt);
c->last_was_session_key = 0;
/* We add a marker control packet instead of the plaintext packet.
* This is so that we can later detect invalid packet sequences.
*/
n = new_kbnode (create_gpg_control (CTRLPKT_PLAINTEXT_MARK, NULL, 0));
if (c->list)
add_kbnode (c->list, n);
else
c->list = n;
}
static int
proc_compressed_cb( IOBUF a, void *info )
{
if ( ((CTX)info)->signed_data.used
&& ((CTX)info)->signed_data.data_fd != -1)
return proc_signature_packets_by_fd (((CTX)info)->ctrl, info, a,
((CTX)info)->signed_data.data_fd);
else
return proc_signature_packets (((CTX)info)->ctrl, info, a,
((CTX)info)->signed_data.data_names,
((CTX)info)->sigfilename );
}
static int
proc_encrypt_cb (IOBUF a, void *info )
{
CTX c = info;
return proc_encryption_packets (c->ctrl, info, a );
}
static void
proc_compressed( CTX c, PACKET *pkt )
{
PKT_compressed *zd = pkt->pkt.compressed;
int rc;
/*printf("zip: compressed data packet\n");*/
if( !zd->algorithm )
rc=G10ERR_COMPR_ALGO;
else if( c->sigs_only )
rc = handle_compressed (c->ctrl, c, zd, proc_compressed_cb, c );
else if( c->encrypt_only )
rc = handle_compressed (c->ctrl, c, zd, proc_encrypt_cb, c );
else
rc = handle_compressed (c->ctrl, c, zd, NULL, NULL );
if( rc )
log_error("uncompressing failed: %s\n", g10_errstr(rc));
free_packet(pkt);
c->last_was_session_key = 0;
}
/****************
* check the signature
* Returns: 0 = valid signature or an error code
*/
static int
do_check_sig( CTX c, KBNODE node, int *is_selfsig,
int *is_expkey, int *is_revkey )
{
PKT_signature *sig;
gcry_md_hd_t md = NULL, md2 = NULL;
int algo, rc;
assert( node->pkt->pkttype == PKT_SIGNATURE );
if( is_selfsig )
*is_selfsig = 0;
sig = node->pkt->pkt.signature;
algo = sig->digest_algo;
rc = openpgp_md_test_algo(algo);
if (rc)
return rc;
if( sig->sig_class == 0x00 ) {
if( c->mfx.md )
{
if (gcry_md_copy (&md, c->mfx.md ))
BUG ();
}
else /* detached signature */
{
/* signature_check() will enable the md*/
if (gcry_md_open (&md, 0, 0 ))
BUG ();
}
}
else if( sig->sig_class == 0x01 ) {
/* how do we know that we have to hash the (already hashed) text
* in canonical mode ??? (calculating both modes???) */
if( c->mfx.md ) {
if (gcry_md_copy (&md, c->mfx.md ))
BUG ();
if( c->mfx.md2 && gcry_md_copy (&md2, c->mfx.md2 ))
BUG ();
}
else { /* detached signature */
log_debug("Do we really need this here?");
/* signature_check() will enable the md*/
if (gcry_md_open (&md, 0, 0 ))
BUG ();
if (gcry_md_open (&md2, 0, 0 ))
BUG ();
}
}
else if( (sig->sig_class&~3) == 0x10
|| sig->sig_class == 0x18
|| sig->sig_class == 0x1f
|| sig->sig_class == 0x20
|| sig->sig_class == 0x28
|| sig->sig_class == 0x30 ) {
if( c->list->pkt->pkttype == PKT_PUBLIC_KEY
|| c->list->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
return check_key_signature( c->list, node, is_selfsig );
}
else if( sig->sig_class == 0x20 ) {
log_error (_("standalone revocation - "
"use \"gpg --import\" to apply\n"));
return G10ERR_NOT_PROCESSED;
}
else {
log_error("invalid root packet for sigclass %02x\n",
sig->sig_class);
return G10ERR_SIG_CLASS;
}
}
else
return G10ERR_SIG_CLASS;
rc = signature_check2( sig, md, NULL, is_expkey, is_revkey, NULL );
if( gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE && md2 )
rc = signature_check2( sig, md2, NULL, is_expkey, is_revkey, NULL );
gcry_md_close(md);
gcry_md_close(md2);
return rc;
}
static void
print_userid( PACKET *pkt )
{
if( !pkt )
BUG();
if( pkt->pkttype != PKT_USER_ID ) {
printf("ERROR: unexpected packet type %d", pkt->pkttype );
return;
}
if( opt.with_colons )
{
if(pkt->pkt.user_id->attrib_data)
printf("%u %lu",
pkt->pkt.user_id->numattribs,
pkt->pkt.user_id->attrib_len);
else
es_write_sanitized (es_stdout, pkt->pkt.user_id->name,
pkt->pkt.user_id->len, ":", NULL);
}
else
print_utf8_buffer (es_stdout, pkt->pkt.user_id->name,
pkt->pkt.user_id->len );
}
/****************
* List the certificate in a user friendly way
*/
static void
list_node( CTX c, KBNODE node )
{
int any=0;
int mainkey;
if( !node )
;
else if( (mainkey = (node->pkt->pkttype == PKT_PUBLIC_KEY) )
|| node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
PKT_public_key *pk = node->pkt->pkt.public_key;
if( opt.with_colons )
{
u32 keyid[2];
keyid_from_pk( pk, keyid );
if( mainkey )
c->trustletter = opt.fast_list_mode?
0 : get_validity_info( pk, NULL );
printf("%s:", mainkey? "pub":"sub" );
if( c->trustletter )
putchar( c->trustletter );
printf(":%u:%d:%08lX%08lX:%s:%s::",
nbits_from_pk( pk ),
pk->pubkey_algo,
(ulong)keyid[0],(ulong)keyid[1],
colon_datestr_from_pk( pk ),
colon_strtime (pk->expiredate) );
if( mainkey && !opt.fast_list_mode )
putchar( get_ownertrust_info (pk) );
putchar(':');
if( node->next && node->next->pkt->pkttype == PKT_RING_TRUST) {
putchar('\n'); any=1;
if( opt.fingerprint )
print_fingerprint (pk, 0);
printf("rtv:1:%u:\n",
node->next->pkt->pkt.ring_trust->trustval );
}
}
else
printf("%s %4u%c/%s %s%s",
mainkey? "pub":"sub", nbits_from_pk( pk ),
pubkey_letter( pk->pubkey_algo ), keystr_from_pk( pk ),
datestr_from_pk( pk ), mainkey?" ":"");
if( mainkey ) {
/* and now list all userids with their signatures */
for( node = node->next; node; node = node->next ) {
if( node->pkt->pkttype == PKT_SIGNATURE ) {
if( !any ) {
if( node->pkt->pkt.signature->sig_class == 0x20 )
puts("[revoked]");
else
putchar('\n');
any = 1;
}
list_node(c, node );
}
else if( node->pkt->pkttype == PKT_USER_ID ) {
if( any ) {
if( opt.with_colons )
printf("%s:::::::::",
node->pkt->pkt.user_id->attrib_data?"uat":"uid");
else
printf( "uid%*s", 28, "" );
}
print_userid( node->pkt );
if( opt.with_colons )
putchar(':');
putchar('\n');
if( opt.fingerprint && !any )
print_fingerprint ( pk, 0 );
if( opt.with_colons
&& node->next
&& node->next->pkt->pkttype == PKT_RING_TRUST ) {
printf("rtv:2:%u:\n",
node->next->pkt->pkt.ring_trust?
node->next->pkt->pkt.ring_trust->trustval : 0);
}
any=1;
}
else if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
if( !any ) {
putchar('\n');
any = 1;
}
list_node(c, node );
}
}
}
else
{
/* of subkey */
if( pk->flags.revoked )
{
printf(" [");
printf(_("revoked: %s"),revokestr_from_pk(pk));
printf("]");
}
else if( pk->expiredate )
{
printf(" [");
printf(_("expires: %s"),expirestr_from_pk(pk));
printf("]");
}
}
if( !any )
putchar('\n');
if( !mainkey && opt.fingerprint > 1 )
print_fingerprint( pk, 0 );
}
else if( (mainkey = (node->pkt->pkttype == PKT_SECRET_KEY) )
|| node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
log_debug ("FIXME: No way to print secret key packets here\n");
/* fixme: We may use a fucntion to trun a secret key packet into
a public key one and use that here. */
/* PKT_secret_key *sk = node->pkt->pkt.secret_key; */
/* if( opt.with_colons ) */
/* { */
/* u32 keyid[2]; */
/* keyid_from_sk( sk, keyid ); */
/* printf("%s::%u:%d:%08lX%08lX:%s:%s:::", */
/* mainkey? "sec":"ssb", */
/* nbits_from_sk( sk ), */
/* sk->pubkey_algo, */
/* (ulong)keyid[0],(ulong)keyid[1], */
/* colon_datestr_from_sk( sk ), */
/* colon_strtime (sk->expiredate) */
/* /\* fixme: add LID *\/ ); */
/* } */
/* else */
/* printf("%s %4u%c/%s %s ", mainkey? "sec":"ssb", */
/* nbits_from_sk( sk ), pubkey_letter( sk->pubkey_algo ), */
/* keystr_from_sk( sk ), datestr_from_sk( sk )); */
/* if( mainkey ) { */
/* /\* and now list all userids with their signatures *\/ */
/* for( node = node->next; node; node = node->next ) { */
/* if( node->pkt->pkttype == PKT_SIGNATURE ) { */
/* if( !any ) { */
/* if( node->pkt->pkt.signature->sig_class == 0x20 ) */
/* puts("[revoked]"); */
/* else */
/* putchar('\n'); */
/* any = 1; */
/* } */
/* list_node(c, node ); */
/* } */
/* else if( node->pkt->pkttype == PKT_USER_ID ) { */
/* if( any ) { */
/* if( opt.with_colons ) */
/* printf("%s:::::::::", */
/* node->pkt->pkt.user_id->attrib_data?"uat":"uid"); */
/* else */
/* printf( "uid%*s", 28, "" ); */
/* } */
/* print_userid( node->pkt ); */
/* if( opt.with_colons ) */
/* putchar(':'); */
/* putchar('\n'); */
/* if( opt.fingerprint && !any ) */
/* print_fingerprint( NULL, sk, 0 ); */
/* any=1; */
/* } */
/* else if( node->pkt->pkttype == PKT_SECRET_SUBKEY ) { */
/* if( !any ) { */
/* putchar('\n'); */
/* any = 1; */
/* } */
/* list_node(c, node ); */
/* } */
/* } */
/* } */
/* if( !any ) */
/* putchar('\n'); */
/* if( !mainkey && opt.fingerprint > 1 ) */
/* print_fingerprint( NULL, sk, 0 ); */
}
else if( node->pkt->pkttype == PKT_SIGNATURE ) {
PKT_signature *sig = node->pkt->pkt.signature;
int is_selfsig = 0;
int rc2=0;
size_t n;
char *p;
int sigrc = ' ';
if( !opt.verbose )
return;
if( sig->sig_class == 0x20 || sig->sig_class == 0x30 )
fputs("rev", stdout);
else
fputs("sig", stdout);
if( opt.check_sigs ) {
fflush(stdout);
rc2=do_check_sig( c, node, &is_selfsig, NULL, NULL );
switch (gpg_err_code (rc2)) {
case 0: sigrc = '!'; break;
case GPG_ERR_BAD_SIGNATURE: sigrc = '-'; break;
case GPG_ERR_NO_PUBKEY:
case GPG_ERR_UNUSABLE_PUBKEY: sigrc = '?'; break;
default: sigrc = '%'; break;
}
}
else { /* check whether this is a self signature */
u32 keyid[2];
if( c->list->pkt->pkttype == PKT_PUBLIC_KEY
|| c->list->pkt->pkttype == PKT_SECRET_KEY )
{
keyid_from_pk (c->list->pkt->pkt.public_key, keyid);
if( keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1] )
is_selfsig = 1;
}
}
if( opt.with_colons ) {
putchar(':');
if( sigrc != ' ' )
putchar(sigrc);
printf("::%d:%08lX%08lX:%s:%s:", sig->pubkey_algo,
(ulong)sig->keyid[0], (ulong)sig->keyid[1],
colon_datestr_from_sig(sig),
colon_expirestr_from_sig(sig));
if(sig->trust_depth || sig->trust_value)
printf("%d %d",sig->trust_depth,sig->trust_value);
printf(":");
if(sig->trust_regexp)
es_write_sanitized (es_stdout,sig->trust_regexp,
strlen(sig->trust_regexp), ":", NULL);
printf(":");
}
else
printf("%c %s %s ",
sigrc, keystr(sig->keyid), datestr_from_sig(sig));
if( sigrc == '%' )
printf("[%s] ", g10_errstr(rc2) );
else if( sigrc == '?' )
;
else if( is_selfsig ) {
if( opt.with_colons )
putchar(':');
fputs( sig->sig_class == 0x18? "[keybind]":"[selfsig]", stdout);
if( opt.with_colons )
putchar(':');
}
else if( !opt.fast_list_mode ) {
p = get_user_id( sig->keyid, &n );
es_write_sanitized (es_stdout, p, n,
opt.with_colons?":":NULL, NULL );
xfree(p);
}
if( opt.with_colons )
printf(":%02x%c:", sig->sig_class, sig->flags.exportable?'x':'l');
putchar('\n');
}
else
log_error("invalid node with packet of type %d\n", node->pkt->pkttype);
}
int
proc_packets (ctrl_t ctrl, void *anchor, IOBUF a )
{
int rc;
CTX c = xmalloc_clear( sizeof *c );
c->ctrl = ctrl;
c->anchor = anchor;
rc = do_proc_packets( c, a );
xfree( c );
return rc;
}
int
proc_signature_packets (ctrl_t ctrl, void *anchor, IOBUF a,
strlist_t signedfiles, const char *sigfilename )
{
CTX c = xmalloc_clear( sizeof *c );
int rc;
c->ctrl = ctrl;
c->anchor = anchor;
c->sigs_only = 1;
c->signed_data.data_fd = -1;
c->signed_data.data_names = signedfiles;
c->signed_data.used = !!signedfiles;
c->sigfilename = sigfilename;
rc = do_proc_packets( c, a );
/* If we have not encountered any signature we print an error
messages, send a NODATA status back and return an error code.
Using log_error is required because verify_files does not check
error codes for each file but we want to terminate the process
with an error. */
if (!rc && !c->any_sig_seen)
{
write_status_text (STATUS_NODATA, "4");
log_error (_("no signature found\n"));
rc = G10ERR_NO_DATA;
}
/* Propagate the signature seen flag upward. Do this only on
success so that we won't issue the nodata status several
times. */
if (!rc && c->anchor && c->any_sig_seen)
c->anchor->any_sig_seen = 1;
xfree( c );
return rc;
}
int
proc_signature_packets_by_fd (ctrl_t ctrl,
void *anchor, IOBUF a, int signed_data_fd )
{
int rc;
CTX c;
c = xtrycalloc (1, sizeof *c);
if (!c)
return gpg_error_from_syserror ();
c->ctrl = ctrl;
c->anchor = anchor;
c->sigs_only = 1;
c->signed_data.data_fd = signed_data_fd;
c->signed_data.data_names = NULL;
c->signed_data.used = (signed_data_fd != -1);
rc = do_proc_packets ( c, a );
/* If we have not encountered any signature we print an error
messages, send a NODATA status back and return an error code.
Using log_error is required because verify_files does not check
error codes for each file but we want to terminate the process
with an error. */
if (!rc && !c->any_sig_seen)
{
write_status_text (STATUS_NODATA, "4");
log_error (_("no signature found\n"));
rc = gpg_error (GPG_ERR_NO_DATA);
}
/* Propagate the signature seen flag upward. Do this only on success
so that we won't issue the nodata status several times. */
if (!rc && c->anchor && c->any_sig_seen)
c->anchor->any_sig_seen = 1;
xfree ( c );
return rc;
}
int
proc_encryption_packets (ctrl_t ctrl, void *anchor, IOBUF a )
{
CTX c = xmalloc_clear( sizeof *c );
int rc;
c->ctrl = ctrl;
c->anchor = anchor;
c->encrypt_only = 1;
rc = do_proc_packets( c, a );
xfree( c );
return rc;
}
int
do_proc_packets( CTX c, IOBUF a )
{
PACKET *pkt = xmalloc( sizeof *pkt );
int rc=0;
int any_data=0;
int newpkt;
c->iobuf = a;
init_packet(pkt);
while( (rc=parse_packet(a, pkt)) != -1 ) {
any_data = 1;
if( rc ) {
free_packet(pkt);
/* stop processing when an invalid packet has been encountered
* but don't do so when we are doing a --list-packets. */
if (gpg_err_code (rc) == GPG_ERR_INV_PACKET
&& opt.list_packets != 2 )
break;
continue;
}
newpkt = -1;
if( opt.list_packets ) {
switch( pkt->pkttype ) {
case PKT_PUBKEY_ENC: proc_pubkey_enc( c, pkt ); break;
case PKT_SYMKEY_ENC: proc_symkey_enc( c, pkt ); break;
case PKT_ENCRYPTED:
case PKT_ENCRYPTED_MDC: proc_encrypted( c, pkt ); break;
case PKT_COMPRESSED: proc_compressed( c, pkt ); break;
default: newpkt = 0; break;
}
}
else if( c->sigs_only ) {
switch( pkt->pkttype ) {
case PKT_PUBLIC_KEY:
case PKT_SECRET_KEY:
case PKT_USER_ID:
case PKT_SYMKEY_ENC:
case PKT_PUBKEY_ENC:
case PKT_ENCRYPTED:
case PKT_ENCRYPTED_MDC:
write_status_text( STATUS_UNEXPECTED, "0" );
rc = G10ERR_UNEXPECTED;
goto leave;
case PKT_SIGNATURE: newpkt = add_signature( c, pkt ); break;
case PKT_PLAINTEXT: proc_plaintext( c, pkt ); break;
case PKT_COMPRESSED: proc_compressed( c, pkt ); break;
case PKT_ONEPASS_SIG: newpkt = add_onepass_sig( c, pkt ); break;
case PKT_GPG_CONTROL: newpkt = add_gpg_control(c, pkt); break;
default: newpkt = 0; break;
}
}
else if( c->encrypt_only ) {
switch( pkt->pkttype ) {
case PKT_PUBLIC_KEY:
case PKT_SECRET_KEY:
case PKT_USER_ID:
write_status_text( STATUS_UNEXPECTED, "0" );
rc = G10ERR_UNEXPECTED;
goto leave;
case PKT_SIGNATURE: newpkt = add_signature( c, pkt ); break;
case PKT_SYMKEY_ENC: proc_symkey_enc( c, pkt ); break;
case PKT_PUBKEY_ENC: proc_pubkey_enc( c, pkt ); break;
case PKT_ENCRYPTED:
case PKT_ENCRYPTED_MDC: proc_encrypted( c, pkt ); break;
case PKT_PLAINTEXT: proc_plaintext( c, pkt ); break;
case PKT_COMPRESSED: proc_compressed( c, pkt ); break;
case PKT_ONEPASS_SIG: newpkt = add_onepass_sig( c, pkt ); break;
case PKT_GPG_CONTROL: newpkt = add_gpg_control(c, pkt); break;
default: newpkt = 0; break;
}
}
else {
switch( pkt->pkttype ) {
case PKT_PUBLIC_KEY:
case PKT_SECRET_KEY:
release_list( c );
c->list = new_kbnode( pkt );
newpkt = 1;
break;
case PKT_PUBLIC_SUBKEY:
case PKT_SECRET_SUBKEY:
newpkt = add_subkey( c, pkt );
break;
case PKT_USER_ID: newpkt = add_user_id( c, pkt ); break;
case PKT_SIGNATURE: newpkt = add_signature( c, pkt ); break;
case PKT_PUBKEY_ENC: proc_pubkey_enc( c, pkt ); break;
case PKT_SYMKEY_ENC: proc_symkey_enc( c, pkt ); break;
case PKT_ENCRYPTED:
case PKT_ENCRYPTED_MDC: proc_encrypted( c, pkt ); break;
case PKT_PLAINTEXT: proc_plaintext( c, pkt ); break;
case PKT_COMPRESSED: proc_compressed( c, pkt ); break;
case PKT_ONEPASS_SIG: newpkt = add_onepass_sig( c, pkt ); break;
case PKT_GPG_CONTROL: newpkt = add_gpg_control(c, pkt); break;
case PKT_RING_TRUST: newpkt = add_ring_trust( c, pkt ); break;
default: newpkt = 0; break;
}
}
/* This is a very ugly construct and frankly, I don't remember why
* I used it. Adding the MDC check here is a hack.
* The right solution is to initiate another context for encrypted
* packet and not to reuse the current one ... It works right
* when there is a compression packet inbetween which adds just
* an extra layer.
* Hmmm: Rewrite this whole module here??
*/
if( pkt->pkttype != PKT_SIGNATURE && pkt->pkttype != PKT_MDC )
c->have_data = pkt->pkttype == PKT_PLAINTEXT;
if( newpkt == -1 )
;
else if( newpkt ) {
pkt = xmalloc( sizeof *pkt );
init_packet(pkt);
}
else
free_packet(pkt);
}
if( rc == G10ERR_INVALID_PACKET )
write_status_text( STATUS_NODATA, "3" );
if( any_data )
rc = 0;
else if( rc == -1 )
write_status_text( STATUS_NODATA, "2" );
leave:
release_list( c );
xfree(c->dek);
free_packet( pkt );
xfree( pkt );
free_md_filter_context( &c->mfx );
return rc;
}
/* Helper for pka_uri_from_sig to parse the to-be-verified address out
of the notation data. */
static pka_info_t *
get_pka_address (PKT_signature *sig)
{
pka_info_t *pka = NULL;
struct notation *nd,*notation;
notation=sig_to_notation(sig);
for(nd=notation;nd;nd=nd->next)
{
if(strcmp(nd->name,"pka-address@gnupg.org")!=0)
continue; /* Not the notation we want. */
/* For now we only use the first valid PKA notation. In future
we might want to keep additional PKA notations in a linked
list. */
if (is_valid_mailbox (nd->value))
{
pka = xmalloc (sizeof *pka + strlen(nd->value));
pka->valid = 0;
pka->checked = 0;
pka->uri = NULL;
strcpy (pka->email, nd->value);
break;
}
}
free_notation(notation);
return pka;
}
/* Return the URI from a DNS PKA record. If this record has already
be retrieved for the signature we merely return it; if not we go
out and try to get that DNS record. */
static const char *
pka_uri_from_sig (PKT_signature *sig)
{
if (!sig->flags.pka_tried)
{
assert (!sig->pka_info);
sig->flags.pka_tried = 1;
sig->pka_info = get_pka_address (sig);
if (sig->pka_info)
{
char *uri;
uri = get_pka_info (sig->pka_info->email, sig->pka_info->fpr);
if (uri)
{
sig->pka_info->valid = 1;
if (!*uri)
xfree (uri);
else
sig->pka_info->uri = uri;
}
}
}
return sig->pka_info? sig->pka_info->uri : NULL;
}
static int
check_sig_and_print( CTX c, KBNODE node )
{
PKT_signature *sig = node->pkt->pkt.signature;
const char *astr;
int rc, is_expkey=0, is_revkey=0;
if (opt.skip_verify)
{
log_info(_("signature verification suppressed\n"));
return 0;
}
/* Check that the message composition is valid.
Per RFC-2440bis (-15) allowed:
S{1,n} -- detached signature.
S{1,n} P -- old style PGP2 signature
O{1,n} P S{1,n} -- standard OpenPGP signature.
C P S{1,n} -- cleartext signature.
O = One-Pass Signature packet.
S = Signature packet.
P = OpenPGP Message packet (Encrypted | Compressed | Literal)
(Note that the current rfc2440bis draft also allows
for a signed message but that does not work as it
introduces ambiguities.)
We keep track of these packages using the marker packet
CTRLPKT_PLAINTEXT_MARK.
C = Marker packet for cleartext signatures.
We reject all other messages.
Actually we are calling this too often, i.e. for verification of
each message but better have some duplicate work than to silently
introduce a bug here.
*/
{
KBNODE n;
int n_onepass, n_sig;
/* log_debug ("checking signature packet composition\n"); */
/* dump_kbnode (c->list); */
n = c->list;
assert (n);
if ( n->pkt->pkttype == PKT_SIGNATURE )
{
/* This is either "S{1,n}" case (detached signature) or
"S{1,n} P" (old style PGP2 signature). */
for (n = n->next; n; n = n->next)
if (n->pkt->pkttype != PKT_SIGNATURE)
break;
if (!n)
; /* Okay, this is a detached signature. */
else if (n->pkt->pkttype == PKT_GPG_CONTROL
&& (n->pkt->pkt.gpg_control->control
== CTRLPKT_PLAINTEXT_MARK) )
{
if (n->next)
goto ambiguous; /* We only allow one P packet. */
}
else
goto ambiguous;
}
else if (n->pkt->pkttype == PKT_ONEPASS_SIG)
{
/* This is the "O{1,n} P S{1,n}" case (standard signature). */
for (n_onepass=1, n = n->next;
n && n->pkt->pkttype == PKT_ONEPASS_SIG; n = n->next)
n_onepass++;
if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL
&& (n->pkt->pkt.gpg_control->control
== CTRLPKT_PLAINTEXT_MARK)))
goto ambiguous;
for (n_sig=0, n = n->next;
n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next)
n_sig++;
if (!n_sig)
goto ambiguous;
/* If we wanted to disallow multiple sig verification, we'd do
something like this:
if (n && !opt.allow_multisig_verification)
goto ambiguous;
However, now that we have --allow-multiple-messages, this
can stay allowable as we can't get here unless multiple
messages (i.e. multiple literals) are allowed. */
if (n_onepass != n_sig)
{
log_info ("number of one-pass packets does not match "
"number of signature packets\n");
goto ambiguous;
}
}
else if (n->pkt->pkttype == PKT_GPG_CONTROL
&& n->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START )
{
/* This is the "C P S{1,n}" case (clear text signature). */
n = n->next;
if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL
&& (n->pkt->pkt.gpg_control->control
== CTRLPKT_PLAINTEXT_MARK)))
goto ambiguous;
for (n_sig=0, n = n->next;
n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next)
n_sig++;
if (n || !n_sig)
goto ambiguous;
}
else
{
ambiguous:
log_error(_("can't handle this ambiguous signature data\n"));
return 0;
}
}
/* (Indendation below not yet changed to GNU style.) */
- astr = gcry_pk_algo_name ( sig->pubkey_algo );
+ astr = openpgp_pk_algo_name ( sig->pubkey_algo );
if(keystrlen()>8)
{
log_info(_("Signature made %s\n"),asctimestamp(sig->timestamp));
log_info(_(" using %s key %s\n"),
astr? astr: "?",keystr(sig->keyid));
}
else
log_info(_("Signature made %s using %s key ID %s\n"),
asctimestamp(sig->timestamp), astr? astr: "?",
keystr(sig->keyid));
rc = do_check_sig(c, node, NULL, &is_expkey, &is_revkey );
/* If the key isn't found, check for a preferred keyserver */
if(rc==G10ERR_NO_PUBKEY && sig->flags.pref_ks)
{
const byte *p;
int seq=0;
size_t n;
while((p=enum_sig_subpkt(sig->hashed,SIGSUBPKT_PREF_KS,&n,&seq,NULL)))
{
/* According to my favorite copy editor, in English
grammar, you say "at" if the key is located on a web
page, but "from" if it is located on a keyserver. I'm
not going to even try to make two strings here :) */
log_info(_("Key available at: ") );
print_utf8_buffer (log_get_stream(), p, n);
log_printf ("\n");
if(opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE
&& opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL)
{
struct keyserver_spec *spec;
spec=parse_preferred_keyserver(sig);
if(spec)
{
int res;
glo_ctrl.in_auto_key_retrieve++;
res = keyserver_import_keyid (c->ctrl, sig->keyid,spec);
glo_ctrl.in_auto_key_retrieve--;
if(!res)
rc=do_check_sig(c, node, NULL, &is_expkey, &is_revkey );
free_keyserver_spec(spec);
if(!rc)
break;
}
}
}
}
/* If the preferred keyserver thing above didn't work, our second
try is to use the URI from a DNS PKA record. */
if ( rc == G10ERR_NO_PUBKEY
&& opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE
&& opt.keyserver_options.options&KEYSERVER_HONOR_PKA_RECORD)
{
const char *uri = pka_uri_from_sig (sig);
if (uri)
{
/* FIXME: We might want to locate the key using the
fingerprint instead of the keyid. */
int res;
struct keyserver_spec *spec;
spec = parse_keyserver_uri (uri, 1, NULL, 0);
if (spec)
{
glo_ctrl.in_auto_key_retrieve++;
res = keyserver_import_keyid (c->ctrl, sig->keyid, spec);
glo_ctrl.in_auto_key_retrieve--;
free_keyserver_spec (spec);
if (!res)
rc = do_check_sig(c, node, NULL, &is_expkey, &is_revkey );
}
}
}
/* If the preferred keyserver thing above didn't work and we got
no information from the DNS PKA, this is a third try. */
if( rc == G10ERR_NO_PUBKEY && opt.keyserver
&& opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE)
{
int res;
glo_ctrl.in_auto_key_retrieve++;
res=keyserver_import_keyid (c->ctrl, sig->keyid, opt.keyserver );
glo_ctrl.in_auto_key_retrieve--;
if(!res)
rc = do_check_sig(c, node, NULL, &is_expkey, &is_revkey );
}
if( !rc || gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE ) {
KBNODE un, keyblock;
int count=0, statno;
char keyid_str[50];
PKT_public_key *pk=NULL;
if(rc)
statno=STATUS_BADSIG;
else if(sig->flags.expired)
statno=STATUS_EXPSIG;
else if(is_expkey)
statno=STATUS_EXPKEYSIG;
else if(is_revkey)
statno=STATUS_REVKEYSIG;
else
statno=STATUS_GOODSIG;
keyblock = get_pubkeyblock( sig->keyid );
sprintf (keyid_str, "%08lX%08lX [uncertain] ",
(ulong)sig->keyid[0], (ulong)sig->keyid[1]);
/* find and print the primary user ID */
for( un=keyblock; un; un = un->next ) {
char *p;
int valid;
if(un->pkt->pkttype==PKT_PUBLIC_KEY)
{
pk=un->pkt->pkt.public_key;
continue;
}
if( un->pkt->pkttype != PKT_USER_ID )
continue;
if ( !un->pkt->pkt.user_id->created )
continue;
if ( un->pkt->pkt.user_id->is_revoked )
continue;
if ( un->pkt->pkt.user_id->is_expired )
continue;
if ( !un->pkt->pkt.user_id->is_primary )
continue;
/* We want the textual primary user ID here */
if ( un->pkt->pkt.user_id->attrib_data )
continue;
assert(pk);
/* Get it before we print anything to avoid interrupting
the output with the "please do a --check-trustdb"
line. */
valid=get_validity(pk,un->pkt->pkt.user_id);
keyid_str[17] = 0; /* cut off the "[uncertain]" part */
write_status_text_and_buffer (statno, keyid_str,
un->pkt->pkt.user_id->name,
un->pkt->pkt.user_id->len,
-1 );
p=utf8_to_native(un->pkt->pkt.user_id->name,
un->pkt->pkt.user_id->len,0);
if(rc)
log_info(_("BAD signature from \"%s\""),p);
else if(sig->flags.expired)
log_info(_("Expired signature from \"%s\""),p);
else
log_info(_("Good signature from \"%s\""),p);
xfree(p);
if(opt.verify_options&VERIFY_SHOW_UID_VALIDITY)
log_printf (" [%s]\n",trust_value_to_string(valid));
else
log_printf ("\n");
count++;
}
if( !count ) { /* just in case that we have no valid textual
userid */
char *p;
/* Try for an invalid textual userid */
for( un=keyblock; un; un = un->next ) {
if( un->pkt->pkttype == PKT_USER_ID &&
!un->pkt->pkt.user_id->attrib_data )
break;
}
/* Try for any userid at all */
if(!un) {
for( un=keyblock; un; un = un->next ) {
if( un->pkt->pkttype == PKT_USER_ID )
break;
}
}
if (opt.trust_model==TM_ALWAYS || !un)
keyid_str[17] = 0; /* cut off the "[uncertain]" part */
write_status_text_and_buffer (statno, keyid_str,
un? un->pkt->pkt.user_id->name:"[?]",
un? un->pkt->pkt.user_id->len:3,
-1 );
if(un)
p=utf8_to_native(un->pkt->pkt.user_id->name,
un->pkt->pkt.user_id->len,0);
else
p=xstrdup("[?]");
if(rc)
log_info(_("BAD signature from \"%s\""),p);
else if(sig->flags.expired)
log_info(_("Expired signature from \"%s\""),p);
else
log_info(_("Good signature from \"%s\""),p);
if (opt.trust_model!=TM_ALWAYS && un)
log_printf (" %s",_("[uncertain]") );
log_printf ("\n");
}
/* If we have a good signature and already printed
* the primary user ID, print all the other user IDs */
if ( count && !rc
&& !(opt.verify_options&VERIFY_SHOW_PRIMARY_UID_ONLY)) {
char *p;
for( un=keyblock; un; un = un->next ) {
if( un->pkt->pkttype != PKT_USER_ID )
continue;
if((un->pkt->pkt.user_id->is_revoked
|| un->pkt->pkt.user_id->is_expired)
&& !(opt.verify_options&VERIFY_SHOW_UNUSABLE_UIDS))
continue;
/* Only skip textual primaries */
if ( un->pkt->pkt.user_id->is_primary &&
!un->pkt->pkt.user_id->attrib_data )
continue;
if(un->pkt->pkt.user_id->attrib_data)
{
dump_attribs (un->pkt->pkt.user_id, pk);
if(opt.verify_options&VERIFY_SHOW_PHOTOS)
show_photos(un->pkt->pkt.user_id->attribs,
un->pkt->pkt.user_id->numattribs,
pk ,un->pkt->pkt.user_id);
}
p=utf8_to_native(un->pkt->pkt.user_id->name,
un->pkt->pkt.user_id->len,0);
log_info(_(" aka \"%s\""),p);
xfree(p);
if(opt.verify_options&VERIFY_SHOW_UID_VALIDITY)
{
const char *valid;
if(un->pkt->pkt.user_id->is_revoked)
valid=_("revoked");
else if(un->pkt->pkt.user_id->is_expired)
valid=_("expired");
else
valid=trust_value_to_string(get_validity(pk,
un->pkt->
pkt.user_id));
log_printf (" [%s]\n",valid);
}
else
log_printf ("\n");
}
}
release_kbnode( keyblock );
if( !rc )
{
if(opt.verify_options&VERIFY_SHOW_POLICY_URLS)
show_policy_url(sig,0,1);
else
show_policy_url(sig,0,2);
if(opt.verify_options&VERIFY_SHOW_KEYSERVER_URLS)
show_keyserver_url(sig,0,1);
else
show_keyserver_url(sig,0,2);
if(opt.verify_options&VERIFY_SHOW_NOTATIONS)
show_notation(sig,0,1,
((opt.verify_options&VERIFY_SHOW_STD_NOTATIONS)?1:0)+
((opt.verify_options&VERIFY_SHOW_USER_NOTATIONS)?2:0));
else
show_notation(sig,0,2,0);
}
if( !rc && is_status_enabled() ) {
/* print a status response with the fingerprint */
PKT_public_key *vpk = xmalloc_clear( sizeof *vpk );
if( !get_pubkey( vpk, sig->keyid ) ) {
byte array[MAX_FINGERPRINT_LEN], *p;
char buf[MAX_FINGERPRINT_LEN*4+90], *bufp;
size_t i, n;
bufp = buf;
fingerprint_from_pk( vpk, array, &n );
p = array;
for(i=0; i < n ; i++, p++, bufp += 2)
sprintf(bufp, "%02X", *p );
/* TODO: Replace the reserved '0' in the field below
with bits for status flags (policy url, notation,
etc.). Remember to make the buffer larger to
match! */
sprintf(bufp, " %s %lu %lu %d 0 %d %d %02X ",
strtimestamp( sig->timestamp ),
(ulong)sig->timestamp,(ulong)sig->expiredate,
sig->version,sig->pubkey_algo,sig->digest_algo,
sig->sig_class);
bufp = bufp + strlen (bufp);
if (!vpk->flags.primary) {
u32 akid[2];
akid[0] = vpk->main_keyid[0];
akid[1] = vpk->main_keyid[1];
free_public_key (vpk);
vpk = xmalloc_clear( sizeof *vpk );
if (get_pubkey (vpk, akid)) {
/* impossible error, we simply return a zeroed out fpr */
n = MAX_FINGERPRINT_LEN < 20? MAX_FINGERPRINT_LEN : 20;
memset (array, 0, n);
}
else
fingerprint_from_pk( vpk, array, &n );
}
p = array;
for(i=0; i < n ; i++, p++, bufp += 2)
sprintf(bufp, "%02X", *p );
write_status_text( STATUS_VALIDSIG, buf );
}
free_public_key( vpk );
}
if (!rc)
{
if(opt.verify_options&VERIFY_PKA_LOOKUPS)
pka_uri_from_sig (sig); /* Make sure PKA info is available. */
rc = check_signatures_trust( sig );
}
if(sig->flags.expired)
{
log_info(_("Signature expired %s\n"),
asctimestamp(sig->expiredate));
rc=G10ERR_GENERAL; /* need a better error here? */
}
else if(sig->expiredate)
log_info(_("Signature expires %s\n"),asctimestamp(sig->expiredate));
if(opt.verbose)
log_info(_("%s signature, digest algorithm %s\n"),
sig->sig_class==0x00?_("binary"):
sig->sig_class==0x01?_("textmode"):_("unknown"),
gcry_md_algo_name (sig->digest_algo));
if( rc )
g10_errors_seen = 1;
if( opt.batch && rc )
g10_exit(1);
}
else {
char buf[50];
sprintf(buf, "%08lX%08lX %d %d %02x %lu %d",
(ulong)sig->keyid[0], (ulong)sig->keyid[1],
sig->pubkey_algo, sig->digest_algo,
sig->sig_class, (ulong)sig->timestamp, rc );
write_status_text( STATUS_ERRSIG, buf );
if( rc == G10ERR_NO_PUBKEY ) {
buf[16] = 0;
write_status_text( STATUS_NO_PUBKEY, buf );
}
if( rc != G10ERR_NOT_PROCESSED )
log_error(_("Can't check signature: %s\n"), g10_errstr(rc) );
}
return rc;
}
/****************
* Process the tree which starts at node
*/
static void
proc_tree( CTX c, KBNODE node )
{
KBNODE n1;
int rc;
if( opt.list_packets || opt.list_only )
return;
/* we must skip our special plaintext marker packets here becuase
they may be the root packet. These packets are only used in
addionla checks and skipping them here doesn't matter */
while ( node
&& node->pkt->pkttype == PKT_GPG_CONTROL
&& node->pkt->pkt.gpg_control->control
== CTRLPKT_PLAINTEXT_MARK ) {
node = node->next;
}
if (!node)
return;
c->trustletter = ' ';
if( node->pkt->pkttype == PKT_PUBLIC_KEY
|| node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
merge_keys_and_selfsig( node );
list_node( c, node );
}
else if( node->pkt->pkttype == PKT_SECRET_KEY ) {
merge_keys_and_selfsig( node );
list_node( c, node );
}
else if( node->pkt->pkttype == PKT_ONEPASS_SIG ) {
/* check all signatures */
if( !c->have_data ) {
int use_textmode = 0;
free_md_filter_context( &c->mfx );
/* prepare to create all requested message digests */
if (gcry_md_open (&c->mfx.md, 0, 0))
BUG ();
/* fixme: why looking for the signature packet and not the
one-pass packet? */
for ( n1 = node; (n1 = find_next_kbnode(n1, PKT_SIGNATURE )); )
{
gcry_md_enable (c->mfx.md,
n1->pkt->pkt.signature->digest_algo);
}
if (n1 && n1->pkt->pkt.onepass_sig->sig_class == 0x01)
use_textmode = 1;
/* Ask for file and hash it. */
if( c->sigs_only ) {
if (c->signed_data.used && c->signed_data.data_fd != -1)
rc = hash_datafile_by_fd (c->mfx.md, NULL,
c->signed_data.data_fd,
use_textmode);
else
rc = hash_datafiles (c->mfx.md, NULL,
c->signed_data.data_names,
c->sigfilename,
use_textmode );
}
else {
rc = ask_for_detached_datafile (c->mfx.md, c->mfx.md2,
iobuf_get_real_fname(c->iobuf),
use_textmode );
}
if( rc ) {
log_error("can't hash datafile: %s\n", g10_errstr(rc));
return;
}
}
else if ( c->signed_data.used ) {
log_error (_("not a detached signature\n") );
return;
}
for( n1 = node; (n1 = find_next_kbnode(n1, PKT_SIGNATURE )); )
check_sig_and_print( c, n1 );
}
else if( node->pkt->pkttype == PKT_GPG_CONTROL
&& node->pkt->pkt.gpg_control->control
== CTRLPKT_CLEARSIGN_START ) {
/* clear text signed message */
if( !c->have_data ) {
log_error("cleartext signature without data\n" );
return;
}
else if ( c->signed_data.used ) {
log_error (_("not a detached signature\n") );
return;
}
for( n1 = node; (n1 = find_next_kbnode(n1, PKT_SIGNATURE )); )
check_sig_and_print( c, n1 );
}
else if( node->pkt->pkttype == PKT_SIGNATURE ) {
PKT_signature *sig = node->pkt->pkt.signature;
int multiple_ok=1;
n1=find_next_kbnode(node, PKT_SIGNATURE);
if(n1)
{
byte class=sig->sig_class;
byte hash=sig->digest_algo;
for(; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE)))
{
/* We can't currently handle multiple signatures of
different classes or digests (we'd pretty much have
to run a different hash context for each), but if
they are all the same, make an exception. */
if(n1->pkt->pkt.signature->sig_class!=class
|| n1->pkt->pkt.signature->digest_algo!=hash)
{
multiple_ok=0;
log_info(_("WARNING: multiple signatures detected. "
"Only the first will be checked.\n"));
break;
}
}
}
if( sig->sig_class != 0x00 && sig->sig_class != 0x01 )
log_info(_("standalone signature of class 0x%02x\n"),
sig->sig_class);
else if( !c->have_data ) {
/* detached signature */
free_md_filter_context( &c->mfx );
if (gcry_md_open (&c->mfx.md, sig->digest_algo, 0))
BUG ();
if( !opt.pgp2_workarounds )
;
else if( sig->digest_algo == DIGEST_ALGO_MD5
&& is_RSA( sig->pubkey_algo ) ) {
/* enable a workaround for a pgp2 bug */
if (gcry_md_open (&c->mfx.md2, DIGEST_ALGO_MD5, 0))
BUG ();
}
else if( sig->digest_algo == DIGEST_ALGO_SHA1
&& sig->pubkey_algo == PUBKEY_ALGO_DSA
&& sig->sig_class == 0x01 ) {
/* enable the workaround also for pgp5 when the detached
* signature has been created in textmode */
if (gcry_md_open (&c->mfx.md2, sig->digest_algo, 0 ))
BUG ();
}
#if 0 /* workaround disabled */
/* Here we have another hack to work around a pgp 2 bug
* It works by not using the textmode for detached signatures;
* this will let the first signature check (on md) fail
* but the second one (on md2) which adds an extra CR should
* then produce the "correct" hash. This is very, very ugly
* hack but it may help in some cases (and break others)
*/
/* c->mfx.md2? 0 :(sig->sig_class == 0x01) */
#endif
if ( DBG_HASHING ) {
gcry_md_start_debug( c->mfx.md, "verify" );
if ( c->mfx.md2 )
gcry_md_start_debug( c->mfx.md2, "verify2" );
}
if( c->sigs_only ) {
if (c->signed_data.used && c->signed_data.data_fd != -1)
rc = hash_datafile_by_fd (c->mfx.md, c->mfx.md2,
c->signed_data.data_fd,
(sig->sig_class == 0x01));
else
rc = hash_datafiles (c->mfx.md, c->mfx.md2,
c->signed_data.data_names,
c->sigfilename,
(sig->sig_class == 0x01));
}
else {
rc = ask_for_detached_datafile( c->mfx.md, c->mfx.md2,
iobuf_get_real_fname(c->iobuf),
(sig->sig_class == 0x01) );
}
if( rc ) {
log_error("can't hash datafile: %s\n", g10_errstr(rc));
return;
}
}
else if ( c->signed_data.used ) {
log_error (_("not a detached signature\n") );
return;
}
else if (!opt.quiet)
log_info(_("old style (PGP 2.x) signature\n"));
if(multiple_ok)
for( n1 = node; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE )) )
check_sig_and_print( c, n1 );
else
check_sig_and_print( c, node );
}
else {
dump_kbnode (c->list);
log_error(_("invalid root packet detected in proc_tree()\n"));
dump_kbnode (node);
}
}
diff --git a/g10/misc.c b/g10/misc.c
index 1725258c5..a09636b60 100644
--- a/g10/misc.c
+++ b/g10/misc.c
@@ -1,1457 +1,1594 @@
/* misc.c - miscellaneous functions
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
* 2008, 2009 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
* 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
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include
#if defined(__linux__) && defined(__alpha__) && __GLIBC__ < 2
#include
#include
#endif
#ifdef HAVE_SETRLIMIT
#include
#include
#include
#endif
#ifdef ENABLE_SELINUX_HACKS
#include
#endif
#ifdef HAVE_W32_SYSTEM
#include
#include
#include
#include
#ifndef CSIDL_APPDATA
#define CSIDL_APPDATA 0x001a
#endif
#ifndef CSIDL_LOCAL_APPDATA
#define CSIDL_LOCAL_APPDATA 0x001c
#endif
#ifndef CSIDL_FLAG_CREATE
#define CSIDL_FLAG_CREATE 0x8000
#endif
#endif /*HAVE_W32_SYSTEM*/
#include "gpg.h"
#ifdef HAVE_W32_SYSTEM
# include "status.h"
#endif /*HAVE_W32_SYSTEM*/
#include "util.h"
#include "main.h"
#include "photoid.h"
#include "options.h"
#include "call-agent.h"
#include "i18n.h"
+#include
static int
string_count_chr (const char *string, int c)
{
int count;
for (count=0; *string; string++ )
if ( *string == c )
count++;
return count;
}
#ifdef ENABLE_SELINUX_HACKS
/* A object and a global variable to keep track of files marked as
secured. */
struct secured_file_item
{
struct secured_file_item *next;
ino_t ino;
dev_t dev;
};
static struct secured_file_item *secured_files;
#endif /*ENABLE_SELINUX_HACKS*/
/* For the sake of SELinux we want to restrict access through gpg to
certain files we keep under our own control. This function
registers such a file and is_secured_file may then be used to
check whether a file has ben registered as secured. */
void
register_secured_file (const char *fname)
{
#ifdef ENABLE_SELINUX_HACKS
struct stat buf;
struct secured_file_item *sf;
/* Note that we stop immediatley if something goes wrong here. */
if (stat (fname, &buf))
log_fatal (_("fstat of `%s' failed in %s: %s\n"), fname,
"register_secured_file", strerror (errno));
/* log_debug ("registering `%s' i=%lu.%lu\n", fname, */
/* (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
for (sf=secured_files; sf; sf = sf->next)
{
if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
return; /* Already registered. */
}
sf = xmalloc (sizeof *sf);
sf->ino = buf.st_ino;
sf->dev = buf.st_dev;
sf->next = secured_files;
secured_files = sf;
#else /*!ENABLE_SELINUX_HACKS*/
(void)fname;
#endif /*!ENABLE_SELINUX_HACKS*/
}
/* Remove a file registered as secure. */
void
unregister_secured_file (const char *fname)
{
#ifdef ENABLE_SELINUX_HACKS
struct stat buf;
struct secured_file_item *sf, *sfprev;
if (stat (fname, &buf))
{
log_error (_("fstat of `%s' failed in %s: %s\n"), fname,
"unregister_secured_file", strerror (errno));
return;
}
/* log_debug ("unregistering `%s' i=%lu.%lu\n", fname, */
/* (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
for (sfprev=NULL,sf=secured_files; sf; sfprev=sf, sf = sf->next)
{
if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
{
if (sfprev)
sfprev->next = sf->next;
else
secured_files = sf->next;
xfree (sf);
return;
}
}
#else /*!ENABLE_SELINUX_HACKS*/
(void)fname;
#endif /*!ENABLE_SELINUX_HACKS*/
}
/* Return true if FD is corresponds to a secured file. Using -1 for
FS is allowed and will return false. */
int
is_secured_file (int fd)
{
#ifdef ENABLE_SELINUX_HACKS
struct stat buf;
struct secured_file_item *sf;
if (fd == -1)
return 0; /* No file descriptor so it can't be secured either. */
/* Note that we print out a error here and claim that a file is
secure if something went wrong. */
if (fstat (fd, &buf))
{
log_error (_("fstat(%d) failed in %s: %s\n"), fd,
"is_secured_file", strerror (errno));
return 1;
}
/* log_debug ("is_secured_file (%d) i=%lu.%lu\n", fd, */
/* (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
for (sf=secured_files; sf; sf = sf->next)
{
if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
return 1; /* Yes. */
}
#else /*!ENABLE_SELINUX_HACKS*/
(void)fd;
#endif /*!ENABLE_SELINUX_HACKS*/
return 0; /* No. */
}
/* Return true if FNAME is corresponds to a secured file. Using NULL,
"" or "-" for FS is allowed and will return false. This function is
used before creating a file, thus it won't fail if the file does
not exist. */
int
is_secured_filename (const char *fname)
{
#ifdef ENABLE_SELINUX_HACKS
struct stat buf;
struct secured_file_item *sf;
if (iobuf_is_pipe_filename (fname) || !*fname)
return 0;
/* Note that we print out a error here and claim that a file is
secure if something went wrong. */
if (stat (fname, &buf))
{
if (errno == ENOENT || errno == EPERM || errno == EACCES)
return 0;
log_error (_("fstat of `%s' failed in %s: %s\n"), fname,
"is_secured_filename", strerror (errno));
return 1;
}
/* log_debug ("is_secured_filename (%s) i=%lu.%lu\n", fname, */
/* (unsigned long)buf.st_dev, (unsigned long)buf.st_ino); */
for (sf=secured_files; sf; sf = sf->next)
{
if (sf->ino == buf.st_ino && sf->dev == buf.st_dev)
return 1; /* Yes. */
}
#else /*!ENABLE_SELINUX_HACKS*/
(void)fname;
#endif /*!ENABLE_SELINUX_HACKS*/
return 0; /* No. */
}
u16
checksum_u16( unsigned n )
{
u16 a;
a = (n >> 8) & 0xff;
a += n & 0xff;
return a;
}
u16
checksum( byte *p, unsigned n )
{
u16 a;
for(a=0; n; n-- )
a += *p++;
return a;
}
u16
checksum_mpi (gcry_mpi_t a)
{
u16 csum;
byte *buffer;
size_t nbytes;
if ( gcry_mpi_print (GCRYMPI_FMT_PGP, NULL, 0, &nbytes, a) )
BUG ();
/* Fixme: For numbers not in secure memory we should use a stack
* based buffer and only allocate a larger one if mpi_print returns
* an error. */
buffer = (gcry_is_secure(a)?
gcry_xmalloc_secure (nbytes) : gcry_xmalloc (nbytes));
if ( gcry_mpi_print (GCRYMPI_FMT_PGP, buffer, nbytes, NULL, a) )
BUG ();
csum = checksum (buffer, nbytes);
xfree (buffer);
return csum;
}
u32
buffer_to_u32( const byte *buffer )
{
unsigned long a;
a = *buffer << 24;
a |= buffer[1] << 16;
a |= buffer[2] << 8;
a |= buffer[3];
return a;
}
void
print_pubkey_algo_note( int algo )
{
if(algo >= 100 && algo <= 110)
{
static int warn=0;
if(!warn)
{
warn=1;
log_info (_("WARNING: using experimental public key algorithm %s\n"),
- gcry_pk_algo_name (algo));
+ openpgp_cipher_algo_name (algo));
}
}
else if (algo == 20)
{
log_info (_("WARNING: Elgamal sign+encrypt keys are deprecated\n"));
}
}
void
print_cipher_algo_note( int algo )
{
if(algo >= 100 && algo <= 110)
{
static int warn=0;
if(!warn)
{
warn=1;
log_info (_("WARNING: using experimental cipher algorithm %s\n"),
openpgp_cipher_algo_name (algo));
}
}
}
void
print_digest_algo_note( int algo )
{
if(algo >= 100 && algo <= 110)
{
static int warn=0;
if(!warn)
{
warn=1;
log_info (_("WARNING: using experimental digest algorithm %s\n"),
gcry_md_algo_name (algo));
}
}
else if(algo==DIGEST_ALGO_MD5)
log_info (_("WARNING: digest algorithm %s is deprecated\n"),
gcry_md_algo_name (algo));
}
/* Map OpenPGP algo numbers to those used by Libgcrypt. We need to do
this for algorithms we implemented in Libgcrypt after they become
part of OpenPGP. */
int
map_cipher_openpgp_to_gcry (int algo)
{
switch (algo)
{
case CIPHER_ALGO_CAMELLIA128: return 310;
case CIPHER_ALGO_CAMELLIA192: return 311;
case CIPHER_ALGO_CAMELLIA256: return 312;
default: return algo;
}
}
/* The inverse fucntion of above. */
static int
map_cipher_gcry_to_openpgp (int algo)
{
switch (algo)
{
case 310: return CIPHER_ALGO_CAMELLIA128;
case 311: return CIPHER_ALGO_CAMELLIA192;
case 312: return CIPHER_ALGO_CAMELLIA256;
default: return algo;
}
}
+int
+map_pk_openpgp_to_gcry (int algo)
+{
+ return (algo==PUBKEY_ALGO_ECDSA ? GCRY_PK_ECDSA : (algo==PUBKEY_ALGO_ECDH ? GCRY_PK_ECDH : algo));
+}
+
/* Return the block length of an OpenPGP cipher algorithm. */
int
openpgp_cipher_blocklen (int algo)
{
/* We use the numbers from OpenPGP to be sure that we get the right
block length. This is so that the packet parsing code works even
for unknown algorithms (for which we assume 8 due to tradition).
NOTE: If you change the the returned blocklen above 16, check
the callers because they may use a fixed size buffer of that
size. */
switch (algo)
{
case 7: case 8: case 9: /* AES */
case 10: /* Twofish */
case 11: case 12: case 13: /* Camellia */
return 16;
default:
return 8;
}
}
/****************
* Wrapper around the libgcrypt function with additonal checks on
* the OpenPGP contraints for the algo ID.
*/
int
openpgp_cipher_test_algo( int algo )
{
/* (5 and 6 are marked reserved by rfc4880.) */
if ( algo < 0 || algo > 110 || algo == 5 || algo == 6 )
return gpg_error (GPG_ERR_CIPHER_ALGO);
return gcry_cipher_test_algo (map_cipher_openpgp_to_gcry (algo));
}
/* Map the OpenPGP cipher algorithm whose ID is contained in ALGORITHM to a
string representation of the algorithm name. For unknown algorithm
IDs this function returns "?". */
const char *
openpgp_cipher_algo_name (int algo)
{
- return gnupg_cipher_algo_name (map_cipher_openpgp_to_gcry (algo));
+ return gcry_cipher_algo_name (map_cipher_openpgp_to_gcry (algo));
+}
+
+const char *
+openpgp_pk_algo_name (int algo)
+{
+ return gcry_pk_algo_name ( algo == PUBKEY_ALGO_ECDSA ? GCRY_PK_ECDSA : ( algo == PUBKEY_ALGO_ECDH ? GCRY_PK_ECDH : algo ) );
}
int
openpgp_pk_test_algo( int algo )
{
/* Dont't allow type 20 keys unless in rfc2440 mode. */
if (!RFC2440 && algo == 20)
return gpg_error (GPG_ERR_PUBKEY_ALGO);
if (algo == GCRY_PK_ELG_E)
algo = GCRY_PK_ELG;
if (algo < 0 || algo > 110)
return gpg_error (GPG_ERR_PUBKEY_ALGO);
- return gcry_pk_test_algo (algo);
+
+ if( algo == PUBKEY_ALGO_ECDSA )
+ algo = GCRY_PK_ECDSA;
+ else if( algo == PUBKEY_ALGO_ECDH )
+ algo = GCRY_PK_ECDH;
+
+ return gcry_pk_test_algo ( algo );
}
int
openpgp_pk_test_algo2( int algo, unsigned int use )
{
size_t use_buf = use;
/* Dont't allow type 20 keys unless in rfc2440 mode. */
if (!RFC2440 && algo == 20)
return gpg_error (GPG_ERR_PUBKEY_ALGO);
if (algo == GCRY_PK_ELG_E)
algo = GCRY_PK_ELG;
if (algo < 0 || algo > 110)
return gpg_error (GPG_ERR_PUBKEY_ALGO);
- return gcry_pk_algo_info (algo, GCRYCTL_TEST_ALGO, NULL, &use_buf);
+ if( algo == PUBKEY_ALGO_ECDSA )
+ algo = GCRY_PK_ECDSA;
+ else if( algo == PUBKEY_ALGO_ECDH )
+ algo = GCRY_PK_ECDH;
+
+ return gcry_pk_algo_info ( algo, GCRYCTL_TEST_ALGO, NULL, &use_buf);
}
int
openpgp_pk_algo_usage ( int algo )
{
int use = 0;
/* They are hardwired in gpg 1.0. */
switch ( algo ) {
case PUBKEY_ALGO_RSA:
use = (PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG
| PUBKEY_USAGE_ENC | PUBKEY_USAGE_AUTH);
break;
case PUBKEY_ALGO_RSA_E:
+ case PUBKEY_ALGO_ECDH:
use = PUBKEY_USAGE_ENC;
break;
case PUBKEY_ALGO_RSA_S:
use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG;
break;
case PUBKEY_ALGO_ELGAMAL:
if (RFC2440)
use = PUBKEY_USAGE_ENC;
break;
case PUBKEY_ALGO_ELGAMAL_E:
use = PUBKEY_USAGE_ENC;
break;
case PUBKEY_ALGO_DSA:
use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG | PUBKEY_USAGE_AUTH;
break;
+ case PUBKEY_ALGO_ECDSA:
+ use = PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG | PUBKEY_USAGE_AUTH;
default:
break;
}
return use;
}
/* Map the OpenPGP pubkey algorithm whose ID is contained in ALGO to a
string representation of the algorithm name. For unknown algorithm
- IDs this function returns "?". */
+ IDs this function returns "?".
const char *
openpgp_pk_algo_name (int algo)
{
switch (algo)
{
case PUBKEY_ALGO_RSA:
case PUBKEY_ALGO_RSA_E:
case PUBKEY_ALGO_RSA_S: return "rsa";
case PUBKEY_ALGO_ELGAMAL:
case PUBKEY_ALGO_ELGAMAL_E: return "elg";
case PUBKEY_ALGO_DSA: return "dsa";
default: return "?";
}
}
+*/
int
openpgp_md_test_algo( int algo )
{
/* Note: If the list of actual supported OpenPGP algorithms changes,
make sure that our hard coded values at
print_status_begin_signing() gets updated. */
/* 4, 5, 6, 7 are defined by rfc2440 but will be removed from the
next revision of the standard. */
if (algo < 0 || algo > 110 || (algo >= 4 && algo <= 7))
return gpg_error (GPG_ERR_DIGEST_ALGO);
return gcry_md_test_algo (algo);
}
/* Map the OpenPGP digest algorithm whose ID is contained in ALGO to a
string representation of the algorithm name. For unknown algorithm
IDs this function returns "?". */
const char *
openpgp_md_algo_name (int algo)
{
if (algo < 0 || algo > 110)
return "?";
return gcry_md_algo_name (algo);
}
#ifdef USE_IDEA
/* Special warning for the IDEA cipher */
void
idea_cipher_warn(int show)
{
static int warned=0;
if(!warned || show)
{
log_info(_("the IDEA cipher plugin is not present\n"));
log_info(_("please see %s for more information\n"),
"http://www.gnupg.org/faq/why-not-idea.html");
warned=1;
}
}
#endif
static unsigned long
get_signature_count (PKT_public_key *pk)
{
#ifdef ENABLE_CARD_SUPPORT
struct agent_card_info_s info;
#warning fixme: We should check that the correct card has been inserted
if (!agent_scd_getattr ("SIG-COUNTER",&info))
return info.sig_counter;
else
return 0;
#else
(void)pk;
return 0;
#endif
}
/* Expand %-strings. Returns a string which must be xfreed. Returns
NULL if the string cannot be expanded (too large). */
char *
pct_expando(const char *string,struct expando_args *args)
{
const char *ch=string;
int idx=0,maxlen=0,done=0;
u32 pk_keyid[2]={0,0},sk_keyid[2]={0,0};
char *ret=NULL;
if(args->pk)
keyid_from_pk(args->pk,pk_keyid);
if(args->pksk)
keyid_from_pk (args->pksk, sk_keyid);
/* This is used so that %k works in photoid command strings in
--list-secret-keys (which of course has a sk, but no pk). */
if(!args->pk && args->pksk)
keyid_from_pk (args->pksk, pk_keyid);
while(*ch!='\0')
{
if(!done)
{
/* 8192 is way bigger than we'll need here */
if(maxlen>=8192)
goto fail;
maxlen+=1024;
ret=xrealloc(ret,maxlen);
}
done=0;
if(*ch=='%')
{
switch(*(ch+1))
{
case 's': /* short key id */
if(idx+8pksk));
idx+=strlen(&ret[idx]);
done=1;
}
break;
case 'p': /* primary pk fingerprint of a sk */
case 'f': /* pk fingerprint */
case 'g': /* sk fingerprint */
{
byte array[MAX_FINGERPRINT_LEN];
size_t len;
int i;
if((*(ch+1))=='p' && args->pksk)
{
if(args->pksk->flags.primary)
fingerprint_from_pk (args->pksk, array, &len);
else if (args->pksk->main_keyid[0]
|| args->pksk->main_keyid[1])
{
/* FIXME: Document teh code and check whether
it is still needed. */
PKT_public_key *pk=
xmalloc_clear(sizeof(PKT_public_key));
if (!get_pubkey_fast (pk,args->pksk->main_keyid))
fingerprint_from_pk (pk, array, &len);
else
memset (array, 0, (len=MAX_FINGERPRINT_LEN));
free_public_key (pk);
}
else
memset(array,0,(len=MAX_FINGERPRINT_LEN));
}
else if((*(ch+1))=='f' && args->pk)
fingerprint_from_pk (args->pk, array, &len);
else if((*(ch+1))=='g' && args->pksk)
fingerprint_from_pk (args->pksk, array, &len);
else
memset(array,0,(len=MAX_FINGERPRINT_LEN));
if(idx+(len*2)validity_info && idx+1validity_info;
ret[idx]='\0';
done=1;
}
break;
/* The text string types */
case 't':
case 'T':
case 'V':
{
const char *str=NULL;
switch(*(ch+1))
{
case 't': /* e.g. "jpg" */
str=image_type_to_string(args->imagetype,0);
break;
case 'T': /* e.g. "image/jpeg" */
str=image_type_to_string(args->imagetype,2);
break;
case 'V': /* e.g. "full", "expired", etc. */
str=args->validity_string;
break;
}
if(str && idx+strlen(str)='A' && file[0]<='Z')
|| (file[0]>='a' && file[0]<='z'))
&& file[1]==':')
#else
|| file[0]=='/'
#endif
)
return access(file,mode);
else
{
/* At least as large as, but most often larger than we need. */
char *buffer=xmalloc(strlen(envpath)+1+strlen(file)+1);
char *split,*item,*path=xstrdup(envpath);
split=path;
while((item=strsep(&split,PATHSEP_S)))
{
strcpy(buffer,item);
strcat(buffer,"/");
strcat(buffer,file);
ret=access(buffer,mode);
if(ret==0)
break;
}
xfree(path);
xfree(buffer);
}
return ret;
}
/* Temporary helper. */
int
pubkey_get_npkey( int algo )
{
size_t n;
if (algo == GCRY_PK_ELG_E)
algo = GCRY_PK_ELG;
+ else if (algo == PUBKEY_ALGO_ECDSA)
+ algo = GCRY_PK_ECDSA;
+ else if (algo == PUBKEY_ALGO_ECDH)
+ algo = GCRY_PK_ECDH;
if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NPKEY, NULL, &n))
n = 0;
return n;
}
/* Temporary helper. */
int
pubkey_get_nskey( int algo )
{
size_t n;
if (algo == GCRY_PK_ELG_E)
algo = GCRY_PK_ELG;
+ else if (algo == PUBKEY_ALGO_ECDSA)
+ algo = GCRY_PK_ECDSA;
+ else if (algo == PUBKEY_ALGO_ECDH)
+ algo = GCRY_PK_ECDH;
if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NSKEY, NULL, &n ))
n = 0;
return n;
}
/* Temporary helper. */
int
pubkey_get_nsig( int algo )
{
size_t n;
if (algo == GCRY_PK_ELG_E)
algo = GCRY_PK_ELG;
+ else if (algo == PUBKEY_ALGO_ECDSA)
+ algo = GCRY_PK_ECDSA;
+ else if (algo == PUBKEY_ALGO_ECDH)
+ algo = GCRY_PK_ECDH;
if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NSIGN, NULL, &n))
n = 0;
return n;
}
/* Temporary helper. */
int
pubkey_get_nenc( int algo )
{
size_t n;
if (algo == GCRY_PK_ELG_E)
algo = GCRY_PK_ELG;
+ else if (algo == PUBKEY_ALGO_ECDSA)
+ algo = GCRY_PK_ECDSA;
+ else if (algo == PUBKEY_ALGO_ECDH)
+ algo = GCRY_PK_ECDH;
if (gcry_pk_algo_info( algo, GCRYCTL_GET_ALGO_NENCR, NULL, &n ))
n = 0;
return n;
}
/* Temporary helper. */
unsigned int
pubkey_nbits( int algo, gcry_mpi_t *key )
{
int rc, nbits;
gcry_sexp_t sexp;
+ assert( algo != GCRY_PK_ECDSA && algo != GCRY_PK_ECDH );
+
if( algo == GCRY_PK_DSA ) {
rc = gcry_sexp_build ( &sexp, NULL,
"(public-key(dsa(p%m)(q%m)(g%m)(y%m)))",
key[0], key[1], key[2], key[3] );
}
else if( algo == GCRY_PK_ELG || algo == GCRY_PK_ELG_E ) {
rc = gcry_sexp_build ( &sexp, NULL,
"(public-key(elg(p%m)(g%m)(y%m)))",
key[0], key[1], key[2] );
}
else if( algo == GCRY_PK_RSA ) {
rc = gcry_sexp_build ( &sexp, NULL,
"(public-key(rsa(n%m)(e%m)))",
key[0], key[1] );
}
+ else if( algo == PUBKEY_ALGO_ECDSA || algo == PUBKEY_ALGO_ECDH ) {
+ rc = gcry_sexp_build ( &sexp, NULL,
+ "(public-key(ecc(c%m)(q%m)))",
+ key[0], key[1] /* not affecting the size calculation, so use 'ecc' == 'ecdsa' */ );
+ }
else
return 0;
if ( rc )
BUG ();
nbits = gcry_pk_get_nbits( sexp );
gcry_sexp_release( sexp );
return nbits;
}
/* FIXME: Use gcry_mpi_print directly. */
int
mpi_print (estream_t fp, gcry_mpi_t a, int mode)
{
int n=0;
if (!a)
return es_fprintf (fp, "[MPI_NULL]");
if (!mode)
{
unsigned int n1;
n1 = gcry_mpi_get_nbits(a);
n += es_fprintf (fp, "[%u bits]", n1);
}
else
{
unsigned char *buffer;
if (gcry_mpi_aprint (GCRYMPI_FMT_HEX, &buffer, NULL, a))
BUG ();
es_fputs (buffer, fp);
n += strlen (buffer);
gcry_free (buffer);
}
return n;
}
+/*
+ * Write a special size+body mpi a, to OUT. The format of the content of the MPI is
+ * one byte LEN, following by LEN bytes
+ */
+int
+iobuf_write_size_body_mpi (iobuf_t out, gcry_mpi_t a)
+{
+ byte buffer[256]; /* Fixed buffer for a public parameter, max possible */
+ size_t nbytes = (mpi_get_nbits (a)+7)/8;
+ int rc;
+
+ if( nbytes > sizeof(buffer) ) {
+ log_error("mpi with size+body is too large (%u bytes)\n", nbytes);
+ return gpg_error (GPG_ERR_TOO_LARGE);
+ }
+
+ rc = gcry_mpi_print (GCRYMPI_FMT_USG, buffer, sizeof(buffer), &nbytes, a);
+ if( rc ) {
+ log_error("Failed to exported size+body mpi\n");
+ return rc;
+ }
+ if( nbytes < 2 || buffer[0] != nbytes-1 ) {
+ if( nbytes > 2 )
+ log_error("Internal size mismatch in mpi size+body: %02x != %02x (other bytes: %02x %02x ... %02x %02x)\n",
+ buffer[0], nbytes-1, buffer[1], buffer[2], buffer[nbytes-2], buffer[nbytes-1]);
+ else
+ log_error("Internal size mismatch in mpi size+body: only %d bytes\n", nbytes );
+ return gpg_error (GPG_ERR_INV_DATA);
+ }
+ return iobuf_write( out, buffer, nbytes );
+}
+
+/*
+ * Read a special size+body from inp into body[body_max_size] and return it in a buffer and as MPI.
+ * On success the number of consumed bytes will body[0]+1.
+ * The format of the content of the returned MPI is one byte LEN, following by LEN bytes.
+ * Caller is expected to pre-allocate fixed-size 255 byte buffer (or smaller when appropriate).
+ */
+int
+iobuf_read_size_body( iobuf_t inp, byte *body, int body_max_size, int pktlen, gcry_mpi_t *out ) {
+ unsigned n;
+ int rc;
+ gcry_mpi_t result;
+
+ *out = NULL;
+
+ if( (n = iobuf_readbyte(inp)) == -1 ) {
+ return G10ERR_INVALID_PACKET;
+ }
+ if( n >= body_max_size || n < 2) {
+ log_error("invalid size+body field\n");
+ return G10ERR_INVALID_PACKET;
+ }
+ body[0] = n;
+ if( (n = iobuf_read(inp, body+1, n)) == -1 ) {
+ log_error("invalid size+body field\n");
+ return G10ERR_INVALID_PACKET;
+ }
+ if( n+1 > pktlen ) {
+ log_error("size+body field is larger than the packet\n");
+ return G10ERR_INVALID_PACKET;
+ }
+ rc = gcry_mpi_scan (&result, GCRYMPI_FMT_USG, body, n+1, NULL);
+ if (rc)
+ log_fatal ("mpi_scan failed: %s\n", gpg_strerror (rc));
+
+ *out = result;
+
+ return rc;
+}
+
+
+/* pkey[1] or skey[1] is Q for ECDSA, which is an uncompressed point, i.e. 04 */
+int ecdsa_qbits_from_Q( int qbits ) {
+ if( qbits%8>3 ) {
+ log_error(_("ECDSA public key is expected to be in SEC encoding multiple of 8 bits\n"));
+ return 0;
+ }
+ qbits -= qbits%8;
+ qbits /= 2;
+ return qbits;
+}
+
+
+
+
diff --git a/g10/parse-packet.c b/g10/parse-packet.c
index 3714739d4..42d680ac5 100644
--- a/g10/parse-packet.c
+++ b/g10/parse-packet.c
@@ -1,2767 +1,2828 @@
/* parse-packet.c - read packets
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
* 2007, 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
* 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
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include "gpg.h"
#include "util.h"
#include "packet.h"
#include "iobuf.h"
#include "cipher.h"
#include "filter.h"
#include "photoid.h"
#include "options.h"
#include "main.h"
#include "i18n.h"
static int mpi_print_mode;
static int list_mode;
static estream_t listfp;
static int parse (IOBUF inp, PACKET * pkt, int onlykeypkts,
off_t * retpos, int *skip, IOBUF out, int do_skip
#ifdef DEBUG_PARSE_PACKET
, const char *dbg_w, const char *dbg_f, int dbg_l
#endif
);
static int copy_packet (IOBUF inp, IOBUF out, int pkttype,
unsigned long pktlen, int partial);
static void skip_packet (IOBUF inp, int pkttype,
unsigned long pktlen, int partial);
static void *read_rest (IOBUF inp, size_t pktlen, int partial);
static int parse_marker (IOBUF inp, int pkttype, unsigned long pktlen);
static int parse_symkeyenc (IOBUF inp, int pkttype, unsigned long pktlen,
PACKET * packet);
static int parse_pubkeyenc (IOBUF inp, int pkttype, unsigned long pktlen,
PACKET * packet);
static int parse_onepass_sig (IOBUF inp, int pkttype, unsigned long pktlen,
PKT_onepass_sig * ops);
static int parse_key (IOBUF inp, int pkttype, unsigned long pktlen,
byte * hdr, int hdrlen, PACKET * packet);
static int parse_user_id (IOBUF inp, int pkttype, unsigned long pktlen,
PACKET * packet);
static int parse_attribute (IOBUF inp, int pkttype, unsigned long pktlen,
PACKET * packet);
static int parse_comment (IOBUF inp, int pkttype, unsigned long pktlen,
PACKET * packet);
static void parse_trust (IOBUF inp, int pkttype, unsigned long pktlen,
PACKET * packet);
static int parse_plaintext (IOBUF inp, int pkttype, unsigned long pktlen,
PACKET * packet, int new_ctb, int partial);
static int parse_compressed (IOBUF inp, int pkttype, unsigned long pktlen,
PACKET * packet, int new_ctb);
static int parse_encrypted (IOBUF inp, int pkttype, unsigned long pktlen,
PACKET * packet, int new_ctb, int partial);
static int parse_mdc (IOBUF inp, int pkttype, unsigned long pktlen,
PACKET * packet, int new_ctb);
static int parse_gpg_control (IOBUF inp, int pkttype, unsigned long pktlen,
PACKET * packet, int partial);
static unsigned short
read_16 (IOBUF inp)
{
unsigned short a;
a = iobuf_get_noeof (inp) << 8;
a |= iobuf_get_noeof (inp);
return a;
}
static unsigned long
read_32 (IOBUF inp)
{
unsigned long a;
a = iobuf_get_noeof (inp) << 24;
a |= iobuf_get_noeof (inp) << 16;
a |= iobuf_get_noeof (inp) << 8;
a |= iobuf_get_noeof (inp);
return a;
}
/* Read an external representation of an mpi and return the MPI. The
* external format is a 16 bit unsigned value stored in network byte
* order, giving the number of bits for the following integer. The
* integer is stored with MSB first (left padded with zeroes to align
* on a byte boundary). */
static gcry_mpi_t
mpi_read (iobuf_t inp, unsigned int *ret_nread, int secure)
{
/*FIXME: Needs to be synced with gnupg14/mpi/mpicoder.c */
int c, c1, c2, i;
unsigned int nbits, nbytes;
size_t nread = 0;
gcry_mpi_t a = NULL;
byte *buf = NULL;
byte *p;
if ((c = c1 = iobuf_get (inp)) == -1)
goto leave;
nbits = c << 8;
if ((c = c2 = iobuf_get (inp)) == -1)
goto leave;
nbits |= c;
if (nbits > MAX_EXTERN_MPI_BITS)
{
log_error ("mpi too large (%u bits)\n", nbits);
goto leave;
}
nread = 2;
nbytes = (nbits + 7) / 8;
buf = secure ? gcry_xmalloc_secure (nbytes + 2) : gcry_xmalloc (nbytes + 2);
p = buf;
p[0] = c1;
p[1] = c2;
for (i = 0; i < nbytes; i++)
{
p[i + 2] = iobuf_get (inp) & 0xff;
nread++;
}
if (nread >= 2 && !(buf[0] << 8 | buf[1]))
{
/* Libgcrypt < 1.5.0 accidently rejects zero-length (i.e. zero)
MPIs. We fix this here. */
a = gcry_mpi_new (0);
}
else
{
if (gcry_mpi_scan (&a, GCRYMPI_FMT_PGP, buf, nread, &nread))
a = NULL;
}
leave:
gcry_free (buf);
if (nread > *ret_nread)
log_bug ("mpi larger than packet");
else
*ret_nread = nread;
return a;
}
int
set_packet_list_mode (int mode)
{
int old = list_mode;
list_mode = mode;
/* FIXME(gcrypt) mpi_print_mode = DBG_MPI; */
/* We use stdout print only if invoked by the --list-packets command
but switch to stderr in all other cases. This breaks the
previous behaviour but that seems to be more of a bug than
intentional. I don't believe that any application makes use of
this long standing annoying way of printing to stdout except when
doing a --list-packets. If this assumption fails, it will be easy
to add an option for the listing stream. Note that we initialize
it only once; mainly because some code may switch the option
value later back to 1 and we want to have all output to the same
stream.
Using stderr is not actually very clean because it bypasses the
logging code but it is a special thing anyway. I am not sure
whether using log_stream() would be better. Perhaps we should
enable the list mdoe only with a special option. */
if (!listfp)
listfp = opt.list_packets == 2 ? es_stdout : es_stderr;
return old;
}
static void
unknown_pubkey_warning (int algo)
{
static byte unknown_pubkey_algos[256];
algo &= 0xff;
if (!unknown_pubkey_algos[algo])
{
if (opt.verbose)
log_info (_("can't handle public key algorithm %d\n"), algo);
unknown_pubkey_algos[algo] = 1;
}
}
/* Parse a packet and return it in packet structure.
* Returns: 0 := valid packet in pkt
* -1 := no more packets
* >0 := error
* Note: The function may return an error and a partly valid packet;
* caller must free this packet. */
#ifdef DEBUG_PARSE_PACKET
int
dbg_parse_packet (IOBUF inp, PACKET *pkt, const char *dbg_f, int dbg_l)
{
int skip, rc;
do
{
rc = parse (inp, pkt, 0, NULL, &skip, NULL, 0, "parse", dbg_f, dbg_l);
}
while (skip);
return rc;
}
#else /*!DEBUG_PARSE_PACKET*/
int
parse_packet (IOBUF inp, PACKET * pkt)
{
int skip, rc;
do
{
rc = parse (inp, pkt, 0, NULL, &skip, NULL, 0);
}
while (skip);
return rc;
}
#endif /*!DEBUG_PARSE_PACKET*/
/*
* Like parse packet, but only return secret or public (sub)key
* packets.
*/
#ifdef DEBUG_PARSE_PACKET
int
dbg_search_packet (IOBUF inp, PACKET * pkt, off_t * retpos, int with_uid,
const char *dbg_f, int dbg_l)
{
int skip, rc;
do
{
rc =
parse (inp, pkt, with_uid ? 2 : 1, retpos, &skip, NULL, 0, "search",
dbg_f, dbg_l);
}
while (skip);
return rc;
}
#else /*!DEBUG_PARSE_PACKET*/
int
search_packet (IOBUF inp, PACKET * pkt, off_t * retpos, int with_uid)
{
int skip, rc;
do
{
rc = parse (inp, pkt, with_uid ? 2 : 1, retpos, &skip, NULL, 0);
}
while (skip);
return rc;
}
#endif /*!DEBUG_PARSE_PACKET*/
/*
* Copy all packets from INP to OUT, thereby removing unused spaces.
*/
#ifdef DEBUG_PARSE_PACKET
int
dbg_copy_all_packets (IOBUF inp, IOBUF out, const char *dbg_f, int dbg_l)
{
PACKET pkt;
int skip, rc = 0;
do
{
init_packet (&pkt);
}
while (!
(rc =
parse (inp, &pkt, 0, NULL, &skip, out, 0, "copy", dbg_f, dbg_l)));
return rc;
}
#else /*!DEBUG_PARSE_PACKET*/
int
copy_all_packets (IOBUF inp, IOBUF out)
{
PACKET pkt;
int skip, rc = 0;
do
{
init_packet (&pkt);
}
while (!(rc = parse (inp, &pkt, 0, NULL, &skip, out, 0)));
return rc;
}
#endif /*!DEBUG_PARSE_PACKET*/
/*
* Copy some packets from INP to OUT, thereby removing unused spaces.
* Stop at offset STOPoff (i.e. don't copy packets at this or later
* offsets)
*/
#ifdef DEBUG_PARSE_PACKET
int
dbg_copy_some_packets (IOBUF inp, IOBUF out, off_t stopoff,
const char *dbg_f, int dbg_l)
{
PACKET pkt;
int skip, rc = 0;
do
{
if (iobuf_tell (inp) >= stopoff)
return 0;
init_packet (&pkt);
}
while (!(rc = parse (inp, &pkt, 0, NULL, &skip, out, 0,
"some", dbg_f, dbg_l)));
return rc;
}
#else /*!DEBUG_PARSE_PACKET*/
int
copy_some_packets (IOBUF inp, IOBUF out, off_t stopoff)
{
PACKET pkt;
int skip, rc = 0;
do
{
if (iobuf_tell (inp) >= stopoff)
return 0;
init_packet (&pkt);
}
while (!(rc = parse (inp, &pkt, 0, NULL, &skip, out, 0)));
return rc;
}
#endif /*!DEBUG_PARSE_PACKET*/
/*
* Skip over N packets
*/
#ifdef DEBUG_PARSE_PACKET
int
dbg_skip_some_packets (IOBUF inp, unsigned n, const char *dbg_f, int dbg_l)
{
int skip, rc = 0;
PACKET pkt;
for (; n && !rc; n--)
{
init_packet (&pkt);
rc = parse (inp, &pkt, 0, NULL, &skip, NULL, 1, "skip", dbg_f, dbg_l);
}
return rc;
}
#else /*!DEBUG_PARSE_PACKET*/
int
skip_some_packets (IOBUF inp, unsigned n)
{
int skip, rc = 0;
PACKET pkt;
for (; n && !rc; n--)
{
init_packet (&pkt);
rc = parse (inp, &pkt, 0, NULL, &skip, NULL, 1);
}
return rc;
}
#endif /*!DEBUG_PARSE_PACKET*/
/*
* Parse packet. Stores 1 at SKIP 1 if the packet should be skipped;
* this is the case if either ONLYKEYPKTS is set and the parsed packet
* isn't a key packet or the packet-type is 0, indicating deleted
* stuff. If OUT is not NULL, a special copymode is used.
*/
static int
parse (IOBUF inp, PACKET * pkt, int onlykeypkts, off_t * retpos,
int *skip, IOBUF out, int do_skip
#ifdef DEBUG_PARSE_PACKET
, const char *dbg_w, const char *dbg_f, int dbg_l
#endif
)
{
int rc = 0, c, ctb, pkttype, lenbytes;
unsigned long pktlen;
byte hdr[8];
int hdrlen;
int new_ctb = 0, partial = 0;
int with_uid = (onlykeypkts == 2);
*skip = 0;
assert (!pkt->pkt.generic);
if (retpos)
*retpos = iobuf_tell (inp);
if ((ctb = iobuf_get (inp)) == -1)
{
rc = -1;
goto leave;
}
hdrlen = 0;
hdr[hdrlen++] = ctb;
if (!(ctb & 0x80))
{
log_error ("%s: invalid packet (ctb=%02x)\n", iobuf_where (inp), ctb);
rc = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
pktlen = 0;
new_ctb = !!(ctb & 0x40);
if (new_ctb)
{
pkttype = ctb & 0x3f;
if ((c = iobuf_get (inp)) == -1)
{
log_error ("%s: 1st length byte missing\n", iobuf_where (inp));
rc = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
hdr[hdrlen++] = c;
if (c < 192)
pktlen = c;
else if (c < 224)
{
pktlen = (c - 192) * 256;
if ((c = iobuf_get (inp)) == -1)
{
log_error ("%s: 2nd length byte missing\n",
iobuf_where (inp));
rc = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
hdr[hdrlen++] = c;
pktlen += c + 192;
}
else if (c == 255)
{
pktlen = (hdr[hdrlen++] = iobuf_get_noeof (inp)) << 24;
pktlen |= (hdr[hdrlen++] = iobuf_get_noeof (inp)) << 16;
pktlen |= (hdr[hdrlen++] = iobuf_get_noeof (inp)) << 8;
if ((c = iobuf_get (inp)) == -1)
{
log_error ("%s: 4 byte length invalid\n", iobuf_where (inp));
rc = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
pktlen |= (hdr[hdrlen++] = c);
}
else /* Partial body length. */
{
switch (pkttype)
{
case PKT_PLAINTEXT:
case PKT_ENCRYPTED:
case PKT_ENCRYPTED_MDC:
case PKT_COMPRESSED:
iobuf_set_partial_block_mode (inp, c & 0xff);
pktlen = 0; /* To indicate partial length. */
partial = 1;
break;
default:
log_error ("%s: partial length for invalid"
" packet type %d\n", iobuf_where (inp), pkttype);
rc = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
}
}
else
{
pkttype = (ctb >> 2) & 0xf;
lenbytes = ((ctb & 3) == 3) ? 0 : (1 << (ctb & 3));
if (!lenbytes)
{
pktlen = 0; /* Don't know the value. */
/* This isn't really partial, but we can treat it the same
in a "read until the end" sort of way. */
partial = 1;
if (pkttype != PKT_ENCRYPTED && pkttype != PKT_PLAINTEXT
&& pkttype != PKT_COMPRESSED)
{
log_error ("%s: indeterminate length for invalid"
" packet type %d\n", iobuf_where (inp), pkttype);
rc = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
}
else
{
for (; lenbytes; lenbytes--)
{
pktlen <<= 8;
pktlen |= hdr[hdrlen++] = iobuf_get_noeof (inp);
}
}
}
if (pktlen == (unsigned long) (-1))
{
/* With some probability this is caused by a problem in the
* the uncompressing layer - in some error cases it just loops
* and spits out 0xff bytes. */
log_error ("%s: garbled packet detected\n", iobuf_where (inp));
g10_exit (2);
}
if (out && pkttype)
{
rc = iobuf_write (out, hdr, hdrlen);
if (!rc)
rc = copy_packet (inp, out, pkttype, pktlen, partial);
goto leave;
}
if (with_uid && pkttype == PKT_USER_ID)
;
else if (do_skip
|| !pkttype
|| (onlykeypkts && pkttype != PKT_PUBLIC_SUBKEY
&& pkttype != PKT_PUBLIC_KEY
&& pkttype != PKT_SECRET_SUBKEY && pkttype != PKT_SECRET_KEY))
{
iobuf_skip_rest (inp, pktlen, partial);
*skip = 1;
rc = 0;
goto leave;
}
if (DBG_PACKET)
{
#ifdef DEBUG_PARSE_PACKET
log_debug ("parse_packet(iob=%d): type=%d length=%lu%s (%s.%s.%d)\n",
iobuf_id (inp), pkttype, pktlen, new_ctb ? " (new_ctb)" : "",
dbg_w, dbg_f, dbg_l);
#else
log_debug ("parse_packet(iob=%d): type=%d length=%lu%s\n",
iobuf_id (inp), pkttype, pktlen,
new_ctb ? " (new_ctb)" : "");
#endif
}
pkt->pkttype = pkttype;
rc = G10ERR_UNKNOWN_PACKET; /* default error */
switch (pkttype)
{
case PKT_PUBLIC_KEY:
case PKT_PUBLIC_SUBKEY:
case PKT_SECRET_KEY:
case PKT_SECRET_SUBKEY:
pkt->pkt.public_key = xmalloc_clear (sizeof *pkt->pkt.public_key);
rc = parse_key (inp, pkttype, pktlen, hdr, hdrlen, pkt);
break;
case PKT_SYMKEY_ENC:
rc = parse_symkeyenc (inp, pkttype, pktlen, pkt);
break;
case PKT_PUBKEY_ENC:
rc = parse_pubkeyenc (inp, pkttype, pktlen, pkt);
break;
case PKT_SIGNATURE:
pkt->pkt.signature = xmalloc_clear (sizeof *pkt->pkt.signature);
rc = parse_signature (inp, pkttype, pktlen, pkt->pkt.signature);
break;
case PKT_ONEPASS_SIG:
pkt->pkt.onepass_sig = xmalloc_clear (sizeof *pkt->pkt.onepass_sig);
rc = parse_onepass_sig (inp, pkttype, pktlen, pkt->pkt.onepass_sig);
break;
case PKT_USER_ID:
rc = parse_user_id (inp, pkttype, pktlen, pkt);
break;
case PKT_ATTRIBUTE:
pkt->pkttype = pkttype = PKT_USER_ID; /* we store it in the userID */
rc = parse_attribute (inp, pkttype, pktlen, pkt);
break;
case PKT_OLD_COMMENT:
case PKT_COMMENT:
rc = parse_comment (inp, pkttype, pktlen, pkt);
break;
case PKT_RING_TRUST:
parse_trust (inp, pkttype, pktlen, pkt);
rc = 0;
break;
case PKT_PLAINTEXT:
rc = parse_plaintext (inp, pkttype, pktlen, pkt, new_ctb, partial);
break;
case PKT_COMPRESSED:
rc = parse_compressed (inp, pkttype, pktlen, pkt, new_ctb);
break;
case PKT_ENCRYPTED:
case PKT_ENCRYPTED_MDC:
rc = parse_encrypted (inp, pkttype, pktlen, pkt, new_ctb, partial);
break;
case PKT_MDC:
rc = parse_mdc (inp, pkttype, pktlen, pkt, new_ctb);
break;
case PKT_GPG_CONTROL:
rc = parse_gpg_control (inp, pkttype, pktlen, pkt, partial);
break;
case PKT_MARKER:
rc = parse_marker (inp, pkttype, pktlen);
break;
default:
skip_packet (inp, pkttype, pktlen, partial);
break;
}
leave:
/* FIXME: Do we leak in case of an error? */
if (!rc && iobuf_error (inp))
rc = G10ERR_INV_KEYRING;
return rc;
}
static void
dump_hex_line (int c, int *i)
{
if (*i && !(*i % 8))
{
if (*i && !(*i % 24))
es_fprintf (listfp, "\n%4d:", *i);
else
es_putc (' ', listfp);
}
if (c == -1)
es_fprintf (listfp, " EOF");
else
es_fprintf (listfp, " %02x", c);
++*i;
}
static int
copy_packet (IOBUF inp, IOBUF out, int pkttype,
unsigned long pktlen, int partial)
{
int rc;
int n;
char buf[100];
if (partial)
{
while ((n = iobuf_read (inp, buf, 100)) != -1)
if ((rc = iobuf_write (out, buf, n)))
return rc; /* write error */
}
else if (!pktlen && pkttype == PKT_COMPRESSED)
{
log_debug ("copy_packet: compressed!\n");
/* compressed packet, copy till EOF */
while ((n = iobuf_read (inp, buf, 100)) != -1)
if ((rc = iobuf_write (out, buf, n)))
return rc; /* write error */
}
else
{
for (; pktlen; pktlen -= n)
{
n = pktlen > 100 ? 100 : pktlen;
n = iobuf_read (inp, buf, n);
if (n == -1)
return gpg_error (GPG_ERR_EOF);
if ((rc = iobuf_write (out, buf, n)))
return rc; /* write error */
}
}
return 0;
}
static void
skip_packet (IOBUF inp, int pkttype, unsigned long pktlen, int partial)
{
if (list_mode)
{
es_fprintf (listfp, ":unknown packet: type %2d, length %lu\n",
pkttype, pktlen);
if (pkttype)
{
int c, i = 0;
es_fputs ("dump:", listfp);
if (partial)
{
while ((c = iobuf_get (inp)) != -1)
dump_hex_line (c, &i);
}
else
{
for (; pktlen; pktlen--)
{
dump_hex_line ((c = iobuf_get (inp)), &i);
if (c == -1)
break;
}
}
es_putc ('\n', listfp);
return;
}
}
iobuf_skip_rest (inp, pktlen, partial);
}
static void *
read_rest (IOBUF inp, size_t pktlen, int partial)
{
byte *p;
int i;
if (partial)
{
log_error ("read_rest: can't store stream data\n");
p = NULL;
}
else
{
p = xmalloc (pktlen);
for (i = 0; pktlen; pktlen--, i++)
p[i] = iobuf_get (inp);
}
return p;
}
static int
parse_marker (IOBUF inp, int pkttype, unsigned long pktlen)
{
(void) pkttype;
if (pktlen != 3)
goto fail;
if (iobuf_get (inp) != 'P')
{
pktlen--;
goto fail;
}
if (iobuf_get (inp) != 'G')
{
pktlen--;
goto fail;
}
if (iobuf_get (inp) != 'P')
{
pktlen--;
goto fail;
}
if (list_mode)
es_fputs (":marker packet: PGP\n", listfp);
return 0;
fail:
log_error ("invalid marker packet\n");
iobuf_skip_rest (inp, pktlen, 0);
return G10ERR_INVALID_PACKET;
}
static int
parse_symkeyenc (IOBUF inp, int pkttype, unsigned long pktlen,
PACKET * packet)
{
PKT_symkey_enc *k;
int rc = 0;
int i, version, s2kmode, cipher_algo, hash_algo, seskeylen, minlen;
if (pktlen < 4)
{
log_error ("packet(%d) too short\n", pkttype);
rc = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
version = iobuf_get_noeof (inp);
pktlen--;
if (version != 4)
{
log_error ("packet(%d) with unknown version %d\n", pkttype, version);
rc = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
if (pktlen > 200)
{ /* (we encode the seskeylen in a byte) */
log_error ("packet(%d) too large\n", pkttype);
rc = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
cipher_algo = iobuf_get_noeof (inp);
pktlen--;
s2kmode = iobuf_get_noeof (inp);
pktlen--;
hash_algo = iobuf_get_noeof (inp);
pktlen--;
switch (s2kmode)
{
case 0: /* Simple S2K. */
minlen = 0;
break;
case 1: /* Salted S2K. */
minlen = 8;
break;
case 3: /* Iterated+salted S2K. */
minlen = 9;
break;
default:
log_error ("unknown S2K mode %d\n", s2kmode);
goto leave;
}
if (minlen > pktlen)
{
log_error ("packet with S2K %d too short\n", s2kmode);
rc = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
seskeylen = pktlen - minlen;
k = packet->pkt.symkey_enc = xmalloc_clear (sizeof *packet->pkt.symkey_enc
+ seskeylen - 1);
k->version = version;
k->cipher_algo = cipher_algo;
k->s2k.mode = s2kmode;
k->s2k.hash_algo = hash_algo;
if (s2kmode == 1 || s2kmode == 3)
{
for (i = 0; i < 8 && pktlen; i++, pktlen--)
k->s2k.salt[i] = iobuf_get_noeof (inp);
}
if (s2kmode == 3)
{
k->s2k.count = iobuf_get (inp);
pktlen--;
}
k->seskeylen = seskeylen;
if (k->seskeylen)
{
for (i = 0; i < seskeylen && pktlen; i++, pktlen--)
k->seskey[i] = iobuf_get_noeof (inp);
/* What we're watching out for here is a session key decryptor
with no salt. The RFC says that using salt for this is a
MUST. */
if (s2kmode != 1 && s2kmode != 3)
log_info (_("WARNING: potentially insecure symmetrically"
" encrypted session key\n"));
}
assert (!pktlen);
if (list_mode)
{
es_fprintf (listfp,
":symkey enc packet: version %d, cipher %d, s2k %d, hash %d",
version, cipher_algo, s2kmode, hash_algo);
if (seskeylen)
es_fprintf (listfp, ", seskey %d bits", (seskeylen - 1) * 8);
es_fprintf (listfp, "\n");
if (s2kmode == 1 || s2kmode == 3)
{
es_fprintf (listfp, "\tsalt ");
es_write_hexstring (listfp, k->s2k.salt, 8, 0, NULL);
if (s2kmode == 3)
es_fprintf (listfp, ", count %lu (%lu)",
S2K_DECODE_COUNT ((ulong) k->s2k.count),
(ulong) k->s2k.count);
es_fprintf (listfp, "\n");
}
}
leave:
iobuf_skip_rest (inp, pktlen, 0);
return rc;
}
static int
parse_pubkeyenc (IOBUF inp, int pkttype, unsigned long pktlen,
PACKET * packet)
{
unsigned int n;
int rc = 0;
int i, ndata;
PKT_pubkey_enc *k;
k = packet->pkt.pubkey_enc = xmalloc_clear (sizeof *packet->pkt.pubkey_enc);
if (pktlen < 12)
{
log_error ("packet(%d) too short\n", pkttype);
rc = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
k->version = iobuf_get_noeof (inp);
pktlen--;
if (k->version != 2 && k->version != 3)
{
log_error ("packet(%d) with unknown version %d\n", pkttype, k->version);
rc = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
k->keyid[0] = read_32 (inp);
pktlen -= 4;
k->keyid[1] = read_32 (inp);
pktlen -= 4;
k->pubkey_algo = iobuf_get_noeof (inp);
pktlen--;
k->throw_keyid = 0; /* Only used as flag for build_packet. */
if (list_mode)
es_fprintf (listfp,
":pubkey enc packet: version %d, algo %d, keyid %08lX%08lX\n",
k->version, k->pubkey_algo, (ulong) k->keyid[0],
(ulong) k->keyid[1]);
ndata = pubkey_get_nenc (k->pubkey_algo);
if (!ndata)
{
if (list_mode)
es_fprintf (listfp, "\tunsupported algorithm %d\n", k->pubkey_algo);
unknown_pubkey_warning (k->pubkey_algo);
k->data[0] = NULL; /* No need to store the encrypted data. */
}
else
{
- for (i = 0; i < ndata; i++)
- {
- n = pktlen;
- k->data[i] = mpi_read (inp, &n, 0);
- pktlen -= n;
- if (list_mode)
- {
- es_fprintf (listfp, "\tdata: ");
- mpi_print (listfp, k->data[i], mpi_print_mode);
- es_putc ('\n', listfp);
- }
- if (!k->data[i])
- rc = gpg_error (GPG_ERR_INV_PACKET);
- }
+ if( k->pubkey_algo != PUBKEY_ALGO_ECDH ) {
+ for (i = 0; i < ndata; i++)
+ {
+ n = pktlen;
+ k->data[i] = mpi_read (inp, &n, 0);
+ pktlen -= n;
+ if (list_mode)
+ {
+ es_fprintf (listfp, "\tdata: ");
+ mpi_print (listfp, k->data[i], mpi_print_mode);
+ es_putc ('\n', listfp);
+ }
+ if (!k->data[i])
+ rc = gpg_error (GPG_ERR_INV_PACKET);
+ }
+ }
+ else
+ {
+ byte encr_buf[255];
+ assert( ndata == 2 );
+ n = pktlen; k->data[0] = mpi_read(inp, &n, 0); pktlen -=n;
+ rc = iobuf_read_size_body( inp, encr_buf, sizeof(encr_buf), pktlen, k->data+1 );
+ if( rc )
+ goto leave;
+ if( list_mode ) {
+ es_fprintf (listfp, "\tdata: ");
+ mpi_print(listfp, k->data[0], mpi_print_mode );
+ es_putc ('\n', listfp);
+ es_fprintf (listfp, "\tdata: [% 3d bytes] ", encr_buf[0]);
+ mpi_print(listfp, k->data[1], mpi_print_mode );
+ es_putc ('\n', listfp);
+ }
+ pktlen -= (encr_buf[0]+1);
+ }
}
leave:
iobuf_skip_rest (inp, pktlen, 0);
return rc;
}
static void
dump_sig_subpkt (int hashed, int type, int critical,
const byte * buffer, size_t buflen, size_t length)
{
const char *p = NULL;
int i;
/* The CERT has warning out with explains how to use GNUPG to detect
* the ARRs - we print our old message here when it is a faked ARR
* and add an additional notice. */
if (type == SIGSUBPKT_ARR && !hashed)
{
es_fprintf (listfp,
"\tsubpkt %d len %u (additional recipient request)\n"
"WARNING: PGP versions > 5.0 and < 6.5.8 will automagically "
"encrypt to this key and thereby reveal the plaintext to "
"the owner of this ARR key. Detailed info follows:\n",
type, (unsigned) length);
}
buffer++;
length--;
es_fprintf (listfp, "\t%s%ssubpkt %d len %u (", /*) */
critical ? "critical " : "",
hashed ? "hashed " : "", type, (unsigned) length);
if (length > buflen)
{
es_fprintf (listfp, "too short: buffer is only %u)\n", (unsigned) buflen);
return;
}
switch (type)
{
case SIGSUBPKT_SIG_CREATED:
if (length >= 4)
es_fprintf (listfp, "sig created %s",
strtimestamp (buffer_to_u32 (buffer)));
break;
case SIGSUBPKT_SIG_EXPIRE:
if (length >= 4)
{
if (buffer_to_u32 (buffer))
es_fprintf (listfp, "sig expires after %s",
strtimevalue (buffer_to_u32 (buffer)));
else
es_fprintf (listfp, "sig does not expire");
}
break;
case SIGSUBPKT_EXPORTABLE:
if (length)
es_fprintf (listfp, "%sexportable", *buffer ? "" : "not ");
break;
case SIGSUBPKT_TRUST:
if (length != 2)
p = "[invalid trust subpacket]";
else
es_fprintf (listfp, "trust signature of depth %d, value %d", buffer[0],
buffer[1]);
break;
case SIGSUBPKT_REGEXP:
if (!length)
p = "[invalid regexp subpacket]";
else
es_fprintf (listfp, "regular expression: \"%s\"", buffer);
break;
case SIGSUBPKT_REVOCABLE:
if (length)
es_fprintf (listfp, "%srevocable", *buffer ? "" : "not ");
break;
case SIGSUBPKT_KEY_EXPIRE:
if (length >= 4)
{
if (buffer_to_u32 (buffer))
es_fprintf (listfp, "key expires after %s",
strtimevalue (buffer_to_u32 (buffer)));
else
es_fprintf (listfp, "key does not expire");
}
break;
case SIGSUBPKT_PREF_SYM:
es_fputs ("pref-sym-algos:", listfp);
for (i = 0; i < length; i++)
es_fprintf (listfp, " %d", buffer[i]);
break;
case SIGSUBPKT_REV_KEY:
es_fputs ("revocation key: ", listfp);
if (length < 22)
p = "[too short]";
else
{
es_fprintf (listfp, "c=%02x a=%d f=", buffer[0], buffer[1]);
for (i = 2; i < length; i++)
es_fprintf (listfp, "%02X", buffer[i]);
}
break;
case SIGSUBPKT_ISSUER:
if (length >= 8)
es_fprintf (listfp, "issuer key ID %08lX%08lX",
(ulong) buffer_to_u32 (buffer),
(ulong) buffer_to_u32 (buffer + 4));
break;
case SIGSUBPKT_NOTATION:
{
es_fputs ("notation: ", listfp);
if (length < 8)
p = "[too short]";
else
{
const byte *s = buffer;
size_t n1, n2;
n1 = (s[4] << 8) | s[5];
n2 = (s[6] << 8) | s[7];
s += 8;
if (8 + n1 + n2 != length)
p = "[error]";
else
{
es_write_sanitized (listfp, s, n1, ")", NULL);
es_putc ('=', listfp);
if (*buffer & 0x80)
es_write_sanitized (listfp, s + n1, n2, ")", NULL);
else
p = "[not human readable]";
}
}
}
break;
case SIGSUBPKT_PREF_HASH:
es_fputs ("pref-hash-algos:", listfp);
for (i = 0; i < length; i++)
es_fprintf (listfp, " %d", buffer[i]);
break;
case SIGSUBPKT_PREF_COMPR:
es_fputs ("pref-zip-algos:", listfp);
for (i = 0; i < length; i++)
es_fprintf (listfp, " %d", buffer[i]);
break;
case SIGSUBPKT_KS_FLAGS:
es_fputs ("key server preferences:", listfp);
for (i = 0; i < length; i++)
es_fprintf (listfp, " %02X", buffer[i]);
break;
case SIGSUBPKT_PREF_KS:
es_fputs ("preferred key server: ", listfp);
es_write_sanitized (listfp, buffer, length, ")", NULL);
break;
case SIGSUBPKT_PRIMARY_UID:
p = "primary user ID";
break;
case SIGSUBPKT_POLICY:
es_fputs ("policy: ", listfp);
es_write_sanitized (listfp, buffer, length, ")", NULL);
break;
case SIGSUBPKT_KEY_FLAGS:
es_fputs ("key flags:", listfp);
for (i = 0; i < length; i++)
es_fprintf (listfp, " %02X", buffer[i]);
break;
case SIGSUBPKT_SIGNERS_UID:
p = "signer's user ID";
break;
case SIGSUBPKT_REVOC_REASON:
if (length)
{
es_fprintf (listfp, "revocation reason 0x%02x (", *buffer);
es_write_sanitized (listfp, buffer + 1, length - 1, ")", NULL);
p = ")";
}
break;
case SIGSUBPKT_ARR:
es_fputs ("Big Brother's key (ignored): ", listfp);
if (length < 22)
p = "[too short]";
else
{
es_fprintf (listfp, "c=%02x a=%d f=", buffer[0], buffer[1]);
if (length > 2)
es_write_hexstring (listfp, buffer+2, length-2, 0, NULL);
}
break;
case SIGSUBPKT_FEATURES:
es_fputs ("features:", listfp);
for (i = 0; i < length; i++)
es_fprintf (listfp, " %02x", buffer[i]);
break;
case SIGSUBPKT_SIGNATURE:
es_fputs ("signature: ", listfp);
if (length < 17)
p = "[too short]";
else
es_fprintf (listfp, "v%d, class 0x%02X, algo %d, digest algo %d",
buffer[0],
buffer[0] == 3 ? buffer[2] : buffer[1],
buffer[0] == 3 ? buffer[15] : buffer[2],
buffer[0] == 3 ? buffer[16] : buffer[3]);
break;
default:
if (type >= 100 && type <= 110)
p = "experimental / private subpacket";
else
p = "?";
break;
}
es_fprintf (listfp, "%s)\n", p ? p : "");
}
/*
* Returns: >= 0 use this offset into buffer
* -1 explicitly reject returning this type
* -2 subpacket too short
*/
int
parse_one_sig_subpkt (const byte * buffer, size_t n, int type)
{
switch (type)
{
case SIGSUBPKT_REV_KEY:
if (n < 22)
break;
return 0;
case SIGSUBPKT_SIG_CREATED:
case SIGSUBPKT_SIG_EXPIRE:
case SIGSUBPKT_KEY_EXPIRE:
if (n < 4)
break;
return 0;
case SIGSUBPKT_KEY_FLAGS:
case SIGSUBPKT_KS_FLAGS:
case SIGSUBPKT_PREF_SYM:
case SIGSUBPKT_PREF_HASH:
case SIGSUBPKT_PREF_COMPR:
case SIGSUBPKT_POLICY:
case SIGSUBPKT_PREF_KS:
case SIGSUBPKT_FEATURES:
case SIGSUBPKT_REGEXP:
return 0;
case SIGSUBPKT_SIGNATURE:
case SIGSUBPKT_EXPORTABLE:
case SIGSUBPKT_REVOCABLE:
case SIGSUBPKT_REVOC_REASON:
if (!n)
break;
return 0;
case SIGSUBPKT_ISSUER: /* issuer key ID */
if (n < 8)
break;
return 0;
case SIGSUBPKT_NOTATION:
/* minimum length needed, and the subpacket must be well-formed
where the name length and value length all fit inside the
packet. */
if (n < 8
|| 8 + ((buffer[4] << 8) | buffer[5]) +
((buffer[6] << 8) | buffer[7]) != n)
break;
return 0;
case SIGSUBPKT_PRIMARY_UID:
if (n != 1)
break;
return 0;
case SIGSUBPKT_TRUST:
if (n != 2)
break;
return 0;
default:
return 0;
}
return -2;
}
/* Return true if we understand the critical notation. */
static int
can_handle_critical_notation (const byte * name, size_t len)
{
if (len == 32 && memcmp (name, "preferred-email-encoding@pgp.com", 32) == 0)
return 1;
if (len == 21 && memcmp (name, "pka-address@gnupg.org", 21) == 0)
return 1;
return 0;
}
static int
can_handle_critical (const byte * buffer, size_t n, int type)
{
switch (type)
{
case SIGSUBPKT_NOTATION:
if (n >= 8)
return can_handle_critical_notation (buffer + 8,
(buffer[4] << 8) | buffer[5]);
else
return 0;
case SIGSUBPKT_SIGNATURE:
case SIGSUBPKT_SIG_CREATED:
case SIGSUBPKT_SIG_EXPIRE:
case SIGSUBPKT_KEY_EXPIRE:
case SIGSUBPKT_EXPORTABLE:
case SIGSUBPKT_REVOCABLE:
case SIGSUBPKT_REV_KEY:
case SIGSUBPKT_ISSUER: /* issuer key ID */
case SIGSUBPKT_PREF_SYM:
case SIGSUBPKT_PREF_HASH:
case SIGSUBPKT_PREF_COMPR:
case SIGSUBPKT_KEY_FLAGS:
case SIGSUBPKT_PRIMARY_UID:
case SIGSUBPKT_FEATURES:
case SIGSUBPKT_TRUST:
case SIGSUBPKT_REGEXP:
/* Is it enough to show the policy or keyserver? */
case SIGSUBPKT_POLICY:
case SIGSUBPKT_PREF_KS:
return 1;
default:
return 0;
}
}
const byte *
enum_sig_subpkt (const subpktarea_t * pktbuf, sigsubpkttype_t reqtype,
size_t * ret_n, int *start, int *critical)
{
const byte *buffer;
int buflen;
int type;
int critical_dummy;
int offset;
size_t n;
int seq = 0;
int reqseq = start ? *start : 0;
if (!critical)
critical = &critical_dummy;
if (!pktbuf || reqseq == -1)
{
/* return some value different from NULL to indicate that
* there is no critical bit we do not understand. The caller
* will never use the value. Yes I know, it is an ugly hack */
return reqtype ==
SIGSUBPKT_TEST_CRITICAL ? (const byte *) &pktbuf : NULL;
}
buffer = pktbuf->data;
buflen = pktbuf->len;
while (buflen)
{
n = *buffer++;
buflen--;
if (n == 255) /* 4 byte length header. */
{
if (buflen < 4)
goto too_short;
n = (buffer[0] << 24) | (buffer[1] << 16)
| (buffer[2] << 8) | buffer[3];
buffer += 4;
buflen -= 4;
}
else if (n >= 192) /* 4 byte special encoded length header. */
{
if (buflen < 2)
goto too_short;
n = ((n - 192) << 8) + *buffer + 192;
buffer++;
buflen--;
}
if (buflen < n)
goto too_short;
type = *buffer;
if (type & 0x80)
{
type &= 0x7f;
*critical = 1;
}
else
*critical = 0;
if (!(++seq > reqseq))
;
else if (reqtype == SIGSUBPKT_TEST_CRITICAL)
{
if (*critical)
{
if (n - 1 > buflen + 1)
goto too_short;
if (!can_handle_critical (buffer + 1, n - 1, type))
{
if (opt.verbose)
log_info (_("subpacket of type %d has "
"critical bit set\n"), type);
if (start)
*start = seq;
return NULL; /* This is an error. */
}
}
}
else if (reqtype < 0) /* List packets. */
dump_sig_subpkt (reqtype == SIGSUBPKT_LIST_HASHED,
type, *critical, buffer, buflen, n);
else if (type == reqtype) /* Found. */
{
buffer++;
n--;
if (n > buflen)
goto too_short;
if (ret_n)
*ret_n = n;
offset = parse_one_sig_subpkt (buffer, n, type);
switch (offset)
{
case -2:
log_error ("subpacket of type %d too short\n", type);
return NULL;
case -1:
return NULL;
default:
break;
}
if (start)
*start = seq;
return buffer + offset;
}
buffer += n;
buflen -= n;
}
if (reqtype == SIGSUBPKT_TEST_CRITICAL)
return buffer; /* Used as True to indicate that there is no. */
/* Critical bit we don't understand. */
if (start)
*start = -1;
return NULL; /* End of packets; not found. */
too_short:
if (opt.verbose)
log_info ("buffer shorter than subpacket\n");
if (start)
*start = -1;
return NULL;
}
const byte *
parse_sig_subpkt (const subpktarea_t * buffer, sigsubpkttype_t reqtype,
size_t * ret_n)
{
return enum_sig_subpkt (buffer, reqtype, ret_n, NULL, NULL);
}
const byte *
parse_sig_subpkt2 (PKT_signature * sig, sigsubpkttype_t reqtype,
size_t * ret_n)
{
const byte *p;
p = parse_sig_subpkt (sig->hashed, reqtype, ret_n);
if (!p)
p = parse_sig_subpkt (sig->unhashed, reqtype, ret_n);
return p;
}
/* Find all revocation keys. Look in hashed area only. */
void
parse_revkeys (PKT_signature * sig)
{
struct revocation_key *revkey;
int seq = 0;
size_t len;
if (sig->sig_class != 0x1F)
return;
while ((revkey =
(struct revocation_key *) enum_sig_subpkt (sig->hashed,
SIGSUBPKT_REV_KEY,
&len, &seq, NULL)))
{
if (len == sizeof (struct revocation_key)
&& (revkey->class & 0x80)) /* 0x80 bit must be set. */
{
sig->revkey = xrealloc (sig->revkey,
sizeof (struct revocation_key *) *
(sig->numrevkeys + 1));
sig->revkey[sig->numrevkeys] = revkey;
sig->numrevkeys++;
}
}
}
int
parse_signature (IOBUF inp, int pkttype, unsigned long pktlen,
PKT_signature * sig)
{
int md5_len = 0;
unsigned n;
int is_v4 = 0;
int rc = 0;
int i, ndata;
if (pktlen < 16)
{
log_error ("packet(%d) too short\n", pkttype);
goto leave;
}
sig->version = iobuf_get_noeof (inp);
pktlen--;
if (sig->version == 4)
is_v4 = 1;
else if (sig->version != 2 && sig->version != 3)
{
log_error ("packet(%d) with unknown version %d\n",
pkttype, sig->version);
rc = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
if (!is_v4)
{
md5_len = iobuf_get_noeof (inp);
pktlen--;
}
sig->sig_class = iobuf_get_noeof (inp);
pktlen--;
if (!is_v4)
{
sig->timestamp = read_32 (inp);
pktlen -= 4;
sig->keyid[0] = read_32 (inp);
pktlen -= 4;
sig->keyid[1] = read_32 (inp);
pktlen -= 4;
}
sig->pubkey_algo = iobuf_get_noeof (inp);
pktlen--;
sig->digest_algo = iobuf_get_noeof (inp);
pktlen--;
sig->flags.exportable = 1;
sig->flags.revocable = 1;
if (is_v4) /* Read subpackets. */
{
n = read_16 (inp);
pktlen -= 2; /* Length of hashed data. */
if (n > 10000)
{
log_error ("signature packet: hashed data too long\n");
rc = G10ERR_INVALID_PACKET;
goto leave;
}
if (n)
{
sig->hashed = xmalloc (sizeof (*sig->hashed) + n - 1);
sig->hashed->size = n;
sig->hashed->len = n;
if (iobuf_read (inp, sig->hashed->data, n) != n)
{
log_error ("premature eof while reading "
"hashed signature data\n");
rc = -1;
goto leave;
}
pktlen -= n;
}
n = read_16 (inp);
pktlen -= 2; /* Length of unhashed data. */
if (n > 10000)
{
log_error ("signature packet: unhashed data too long\n");
rc = G10ERR_INVALID_PACKET;
goto leave;
}
if (n)
{
sig->unhashed = xmalloc (sizeof (*sig->unhashed) + n - 1);
sig->unhashed->size = n;
sig->unhashed->len = n;
if (iobuf_read (inp, sig->unhashed->data, n) != n)
{
log_error ("premature eof while reading "
"unhashed signature data\n");
rc = -1;
goto leave;
}
pktlen -= n;
}
}
if (pktlen < 5) /* Sanity check. */
{
log_error ("packet(%d) too short\n", pkttype);
rc = G10ERR_INVALID_PACKET;
goto leave;
}
sig->digest_start[0] = iobuf_get_noeof (inp);
pktlen--;
sig->digest_start[1] = iobuf_get_noeof (inp);
pktlen--;
if (is_v4 && sig->pubkey_algo) /* Extract required information. */
{
const byte *p;
size_t len;
/* Set sig->flags.unknown_critical if there is a critical bit
* set for packets which we do not understand. */
if (!parse_sig_subpkt (sig->hashed, SIGSUBPKT_TEST_CRITICAL, NULL)
|| !parse_sig_subpkt (sig->unhashed, SIGSUBPKT_TEST_CRITICAL, NULL))
sig->flags.unknown_critical = 1;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_SIG_CREATED, NULL);
if (p)
sig->timestamp = buffer_to_u32 (p);
else if (!(sig->pubkey_algo >= 100 && sig->pubkey_algo <= 110)
&& opt.verbose)
log_info ("signature packet without timestamp\n");
p = parse_sig_subpkt2 (sig, SIGSUBPKT_ISSUER, NULL);
if (p)
{
sig->keyid[0] = buffer_to_u32 (p);
sig->keyid[1] = buffer_to_u32 (p + 4);
}
else if (!(sig->pubkey_algo >= 100 && sig->pubkey_algo <= 110)
&& opt.verbose)
log_info ("signature packet without keyid\n");
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_SIG_EXPIRE, NULL);
if (p && buffer_to_u32 (p))
sig->expiredate = sig->timestamp + buffer_to_u32 (p);
if (sig->expiredate && sig->expiredate <= make_timestamp ())
sig->flags.expired = 1;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_POLICY, NULL);
if (p)
sig->flags.policy_url = 1;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_KS, NULL);
if (p)
sig->flags.pref_ks = 1;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_NOTATION, NULL);
if (p)
sig->flags.notation = 1;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_REVOCABLE, NULL);
if (p && *p == 0)
sig->flags.revocable = 0;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_TRUST, &len);
if (p && len == 2)
{
sig->trust_depth = p[0];
sig->trust_value = p[1];
/* Only look for a regexp if there is also a trust
subpacket. */
sig->trust_regexp =
parse_sig_subpkt (sig->hashed, SIGSUBPKT_REGEXP, &len);
/* If the regular expression is of 0 length, there is no
regular expression. */
if (len == 0)
sig->trust_regexp = NULL;
}
/* We accept the exportable subpacket from either the hashed or
unhashed areas as older versions of gpg put it in the
unhashed area. In theory, anyway, we should never see this
packet off of a local keyring. */
p = parse_sig_subpkt2 (sig, SIGSUBPKT_EXPORTABLE, NULL);
if (p && *p == 0)
sig->flags.exportable = 0;
/* Find all revocation keys. */
if (sig->sig_class == 0x1F)
parse_revkeys (sig);
}
if (list_mode)
{
es_fprintf (listfp, ":signature packet: algo %d, keyid %08lX%08lX\n"
"\tversion %d, created %lu, md5len %d, sigclass 0x%02x\n"
"\tdigest algo %d, begin of digest %02x %02x\n",
sig->pubkey_algo,
(ulong) sig->keyid[0], (ulong) sig->keyid[1],
sig->version, (ulong) sig->timestamp, md5_len, sig->sig_class,
sig->digest_algo, sig->digest_start[0], sig->digest_start[1]);
if (is_v4)
{
parse_sig_subpkt (sig->hashed, SIGSUBPKT_LIST_HASHED, NULL);
parse_sig_subpkt (sig->unhashed, SIGSUBPKT_LIST_UNHASHED, NULL);
}
}
ndata = pubkey_get_nsig (sig->pubkey_algo);
if (!ndata)
{
if (list_mode)
es_fprintf (listfp, "\tunknown algorithm %d\n", sig->pubkey_algo);
unknown_pubkey_warning (sig->pubkey_algo);
/* We store the plain material in data[0], so that we are able
* to write it back with build_packet(). */
if (pktlen > (5 * MAX_EXTERN_MPI_BITS / 8))
{
/* We include a limit to avoid too trivial DoS attacks by
having gpg allocate too much memory. */
log_error ("signature packet: too much data\n");
rc = G10ERR_INVALID_PACKET;
}
else
{
sig->data[0] =
gcry_mpi_set_opaque (NULL, read_rest (inp, pktlen, 0),
pktlen * 8);
pktlen = 0;
}
}
else
{
for (i = 0; i < ndata; i++)
{
n = pktlen;
sig->data[i] = mpi_read (inp, &n, 0);
pktlen -= n;
if (list_mode)
{
es_fprintf (listfp, "\tdata: ");
mpi_print (listfp, sig->data[i], mpi_print_mode);
es_putc ('\n', listfp);
}
if (!sig->data[i])
rc = G10ERR_INVALID_PACKET;
}
}
leave:
iobuf_skip_rest (inp, pktlen, 0);
return rc;
}
static int
parse_onepass_sig (IOBUF inp, int pkttype, unsigned long pktlen,
PKT_onepass_sig * ops)
{
int version;
int rc = 0;
if (pktlen < 13)
{
log_error ("packet(%d) too short\n", pkttype);
rc = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
version = iobuf_get_noeof (inp);
pktlen--;
if (version != 3)
{
log_error ("onepass_sig with unknown version %d\n", version);
rc = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
ops->sig_class = iobuf_get_noeof (inp);
pktlen--;
ops->digest_algo = iobuf_get_noeof (inp);
pktlen--;
ops->pubkey_algo = iobuf_get_noeof (inp);
pktlen--;
ops->keyid[0] = read_32 (inp);
pktlen -= 4;
ops->keyid[1] = read_32 (inp);
pktlen -= 4;
ops->last = iobuf_get_noeof (inp);
pktlen--;
if (list_mode)
es_fprintf (listfp,
":onepass_sig packet: keyid %08lX%08lX\n"
"\tversion %d, sigclass 0x%02x, digest %d, pubkey %d, "
"last=%d\n",
(ulong) ops->keyid[0], (ulong) ops->keyid[1],
version, ops->sig_class,
ops->digest_algo, ops->pubkey_algo, ops->last);
leave:
iobuf_skip_rest (inp, pktlen, 0);
return rc;
}
static gcry_mpi_t
read_protected_v3_mpi (IOBUF inp, unsigned long *length)
{
int c;
unsigned int nbits, nbytes;
unsigned char *buf, *p;
gcry_mpi_t val;
if (*length < 2)
{
log_error ("mpi too small\n");
return NULL;
}
if ((c = iobuf_get (inp)) == -1)
return NULL;
--*length;
nbits = c << 8;
if ((c = iobuf_get (inp)) == -1)
return NULL;
--*length;
nbits |= c;
if (nbits > 16384)
{
log_error ("mpi too large (%u bits)\n", nbits);
return NULL;
}
nbytes = (nbits + 7) / 8;
buf = p = xmalloc (2 + nbytes);
*p++ = nbits >> 8;
*p++ = nbits;
for (; nbytes && *length; nbytes--, --*length)
*p++ = iobuf_get (inp);
if (nbytes)
{
log_error ("packet shorter than mpi\n");
xfree (buf);
return NULL;
}
/* Convert buffer into an opaque MPI. */
val = gcry_mpi_set_opaque (NULL, buf, (p - buf) * 8);
return val;
}
static int
parse_key (IOBUF inp, int pkttype, unsigned long pktlen,
byte * hdr, int hdrlen, PACKET * pkt)
{
gpg_error_t err = 0;
int i, version, algorithm;
unsigned n;
unsigned long timestamp, expiredate, max_expiredate;
int npkey, nskey;
int is_v4 = 0;
int rc = 0;
u32 keyid[2];
PKT_public_key *pk;
(void) hdr;
pk = pkt->pkt.public_key; /* PK has been cleared. */
version = iobuf_get_noeof (inp);
pktlen--;
if (pkttype == PKT_PUBLIC_SUBKEY && version == '#')
{
/* Early versions of G10 used the old PGP comments packets;
* luckily all those comments are started by a hash. */
if (list_mode)
{
es_fprintf (listfp, ":rfc1991 comment packet: \"");
for (; pktlen; pktlen--)
{
int c;
c = iobuf_get_noeof (inp);
if (c >= ' ' && c <= 'z')
es_putc (c, listfp);
else
es_fprintf (listfp, "\\x%02x", c);
}
es_fprintf (listfp, "\"\n");
}
iobuf_skip_rest (inp, pktlen, 0);
return 0;
}
else if (version == 4)
is_v4 = 1;
else if (version != 2 && version != 3)
{
log_error ("packet(%d) with unknown version %d\n", pkttype, version);
err = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
if (pktlen < 11)
{
log_error ("packet(%d) too short\n", pkttype);
err = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
timestamp = read_32 (inp);
pktlen -= 4;
if (is_v4)
{
expiredate = 0; /* have to get it from the selfsignature */
max_expiredate = 0;
}
else
{
unsigned short ndays;
ndays = read_16 (inp);
pktlen -= 2;
if (ndays)
expiredate = timestamp + ndays * 86400L;
else
expiredate = 0;
max_expiredate = expiredate;
}
algorithm = iobuf_get_noeof (inp);
pktlen--;
if (list_mode)
es_fprintf (listfp, ":%s key packet:\n"
"\tversion %d, algo %d, created %lu, expires %lu\n",
pkttype == PKT_PUBLIC_KEY ? "public" :
pkttype == PKT_SECRET_KEY ? "secret" :
pkttype == PKT_PUBLIC_SUBKEY ? "public sub" :
pkttype == PKT_SECRET_SUBKEY ? "secret sub" : "??",
version, algorithm, timestamp, expiredate);
pk->timestamp = timestamp;
pk->expiredate = expiredate;
pk->max_expiredate = max_expiredate;
pk->hdrbytes = hdrlen;
pk->version = version;
pk->flags.primary = (pkttype == PKT_PUBLIC_KEY || pkttype == PKT_SECRET_KEY);
pk->pubkey_algo = algorithm;
nskey = pubkey_get_nskey (algorithm);
npkey = pubkey_get_npkey (algorithm);
if (!npkey)
{
if (list_mode)
es_fprintf (listfp, "\tunknown algorithm %d\n", algorithm);
unknown_pubkey_warning (algorithm);
}
if (!npkey)
{
/* Unknown algorithm - put data into an opaque MPI. */
pk->pkey[0] = gcry_mpi_set_opaque (NULL,
read_rest (inp, pktlen, 0),
pktlen * 8);
pktlen = 0;
goto leave;
}
else
{
/* Fill in public key parameters. */
- for (i = 0; i < npkey; i++)
- {
- n = pktlen;
- pk->pkey[i] = mpi_read (inp, &n, 0);
- pktlen -= n;
- if (list_mode)
- {
- es_fprintf (listfp, "\tpkey[%d]: ", i);
- mpi_print (listfp, pk->pkey[i], mpi_print_mode);
- es_putc ('\n', listfp);
+ if( algorithm != PUBKEY_ALGO_ECDSA && algorithm != PUBKEY_ALGO_ECDH ) {
+ for (i = 0; i < npkey; i++)
+ {
+ n = pktlen;
+ pk->pkey[i] = mpi_read (inp, &n, 0);
+ pktlen -= n;
+ if (list_mode)
+ {
+ es_fprintf (listfp, "\tpkey[%d]: ", i);
+ mpi_print (listfp, pk->pkey[i], mpi_print_mode);
+ es_putc ('\n', listfp);
+ }
+ if (!pk->pkey[i])
+ err = gpg_error (GPG_ERR_INV_PACKET);
+ }
+ }
+ else {
+ /* note that the code in this function ignores the errors */
+ byte name_oid[256];
+ err = iobuf_read_size_body( inp, name_oid, sizeof(name_oid), pktlen, pk->pkey+0 );
+ if( err )
+ goto leave;
+ n = name_oid[0];
+ if( list_mode )
+ es_fprintf (listfp, "\tpkey[0]: curve OID [%d] ...%02x %02x\n",
+ n, name_oid[1+n-2], name_oid[1+n-1] );
+ pktlen -= (n+1);
+ /* set item [1], which corresponds to the public key; these two fields are all we need to uniquely define the key */
+ // log_debug("Parsing ecc public key in the public packet, pktlen=%lu\n", pktlen);
+ n = pktlen; pk->pkey[1] = mpi_read( inp, &n, 0 ); pktlen -=n;
+ if( pk->pkey[1]==NULL )
+ err = gpg_error(G10ERR_INVALID_PACKET);
+ else if( list_mode ) {
+ es_fprintf (listfp, "\tpkey[1]: ");
+ mpi_print(listfp, pk->pkey[1], mpi_print_mode);
+ es_putc ('\n', listfp);
}
- if (!pk->pkey[i])
- err = gpg_error (GPG_ERR_INV_PACKET);
- }
+ /* One more field for ECDH */
+ if( algorithm == PUBKEY_ALGO_ECDH ) {
+#define kek_params name_oid
+ err = iobuf_read_size_body( inp, kek_params, sizeof(kek_params), pktlen, pk->pkey+2 );
+ if( err )
+ goto leave;
+ n = kek_params[0];
+ if( kek_params[1] != 1 ) {
+ log_error("invalid ecdh KEK parameters field type in private key: understand type 1, but found 0x%02x\n", kek_params[1]);
+ err = gpg_error(G10ERR_INVALID_PACKET);
+ goto leave;
+ }
+ if( list_mode )
+ es_fprintf (listfp, "\tpkey[2]: KEK params type=01 hash:%d sym-algo:%d\n", kek_params[1+n-2], kek_params[1+n-1] );
+ pktlen -= (n+1);
+#undef kek_params
+ }
+ }
if (err)
goto leave;
}
if (list_mode)
keyid_from_pk (pk, keyid);
if (pkttype == PKT_SECRET_KEY || pkttype == PKT_SECRET_SUBKEY)
{
struct seckey_info *ski;
byte temp[16];
size_t snlen = 0;
pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
if (!pk->seckey_info)
{
err = gpg_error_from_syserror ();
goto leave;
}
ski->algo = iobuf_get_noeof (inp);
pktlen--;
if (ski->algo)
{
ski->is_protected = 1;
ski->s2k.count = 0;
if (ski->algo == 254 || ski->algo == 255)
{
if (pktlen < 3)
{
err = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
ski->sha1chk = (ski->algo == 254);
ski->algo = iobuf_get_noeof (inp);
pktlen--;
/* Note that a ski->algo > 110 is illegal, but I'm not
erroring on it here as otherwise there would be no
way to delete such a key. */
ski->s2k.mode = iobuf_get_noeof (inp);
pktlen--;
ski->s2k.hash_algo = iobuf_get_noeof (inp);
pktlen--;
/* Check for the special GNU extension. */
if (is_v4 && ski->s2k.mode == 101)
{
for (i = 0; i < 4 && pktlen; i++, pktlen--)
temp[i] = iobuf_get_noeof (inp);
if (i < 4 || memcmp (temp, "GNU", 3))
{
if (list_mode)
es_fprintf (listfp, "\tunknown S2K %d\n",
ski->s2k.mode);
err = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
/* Here we know that it is a GNU extension. What
* follows is the GNU protection mode: All values
* have special meanings and they are mapped to MODE
* with a base of 1000. */
ski->s2k.mode = 1000 + temp[3];
}
/* Read the salt. */
switch (ski->s2k.mode)
{
case 1:
case 3:
for (i = 0; i < 8 && pktlen; i++, pktlen--)
temp[i] = iobuf_get_noeof (inp);
memcpy (ski->s2k.salt, temp, 8);
break;
}
/* Check the mode. */
switch (ski->s2k.mode)
{
case 0:
if (list_mode)
es_fprintf (listfp, "\tsimple S2K");
break;
case 1:
if (list_mode)
es_fprintf (listfp, "\tsalted S2K");
break;
case 3:
if (list_mode)
es_fprintf (listfp, "\titer+salt S2K");
break;
case 1001:
if (list_mode)
es_fprintf (listfp, "\tgnu-dummy S2K");
break;
case 1002:
if (list_mode)
es_fprintf (listfp, "\tgnu-divert-to-card S2K");
break;
default:
if (list_mode)
es_fprintf (listfp, "\tunknown %sS2K %d\n",
ski->s2k.mode < 1000 ? "" : "GNU ",
ski->s2k.mode);
err = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
/* Print some info. */
if (list_mode)
{
es_fprintf (listfp, ", algo: %d,%s hash: %d",
ski->algo,
ski->sha1chk ? " SHA1 protection,"
: " simple checksum,", ski->s2k.hash_algo);
if (ski->s2k.mode == 1 || ski->s2k.mode == 3)
{
es_fprintf (listfp, ", salt: ");
es_write_hexstring (listfp, ski->s2k.salt, 8, 0, NULL);
}
es_putc ('\n', listfp);
}
/* Read remaining protection parameters. */
if (ski->s2k.mode == 3)
{
if (pktlen < 1)
{
err = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
ski->s2k.count = iobuf_get (inp);
pktlen--;
if (list_mode)
es_fprintf (listfp, "\tprotect count: %lu\n",
(ulong) ski->s2k.count);
}
else if (ski->s2k.mode == 1002)
{
/* Read the serial number. */
if (pktlen < 1)
{
err = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
snlen = iobuf_get (inp);
pktlen--;
if (pktlen < snlen || snlen == (size_t)(-1))
{
err = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
}
}
else /* Old version; no S2K, so we set mode to 0, hash MD5. */
{
/* Note that a ski->algo > 110 is illegal, but I'm not
erroring on it here as otherwise there would be no
way to delete such a key. */
ski->s2k.mode = 0;
ski->s2k.hash_algo = DIGEST_ALGO_MD5;
if (list_mode)
es_fprintf (listfp, "\tprotect algo: %d (hash algo: %d)\n",
ski->algo, ski->s2k.hash_algo);
}
/* It is really ugly that we don't know the size
* of the IV here in cases we are not aware of the algorithm.
* so a
* ski->ivlen = cipher_get_blocksize (ski->algo);
* won't work. The only solution I see is to hardwire it.
* NOTE: if you change the ivlen above 16, don't forget to
* enlarge temp. */
ski->ivlen = openpgp_cipher_blocklen (ski->algo);
assert (ski->ivlen <= sizeof (temp));
if (ski->s2k.mode == 1001)
ski->ivlen = 0;
else if (ski->s2k.mode == 1002)
ski->ivlen = snlen < 16 ? snlen : 16;
if (pktlen < ski->ivlen)
{
err = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
for (i = 0; i < ski->ivlen && pktlen; i++, pktlen--)
temp[i] = iobuf_get_noeof (inp);
if (list_mode)
{
es_fprintf (listfp,
ski->s2k.mode == 1002 ? "\tserial-number: "
: "\tprotect IV: ");
for (i = 0; i < ski->ivlen; i++)
es_fprintf (listfp, " %02x", temp[i]);
es_putc ('\n', listfp);
}
memcpy (ski->iv, temp, ski->ivlen);
}
/* It does not make sense to read it into secure memory.
* If the user is so careless, not to protect his secret key,
* we can assume, that he operates an open system :=(.
* So we put the key into secure memory when we unprotect it. */
if (ski->s2k.mode == 1001 || ski->s2k.mode == 1002)
{
/* Better set some dummy stuff here. */
pk->pkey[npkey] = gcry_mpi_set_opaque (NULL,
xstrdup ("dummydata"),
10 * 8);
pktlen = 0;
}
else if (is_v4 && ski->is_protected)
{
/* Ugly: The length is encrypted too, so we read all stuff
* up to the end of the packet into the first SKEY
* element. */
pk->pkey[npkey] = gcry_mpi_set_opaque (NULL,
read_rest (inp, pktlen, 0),
pktlen * 8);
pktlen = 0;
if (list_mode)
es_fprintf (listfp, "\tskey[%d]: [v4 protected]\n", npkey);
}
else
{
/* The v3 method: The mpi length is not encrypted. */
for (i = npkey; i < nskey; i++)
{
if (ski->is_protected)
{
pk->pkey[i] = read_protected_v3_mpi (inp, &pktlen);
if (list_mode)
es_fprintf (listfp, "\tskey[%d]: [v3 protected]\n", i);
}
else
{
n = pktlen;
pk->pkey[i] = mpi_read (inp, &n, 0);
pktlen -= n;
if (list_mode)
{
es_fprintf (listfp, "\tskey[%d]: ", i);
mpi_print (listfp, pk->pkey[i], mpi_print_mode);
es_putc ('\n', listfp);
}
}
if (!pk->pkey[i])
err = gpg_error (GPG_ERR_INV_PACKET);
}
if (err)
goto leave;
ski->csum = read_16 (inp);
pktlen -= 2;
if (list_mode)
es_fprintf (listfp, "\tchecksum: %04hx\n", ski->csum);
}
}
if (list_mode)
es_fprintf (listfp, "\tkeyid: %08lX%08lX\n",
(ulong) keyid[0], (ulong) keyid[1]);
leave:
iobuf_skip_rest (inp, pktlen, 0);
return rc;
}
/* Attribute subpackets have the same format as v4 signature
subpackets. This is not part of OpenPGP, but is done in several
versions of PGP nevertheless. */
int
parse_attribute_subpkts (PKT_user_id * uid)
{
size_t n;
int count = 0;
struct user_attribute *attribs = NULL;
const byte *buffer = uid->attrib_data;
int buflen = uid->attrib_len;
byte type;
xfree (uid->attribs);
while (buflen)
{
n = *buffer++;
buflen--;
if (n == 255) /* 4 byte length header. */
{
if (buflen < 4)
goto too_short;
n = (buffer[0] << 24) | (buffer[1] << 16)
| (buffer[2] << 8) | buffer[3];
buffer += 4;
buflen -= 4;
}
else if (n >= 192) /* 2 byte special encoded length header. */
{
if (buflen < 2)
goto too_short;
n = ((n - 192) << 8) + *buffer + 192;
buffer++;
buflen--;
}
if (buflen < n)
goto too_short;
attribs =
xrealloc (attribs, (count + 1) * sizeof (struct user_attribute));
memset (&attribs[count], 0, sizeof (struct user_attribute));
type = *buffer;
buffer++;
buflen--;
n--;
attribs[count].type = type;
attribs[count].data = buffer;
attribs[count].len = n;
buffer += n;
buflen -= n;
count++;
}
uid->attribs = attribs;
uid->numattribs = count;
return count;
too_short:
if (opt.verbose)
log_info ("buffer shorter than attribute subpacket\n");
uid->attribs = attribs;
uid->numattribs = count;
return count;
}
static int
parse_user_id (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * packet)
{
byte *p;
/* Cap the size of a user ID at 2k: a value absurdly large enough
that there is no sane user ID string (which is printable text
as of RFC2440bis) that won't fit in it, but yet small enough to
avoid allocation problems. A large pktlen may not be
allocatable, and a very large pktlen could actually cause our
allocation to wrap around in xmalloc to a small number. */
if (pktlen > 2048)
{
log_error ("packet(%d) too large\n", pkttype);
iobuf_skip_rest (inp, pktlen, 0);
return G10ERR_INVALID_PACKET;
}
packet->pkt.user_id = xmalloc_clear (sizeof *packet->pkt.user_id + pktlen);
packet->pkt.user_id->len = pktlen;
packet->pkt.user_id->ref = 1;
p = packet->pkt.user_id->name;
for (; pktlen; pktlen--, p++)
*p = iobuf_get_noeof (inp);
*p = 0;
if (list_mode)
{
int n = packet->pkt.user_id->len;
es_fprintf (listfp, ":user ID packet: \"");
/* fixme: Hey why don't we replace this with es_write_sanitized?? */
for (p = packet->pkt.user_id->name; n; p++, n--)
{
if (*p >= ' ' && *p <= 'z')
es_putc (*p, listfp);
else
es_fprintf (listfp, "\\x%02x", *p);
}
es_fprintf (listfp, "\"\n");
}
return 0;
}
void
make_attribute_uidname (PKT_user_id * uid, size_t max_namelen)
{
assert (max_namelen > 70);
if (uid->numattribs <= 0)
sprintf (uid->name, "[bad attribute packet of size %lu]",
uid->attrib_len);
else if (uid->numattribs > 1)
sprintf (uid->name, "[%d attributes of size %lu]",
uid->numattribs, uid->attrib_len);
else
{
/* Only one attribute, so list it as the "user id" */
if (uid->attribs->type == ATTRIB_IMAGE)
{
u32 len;
byte type;
if (parse_image_header (uid->attribs, &type, &len))
sprintf (uid->name, "[%.20s image of size %lu]",
image_type_to_string (type, 1), (ulong) len);
else
sprintf (uid->name, "[invalid image]");
}
else
sprintf (uid->name, "[unknown attribute of size %lu]",
(ulong) uid->attribs->len);
}
uid->len = strlen (uid->name);
}
static int
parse_attribute (IOBUF inp, int pkttype, unsigned long pktlen,
PACKET * packet)
{
byte *p;
(void) pkttype;
#define EXTRA_UID_NAME_SPACE 71
packet->pkt.user_id = xmalloc_clear (sizeof *packet->pkt.user_id
+ EXTRA_UID_NAME_SPACE);
packet->pkt.user_id->ref = 1;
packet->pkt.user_id->attrib_data = xmalloc (pktlen);
packet->pkt.user_id->attrib_len = pktlen;
p = packet->pkt.user_id->attrib_data;
for (; pktlen; pktlen--, p++)
*p = iobuf_get_noeof (inp);
/* Now parse out the individual attribute subpackets. This is
somewhat pointless since there is only one currently defined
attribute type (jpeg), but it is correct by the spec. */
parse_attribute_subpkts (packet->pkt.user_id);
make_attribute_uidname (packet->pkt.user_id, EXTRA_UID_NAME_SPACE);
if (list_mode)
{
es_fprintf (listfp, ":attribute packet: %s\n", packet->pkt.user_id->name);
}
return 0;
}
static int
parse_comment (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * packet)
{
byte *p;
/* Cap comment packet at a reasonable value to avoid an integer
overflow in the malloc below. Comment packets are actually not
anymore define my OpenPGP and we even stopped to use our
private comment packet. */
if (pktlen > 65536)
{
log_error ("packet(%d) too large\n", pkttype);
iobuf_skip_rest (inp, pktlen, 0);
return G10ERR_INVALID_PACKET;
}
packet->pkt.comment = xmalloc (sizeof *packet->pkt.comment + pktlen - 1);
packet->pkt.comment->len = pktlen;
p = packet->pkt.comment->data;
for (; pktlen; pktlen--, p++)
*p = iobuf_get_noeof (inp);
if (list_mode)
{
int n = packet->pkt.comment->len;
es_fprintf (listfp, ":%scomment packet: \"", pkttype == PKT_OLD_COMMENT ?
"OpenPGP draft " : "");
for (p = packet->pkt.comment->data; n; p++, n--)
{
if (*p >= ' ' && *p <= 'z')
es_putc (*p, listfp);
else
es_fprintf (listfp, "\\x%02x", *p);
}
es_fprintf (listfp, "\"\n");
}
return 0;
}
static void
parse_trust (IOBUF inp, int pkttype, unsigned long pktlen, PACKET * pkt)
{
int c;
(void) pkttype;
if (pktlen)
{
c = iobuf_get_noeof (inp);
pktlen--;
pkt->pkt.ring_trust = xmalloc (sizeof *pkt->pkt.ring_trust);
pkt->pkt.ring_trust->trustval = c;
pkt->pkt.ring_trust->sigcache = 0;
if (!c && pktlen == 1)
{
c = iobuf_get_noeof (inp);
pktlen--;
/* We require that bit 7 of the sigcache is 0 (easier eof
handling). */
if (!(c & 0x80))
pkt->pkt.ring_trust->sigcache = c;
}
if (list_mode)
es_fprintf (listfp, ":trust packet: flag=%02x sigcache=%02x\n",
pkt->pkt.ring_trust->trustval,
pkt->pkt.ring_trust->sigcache);
}
else
{
if (list_mode)
es_fprintf (listfp, ":trust packet: empty\n");
}
iobuf_skip_rest (inp, pktlen, 0);
}
static int
parse_plaintext (IOBUF inp, int pkttype, unsigned long pktlen,
PACKET * pkt, int new_ctb, int partial)
{
int rc = 0;
int mode, namelen;
PKT_plaintext *pt;
byte *p;
int c, i;
if (!partial && pktlen < 6)
{
log_error ("packet(%d) too short (%lu)\n", pkttype, (ulong) pktlen);
rc = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
mode = iobuf_get_noeof (inp);
if (pktlen)
pktlen--;
namelen = iobuf_get_noeof (inp);
if (pktlen)
pktlen--;
/* Note that namelen will never exceed 255 bytes. */
pt = pkt->pkt.plaintext =
xmalloc (sizeof *pkt->pkt.plaintext + namelen - 1);
pt->new_ctb = new_ctb;
pt->mode = mode;
pt->namelen = namelen;
pt->is_partial = partial;
if (pktlen)
{
for (i = 0; pktlen > 4 && i < namelen; pktlen--, i++)
pt->name[i] = iobuf_get_noeof (inp);
}
else
{
for (i = 0; i < namelen; i++)
if ((c = iobuf_get (inp)) == -1)
break;
else
pt->name[i] = c;
}
pt->timestamp = read_32 (inp);
if (pktlen)
pktlen -= 4;
pt->len = pktlen;
pt->buf = inp;
pktlen = 0;
if (list_mode)
{
es_fprintf (listfp, ":literal data packet:\n"
"\tmode %c (%X), created %lu, name=\"",
mode >= ' ' && mode < 'z' ? mode : '?', mode,
(ulong) pt->timestamp);
for (p = pt->name, i = 0; i < namelen; p++, i++)
{
if (*p >= ' ' && *p <= 'z')
es_putc (*p, listfp);
else
es_fprintf (listfp, "\\x%02x", *p);
}
es_fprintf (listfp, "\",\n\traw data: ");
if (partial)
es_fprintf (listfp, "unknown length\n");
else
es_fprintf (listfp, "%lu bytes\n", (ulong) pt->len);
}
leave:
return rc;
}
static int
parse_compressed (IOBUF inp, int pkttype, unsigned long pktlen,
PACKET * pkt, int new_ctb)
{
PKT_compressed *zd;
/* PKTLEN is here 0, but data follows (this should be the last
object in a file or the compress algorithm should know the
length). */
(void) pkttype;
(void) pktlen;
zd = pkt->pkt.compressed = xmalloc (sizeof *pkt->pkt.compressed);
zd->algorithm = iobuf_get_noeof (inp);
zd->len = 0; /* not used */
zd->new_ctb = new_ctb;
zd->buf = inp;
if (list_mode)
es_fprintf (listfp, ":compressed packet: algo=%d\n", zd->algorithm);
return 0;
}
static int
parse_encrypted (IOBUF inp, int pkttype, unsigned long pktlen,
PACKET * pkt, int new_ctb, int partial)
{
int rc = 0;
PKT_encrypted *ed;
unsigned long orig_pktlen = pktlen;
ed = pkt->pkt.encrypted = xmalloc (sizeof *pkt->pkt.encrypted);
/* ed->len is set below. */
ed->extralen = 0; /* Unknown here; only used in build_packet. */
ed->buf = NULL;
ed->new_ctb = new_ctb;
ed->is_partial = partial;
if (pkttype == PKT_ENCRYPTED_MDC)
{
/* Fixme: add some pktlen sanity checks. */
int version;
version = iobuf_get_noeof (inp);
if (orig_pktlen)
pktlen--;
if (version != 1)
{
log_error ("encrypted_mdc packet with unknown version %d\n",
version);
/*skip_rest(inp, pktlen); should we really do this? */
rc = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
ed->mdc_method = DIGEST_ALGO_SHA1;
}
else
ed->mdc_method = 0;
/* A basic sanity check. We need at least an 8 byte IV plus the 2
detection bytes. Note that we don't known the algorithm and thus
we may only check against the minimum blocksize. */
if (orig_pktlen && pktlen < 10)
{
/* Actually this is blocksize+2. */
log_error ("packet(%d) too short\n", pkttype);
rc = G10ERR_INVALID_PACKET;
iobuf_skip_rest (inp, pktlen, partial);
goto leave;
}
/* Store the remaining length of the encrypted data (i.e. without
the MDC version number but with the IV etc.). This value is
required during decryption. */
ed->len = pktlen;
if (list_mode)
{
if (orig_pktlen)
es_fprintf (listfp, ":encrypted data packet:\n\tlength: %lu\n",
orig_pktlen);
else
es_fprintf (listfp, ":encrypted data packet:\n\tlength: unknown\n");
if (ed->mdc_method)
es_fprintf (listfp, "\tmdc_method: %d\n", ed->mdc_method);
}
ed->buf = inp;
leave:
return rc;
}
/* Note, that this code is not anymore used in real life because the
MDC checking is now done right after the decryption in
decrypt_data. */
static int
parse_mdc (IOBUF inp, int pkttype, unsigned long pktlen,
PACKET * pkt, int new_ctb)
{
int rc = 0;
PKT_mdc *mdc;
byte *p;
(void) pkttype;
mdc = pkt->pkt.mdc = xmalloc (sizeof *pkt->pkt.mdc);
if (list_mode)
es_fprintf (listfp, ":mdc packet: length=%lu\n", pktlen);
if (!new_ctb || pktlen != 20)
{
log_error ("mdc_packet with invalid encoding\n");
rc = gpg_error (GPG_ERR_INV_PACKET);
goto leave;
}
p = mdc->hash;
for (; pktlen; pktlen--, p++)
*p = iobuf_get_noeof (inp);
leave:
return rc;
}
/*
* This packet is internally generated by us (ibn armor.c) to transfer
* some information to the lower layer. To make sure that this packet
* is really a GPG faked one and not one comming from outside, we
* first check that there is a unique tag in it.
*
* The format of such a control packet is:
* n byte session marker
* 1 byte control type CTRLPKT_xxxxx
* m byte control data
*/
static int
parse_gpg_control (IOBUF inp, int pkttype, unsigned long pktlen,
PACKET * packet, int partial)
{
byte *p;
const byte *sesmark;
size_t sesmarklen;
int i;
(void) pkttype;
if (list_mode)
es_fprintf (listfp, ":packet 63: length %lu ", pktlen);
sesmark = get_session_marker (&sesmarklen);
if (pktlen < sesmarklen + 1) /* 1 is for the control bytes */
goto skipit;
for (i = 0; i < sesmarklen; i++, pktlen--)
{
if (sesmark[i] != iobuf_get_noeof (inp))
goto skipit;
}
if (pktlen > 4096)
goto skipit; /* Definitely too large. We skip it to avoid an
overflow in the malloc. */
if (list_mode)
puts ("- gpg control packet");
packet->pkt.gpg_control = xmalloc (sizeof *packet->pkt.gpg_control
+ pktlen - 1);
packet->pkt.gpg_control->control = iobuf_get_noeof (inp);
pktlen--;
packet->pkt.gpg_control->datalen = pktlen;
p = packet->pkt.gpg_control->data;
for (; pktlen; pktlen--, p++)
*p = iobuf_get_noeof (inp);
return 0;
skipit:
if (list_mode)
{
int c;
i = 0;
es_fprintf (listfp, "- private (rest length %lu)\n", pktlen);
if (partial)
{
while ((c = iobuf_get (inp)) != -1)
dump_hex_line (c, &i);
}
else
{
for (; pktlen; pktlen--)
{
dump_hex_line ((c = iobuf_get (inp)), &i);
if (c == -1)
break;
}
}
es_putc ('\n', listfp);
}
iobuf_skip_rest (inp, pktlen, 0);
return gpg_error (GPG_ERR_INV_PACKET);
}
/* Create a GPG control packet to be used internally as a placeholder. */
PACKET *
create_gpg_control (ctrlpkttype_t type, const byte * data, size_t datalen)
{
PACKET *packet;
byte *p;
packet = xmalloc (sizeof *packet);
init_packet (packet);
packet->pkttype = PKT_GPG_CONTROL;
packet->pkt.gpg_control = xmalloc (sizeof *packet->pkt.gpg_control
+ datalen - 1);
packet->pkt.gpg_control->control = type;
packet->pkt.gpg_control->datalen = datalen;
p = packet->pkt.gpg_control->data;
for (; datalen; datalen--, p++)
*p = *data++;
return packet;
}
diff --git a/g10/passphrase.c b/g10/passphrase.c
index 9f1218b6b..f29fca72f 100644
--- a/g10/passphrase.c
+++ b/g10/passphrase.c
@@ -1,743 +1,743 @@
/* passphrase.c - Get a passphrase
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
* 2005, 2006, 2007, 2009 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
* 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
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#ifdef HAVE_LOCALE_H
#include
#endif
#ifdef HAVE_LANGINFO_CODESET
#include
#endif
#include "gpg.h"
#include "util.h"
#include "options.h"
#include "ttyio.h"
#include "cipher.h"
#include "keydb.h"
#include "main.h"
#include "i18n.h"
#include "status.h"
#include "call-agent.h"
static char *fd_passwd = NULL;
static char *next_pw = NULL;
static char *last_pw = NULL;
/* Pack an s2k iteration count into the form specified in 2440. If
we're in between valid values, round up. With value 0 return the
old default. */
unsigned char
encode_s2k_iterations (int iterations)
{
gpg_error_t err;
unsigned char c=0;
unsigned char result;
unsigned int count;
if (!iterations)
{
unsigned long mycnt;
/* Ask the gpg-agent for a useful iteration count. */
err = agent_get_s2k_count (&mycnt);
if (err || mycnt < 65536)
{
/* Don't print an error if an older agent is used. */
if (err && gpg_err_code (err) != GPG_ERR_ASS_PARAMETER)
log_error (_("problem with the agent: %s\n"), gpg_strerror (err));
/* Default to 65536 which we used up to 2.0.13. */
return 96;
}
else if (mycnt >= 65011712)
return 255; /* Largest possible value. */
else
return encode_s2k_iterations ((int)mycnt);
}
if (iterations <= 1024)
return 0; /* Command line arg compatibility. */
if (iterations >= 65011712)
return 255;
/* Need count to be in the range 16-31 */
for (count=iterations>>6; count>=32; count>>=1)
c++;
result = (c<<4)|(count-16);
if (S2K_DECODE_COUNT(result) < iterations)
result++;
return result;
}
/* Hash a passphrase using the supplied s2k.
Always needs: dek->algo, s2k->mode, s2k->hash_algo. */
static void
hash_passphrase ( DEK *dek, char *pw, STRING2KEY *s2k)
{
gcry_md_hd_t md;
int pass, i;
int used = 0;
int pwlen = strlen(pw);
assert ( s2k->hash_algo );
dek->keylen = openpgp_cipher_get_algo_keylen (dek->algo);
if ( !(dek->keylen > 0 && dek->keylen <= DIM(dek->key)) )
BUG();
if (gcry_md_open (&md, s2k->hash_algo, 1))
BUG ();
for (pass=0; used < dek->keylen ; pass++ )
{
if ( pass )
{
gcry_md_reset (md);
for (i=0; i < pass; i++ ) /* Preset the hash context. */
gcry_md_putc (md, 0 );
}
if ( s2k->mode == 1 || s2k->mode == 3 )
{
int len2 = pwlen + 8;
ulong count = len2;
if ( s2k->mode == 3 )
{
count = S2K_DECODE_COUNT(s2k->count);
if ( count < len2 )
count = len2;
}
/* Fixme: To avoid DoS attacks by sending an sym-encrypted
packet with a very high S2K count, we should either cap
the iteration count or CPU seconds based timeout. */
/* A little bit complicated because we need a ulong for count. */
while ( count > len2 ) /* maybe iterated+salted */
{
gcry_md_write ( md, s2k->salt, 8 );
gcry_md_write ( md, pw, pwlen );
count -= len2;
}
if ( count < 8 )
gcry_md_write ( md, s2k->salt, count );
else
{
gcry_md_write ( md, s2k->salt, 8 );
count -= 8;
gcry_md_write ( md, pw, count );
}
}
else
gcry_md_write ( md, pw, pwlen );
gcry_md_final( md );
i = gcry_md_get_algo_dlen ( s2k->hash_algo );
if ( i > dek->keylen - used )
i = dek->keylen - used;
memcpy (dek->key+used, gcry_md_read (md, s2k->hash_algo), i);
used += i;
}
gcry_md_close(md);
}
int
have_static_passphrase()
{
return !!fd_passwd && opt.batch;
}
/****************
* Set the passphrase to be used for the next query and only for the next
* one.
*/
void
set_next_passphrase( const char *s )
{
xfree(next_pw);
next_pw = NULL;
if ( s )
{
next_pw = xmalloc_secure( strlen(s)+1 );
strcpy (next_pw, s );
}
}
/****************
* Get the last passphrase used in passphrase_to_dek.
* Note: This removes the passphrase from this modules and
* the caller must free the result. May return NULL:
*/
char *
get_last_passphrase()
{
char *p = last_pw;
last_pw = NULL;
return p;
}
/* Here's an interesting question: since this passphrase was passed in
on the command line, is there really any point in using secure
memory for it? I'm going with 'yes', since it doesn't hurt, and
might help in some small way (swapping). */
void
set_passphrase_from_string(const char *pass)
{
xfree (fd_passwd);
fd_passwd = xmalloc_secure(strlen(pass)+1);
strcpy (fd_passwd, pass);
}
void
read_passphrase_from_fd( int fd )
{
int i, len;
char *pw;
if ( !opt.batch )
{ /* Not used but we have to do a dummy read, so that it won't end
up at the begin of the message if the quite usual trick to
prepend the passphtrase to the message is used. */
char buf[1];
while (!(read (fd, buf, 1) != 1 || *buf == '\n' ))
;
*buf = 0;
return;
}
for (pw = NULL, i = len = 100; ; i++ )
{
if (i >= len-1 )
{
char *pw2 = pw;
len += 100;
pw = xmalloc_secure( len );
if( pw2 )
{
memcpy(pw, pw2, i );
xfree (pw2);
}
else
i=0;
}
if (read( fd, pw+i, 1) != 1 || pw[i] == '\n' )
break;
}
pw[i] = 0;
if (!opt.batch)
tty_printf("\b\b\b \n" );
xfree ( fd_passwd );
fd_passwd = pw;
}
/*
* Ask the GPG Agent for the passphrase.
* Mode 0: Allow cached passphrase
* 1: No cached passphrase; that is we are asking for a new passphrase
* FIXME: Only partially implemented
*
* Note that TRYAGAIN_TEXT must not be translated. If CANCELED is not
* NULL, the function does set it to 1 if the user canceled the
* operation. If CACHEID is not NULL, it will be used as the cacheID
* for the gpg-agent; if is NULL and a key fingerprint can be
* computed, this will be used as the cacheid.
*/
static char *
passphrase_get ( u32 *keyid, int mode, const char *cacheid, int repeat,
const char *tryagain_text,
const char *custom_description,
const char *custom_prompt, int *canceled)
{
int rc;
char *atext = NULL;
char *pw = NULL;
PKT_public_key *pk = xmalloc_clear( sizeof *pk );
byte fpr[MAX_FINGERPRINT_LEN];
int have_fpr = 0;
char *orig_codeset;
char *my_prompt;
char hexfprbuf[20*2+1];
const char *my_cacheid;
int check = (mode == 1);
if (canceled)
*canceled = 0;
#if MAX_FINGERPRINT_LEN < 20
#error agent needs a 20 byte fingerprint
#endif
memset (fpr, 0, MAX_FINGERPRINT_LEN );
if( keyid && get_pubkey( pk, keyid ) )
{
if (pk)
free_public_key( pk );
pk = NULL; /* oops: no key for some reason */
}
orig_codeset = i18n_switchto_utf8 ();
if (custom_description)
atext = native_to_utf8 (custom_description);
else if ( !mode && pk && keyid )
{
char *uid;
size_t uidlen;
- const char *algo_name = gcry_pk_algo_name ( pk->pubkey_algo );
+ const char *algo_name = openpgp_pk_algo_name ( pk->pubkey_algo );
const char *timestr;
char *maink;
if ( !algo_name )
algo_name = "?";
#define KEYIDSTRING _(" (main key ID %s)")
maink = xmalloc ( strlen (KEYIDSTRING) + keystrlen() + 20 );
if( keyid[2] && keyid[3] && keyid[0] != keyid[2]
&& keyid[1] != keyid[3] )
sprintf( maink, KEYIDSTRING, keystr(&keyid[2]) );
else
*maink = 0;
uid = get_user_id ( keyid, &uidlen );
timestr = strtimestamp (pk->timestamp);
#undef KEYIDSTRING
#define PROMPTSTRING _("Please enter the passphrase to unlock the" \
" secret key for the OpenPGP certificate:\n" \
"\"%.*s\"\n" \
"%u-bit %s key, ID %s,\n" \
"created %s%s.\n" )
atext = xmalloc ( 100 + strlen (PROMPTSTRING)
+ uidlen + 15 + strlen(algo_name) + keystrlen()
+ strlen (timestr) + strlen (maink) );
sprintf (atext, PROMPTSTRING,
(int)uidlen, uid,
nbits_from_pk (pk), algo_name, keystr(&keyid[0]), timestr,
maink );
xfree (uid);
xfree (maink);
#undef PROMPTSTRING
{
size_t dummy;
fingerprint_from_pk( pk, fpr, &dummy );
have_fpr = 1;
}
}
else
atext = xstrdup ( _("Enter passphrase\n") );
if (!mode && cacheid)
my_cacheid = cacheid;
else if (!mode && have_fpr)
my_cacheid = bin2hex (fpr, 20, hexfprbuf);
else
my_cacheid = NULL;
if (tryagain_text)
tryagain_text = _(tryagain_text);
my_prompt = custom_prompt ? native_to_utf8 (custom_prompt): NULL;
rc = agent_get_passphrase (my_cacheid, tryagain_text, my_prompt, atext,
repeat, check, &pw);
xfree (my_prompt);
xfree (atext); atext = NULL;
i18n_switchback (orig_codeset);
if (!rc)
;
else if (gpg_err_code (rc) == GPG_ERR_CANCELED
|| gpg_err_code (rc) == GPG_ERR_FULLY_CANCELED)
{
log_info (_("cancelled by user\n") );
if (canceled)
*canceled = 1;
}
else
{
log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
/* Due to limitations in the API of the upper layers they
consider an error as no passphrase entered. This works in
most cases but not during key creation where this should
definitely not happen and let it continue without requiring a
passphrase. Given that now all the upper layers handle a
cancel correctly, we simply set the cancel flag now for all
errors from the agent. */
if (canceled)
*canceled = 1;
write_status_errcode ("get_passphrase", rc);
}
if (pk)
free_public_key( pk );
if (rc)
{
xfree (pw);
return NULL;
}
return pw;
}
/*
* Clear the cached passphrase. If CACHEID is not NULL, it will be
* used instead of a cache ID derived from KEYID.
*/
void
passphrase_clear_cache ( u32 *keyid, const char *cacheid, int algo )
{
int rc;
(void)algo;
if (!cacheid)
{
PKT_public_key *pk;
# if MAX_FINGERPRINT_LEN < 20
# error agent needs a 20 byte fingerprint
# endif
byte fpr[MAX_FINGERPRINT_LEN];
char hexfprbuf[2*20+1];
size_t dummy;
pk = xcalloc (1, sizeof *pk);
if ( !keyid || get_pubkey( pk, keyid ) )
{
log_error ("key not found in passphrase_clear_cache\n");
free_public_key (pk);
return;
}
memset (fpr, 0, MAX_FINGERPRINT_LEN );
fingerprint_from_pk ( pk, fpr, &dummy );
bin2hex (fpr, 20, hexfprbuf);
rc = agent_clear_passphrase (hexfprbuf);
free_public_key ( pk );
}
else
rc = agent_clear_passphrase (cacheid);
if (rc)
log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
}
/* Return a new DEK object Using the string-to-key sepcifier S2K. Use
KEYID and PUBKEY_ALGO to prompt the user. Returns NULL is the user
selected to cancel the passphrase entry and if CANCELED is not
NULL, sets it to true.
MODE 0: Allow cached passphrase
1: Ignore cached passphrase
2: Ditto, but create a new key
3: Allow cached passphrase; use the S2K salt as the cache ID
4: Ditto, but create a new key
*/
DEK *
passphrase_to_dek_ext (u32 *keyid, int pubkey_algo,
int cipher_algo, STRING2KEY *s2k, int mode,
const char *tryagain_text,
const char *custdesc, const char *custprompt,
int *canceled)
{
char *pw = NULL;
DEK *dek;
STRING2KEY help_s2k;
int dummy_canceled;
char s2k_cacheidbuf[1+16+1], *s2k_cacheid = NULL;
if (!canceled)
canceled = &dummy_canceled;
*canceled = 0;
if ( !s2k )
{
assert (mode != 3 && mode != 4);
/* This is used for the old rfc1991 mode
* Note: This must match the code in encode.c with opt.rfc1991 set */
s2k = &help_s2k;
s2k->mode = 0;
s2k->hash_algo = S2K_DIGEST_ALGO;
}
/* Create a new salt or what else to be filled into the s2k for a
new key. */
if ((mode == 2 || mode == 4) && (s2k->mode == 1 || s2k->mode == 3))
{
gcry_randomize (s2k->salt, 8, GCRY_STRONG_RANDOM);
if ( s2k->mode == 3 )
{
/* We delay the encoding until it is really needed. This is
if we are going to dynamically calibrate it, we need to
call out to gpg-agent and that should not be done during
option processing in main(). */
if (!opt.s2k_count)
opt.s2k_count = encode_s2k_iterations (0);
s2k->count = opt.s2k_count;
}
}
/* If we do not have a passphrase available in NEXT_PW and status
information are request, we print them now. */
if ( !next_pw && is_status_enabled() )
{
char buf[50];
if ( keyid )
{
u32 used_kid[2];
char *us;
if ( keyid[2] && keyid[3] )
{
used_kid[0] = keyid[2];
used_kid[1] = keyid[3];
}
else
{
used_kid[0] = keyid[0];
used_kid[1] = keyid[1];
}
us = get_long_user_id_string ( keyid );
write_status_text ( STATUS_USERID_HINT, us );
xfree(us);
snprintf (buf, sizeof buf -1, "%08lX%08lX %08lX%08lX %d 0",
(ulong)keyid[0], (ulong)keyid[1],
(ulong)used_kid[0], (ulong)used_kid[1],
pubkey_algo );
write_status_text ( STATUS_NEED_PASSPHRASE, buf );
}
else
{
snprintf (buf, sizeof buf -1, "%d %d %d",
cipher_algo, s2k->mode, s2k->hash_algo );
write_status_text ( STATUS_NEED_PASSPHRASE_SYM, buf );
}
}
/* If we do have a keyID, we do not have a passphrase available in
NEXT_PW, we are not running in batch mode and we do not want to
ignore the passphrase cache (mode!=1), print a prompt with
information on that key. */
if ( keyid && !opt.batch && !next_pw && mode!=1 )
{
PKT_public_key *pk = xmalloc_clear( sizeof *pk );
char *p;
p = get_user_id_native(keyid);
tty_printf ("\n");
tty_printf (_("You need a passphrase to unlock the secret key for\n"
"user: \"%s\"\n"),p);
xfree(p);
if ( !get_pubkey( pk, keyid ) )
{
- const char *s = gcry_pk_algo_name ( pk->pubkey_algo );
+ const char *s = openpgp_pk_algo_name ( pk->pubkey_algo );
tty_printf (_("%u-bit %s key, ID %s, created %s"),
nbits_from_pk( pk ), s?s:"?", keystr(keyid),
strtimestamp(pk->timestamp) );
if ( keyid[2] && keyid[3]
&& keyid[0] != keyid[2] && keyid[1] != keyid[3] )
{
if ( keystrlen () > 10 )
{
tty_printf ("\n");
tty_printf (_(" (subkey on main key ID %s)"),
keystr(&keyid[2]) );
}
else
tty_printf ( _(" (main key ID %s)"), keystr(&keyid[2]) );
}
tty_printf("\n");
}
tty_printf("\n");
if (pk)
free_public_key( pk );
}
if ( next_pw )
{
/* Simply return the passphrase we already have in NEXT_PW. */
pw = next_pw;
next_pw = NULL;
}
else if ( have_static_passphrase () )
{
/* Return the passphrase we have stored in FD_PASSWD. */
pw = xmalloc_secure ( strlen(fd_passwd)+1 );
strcpy ( pw, fd_passwd );
}
else
{
if ((mode == 3 || mode == 4) && (s2k->mode == 1 || s2k->mode == 3))
{
memset (s2k_cacheidbuf, 0, sizeof s2k_cacheidbuf);
*s2k_cacheidbuf = 'S';
bin2hex (s2k->salt, 8, s2k_cacheidbuf + 1);
s2k_cacheid = s2k_cacheidbuf;
}
/* Divert to the gpg-agent. */
pw = passphrase_get (keyid, mode == 2, s2k_cacheid,
(mode == 2 || mode == 4)? opt.passphrase_repeat : 0,
tryagain_text, custdesc, custprompt, canceled);
if (*canceled)
{
xfree (pw);
write_status( STATUS_MISSING_PASSPHRASE );
return NULL;
}
}
if ( !pw || !*pw )
write_status( STATUS_MISSING_PASSPHRASE );
/* Hash the passphrase and store it in a newly allocated DEK object.
Keep a copy of the passphrase in LAST_PW for use by
get_last_passphrase(). */
dek = xmalloc_secure_clear ( sizeof *dek );
dek->algo = cipher_algo;
if ( (!pw || !*pw) && (mode == 2 || mode == 4))
dek->keylen = 0;
else
hash_passphrase (dek, pw, s2k);
if (s2k_cacheid)
memcpy (dek->s2k_cacheid, s2k_cacheid, sizeof dek->s2k_cacheid);
xfree(last_pw);
last_pw = pw;
return dek;
}
DEK *
passphrase_to_dek (u32 *keyid, int pubkey_algo,
int cipher_algo, STRING2KEY *s2k, int mode,
const char *tryagain_text, int *canceled)
{
return passphrase_to_dek_ext (keyid, pubkey_algo, cipher_algo,
s2k, mode, tryagain_text, NULL, NULL,
canceled);
}
/* Return an allocated utf-8 string describing the key PK. If ESCAPED
is true spaces and control characters are percent or plus escaped.
MODE 0 is for the common prompt, MODE 1 for the import prompt. */
char *
gpg_format_keydesc (PKT_public_key *pk, int mode, int escaped)
{
char *uid;
size_t uidlen;
const char *algo_name;
const char *timestr;
char *orig_codeset;
char *maink;
char *desc;
const char *prompt;
- algo_name = gcry_pk_algo_name (pk->pubkey_algo);
+ algo_name = openpgp_pk_algo_name (pk->pubkey_algo);
timestr = strtimestamp (pk->timestamp);
uid = get_user_id (pk->keyid, &uidlen);
orig_codeset = i18n_switchto_utf8 ();
if (pk->main_keyid[0] && pk->main_keyid[1]
&& pk->keyid[0] != pk->main_keyid[0]
&& pk->keyid[1] != pk->main_keyid[1])
maink = xtryasprintf (_(" (main key ID %s)"), keystr (pk->main_keyid));
else
maink = NULL;
switch (mode)
{
case 0:
prompt = _("Please enter the passphrase to unlock the"
" secret key for the OpenPGP certificate:");
break;
case 1:
prompt = _("Please enter the passphrase to import the"
" secret key for the OpenPGP certificate:");
break;
default:
prompt = "?";
break;
}
desc = xtryasprintf (_("%s\n"
"\"%.*s\"\n"
"%u-bit %s key, ID %s,\n"
"created %s%s.\n"),
prompt,
(int)uidlen, uid,
nbits_from_pk (pk), algo_name,
keystr (pk->keyid), timestr,
maink?maink:"" );
xfree (maink);
xfree (uid);
i18n_switchback (orig_codeset);
if (escaped)
{
char *tmp = percent_plus_escape (desc);
xfree (desc);
desc = tmp;
}
return desc;
}
diff --git a/g10/pkglue.c b/g10/pkglue.c
index 14a27535f..f78591940 100644
--- a/g10/pkglue.c
+++ b/g10/pkglue.c
@@ -1,246 +1,377 @@
/* pkglue.c - public key operations glue code
* Copyright (C) 2000, 2003 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
* 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
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include
#include "gpg.h"
#include "util.h"
#include "pkglue.h"
+#include "main.h"
-static gcry_mpi_t
+gcry_mpi_t
mpi_from_sexp (gcry_sexp_t sexp, const char * item)
{
gcry_sexp_t list;
gcry_mpi_t data;
list = gcry_sexp_find_token (sexp, item, 0);
assert (list);
data = gcry_sexp_nth_mpi (list, 1, 0);
assert (data);
gcry_sexp_release (list);
return data;
}
+/****************
+ * Emulate our old PK interface here - sometime in the future we might
+ * change the internal design to directly fit to libgcrypt.
+ */
+int
+pk_sign (int algo, gcry_mpi_t * data, gcry_mpi_t hash, gcry_mpi_t * skey)
+{
+ gcry_sexp_t s_sig, s_hash, s_skey;
+ int rc;
+ int gcry_pkalgo = map_pk_openpgp_to_gcry( algo );
+
+ /* make a sexp from skey */
+ if (gcry_pkalgo == GCRY_PK_DSA)
+ {
+ rc = gcry_sexp_build (&s_skey, NULL,
+ "(private-key(dsa(p%m)(q%m)(g%m)(y%m)(x%m)))",
+ skey[0], skey[1], skey[2], skey[3], skey[4]);
+ }
+ else if (gcry_pkalgo == GCRY_PK_RSA || gcry_pkalgo == GCRY_PK_RSA_S)
+ {
+ rc = gcry_sexp_build (&s_skey, NULL,
+ "(private-key(rsa(n%m)(e%m)(d%m)(p%m)(q%m)(u%m)))",
+ skey[0], skey[1], skey[2], skey[3], skey[4],
+ skey[5]);
+ }
+ else if (gcry_pkalgo == GCRY_PK_ELG || gcry_pkalgo == GCRY_PK_ELG_E)
+ {
+ rc = gcry_sexp_build (&s_skey, NULL,
+ "(private-key(elg(p%m)(g%m)(y%m)(x%m)))",
+ skey[0], skey[1], skey[2], skey[3]);
+ }
+ else if (gcry_pkalgo == GCRY_PK_ECDSA)
+ {
+ rc = gcry_sexp_build (&s_skey, NULL,
+ "(private-key(ecdsa(c%m)(q%m)(d%m)))",
+ skey[0], skey[1], skey[2] );
+ }
+ else
+ return GPG_ERR_PUBKEY_ALGO;
+
+ if (rc)
+ BUG ();
+
+ /* put hash into a S-Exp s_hash */
+ if (gcry_sexp_build (&s_hash, NULL, "%m", hash))
+ BUG ();
+
+ rc = gcry_pk_sign (&s_sig, s_hash, s_skey);
+ gcry_sexp_release (s_hash);
+ gcry_sexp_release (s_skey);
+
+ if (rc)
+ ;
+ else if (algo == GCRY_PK_RSA || algo == GCRY_PK_RSA_S)
+ data[0] = mpi_from_sexp (s_sig, "s");
+ else
+ {
+ data[0] = mpi_from_sexp (s_sig, "r");
+ data[1] = mpi_from_sexp (s_sig, "s");
+ }
+
+ gcry_sexp_release (s_sig);
+ return rc;
+}
/****************
* Emulate our old PK interface here - sometime in the future we might
* change the internal design to directly fit to libgcrypt.
*/
int
pk_verify (int algo, gcry_mpi_t hash, gcry_mpi_t * data, gcry_mpi_t * pkey)
{
gcry_sexp_t s_sig, s_hash, s_pkey;
int rc;
+ const int gcry_pkalgo = map_pk_openpgp_to_gcry( algo );
/* make a sexp from pkey */
- if (algo == GCRY_PK_DSA)
+ if (gcry_pkalgo == GCRY_PK_DSA)
{
rc = gcry_sexp_build (&s_pkey, NULL,
"(public-key(dsa(p%m)(q%m)(g%m)(y%m)))",
pkey[0], pkey[1], pkey[2], pkey[3]);
}
- else if (algo == GCRY_PK_ELG || algo == GCRY_PK_ELG_E)
+ else if (gcry_pkalgo == GCRY_PK_ELG || gcry_pkalgo == GCRY_PK_ELG_E)
{
rc = gcry_sexp_build (&s_pkey, NULL,
"(public-key(elg(p%m)(g%m)(y%m)))",
pkey[0], pkey[1], pkey[2]);
}
- else if (algo == GCRY_PK_RSA || algo == GCRY_PK_RSA_S)
+ else if (gcry_pkalgo == GCRY_PK_RSA || gcry_pkalgo == GCRY_PK_RSA_S)
{
rc = gcry_sexp_build (&s_pkey, NULL,
"(public-key(rsa(n%m)(e%m)))", pkey[0], pkey[1]);
}
+ else if (gcry_pkalgo == GCRY_PK_ECDSA) /* same as GCRY_PK_ECDH */
+ {
+ rc = gcry_sexp_build (&s_pkey, NULL,
+ "(public-key(ecdsa(c%m)(q%m)))", pkey[0], pkey[1]);
+ }
else
return GPG_ERR_PUBKEY_ALGO;
if (rc)
BUG (); /* gcry_sexp_build should never fail. */
/* put hash into a S-Exp s_hash */
if (gcry_sexp_build (&s_hash, NULL, "%m", hash))
BUG (); /* gcry_sexp_build should never fail. */
/* Put data into a S-Exp s_sig. */
s_sig = NULL;
- if (algo == GCRY_PK_DSA)
+ if (gcry_pkalgo == GCRY_PK_DSA)
{
if (!data[0] || !data[1])
rc = gpg_error (GPG_ERR_BAD_MPI);
else
rc = gcry_sexp_build (&s_sig, NULL,
"(sig-val(dsa(r%m)(s%m)))", data[0], data[1]);
}
- else if (algo == GCRY_PK_ELG || algo == GCRY_PK_ELG_E)
+ else if (gcry_pkalgo == GCRY_PK_ECDSA)
+ {
+ if (!data[0] || !data[1])
+ rc = gpg_error (GPG_ERR_BAD_MPI);
+ else
+ rc = gcry_sexp_build (&s_sig, NULL,
+ "(sig-val(ecdsa(r%m)(s%m)))", data[0], data[1]);
+ }
+ else if (gcry_pkalgo == GCRY_PK_ELG || gcry_pkalgo == GCRY_PK_ELG_E)
{
if (!data[0] || !data[1])
rc = gpg_error (GPG_ERR_BAD_MPI);
else
rc = gcry_sexp_build (&s_sig, NULL,
"(sig-val(elg(r%m)(s%m)))", data[0], data[1]);
}
- else if (algo == GCRY_PK_RSA || algo == GCRY_PK_RSA_S)
+ else if (gcry_pkalgo == GCRY_PK_RSA || gcry_pkalgo == GCRY_PK_RSA_S)
{
if (!data[0])
rc = gpg_error (GPG_ERR_BAD_MPI);
else
rc = gcry_sexp_build (&s_sig, NULL, "(sig-val(rsa(s%m)))", data[0]);
}
else
BUG ();
if (!rc)
rc = gcry_pk_verify (s_sig, s_hash, s_pkey);
gcry_sexp_release (s_sig);
gcry_sexp_release (s_hash);
gcry_sexp_release (s_pkey);
return rc;
}
/****************
* Emulate our old PK interface here - sometime in the future we might
* change the internal design to directly fit to libgcrypt.
*/
int
-pk_encrypt (int algo, gcry_mpi_t * resarr, gcry_mpi_t data, gcry_mpi_t * pkey)
+pk_encrypt (int algo, gcry_mpi_t * resarr, gcry_mpi_t data, const byte pk_fp[MAX_FINGERPRINT_LEN], gcry_mpi_t * pkey)
{
gcry_sexp_t s_ciph, s_data, s_pkey;
int rc;
/* make a sexp from pkey */
if (algo == GCRY_PK_ELG || algo == GCRY_PK_ELG_E)
{
rc = gcry_sexp_build (&s_pkey, NULL,
"(public-key(elg(p%m)(g%m)(y%m)))",
pkey[0], pkey[1], pkey[2]);
}
else if (algo == GCRY_PK_RSA || algo == GCRY_PK_RSA_E)
{
rc = gcry_sexp_build (&s_pkey, NULL,
"(public-key(rsa(n%m)(e%m)))",
pkey[0], pkey[1]);
}
+ else if (algo == PUBKEY_ALGO_ECDH)
+ {
+ return pk_ecdh_encrypt( resarr, pk_fp, data, pkey );
+ }
else
return GPG_ERR_PUBKEY_ALGO;
if (rc)
BUG ();
/* put the data into a simple list */
if (gcry_sexp_build (&s_data, NULL, "%m", data))
BUG ();
/* pass it to libgcrypt */
rc = gcry_pk_encrypt (&s_ciph, s_data, s_pkey);
gcry_sexp_release (s_data);
gcry_sexp_release (s_pkey);
if (rc)
;
else
{ /* add better error handling or make gnupg use S-Exp directly */
resarr[0] = mpi_from_sexp (s_ciph, "a");
- if (algo != GCRY_PK_RSA && algo != GCRY_PK_RSA_E)
+ if (algo != GCRY_PK_RSA && algo != GCRY_PK_RSA_E && algo != PUBKEY_ALGO_ECDH)
resarr[1] = mpi_from_sexp (s_ciph, "b");
}
gcry_sexp_release (s_ciph);
return rc;
}
/****************
* Emulate our old PK interface here - sometime in the future we might
* change the internal design to directly fit to libgcrypt.
*/
int
-pk_decrypt (int algo, gcry_mpi_t * result, gcry_mpi_t * data,
+pk_decrypt (int algo, gcry_mpi_t * result, const byte sk_fp[MAX_FINGERPRINT_LEN], gcry_mpi_t * data,
gcry_mpi_t * skey)
{
gcry_sexp_t s_skey, s_data, s_plain;
int rc;
*result = NULL;
/* make a sexp from skey */
if (algo == GCRY_PK_ELG || algo == GCRY_PK_ELG_E)
{
rc = gcry_sexp_build (&s_skey, NULL,
"(private-key(elg(p%m)(g%m)(y%m)(x%m)))",
skey[0], skey[1], skey[2], skey[3]);
}
else if (algo == GCRY_PK_RSA || algo == GCRY_PK_RSA_E)
{
rc = gcry_sexp_build (&s_skey, NULL,
"(private-key(rsa(n%m)(e%m)(d%m)(p%m)(q%m)(u%m)))",
skey[0], skey[1], skey[2], skey[3], skey[4],
skey[5]);
}
+ else if( algo == PUBKEY_ALGO_ECDH ) {
+ return pk_ecdh_decrypt( result, sk_fp, data, skey );
+ }
else
return GPG_ERR_PUBKEY_ALGO;
if (rc)
BUG ();
/* put data into a S-Exp s_data */
if (algo == GCRY_PK_ELG || algo == GCRY_PK_ELG_E)
{
if (!data[0] || !data[1])
rc = gpg_error (GPG_ERR_BAD_MPI);
else
rc = gcry_sexp_build (&s_data, NULL,
"(enc-val(elg(a%m)(b%m)))", data[0], data[1]);
}
else if (algo == GCRY_PK_RSA || algo == GCRY_PK_RSA_E)
{
if (!data[0])
rc = gpg_error (GPG_ERR_BAD_MPI);
else
rc = gcry_sexp_build (&s_data, NULL, "(enc-val(rsa(a%m)))", data[0]);
}
else
BUG ();
if (rc)
BUG ();
rc = gcry_pk_decrypt (&s_plain, s_data, s_skey);
gcry_sexp_release (s_skey);
gcry_sexp_release (s_data);
if (rc)
return rc;
*result = gcry_sexp_nth_mpi (s_plain, 0, 0);
gcry_sexp_release (s_plain);
if (!*result)
return -1; /* oops */
return 0;
}
+
+/* Check whether SKEY is a suitable secret key. */
+int
+pk_check_secret_key (int algo, gcry_mpi_t *skey)
+{
+ gcry_sexp_t s_skey;
+ int rc;
+ const int gcry_pkalgo = map_pk_openpgp_to_gcry( algo );
+
+ if (gcry_pkalgo == GCRY_PK_DSA)
+ {
+ rc = gcry_sexp_build (&s_skey, NULL,
+ "(private-key(dsa(p%m)(q%m)(g%m)(y%m)(x%m)))",
+ skey[0], skey[1], skey[2], skey[3], skey[4]);
+ }
+ else if (gcry_pkalgo == GCRY_PK_ELG || gcry_pkalgo == GCRY_PK_ELG_E)
+ {
+ rc = gcry_sexp_build (&s_skey, NULL,
+ "(private-key(elg(p%m)(g%m)(y%m)(x%m)))",
+ skey[0], skey[1], skey[2], skey[3]);
+ }
+ else if (gcry_pkalgo == GCRY_PK_RSA
+ || gcry_pkalgo == GCRY_PK_RSA_S || gcry_pkalgo == GCRY_PK_RSA_E)
+ {
+ rc = gcry_sexp_build (&s_skey, NULL,
+ "(private-key(rsa(n%m)(e%m)(d%m)(p%m)(q%m)(u%m)))",
+ skey[0], skey[1], skey[2], skey[3], skey[4],
+ skey[5]);
+ }
+ else if (gcry_pkalgo == GCRY_PK_ECDSA || gcry_pkalgo == GCRY_PK_ECDH)
+ {
+ rc = gcry_sexp_build (&s_skey, NULL,
+ "(private-key(ecdsa(c%m)(q%m)(d%m)))",
+ skey[0], skey[1], skey[2] );
+ }
+ else
+ return GPG_ERR_PUBKEY_ALGO;
+
+ if (!rc)
+ {
+ rc = gcry_pk_testkey (s_skey);
+ gcry_sexp_release (s_skey);
+ }
+ return rc;
+}
diff --git a/g10/pkglue.h b/g10/pkglue.h
index f97def153..0d5194818 100644
--- a/g10/pkglue.h
+++ b/g10/pkglue.h
@@ -1,32 +1,42 @@
/* pkglue.h - public key operations definitions
* Copyright (C) 2003 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
* 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
* along with this program; if not, see .
*/
#ifndef GNUPG_G10_PKGLUE_H
#define GNUPG_G10_PKGLUE_H
+gcry_mpi_t mpi_from_sexp (gcry_sexp_t sexp, const char * item);
+
+int pk_sign (int algo, gcry_mpi_t *data, gcry_mpi_t hash,
+ gcry_mpi_t *skey);
int pk_verify (int algo, gcry_mpi_t hash, gcry_mpi_t *data,
gcry_mpi_t *pkey);
int pk_encrypt (int algo, gcry_mpi_t *resarr, gcry_mpi_t data,
+ const byte fp[MAX_FINGERPRINT_LEN],
gcry_mpi_t *pkey);
-int pk_decrypt (int algo, gcry_mpi_t *result, gcry_mpi_t *data,
+int pk_decrypt (int algo, gcry_mpi_t *result, const byte fp[MAX_FINGERPRINT_LEN], gcry_mpi_t *data,
gcry_mpi_t *skey);
int pk_check_secret_key (int algo, gcry_mpi_t *skey);
+int pk_ecdh_encrypt (gcry_mpi_t * resarr, const byte pk_fp[MAX_FINGERPRINT_LEN], gcry_mpi_t data, gcry_mpi_t * pkey);
+int pk_ecdh_decrypt (gcry_mpi_t * result, const byte sk_fp[MAX_FINGERPRINT_LEN], gcry_mpi_t *data, gcry_mpi_t * skey);
+
+gcry_mpi_t pk_ecdh_default_params_to_mpi( int qbits );
+byte *pk_ecdh_default_params( int qbits, size_t *sizeout );
#endif /*GNUPG_G10_PKGLUE_H*/
diff --git a/g10/pubkey-enc.c b/g10/pubkey-enc.c
index 312b591e9..a5224e20a 100644
--- a/g10/pubkey-enc.c
+++ b/g10/pubkey-enc.c
@@ -1,364 +1,382 @@
/* 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
* 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
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#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"
static gpg_error_t get_it (PKT_pubkey_enc *k,
DEK *dek, PKT_public_key *sk, u32 *keyid);
/* Check that the given algo is mentioned in one of the valid user-ids. */
static int
is_algo_in_prefs (kbnode_t keyblock, preftype_t type, int algo)
{
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;
}
}
}
return 0;
}
/*
* 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.
*/
gpg_error_t
get_session_key (PKT_pubkey_enc * k, DEK * dek)
{
PKT_public_key *sk = NULL;
int rc;
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. */
if (!(rc = get_seckey (sk, k->keyid)))
rc = get_it (k, dek, sk, k->keyid);
}
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 (;;)
{
if (sk)
free_public_key (sk);
sk = xmalloc_clear (sizeof *sk);
rc = enum_secret_keys (&enum_context, sk);
if (rc)
{
rc = G10ERR_NO_SECKEY;
break;
}
if (sk->pubkey_algo != k->pubkey_algo)
continue;
if (!(sk->pubkey_usage & PUBKEY_USAGE_ENC))
continue;
keyid_from_pk (sk, keyid);
log_info (_("anonymous recipient; trying secret key %s ...\n"),
keystr (keyid));
rc = get_it (k, dek, sk, keyid);
if (!rc)
{
log_info (_("okay, we are the anonymous recipient.\n"));
break;
}
else if (gpg_err_code (rc) == GPG_ERR_FULLY_CANCELED)
break; /* Don't try any more secret keys. */
}
enum_secret_keys (&enum_context, NULL); /* free context */
}
leave:
if (sk)
free_public_key (sk);
return rc;
}
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 card = 0;
gcry_sexp_t s_data;
char *desc;
char *keygrip;
+ byte fp[MAX_FINGERPRINT_LEN];
+ size_t fpn;
/* Get the keygrip. */
err = hexkeygrip_from_pk (sk, &keygrip);
if (err)
goto leave;
/* Convert the data to an S-expression. */
if (sk->pubkey_algo == GCRY_PK_ELG || sk->pubkey_algo == 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 (sk->pubkey_algo == GCRY_PK_RSA || sk->pubkey_algo == 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
err = gpg_error (GPG_ERR_BUG);
if (err)
goto leave;
+ fingerprint_from_pk( sk, fp, &fpn );
+ assert( fpn == 20 );
+
/* Decrypt. */
desc = gpg_format_keydesc (sk, 0, 1);
- err = agent_pkdecrypt (NULL, keygrip, desc, s_data, &frame, &nframe);
+ err = agent_pkdecrypt (NULL, keygrip, desc, s_data, fp, &frame, &nframe);
xfree (desc);
gcry_sexp_release (s_data);
if (err)
goto leave;
/* 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 (!card)
- {
- if (n + 7 > nframe)
- {
- err = gpg_error (G10ERR_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 (G10ERR_CIPHER_ALGO);
- goto leave;
- }
- if (frame[n] != 2) /* Something went wrong. */
- {
- err = gpg_error (G10ERR_WRONG_SECKEY);
- goto leave;
- }
- for (n++; n < nframe && frame[n]; n++) /* Skip the random bytes. */
- ;
- n++; /* Skip the zero byte. */
+
+ if( sk->pubkey_algo != PUBKEY_ALGO_ECDH ) {
+ if (!card)
+ {
+ if (n + 7 > nframe)
+ {
+ err = gpg_error (G10ERR_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 (G10ERR_CIPHER_ALGO);
+ goto leave;
+ }
+ if (frame[n] != 2) /* Something went wrong. */
+ {
+ err = gpg_error (G10ERR_WRONG_SECKEY);
+ goto leave;
+ }
+ for (n++; n < nframe && frame[n]; n++) /* Skip the random bytes. */
+ ;
+ n++; /* Skip the zero byte. */
+ }
+ }
+ else {
+ /* Allow double padding for the benefit of DEK size concealment.
+ * Higher than this is wasteful.
+ */
+ if( frame[nframe-1] > 8*2 || nframe <= 8 ) {
+ err = G10ERR_WRONG_SECKEY; goto leave;
}
+ nframe -= frame[nframe-1]; /* remove padding */
+ assert( n==0 ); /* used just bellow */
+ }
if (n + 4 > nframe)
{
err = gpg_error (G10ERR_WRONG_SECKEY);
goto leave;
}
dek->keylen = nframe - (n + 1) - 2;
dek->algo = frame[n++];
if (dek->algo == CIPHER_ALGO_IDEA)
write_status (STATUS_RSA_OR_IDEA);
err = openpgp_cipher_test_algo (dek->algo);
if (err)
{
if (!opt.quiet && gpg_err_code (err) == GPG_ERR_CIPHER_ALGO)
{
log_info (_("cipher algorithm %d%s is unknown or disabled\n"),
dek->algo,
dek->algo == CIPHER_ALGO_IDEA ? " (IDEA)" : "");
if (dek->algo == CIPHER_ALGO_IDEA)
idea_cipher_warn (0);
}
dek->algo = 0;
goto leave;
}
if (dek->keylen != openpgp_cipher_get_algo_keylen (dek->algo))
{
err = gpg_error (GPG_ERR_WRONG_SECKEY);
goto leave;
}
/* 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);
goto leave;
}
if (DBG_CIPHER)
log_printhex ("DEK is:", dek->key, dek->keylen);
/* Check that the algo is in the preferences and whether it has expired. */
{
PKT_public_key *pk = NULL;
KBNODE pkb = get_pubkeyblock (keyid);
if (!pkb)
{
err = -1;
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)
{
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)
{
log_info (_("NOTE: key has been revoked"));
log_printf ("\n");
show_revocation_reason (pk, 1);
}
release_kbnode (pkb);
err = 0;
}
leave:
xfree (frame);
xfree (keygrip);
return err;
}
/*
* Get the session key from the given string.
* String is supposed to be formatted as this:
* :
*/
gpg_error_t
get_override_session_key (DEK *dek, const char *string)
{
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;
}
if (*s)
return G10ERR_BAD_KEY;
dek->keylen = i;
return 0;
}
diff --git a/g10/seskey.c b/g10/seskey.c
index ee5584c66..4cc9158c9 100644
--- a/g10/seskey.c
+++ b/g10/seskey.c
@@ -1,280 +1,325 @@
/* seskey.c - make sesssion keys etc.
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
* 2006, 2009 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
* 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
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include "gpg.h"
#include "util.h"
#include "cipher.h"
+#include "options.h"
#include "main.h"
#include "i18n.h"
/****************
* Make a session key and put it into DEK
*/
void
make_session_key( DEK *dek )
{
gcry_cipher_hd_t chd;
int i, rc;
dek->keylen = openpgp_cipher_get_algo_keylen (dek->algo);
if (openpgp_cipher_open (&chd, dek->algo, GCRY_CIPHER_MODE_CFB,
(GCRY_CIPHER_SECURE
| (dek->algo >= 100 ?
0 : GCRY_CIPHER_ENABLE_SYNC))) )
BUG();
gcry_randomize (dek->key, dek->keylen, GCRY_STRONG_RANDOM );
for (i=0; i < 16; i++ )
{
rc = gcry_cipher_setkey (chd, dek->key, dek->keylen);
if (!rc)
{
gcry_cipher_close (chd);
return;
}
if (gpg_err_code (rc) != GPG_ERR_WEAK_KEY)
BUG();
log_info(_("weak key created - retrying\n") );
/* Renew the session key until we get a non-weak key. */
gcry_randomize (dek->key, dek->keylen, GCRY_STRONG_RANDOM);
}
log_fatal (_("cannot avoid weak key for symmetric cipher; "
"tried %d times!\n"), i);
}
/****************
* Encode the session key. NBITS is the number of bits which should be used
* for packing the session key.
* returns: A mpi with the session key (caller must free)
*/
gcry_mpi_t
-encode_session_key (DEK *dek, unsigned int nbits)
+encode_session_key (int openpgp_pk_algo, DEK *dek, unsigned int nbits)
{
size_t nframe = (nbits+7) / 8;
byte *p;
byte *frame;
int i,n;
- u16 csum;
+ u16 csum = 0;
gcry_mpi_t a;
+ if( DBG_CIPHER )
+ log_debug("encode_session_key: encoding %d byte DEK", dek->keylen);
+
+ for( p = dek->key, i=0; i < dek->keylen; i++ )
+ csum += *p++;
+
+ /* Shortcut for ECDH. It's padding is minimal to simply make the output be a multiple of 8 bytes. */
+ if( openpgp_pk_algo == PUBKEY_ALGO_ECDH ) {
+ /* pad to 8 byte granulatiry; the padding byte is the number of padded bytes.
+ * A DEK(k bytes) CSUM(2 bytes) 0x 0x 0x 0x ... 0x
+ * +---- x times ---+
+ */
+ nframe = ( 1 + dek->keylen + 2 /* the value so far is always odd */ + 7 ) & (~7);
+ assert( !(nframe%8) && nframe > 1 + dek->keylen + 2 ); /* alg+key+csum fit and the size is congruent to 8 */
+ frame = xmalloc_secure( nframe );
+ n = 0;
+ frame[n++] = dek->algo;
+ memcpy( frame+n, dek->key, dek->keylen ); n += dek->keylen;
+ frame[n++] = csum >>8;
+ frame[n++] = csum;
+ i = nframe - n; /* number padded bytes */
+ memset( frame+n, i, i );/* use it as the value of each padded byte */
+ assert( n+i == nframe );
+
+ if( DBG_CIPHER )
+ log_debug("encode_session_key: [%d] %02x %02x %02x ... %02x %02x %02x", nframe, frame[0],frame[1],frame[2], frame[nframe-3],frame[nframe-2],frame[nframe-1]);
+
+ if (gcry_mpi_scan( &a, GCRYMPI_FMT_USG, frame, nframe, &nframe))
+ BUG();
+ xfree(frame);
+ return a;
+ }
+
/* The current limitation is that we can only use a session key
* whose length is a multiple of BITS_PER_MPI_LIMB
* I think we can live with that.
*/
if( dek->keylen + 7 > nframe || !nframe )
log_bug("can't encode a %d bit key in a %d bits frame\n",
dek->keylen*8, nbits );
/* We encode the session key in this way:
*
* 0 2 RND(n bytes) 0 A DEK(k bytes) CSUM(2 bytes)
*
* (But how can we store the leading 0 - the external representaion
* of MPIs doesn't allow leading zeroes =:-)
*
* RND are non-zero random bytes.
* A is the cipher algorithm
* DEK is the encryption key (session key) length k depends on the
* cipher algorithm (20 is used with blowfish160).
* CSUM is the 16 bit checksum over the DEK
*/
- csum = 0;
- for( p = dek->key, i=0; i < dek->keylen; i++ )
- csum += *p++;
frame = xmalloc_secure( nframe );
n = 0;
frame[n++] = 0;
frame[n++] = 2;
i = nframe - 6 - dek->keylen;
assert( i > 0 );
p = gcry_random_bytes_secure (i, GCRY_STRONG_RANDOM);
/* Replace zero bytes by new values. */
for(;;) {
int j, k;
byte *pp;
/* count the zero bytes */
for(j=k=0; j < i; j++ )
if( !p[j] )
k++;
if( !k )
break; /* okay: no zero bytes */
k += k/128 + 3; /* better get some more */
pp = gcry_random_bytes_secure (k, GCRY_STRONG_RANDOM);
for(j=0; j < i && k ;) {
if( !p[j] )
p[j] = pp[--k];
if (p[j])
j++;
}
xfree(pp);
}
memcpy( frame+n, p, i );
xfree(p);
n += i;
frame[n++] = 0;
frame[n++] = dek->algo;
memcpy( frame+n, dek->key, dek->keylen ); n += dek->keylen;
frame[n++] = csum >>8;
frame[n++] = csum;
assert( n == nframe );
if (gcry_mpi_scan( &a, GCRYMPI_FMT_USG, frame, n, &nframe))
BUG();
xfree(frame);
return a;
}
static gcry_mpi_t
do_encode_md( gcry_md_hd_t md, int algo, size_t len, unsigned nbits,
const byte *asn, size_t asnlen )
{
size_t nframe = (nbits+7) / 8;
byte *frame;
int i,n;
gcry_mpi_t a;
if( len + asnlen + 4 > nframe )
- log_bug("can't encode a %d bit MD into a %d bits frame\n",
- (int)(len*8), (int)nbits);
+ log_bug("can't encode a %d bit MD into a %d bits frame, algo=%d\n",
+ (int)(len*8), (int)nbits, algo);
/* We encode the MD in this way:
*
* 0 1 PAD(n bytes) 0 ASN(asnlen bytes) MD(len bytes)
*
* PAD consists of FF bytes.
*/
frame = gcry_md_is_secure (md)? xmalloc_secure (nframe) : xmalloc (nframe);
n = 0;
frame[n++] = 0;
frame[n++] = 1; /* block type */
i = nframe - len - asnlen -3 ;
assert( i > 1 );
memset( frame+n, 0xff, i ); n += i;
frame[n++] = 0;
memcpy( frame+n, asn, asnlen ); n += asnlen;
memcpy( frame+n, gcry_md_read (md, algo), len ); n += len;
assert( n == nframe );
if (gcry_mpi_scan( &a, GCRYMPI_FMT_USG, frame, n, &nframe ))
BUG();
xfree(frame);
/* Note that PGP before version 2.3 encoded the MD as:
*
* 0 1 MD(16 bytes) 0 PAD(n bytes) 1
*
* The MD is always 16 bytes here because it's always MD5. We do
* not support pre-v2.3 signatures, but I'm including this comment
* so the information is easily found in the future.
*/
return a;
}
/****************
* Encode a message digest into an MPI.
* If it's for a DSA signature, make sure that the hash is large
* enough to fill up q. If the hash is too big, take the leftmost
* bits.
*/
gcry_mpi_t
encode_md_value (PKT_public_key *pk, gcry_md_hd_t md, int hash_algo)
{
gcry_mpi_t frame;
+ int gcry_pkalgo;
assert (hash_algo);
assert (pk);
- if (pk->pubkey_algo == GCRY_PK_DSA)
+ gcry_pkalgo = map_pk_openpgp_to_gcry( pk->pubkey_algo );
+
+ if (gcry_pkalgo == GCRY_PK_DSA || gcry_pkalgo == GCRY_PK_ECDSA )
{
/* It's a DSA signature, so find out the size of q. */
size_t qbytes = gcry_mpi_get_nbits (pk->pkey[1]);
+ /* pkey[1] is Q for ECDSA, which is an uncompressed point, i.e. 04 */
+ if( gcry_pkalgo==GCRY_PK_ECDSA )
+ qbytes = ecdsa_qbits_from_Q( qbytes );
+
/* Make sure it is a multiple of 8 bits. */
if(qbytes%8)
{
log_error(_("DSA requires the hash length to be a"
" multiple of 8 bits\n"));
return NULL;
}
/* Don't allow any q smaller than 160 bits. This might need a
revisit as the DSA2 design firms up, but for now, we don't
want someone to issue signatures from a key with a 16-bit q
or something like that, which would look correct but allow
trivial forgeries. Yes, I know this rules out using MD5 with
DSA. ;) */
if (qbytes < 160)
{
- log_error (_("DSA key %s uses an unsafe (%zu bit) hash\n"),
+ log_error (_("%s key %s uses an unsafe (%zu bit) hash\n"),
+ gcry_pk_algo_name( gcry_pkalgo ),
keystr_from_pk (pk), qbytes);
return NULL;
}
qbytes /= 8;
/* Check if we're too short. Too long is safe as we'll
automatically left-truncate. */
- if (gcry_md_get_algo_dlen (hash_algo) < qbytes)
+ /* This checks would require the use of SHA512 with ECDSA 512. I think this is overkill to fail in this case.
+ * Therefore, relax the check, but only for ECDSA keys. We may need to adjust it later for general case.
+ * ( Note that the check will never pass for ECDSA 521 anyway as the only hash that intended to match it is SHA 512, but 512 < 521 ).
+ */
+ //if (gcry_md_get_algo_dlen (hash_algo) < qbytes )
+ if (gcry_md_get_algo_dlen (hash_algo) < ((gcry_pkalgo==GCRY_PK_ECDSA && qbytes>(521)/8) ? 512/8 : qbytes) )
{
- log_error (_("DSA key %s requires a %zu bit or larger hash\n"),
- keystr_from_pk(pk), qbytes*8);
+ log_error (_("%s key %s requires a %zu bit or larger hash, used hash-algo=%d\n"),
+ gcry_pk_algo_name( gcry_pkalgo ),
+ keystr_from_pk(pk), qbytes*8, hash_algo);
return NULL;
}
if (gcry_mpi_scan (&frame, GCRYMPI_FMT_USG,
gcry_md_read (md, hash_algo), qbytes, &qbytes))
BUG();
}
else
{
gpg_error_t rc;
byte *asn;
size_t asnlen;
rc = gcry_md_algo_info (hash_algo, GCRYCTL_GET_ASNOID, NULL, &asnlen);
if (rc)
log_fatal ("can't get OID of digest algorithm %d: %s\n",
hash_algo, gpg_strerror (rc));
asn = xtrymalloc (asnlen);
if (!asn)
return NULL;
if ( gcry_md_algo_info (hash_algo, GCRYCTL_GET_ASNOID, asn, &asnlen) )
BUG();
frame = do_encode_md (md, hash_algo, gcry_md_get_algo_dlen (hash_algo),
gcry_mpi_get_nbits (pk->pkey[0]), asn, asnlen);
xfree (asn);
}
return frame;
}
diff --git a/g10/sign.c b/g10/sign.c
index 5c00424a6..ccf796446 100644
--- a/g10/sign.c
+++ b/g10/sign.c
@@ -1,1644 +1,1638 @@
/* sign.c - sign data
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
* 2007, 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
* 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
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include
#include "gpg.h"
#include "options.h"
#include "packet.h"
#include "status.h"
#include "iobuf.h"
#include "keydb.h"
#include "util.h"
#include "main.h"
#include "filter.h"
#include "ttyio.h"
#include "trustdb.h"
#include "status.h"
#include "i18n.h"
#include "pkglue.h"
#include "sysutils.h"
#include "call-agent.h"
#ifdef HAVE_DOSISH_SYSTEM
#define LF "\r\n"
#else
#define LF "\n"
#endif
static int recipient_digest_algo=0;
/****************
* Create notations and other stuff. It is assumed that the stings in
* STRLIST are already checked to contain only printable data and have
* a valid NAME=VALUE format.
*/
static void
mk_notation_policy_etc (PKT_signature *sig,
PKT_public_key *pk, PKT_public_key *pksk)
{
const char *string;
char *s=NULL;
strlist_t pu=NULL;
struct notation *nd=NULL;
struct expando_args args;
assert(sig->version>=4);
memset(&args,0,sizeof(args));
args.pk=pk;
args.pksk=pksk;
/* notation data */
if(IS_SIG(sig) && opt.sig_notations)
nd=opt.sig_notations;
else if( IS_CERT(sig) && opt.cert_notations )
nd=opt.cert_notations;
if(nd)
{
struct notation *i;
for(i=nd;i;i=i->next)
{
i->altvalue=pct_expando(i->value,&args);
if(!i->altvalue)
log_error(_("WARNING: unable to %%-expand notation "
"(too large). Using unexpanded.\n"));
}
keygen_add_notations(sig,nd);
for(i=nd;i;i=i->next)
{
xfree(i->altvalue);
i->altvalue=NULL;
}
}
/* set policy URL */
if( IS_SIG(sig) && opt.sig_policy_url )
pu=opt.sig_policy_url;
else if( IS_CERT(sig) && opt.cert_policy_url )
pu=opt.cert_policy_url;
for(;pu;pu=pu->next)
{
string = pu->d;
s=pct_expando(string,&args);
if(!s)
{
log_error(_("WARNING: unable to %%-expand policy URL "
"(too large). Using unexpanded.\n"));
s=xstrdup(string);
}
build_sig_subpkt(sig,SIGSUBPKT_POLICY|
((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0),
s,strlen(s));
xfree(s);
}
/* preferred keyserver URL */
if( IS_SIG(sig) && opt.sig_keyserver_url )
pu=opt.sig_keyserver_url;
for(;pu;pu=pu->next)
{
string = pu->d;
s=pct_expando(string,&args);
if(!s)
{
log_error(_("WARNING: unable to %%-expand preferred keyserver URL"
" (too large). Using unexpanded.\n"));
s=xstrdup(string);
}
build_sig_subpkt(sig,SIGSUBPKT_PREF_KS|
((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0),
s,strlen(s));
xfree(s);
}
}
/*
* Helper to hash a user ID packet.
*/
static void
hash_uid (gcry_md_hd_t md, int sigversion, const PKT_user_id *uid)
{
if ( sigversion >= 4 ) {
byte buf[5];
if(uid->attrib_data) {
buf[0] = 0xd1; /* indicates an attribute packet */
buf[1] = uid->attrib_len >> 24; /* always use 4 length bytes */
buf[2] = uid->attrib_len >> 16;
buf[3] = uid->attrib_len >> 8;
buf[4] = uid->attrib_len;
}
else {
buf[0] = 0xb4; /* indicates a userid packet */
buf[1] = uid->len >> 24; /* always use 4 length bytes */
buf[2] = uid->len >> 16;
buf[3] = uid->len >> 8;
buf[4] = uid->len;
}
gcry_md_write( md, buf, 5 );
}
if(uid->attrib_data)
gcry_md_write (md, uid->attrib_data, uid->attrib_len );
else
gcry_md_write (md, uid->name, uid->len );
}
/*
* Helper to hash some parts from the signature
*/
static void
hash_sigversion_to_magic (gcry_md_hd_t md, const PKT_signature *sig)
{
if (sig->version >= 4)
gcry_md_putc (md, sig->version);
gcry_md_putc (md, sig->sig_class);
if (sig->version < 4) {
u32 a = sig->timestamp;
gcry_md_putc (md, (a >> 24) & 0xff );
gcry_md_putc (md, (a >> 16) & 0xff );
gcry_md_putc (md, (a >> 8) & 0xff );
gcry_md_putc (md, a & 0xff );
}
else {
byte buf[6];
size_t n;
gcry_md_putc (md, sig->pubkey_algo);
gcry_md_putc (md, sig->digest_algo);
if (sig->hashed) {
n = sig->hashed->len;
gcry_md_putc (md, (n >> 8) );
gcry_md_putc (md, n );
gcry_md_write (md, sig->hashed->data, n );
n += 6;
}
else {
gcry_md_putc (md, 0); /* always hash the length of the subpacket*/
gcry_md_putc (md, 0);
n = 6;
}
/* add some magic */
buf[0] = sig->version;
buf[1] = 0xff;
buf[2] = n >> 24; /* hmmm, n is only 16 bit, so this is always 0 */
buf[3] = n >> 16;
buf[4] = n >> 8;
buf[5] = n;
gcry_md_write (md, buf, 6);
}
}
-
-static gcry_mpi_t
-mpi_from_sexp (gcry_sexp_t sexp, const char * item)
-{
- gcry_sexp_t list;
- gcry_mpi_t data;
-
- list = gcry_sexp_find_token (sexp, item, 0);
- assert (list);
- data = gcry_sexp_nth_mpi (list, 1, 0);
- assert (data);
- gcry_sexp_release (list);
- return data;
-}
-
/* Perform the sign operation. If CACHE_NONCE is given the agent is
advised to use that cached passphrase fro the key. */
static int
do_sign (PKT_public_key *pksk, PKT_signature *sig,
gcry_md_hd_t md, int mdalgo, const char *cache_nonce)
{
gpg_error_t err;
gcry_mpi_t frame;
byte *dp;
char *hexgrip;
if (pksk->timestamp > sig->timestamp )
{
ulong d = pksk->timestamp - sig->timestamp;
log_info (d==1 ? _("key has been created %lu second "
"in future (time warp or clock problem)\n")
: _("key has been created %lu seconds "
"in future (time warp or clock problem)\n"), d );
if (!opt.ignore_time_conflict)
return gpg_error (GPG_ERR_TIME_CONFLICT);
}
print_pubkey_algo_note (pksk->pubkey_algo);
if (!mdalgo)
mdalgo = gcry_md_get_algo (md);
print_digest_algo_note (mdalgo);
dp = gcry_md_read (md, mdalgo);
sig->digest_algo = mdalgo;
sig->digest_start[0] = dp[0];
sig->digest_start[1] = dp[1];
sig->data[0] = NULL;
sig->data[1] = NULL;
err = hexkeygrip_from_pk (pksk, &hexgrip);
if (!err)
{
char *desc;
gcry_sexp_t s_sigval;
desc = gpg_format_keydesc (pksk, 0, 1);
err = agent_pksign (NULL/*ctrl*/, cache_nonce, hexgrip, desc,
dp, gcry_md_get_algo_dlen (mdalgo), mdalgo,
&s_sigval);
xfree (desc);
if (err)
;
else if (pksk->pubkey_algo == GCRY_PK_RSA
|| pksk->pubkey_algo == GCRY_PK_RSA_S)
sig->data[0] = mpi_from_sexp (s_sigval, "s");
else
{
sig->data[0] = mpi_from_sexp (s_sigval, "r");
sig->data[1] = mpi_from_sexp (s_sigval, "s");
}
gcry_sexp_release (s_sigval);
}
xfree (hexgrip);
/* Check that the signature verification worked and nothing is
* fooling us e.g. by a bug in the signature create code or by
* deliberately introduced faults. */
if (!err && !opt.no_sig_create_check)
{
PKT_public_key *pk = xmalloc_clear (sizeof *pk);
if (get_pubkey (pk, sig->keyid ))
err = gpg_error (GPG_ERR_NO_PUBKEY);
else
{
frame = encode_md_value (pk, md, sig->digest_algo );
if (!frame)
err = gpg_error (GPG_ERR_GENERAL);
else
err = pk_verify (pk->pubkey_algo, frame, sig->data, pk->pkey);
gcry_mpi_release (frame);
}
if (err)
log_error (_("checking created signature failed: %s\n"),
g10_errstr (err));
free_public_key (pk);
}
if (err)
log_error (_("signing failed: %s\n"), g10_errstr (err));
else
{
if (opt.verbose)
{
char *ustr = get_user_id_string_native (sig->keyid);
log_info (_("%s/%s signature from: \"%s\"\n"),
gcry_pk_algo_name (pksk->pubkey_algo),
gcry_md_algo_name (sig->digest_algo),
ustr);
xfree (ustr);
}
}
return err;
}
int
complete_sig (PKT_signature *sig, PKT_public_key *pksk, gcry_md_hd_t md,
const char *cache_nonce)
{
int rc;
/* if (!(rc = check_secret_key (pksk, 0))) */
rc = do_sign (pksk, sig, md, 0, cache_nonce);
return rc;
}
/* Return true if the key seems to be on a version 1 OpenPGP card.
This works by asking the agent and may fail if the card has not yet
been used with the agent. */
static int
openpgp_card_v1_p (PKT_public_key *pk)
{
gpg_error_t err;
int result;
/* Shortcut if we are not using RSA: The v1 cards only support RSA
thus there is no point in looking any further. */
if (!is_RSA (pk->pubkey_algo))
return 0;
if (!pk->flags.serialno_valid)
{
char *hexgrip;
err = hexkeygrip_from_pk (pk, &hexgrip);
if (err)
{
log_error ("error computing a keygrip: %s\n", gpg_strerror (err));
return 0; /* Ooops. */
}
xfree (pk->serialno);
agent_get_keyinfo (NULL, hexgrip, &pk->serialno);
xfree (hexgrip);
pk->flags.serialno_valid = 1;
}
if (!pk->serialno)
result = 0; /* Error from a past agent_get_keyinfo or no card. */
else
{
/* The version number of the card is included in the serialno. */
result = !strncmp (pk->serialno, "D2760001240101", 14);
}
return result;
}
static int
match_dsa_hash (unsigned int qbytes)
{
if (qbytes <= 20)
return DIGEST_ALGO_SHA1;
if (qbytes <= 28)
return DIGEST_ALGO_SHA224;
if (qbytes <= 32)
return DIGEST_ALGO_SHA256;
if (qbytes <= 48)
return DIGEST_ALGO_SHA384;
- if (qbytes <= 64)
+ if (qbytes <= 66 ) /* 66 corresponds to 521 (64 to 512) */
return DIGEST_ALGO_SHA512;
return DEFAULT_DIGEST_ALGO;
/* DEFAULT_DIGEST_ALGO will certainly fail, but it's the best wrong
answer we have if a digest larger than 512 bits is requested. */
}
/*
First try --digest-algo. If that isn't set, see if the recipient
has a preferred algorithm (which is also filtered through
--preferred-digest-prefs). If we're making a signature without a
particular recipient (i.e. signing, rather than signing+encrypting)
then take the first algorithm in --preferred-digest-prefs that is
usable for the pubkey algorithm. If --preferred-digest-prefs isn't
set, then take the OpenPGP default (i.e. SHA-1).
Possible improvement: Use the highest-ranked usable algorithm from
the signing key prefs either before or after using the personal
list?
*/
static int
hash_for (PKT_public_key *pk)
{
if (opt.def_digest_algo)
{
return opt.def_digest_algo;
}
else if (recipient_digest_algo)
{
return recipient_digest_algo;
}
- else if (pk->pubkey_algo == PUBKEY_ALGO_DSA)
+ else if(pk->pubkey_algo==PUBKEY_ALGO_DSA || pk->pubkey_algo==PUBKEY_ALGO_ECDSA )
{
- unsigned int qbytes = gcry_mpi_get_nbits (pk->pkey[1]) / 8;
+ unsigned int qbytes = gcry_mpi_get_nbits (pk->pkey[1]);
+
+ if( pk->pubkey_algo==PUBKEY_ALGO_ECDSA )
+ qbytes = ecdsa_qbits_from_Q(qbytes);
+ qbytes = qbytes/8;
/* It's a DSA key, so find a hash that is the same size as q or
larger. If q is 160, assume it is an old DSA key and use a
160-bit hash unless --enable-dsa2 is set, in which case act
like a new DSA key that just happens to have a 160-bit q
(i.e. allow truncation). If q is not 160, by definition it
must be a new DSA key. */
if (opt.personal_digest_prefs)
{
prefitem_t *prefs;
if (qbytes != 20 || opt.flags.dsa2)
{
for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
if (gcry_md_get_algo_dlen (prefs->value) >= qbytes)
return prefs->value;
}
else
{
for (prefs=opt.personal_digest_prefs; prefs->type; prefs++)
if (gcry_md_get_algo_dlen (prefs->value) == qbytes)
return prefs->value;
}
}
return match_dsa_hash(qbytes);
}
else if (openpgp_card_v1_p (pk))
{
/* The sk lives on a smartcard, and old smartcards only handle
SHA-1 and RIPEMD/160. Newer smartcards (v2.0) don't have
this restriction anymore. Fortunately the serial number
encodes the version of the card and thus we know that this
key is on a v1 card. */
if(opt.personal_digest_prefs)
{
prefitem_t *prefs;
for (prefs=opt.personal_digest_prefs;prefs->type;prefs++)
if (prefs->value==DIGEST_ALGO_SHA1
|| prefs->value==DIGEST_ALGO_RMD160)
return prefs->value;
}
return DIGEST_ALGO_SHA1;
}
else if (PGP2 && pk->pubkey_algo == PUBKEY_ALGO_RSA && pk->version < 4 )
{
/* Old-style PGP only understands MD5 */
return DIGEST_ALGO_MD5;
}
else if (opt.personal_digest_prefs)
{
/* It's not DSA, so we can use whatever the first hash algorithm
is in the pref list */
return opt.personal_digest_prefs[0].value;
}
else
return DEFAULT_DIGEST_ALGO;
}
/* Return true iff all keys in SK_LIST are old style (v3 RSA). */
static int
only_old_style (SK_LIST sk_list)
{
SK_LIST sk_rover = NULL;
int old_style = 0;
for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
{
PKT_public_key *pk = sk_rover->pk;
if (pk->pubkey_algo == PUBKEY_ALGO_RSA && pk->version < 4)
old_style = 1;
else
return 0;
}
return old_style;
}
static void
print_status_sig_created (PKT_public_key *pk, PKT_signature *sig, int what)
{
byte array[MAX_FINGERPRINT_LEN];
char buf[100+MAX_FINGERPRINT_LEN*2];
size_t n;
snprintf (buf, sizeof buf - 2*MAX_FINGERPRINT_LEN, "%c %d %d %02x %lu ",
what, sig->pubkey_algo, sig->digest_algo, sig->sig_class,
(ulong)sig->timestamp );
fingerprint_from_pk (pk, array, &n);
bin2hex (array, n, buf + strlen (buf));
write_status_text( STATUS_SIG_CREATED, buf );
}
/*
* Loop over the secret certificates in SK_LIST and build the one pass
* signature packets. OpenPGP says that the data should be bracket by
* the onepass-sig and signature-packet; so we build these onepass
* packet here in reverse order
*/
static int
write_onepass_sig_packets (SK_LIST sk_list, IOBUF out, int sigclass )
{
int skcount;
SK_LIST sk_rover;
for (skcount=0, sk_rover=sk_list; sk_rover; sk_rover = sk_rover->next)
skcount++;
for (; skcount; skcount--) {
PKT_public_key *pk;
PKT_onepass_sig *ops;
PACKET pkt;
int i, rc;
for (i=0, sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
if (++i == skcount)
break;
}
pk = sk_rover->pk;
ops = xmalloc_clear (sizeof *ops);
ops->sig_class = sigclass;
ops->digest_algo = hash_for (pk);
ops->pubkey_algo = pk->pubkey_algo;
keyid_from_pk (pk, ops->keyid);
ops->last = (skcount == 1);
init_packet(&pkt);
pkt.pkttype = PKT_ONEPASS_SIG;
pkt.pkt.onepass_sig = ops;
rc = build_packet (out, &pkt);
free_packet (&pkt);
if (rc) {
log_error ("build onepass_sig packet failed: %s\n",
g10_errstr(rc));
return rc;
}
}
return 0;
}
/*
* Helper to write the plaintext (literal data) packet
*/
static int
write_plaintext_packet (IOBUF out, IOBUF inp, const char *fname, int ptmode)
{
PKT_plaintext *pt = NULL;
u32 filesize;
int rc = 0;
if (!opt.no_literal)
pt=setup_plaintext_name(fname,inp);
/* try to calculate the length of the data */
if ( !iobuf_is_pipe_filename (fname) && *fname )
{
off_t tmpsize;
int overflow;
if( !(tmpsize = iobuf_get_filelength(inp, &overflow))
&& !overflow && opt.verbose)
log_info (_("WARNING: `%s' is an empty file\n"), fname);
/* We can't encode the length of very large files because
OpenPGP uses only 32 bit for file sizes. So if the size of
a file is larger than 2^32 minus some bytes for packet
headers, we switch to partial length encoding. */
if ( tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) )
filesize = tmpsize;
else
filesize = 0;
/* Because the text_filter modifies the length of the
* data, it is not possible to know the used length
* without a double read of the file - to avoid that
* we simple use partial length packets. */
if ( ptmode == 't' )
filesize = 0;
}
else
filesize = opt.set_filesize? opt.set_filesize : 0; /* stdin */
if (!opt.no_literal) {
PACKET pkt;
pt->timestamp = make_timestamp ();
pt->mode = ptmode;
pt->len = filesize;
pt->new_ctb = !pt->len && !RFC1991;
pt->buf = inp;
init_packet(&pkt);
pkt.pkttype = PKT_PLAINTEXT;
pkt.pkt.plaintext = pt;
/*cfx.datalen = filesize? calc_packet_length( &pkt ) : 0;*/
if( (rc = build_packet (out, &pkt)) )
log_error ("build_packet(PLAINTEXT) failed: %s\n",
g10_errstr(rc) );
pt->buf = NULL;
}
else {
byte copy_buffer[4096];
int bytes_copied;
while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1)
if ( (rc=iobuf_write(out, copy_buffer, bytes_copied)) ) {
log_error ("copying input to output failed: %s\n",
gpg_strerror (rc));
break;
}
wipememory(copy_buffer,4096); /* burn buffer */
}
/* fixme: it seems that we never freed pt/pkt */
return rc;
}
/*
* Write the signatures from the SK_LIST to OUT. HASH must be a non-finalized
* hash which will not be changes here.
*/
static int
write_signature_packets (SK_LIST sk_list, IOBUF out, gcry_md_hd_t hash,
int sigclass, u32 timestamp, u32 duration,
int status_letter, const char *cache_nonce)
{
SK_LIST sk_rover;
/* Loop over the certificates with secret keys. */
for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
{
PKT_public_key *pk;
PKT_signature *sig;
gcry_md_hd_t md;
int rc;
pk = sk_rover->pk;
/* Build the signature packet. */
sig = xmalloc_clear (sizeof *sig);
if (opt.force_v3_sigs || RFC1991)
sig->version = 3;
else if (duration || opt.sig_policy_url
|| opt.sig_notations || opt.sig_keyserver_url)
sig->version = 4;
else
sig->version = pk->version;
keyid_from_pk (pk, sig->keyid);
sig->digest_algo = hash_for (pk);
sig->pubkey_algo = pk->pubkey_algo;
if (timestamp)
sig->timestamp = timestamp;
else
sig->timestamp = make_timestamp();
if (duration)
sig->expiredate = sig->timestamp + duration;
sig->sig_class = sigclass;
if (gcry_md_copy (&md, hash))
BUG ();
if (sig->version >= 4)
{
build_sig_subpkt_from_sig (sig);
mk_notation_policy_etc (sig, pk, NULL);
}
hash_sigversion_to_magic (md, sig);
gcry_md_final (md);
rc = do_sign (pk, sig, md, hash_for (pk), cache_nonce);
gcry_md_close (md);
if (!rc)
{
/* Write the packet. */
PACKET pkt;
init_packet (&pkt);
pkt.pkttype = PKT_SIGNATURE;
pkt.pkt.signature = sig;
rc = build_packet (out, &pkt);
if (!rc && is_status_enabled())
print_status_sig_created (pk, sig, status_letter);
free_packet (&pkt);
if (rc)
log_error ("build signature packet failed: %s\n", gpg_strerror (rc));
}
if (rc)
return rc;
}
return 0;
}
/****************
* Sign the files whose names are in FILENAME.
* If DETACHED has the value true,
* make a detached signature. If FILENAMES->d is NULL read from stdin
* and ignore the detached mode. Sign the file with all secret keys
* which can be taken from LOCUSR, if this is NULL, use the default one
* If ENCRYPTFLAG is true, use REMUSER (or ask if it is NULL) to encrypt the
* signed data for these users.
* If OUTFILE is not NULL; this file is used for output and the function
* does not ask for overwrite permission; output is then always
* uncompressed, non-armored and in binary mode.
*/
int
sign_file (ctrl_t ctrl, strlist_t filenames, int detached, strlist_t locusr,
int encryptflag, strlist_t remusr, const char *outfile )
{
const char *fname;
armor_filter_context_t *afx;
compress_filter_context_t zfx;
md_filter_context_t mfx;
text_filter_context_t tfx;
progress_filter_context_t *pfx;
encrypt_filter_context_t efx;
IOBUF inp = NULL, out = NULL;
PACKET pkt;
int rc = 0;
PK_LIST pk_list = NULL;
SK_LIST sk_list = NULL;
SK_LIST sk_rover = NULL;
int multifile = 0;
u32 duration=0;
pfx = new_progress_context ();
afx = new_armor_context ();
memset( &zfx, 0, sizeof zfx);
memset( &mfx, 0, sizeof mfx);
memset( &efx, 0, sizeof efx);
init_packet( &pkt );
if( filenames ) {
fname = filenames->d;
multifile = !!filenames->next;
}
else
fname = NULL;
if( fname && filenames->next && (!detached || encryptflag) )
log_bug("multiple files can only be detached signed");
if(encryptflag==2
&& (rc=setup_symkey(&efx.symkey_s2k,&efx.symkey_dek)))
goto leave;
if(!opt.force_v3_sigs && !RFC1991)
{
if(opt.ask_sig_expire && !opt.batch)
duration=ask_expire_interval(1,opt.def_sig_expire);
else
duration=parse_expire_string(opt.def_sig_expire);
}
/* Note: In the old non-agent version the following call used to
unprotect the secret key. This is now done on demand by the agent. */
if( (rc = build_sk_list (locusr, &sk_list, PUBKEY_USAGE_SIG )) )
goto leave;
if(PGP2 && !only_old_style(sk_list))
{
log_info(_("you can only detach-sign with PGP 2.x style keys "
"while in --pgp2 mode\n"));
compliance_failure();
}
if (encryptflag
&& (rc=build_pk_list (ctrl, remusr, &pk_list, PUBKEY_USAGE_ENC)))
goto leave;
/* prepare iobufs */
if( multifile ) /* have list of filenames */
inp = NULL; /* we do it later */
else {
inp = iobuf_open(fname);
if (inp && is_secured_file (iobuf_get_fd (inp)))
{
iobuf_close (inp);
inp = NULL;
gpg_err_set_errno (EPERM);
}
if( !inp )
{
rc = gpg_error_from_syserror ();
log_error (_("can't open `%s': %s\n"), fname? fname: "[stdin]",
strerror(errno) );
goto leave;
}
handle_progress (pfx, inp, fname);
}
if( outfile ) {
if (is_secured_filename ( outfile )) {
out = NULL;
gpg_err_set_errno (EPERM);
}
else
out = iobuf_create( outfile );
if( !out )
{
rc = gpg_error_from_syserror ();
log_error(_("can't create `%s': %s\n"), outfile, strerror(errno) );
goto leave;
}
else if( opt.verbose )
log_info(_("writing to `%s'\n"), outfile );
}
else if( (rc = open_outfile (GNUPG_INVALID_FD, fname,
opt.armor? 1: detached? 2:0, &out )))
goto leave;
/* prepare to calculate the MD over the input */
if( opt.textmode && !outfile && !multifile )
{
memset( &tfx, 0, sizeof tfx);
iobuf_push_filter( inp, text_filter, &tfx );
}
if ( gcry_md_open (&mfx.md, 0, 0) )
BUG ();
if (DBG_HASHING)
gcry_md_start_debug (mfx.md, "sign");
/* If we're encrypting and signing, it is reasonable to pick the
hash algorithm to use out of the recipient key prefs. This is
best effort only, as in a DSA2 and smartcard world there are
cases where we cannot please everyone with a single hash (DSA2
wants >160 and smartcards want =160). In the future this could
be more complex with different hashes for each sk, but the
current design requires a single hash for all SKs. */
if(pk_list)
{
if(opt.def_digest_algo)
{
if(!opt.expert &&
select_algo_from_prefs(pk_list,PREFTYPE_HASH,
opt.def_digest_algo,
NULL)!=opt.def_digest_algo)
log_info(_("WARNING: forcing digest algorithm %s (%d)"
" violates recipient preferences\n"),
gcry_md_algo_name (opt.def_digest_algo),
opt.def_digest_algo );
}
else
{
int algo, smartcard=0;
union pref_hint hint;
hint.digest_length = 0;
/* Of course, if the recipient asks for something
unreasonable (like the wrong hash for a DSA key) then
don't do it. Check all sk's - if any are DSA or live
on a smartcard, then the hash has restrictions and we
may not be able to give the recipient what they want.
For DSA, pass a hint for the largest q we have. Note
that this means that a q>160 key will override a q=160
key and force the use of truncation for the q=160 key.
The alternative would be to ignore the recipient prefs
completely and get a different hash for each DSA key in
hash_for(). The override behavior here is more or less
reasonable as it is under the control of the user which
keys they sign with for a given message and the fact
that the message with multiple signatures won't be
usable on an implementation that doesn't understand
DSA2 anyway. */
for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next )
{
- if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_DSA)
+ if (sk_rover->pk->pubkey_algo == PUBKEY_ALGO_DSA || sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA )
{
- int temp_hashlen = gcry_mpi_get_nbits
- (sk_rover->pk->pkey[1])+7/8;
+ int temp_hashlen = gcry_mpi_get_nbits(sk_rover->pk->pkey[1]);
+
+ if( sk_rover->pk->pubkey_algo == PUBKEY_ALGO_ECDSA )
+ temp_hashlen = ecdsa_qbits_from_Q( temp_hashlen );
+ temp_hashlen = (temp_hashlen+7)/8;
/* Pick a hash that is large enough for our
largest q */
if (hint.digest_lengthpk->is_protected */
/* && sk_rover->pk->protect.s2k.mode == 1002) */
/* smartcard = 1; */
}
/* Current smartcards only do 160-bit hashes. If we have
to have a >160-bit hash, then we can't use the
recipient prefs as we'd need both =160 and >160 at the
same time and recipient prefs currently require a
single hash for all signatures. All this may well have
to change as the cards add algorithms. */
if (!smartcard || (smartcard && hint.digest_length==20))
if ( (algo=
select_algo_from_prefs(pk_list,PREFTYPE_HASH,-1,&hint)) > 0)
recipient_digest_algo=algo;
}
}
for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
gcry_md_enable (mfx.md, hash_for (sk_rover->pk));
if( !multifile )
iobuf_push_filter( inp, md_filter, &mfx );
if( detached && !encryptflag && !RFC1991 )
afx->what = 2;
if( opt.armor && !outfile )
push_armor_filter (afx, out);
if( encryptflag ) {
efx.pk_list = pk_list;
/* fixme: set efx.cfx.datalen if known */
iobuf_push_filter( out, encrypt_filter, &efx );
}
if( opt.compress_algo && !outfile && ( !detached || opt.compress_sigs) )
{
int compr_algo=opt.compress_algo;
/* If not forced by user */
if(compr_algo==-1)
{
/* If we're not encrypting, then select_algo_from_prefs
will fail and we'll end up with the default. If we are
encrypting, select_algo_from_prefs cannot fail since
there is an assumed preference for uncompressed data.
Still, if it did fail, we'll also end up with the
default. */
if((compr_algo=
select_algo_from_prefs(pk_list,PREFTYPE_ZIP,-1,NULL))==-1)
compr_algo=default_compress_algo();
}
else if(!opt.expert && pk_list
&& select_algo_from_prefs(pk_list,PREFTYPE_ZIP,
compr_algo,NULL)!=compr_algo)
log_info(_("WARNING: forcing compression algorithm %s (%d)"
" violates recipient preferences\n"),
compress_algo_to_string(compr_algo),compr_algo);
/* algo 0 means no compression */
if( compr_algo )
push_compress_filter(out,&zfx,compr_algo);
}
/* Write the one-pass signature packets if needed */
if (!detached && !RFC1991) {
rc = write_onepass_sig_packets (sk_list, out,
opt.textmode && !outfile ? 0x01:0x00);
if (rc)
goto leave;
}
write_status_begin_signing (mfx.md);
/* Setup the inner packet. */
if( detached ) {
if( multifile ) {
strlist_t sl;
if( opt.verbose )
log_info(_("signing:") );
/* must walk reverse trough this list */
for( sl = strlist_last(filenames); sl;
sl = strlist_prev( filenames, sl ) ) {
inp = iobuf_open(sl->d);
if (inp && is_secured_file (iobuf_get_fd (inp)))
{
iobuf_close (inp);
inp = NULL;
gpg_err_set_errno (EPERM);
}
if( !inp )
{
rc = gpg_error_from_syserror ();
log_error(_("can't open `%s': %s\n"),
sl->d,strerror(errno));
goto leave;
}
handle_progress (pfx, inp, sl->d);
if( opt.verbose )
fprintf(stderr, " `%s'", sl->d );
if(opt.textmode)
{
memset( &tfx, 0, sizeof tfx);
iobuf_push_filter( inp, text_filter, &tfx );
}
iobuf_push_filter( inp, md_filter, &mfx );
while( iobuf_get(inp) != -1 )
;
iobuf_close(inp); inp = NULL;
}
if( opt.verbose )
putc( '\n', stderr );
}
else {
/* read, so that the filter can calculate the digest */
while( iobuf_get(inp) != -1 )
;
}
}
else {
rc = write_plaintext_packet (out, inp, fname,
opt.textmode && !outfile ? 't':'b');
}
/* catch errors from above */
if (rc)
goto leave;
/* write the signatures */
rc = write_signature_packets (sk_list, out, mfx.md,
opt.textmode && !outfile? 0x01 : 0x00,
0, duration, detached ? 'D':'S', NULL);
if( rc )
goto leave;
leave:
if( rc )
iobuf_cancel(out);
else {
iobuf_close(out);
if (encryptflag)
write_status( STATUS_END_ENCRYPTION );
}
iobuf_close(inp);
gcry_md_close ( mfx.md );
release_sk_list( sk_list );
release_pk_list( pk_list );
recipient_digest_algo=0;
release_progress_context (pfx);
release_armor_context (afx);
return rc;
}
/****************
* make a clear signature. note that opt.armor is not needed
*/
int
clearsign_file( const char *fname, strlist_t locusr, const char *outfile )
{
armor_filter_context_t *afx;
progress_filter_context_t *pfx;
gcry_md_hd_t textmd = NULL;
IOBUF inp = NULL, out = NULL;
PACKET pkt;
int rc = 0;
SK_LIST sk_list = NULL;
SK_LIST sk_rover = NULL;
int old_style = RFC1991;
int only_md5 = 0;
u32 duration=0;
pfx = new_progress_context ();
afx = new_armor_context ();
init_packet( &pkt );
if(!opt.force_v3_sigs && !RFC1991)
{
if(opt.ask_sig_expire && !opt.batch)
duration=ask_expire_interval(1,opt.def_sig_expire);
else
duration=parse_expire_string(opt.def_sig_expire);
}
/* Note: In the old non-agent version the following call used to
unprotect the secret key. This is now done on demand by the agent. */
if( (rc=build_sk_list( locusr, &sk_list, PUBKEY_USAGE_SIG )) )
goto leave;
if( !old_style && !duration )
old_style = only_old_style( sk_list );
if(PGP2 && !only_old_style(sk_list))
{
log_info(_("you can only clearsign with PGP 2.x style keys "
"while in --pgp2 mode\n"));
compliance_failure();
}
/* prepare iobufs */
inp = iobuf_open(fname);
if (inp && is_secured_file (iobuf_get_fd (inp)))
{
iobuf_close (inp);
inp = NULL;
gpg_err_set_errno (EPERM);
}
if( !inp ) {
rc = gpg_error_from_syserror ();
log_error (_("can't open `%s': %s\n"),
fname? fname: "[stdin]", strerror(errno) );
goto leave;
}
handle_progress (pfx, inp, fname);
if( outfile ) {
if (is_secured_filename (outfile) ) {
outfile = NULL;
gpg_err_set_errno (EPERM);
}
else
out = iobuf_create( outfile );
if( !out )
{
rc = gpg_error_from_syserror ();
log_error(_("can't create `%s': %s\n"), outfile, strerror(errno) );
goto leave;
}
else if( opt.verbose )
log_info(_("writing to `%s'\n"), outfile );
}
else if( (rc = open_outfile (GNUPG_INVALID_FD, fname, 1, &out )) )
goto leave;
iobuf_writestr(out, "-----BEGIN PGP SIGNED MESSAGE-----" LF );
for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
{
if (hash_for (sk_rover->pk) == DIGEST_ALGO_MD5)
only_md5 = 1;
else
{
only_md5 = 0;
break;
}
}
if( !(old_style && only_md5) ) {
const char *s;
int any = 0;
byte hashs_seen[256];
memset( hashs_seen, 0, sizeof hashs_seen );
iobuf_writestr(out, "Hash: " );
for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
int i = hash_for (sk_rover->pk);
if( !hashs_seen[ i & 0xff ] ) {
s = gcry_md_algo_name ( i );
if( s ) {
hashs_seen[ i & 0xff ] = 1;
if( any )
iobuf_put(out, ',' );
iobuf_writestr(out, s );
any = 1;
}
}
}
assert(any);
iobuf_writestr(out, LF );
}
if( opt.not_dash_escaped )
iobuf_writestr( out,
"NotDashEscaped: You need GnuPG to verify this message" LF );
iobuf_writestr(out, LF );
if ( gcry_md_open (&textmd, 0, 0) )
BUG ();
for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
gcry_md_enable (textmd, hash_for(sk_rover->pk));
if ( DBG_HASHING )
gcry_md_start_debug ( textmd, "clearsign" );
copy_clearsig_text( out, inp, textmd, !opt.not_dash_escaped,
opt.escape_from, (old_style && only_md5) );
/* fixme: check for read errors */
/* now write the armor */
afx->what = 2;
push_armor_filter (afx, out);
/* Write the signatures. */
rc = write_signature_packets (sk_list, out, textmd, 0x01, 0, duration, 'C',
NULL);
if( rc )
goto leave;
leave:
if( rc )
iobuf_cancel(out);
else
iobuf_close(out);
iobuf_close(inp);
gcry_md_close ( textmd );
release_sk_list( sk_list );
release_progress_context (pfx);
release_armor_context (afx);
return rc;
}
/*
* Sign and conventionally encrypt the given file.
* FIXME: Far too much code is duplicated - revamp the whole file.
*/
int
sign_symencrypt_file (const char *fname, strlist_t locusr)
{
armor_filter_context_t *afx;
progress_filter_context_t *pfx;
compress_filter_context_t zfx;
md_filter_context_t mfx;
text_filter_context_t tfx;
cipher_filter_context_t cfx;
IOBUF inp = NULL, out = NULL;
PACKET pkt;
STRING2KEY *s2k = NULL;
int rc = 0;
SK_LIST sk_list = NULL;
SK_LIST sk_rover = NULL;
int algo;
u32 duration=0;
int canceled;
pfx = new_progress_context ();
afx = new_armor_context ();
memset( &zfx, 0, sizeof zfx);
memset( &mfx, 0, sizeof mfx);
memset( &tfx, 0, sizeof tfx);
memset( &cfx, 0, sizeof cfx);
init_packet( &pkt );
if(!opt.force_v3_sigs && !RFC1991)
{
if(opt.ask_sig_expire && !opt.batch)
duration=ask_expire_interval(1,opt.def_sig_expire);
else
duration=parse_expire_string(opt.def_sig_expire);
}
/* Note: In the old non-agent version the following call used to
unprotect the secret key. This is now done on demand by the agent. */
rc = build_sk_list (locusr, &sk_list, PUBKEY_USAGE_SIG);
if (rc)
goto leave;
/* prepare iobufs */
inp = iobuf_open(fname);
if (inp && is_secured_file (iobuf_get_fd (inp)))
{
iobuf_close (inp);
inp = NULL;
gpg_err_set_errno (EPERM);
}
if( !inp ) {
rc = gpg_error_from_syserror ();
log_error (_("can't open `%s': %s\n"),
fname? fname: "[stdin]", strerror(errno) );
goto leave;
}
handle_progress (pfx, inp, fname);
/* prepare key */
s2k = xmalloc_clear( sizeof *s2k );
s2k->mode = RFC1991? 0:opt.s2k_mode;
s2k->hash_algo = S2K_DIGEST_ALGO;
algo = default_cipher_algo();
if (!opt.quiet || !opt.batch)
log_info (_("%s encryption will be used\n"),
openpgp_cipher_algo_name (algo) );
cfx.dek = passphrase_to_dek( NULL, 0, algo, s2k, 2, NULL, &canceled);
if (!cfx.dek || !cfx.dek->keylen) {
rc = gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_BAD_PASSPHRASE);
log_error(_("error creating passphrase: %s\n"), gpg_strerror (rc) );
goto leave;
}
/* We have no way to tell if the recipient can handle messages
with an MDC, so this defaults to no. Perhaps in a few years,
this can be defaulted to yes. Note that like regular
encrypting, --force-mdc overrides --disable-mdc. */
if(opt.force_mdc)
cfx.dek->use_mdc=1;
/* now create the outfile */
rc = open_outfile (GNUPG_INVALID_FD, fname, opt.armor? 1:0, &out);
if (rc)
goto leave;
/* prepare to calculate the MD over the input */
if (opt.textmode)
iobuf_push_filter (inp, text_filter, &tfx);
if ( gcry_md_open (&mfx.md, 0, 0) )
BUG ();
if ( DBG_HASHING )
gcry_md_start_debug (mfx.md, "symc-sign");
for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
gcry_md_enable (mfx.md, hash_for (sk_rover->pk));
iobuf_push_filter (inp, md_filter, &mfx);
/* Push armor output filter */
if (opt.armor)
push_armor_filter (afx, out);
/* Write the symmetric key packet */
/*(current filters: armor)*/
if (!RFC1991) {
PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc );
enc->version = 4;
enc->cipher_algo = cfx.dek->algo;
enc->s2k = *s2k;
pkt.pkttype = PKT_SYMKEY_ENC;
pkt.pkt.symkey_enc = enc;
if( (rc = build_packet( out, &pkt )) )
log_error("build symkey packet failed: %s\n", g10_errstr(rc) );
xfree(enc);
}
/* Push the encryption filter */
iobuf_push_filter( out, cipher_filter, &cfx );
/* Push the compress filter */
if (default_compress_algo())
push_compress_filter(out,&zfx,default_compress_algo());
/* Write the one-pass signature packets */
/*(current filters: zip - encrypt - armor)*/
if (!RFC1991) {
rc = write_onepass_sig_packets (sk_list, out,
opt.textmode? 0x01:0x00);
if (rc)
goto leave;
}
write_status_begin_signing (mfx.md);
/* Pipe data through all filters; i.e. write the signed stuff */
/*(current filters: zip - encrypt - armor)*/
rc = write_plaintext_packet (out, inp, fname, opt.textmode ? 't':'b');
if (rc)
goto leave;
/* Write the signatures */
/*(current filters: zip - encrypt - armor)*/
rc = write_signature_packets (sk_list, out, mfx.md,
opt.textmode? 0x01 : 0x00,
0, duration, 'S', NULL);
if( rc )
goto leave;
leave:
if( rc )
iobuf_cancel(out);
else {
iobuf_close(out);
write_status( STATUS_END_ENCRYPTION );
}
iobuf_close(inp);
release_sk_list( sk_list );
gcry_md_close( mfx.md );
xfree(cfx.dek);
xfree(s2k);
release_progress_context (pfx);
release_armor_context (afx);
return rc;
}
/****************
* Create a signature packet for the given public key certificate and
* the user id and return it in ret_sig. User signature class SIGCLASS
* user-id is not used (and may be NULL if sigclass is 0x20) If
* DIGEST_ALGO is 0 the function selects an appropriate one.
* SIGVERSION gives the minimal required signature packet version;
* this is needed so that special properties like local sign are not
* applied (actually: dropped) when a v3 key is used. TIMESTAMP is
* the timestamp to use for the signature. 0 means "now" */
int
make_keysig_packet( PKT_signature **ret_sig, PKT_public_key *pk,
PKT_user_id *uid, PKT_public_key *subpk,
PKT_public_key *pksk,
int sigclass, int digest_algo,
int sigversion, u32 timestamp, u32 duration,
int (*mksubpkt)(PKT_signature *, void *), void *opaque,
const char *cache_nonce)
{
PKT_signature *sig;
int rc=0;
gcry_md_hd_t md;
assert( (sigclass >= 0x10 && sigclass <= 0x13) || sigclass == 0x1F
|| sigclass == 0x20 || sigclass == 0x18 || sigclass == 0x19
|| sigclass == 0x30 || sigclass == 0x28 );
if (opt.force_v4_certs)
sigversion = 4;
if (sigversion < pksk->version)
sigversion = pksk->version;
/* If you are making a signature on a v4 key using your v3 key, it
doesn't make sense to generate a v3 sig. After all, no v3-only
PGP implementation could understand the v4 key in the first
place. Note that this implies that a signature on an attribute
uid is usually going to be v4 as well, since they are not
generally found on v3 keys. */
if (sigversion < pk->version)
sigversion = pk->version;
if( !digest_algo )
{
/* Basically, this means use SHA1 always unless it's a v3 RSA
key making a v3 cert (use MD5), or the user specified
something (use whatever they said), or it's DSA (use the
best match). They still can't pick an inappropriate hash
for DSA or the signature will fail. Note that this still
allows the caller of make_keysig_packet to override the
user setting if it must. */
if(opt.cert_digest_algo)
digest_algo=opt.cert_digest_algo;
else if(pksk->pubkey_algo==PUBKEY_ALGO_RSA
&& pk->version<4 && sigversion<4)
digest_algo = DIGEST_ALGO_MD5;
else if(pksk->pubkey_algo==PUBKEY_ALGO_DSA)
- digest_algo = match_dsa_hash (gcry_mpi_get_nbits (pksk->pkey[1])/8);
+ digest_algo = match_dsa_hash (gcry_mpi_get_nbits (pksk->pkey[1])/8 );
+ else if(pksk->pubkey_algo==PUBKEY_ALGO_ECDSA )
+ digest_algo = match_dsa_hash (ecdsa_qbits_from_Q( gcry_mpi_get_nbits (pksk->pkey[1]) ) / 8);
else
digest_algo = DIGEST_ALGO_SHA1;
}
if ( gcry_md_open (&md, digest_algo, 0 ) )
BUG ();
/* Hash the public key certificate. */
hash_public_key( md, pk );
if( sigclass == 0x18 || sigclass == 0x19 || sigclass == 0x28 )
{
/* hash the subkey binding/backsig/revocation */
hash_public_key( md, subpk );
}
else if( sigclass != 0x1F && sigclass != 0x20 )
{
/* hash the user id */
hash_uid (md, sigversion, uid);
}
/* and make the signature packet */
sig = xmalloc_clear( sizeof *sig );
sig->version = sigversion;
sig->flags.exportable=1;
sig->flags.revocable=1;
keyid_from_pk (pksk, sig->keyid);
sig->pubkey_algo = pksk->pubkey_algo;
sig->digest_algo = digest_algo;
if(timestamp)
sig->timestamp=timestamp;
else
sig->timestamp=make_timestamp();
if(duration)
sig->expiredate=sig->timestamp+duration;
sig->sig_class = sigclass;
if( sig->version >= 4 )
{
build_sig_subpkt_from_sig( sig );
mk_notation_policy_etc (sig, pk, pksk);
}
/* Crucial that the call to mksubpkt comes LAST before the calls
to finalize the sig as that makes it possible for the mksubpkt
function to get a reliable pointer to the subpacket area. */
if( sig->version >= 4 && mksubpkt )
rc = (*mksubpkt)( sig, opaque );
if( !rc ) {
hash_sigversion_to_magic (md, sig);
gcry_md_final (md);
rc = complete_sig (sig, pksk, md, cache_nonce);
}
gcry_md_close (md);
if( rc )
free_seckey_enc( sig );
else
*ret_sig = sig;
return rc;
}
/****************
* Create a new signature packet based on an existing one.
* Only user ID signatures are supported for now.
* PK is the public key to work on.
* PKSK is the key used to make the signature.
*
* TODO: Merge this with make_keysig_packet.
*/
int
update_keysig_packet( PKT_signature **ret_sig,
PKT_signature *orig_sig,
PKT_public_key *pk,
PKT_user_id *uid,
PKT_public_key *subpk,
PKT_public_key *pksk,
int (*mksubpkt)(PKT_signature *, void *),
void *opaque)
{
PKT_signature *sig;
int rc=0;
gcry_md_hd_t md;
if ((!orig_sig || !pk || !pksk)
|| (orig_sig->sig_class >= 0x10 && orig_sig->sig_class <= 0x13 && !uid)
|| (orig_sig->sig_class == 0x18 && !subpk))
return G10ERR_GENERAL;
if ( gcry_md_open (&md, orig_sig->digest_algo, 0 ) )
BUG ();
/* Hash the public key certificate and the user id. */
hash_public_key( md, pk );
if( orig_sig->sig_class == 0x18 )
hash_public_key( md, subpk );
else
hash_uid (md, orig_sig->version, uid);
/* create a new signature packet */
sig = copy_signature (NULL, orig_sig);
/* We need to create a new timestamp so that new sig expiration
calculations are done correctly... */
sig->timestamp=make_timestamp();
/* ... but we won't make a timestamp earlier than the existing
one. */
while(sig->timestamp<=orig_sig->timestamp)
{
gnupg_sleep (1);
sig->timestamp=make_timestamp();
}
/* Note that already expired sigs will remain expired (with a
duration of 1) since build-packet.c:build_sig_subpkt_from_sig
detects this case. */
if( sig->version >= 4 )
{
/* Put the updated timestamp into the sig. Note that this
will automagically lower any sig expiration dates to
correctly correspond to the differences in the timestamps
(i.e. the duration will shrink). */
build_sig_subpkt_from_sig( sig );
if (mksubpkt)
rc = (*mksubpkt)(sig, opaque);
}
if (!rc) {
hash_sigversion_to_magic (md, sig);
gcry_md_final (md);
rc = complete_sig (sig, pksk, md, NULL);
}
gcry_md_close (md);
if( rc )
free_seckey_enc (sig);
else
*ret_sig = sig;
return rc;
}
diff --git a/g10/pkglue.h b/g10/verify-stubs.c
similarity index 56%
copy from g10/pkglue.h
copy to g10/verify-stubs.c
index f97def153..d1f0aa105 100644
--- a/g10/pkglue.h
+++ b/g10/verify-stubs.c
@@ -1,32 +1,30 @@
-/* pkglue.h - public key operations definitions
- * Copyright (C) 2003 Free Software Foundation, Inc.
+/* To satisfy the linker for the gpgv target
+ * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2005, 2006,
+ * 2007 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
* 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
* along with this program; if not, see .
*/
-#ifndef GNUPG_G10_PKGLUE_H
-#define GNUPG_G10_PKGLUE_H
+#include
-int pk_verify (int algo, gcry_mpi_t hash, gcry_mpi_t *data,
- gcry_mpi_t *pkey);
-int pk_encrypt (int algo, gcry_mpi_t *resarr, gcry_mpi_t data,
- gcry_mpi_t *pkey);
-int pk_decrypt (int algo, gcry_mpi_t *result, gcry_mpi_t *data,
- gcry_mpi_t *skey);
-int pk_check_secret_key (int algo, gcry_mpi_t *skey);
+#include
+#include "gpg.h"
+#include "main.h"
-
-#endif /*GNUPG_G10_PKGLUE_H*/
+int
+pk_ecc_keypair_gen( PKT_public_key **pk_out, int algo, int keygen_flags, char **cache_nonce_addr, unsigned nbits) {
+ return GPG_ERR_NOT_IMPLEMENTED;
+}
diff --git a/g13/utils.c b/g13/utils.c
index ef0c572a6..1ea7f3275 100644
--- a/g13/utils.c
+++ b/g13/utils.c
@@ -1,180 +1,182 @@
/* utils.c - Utility functions
* Copyright (C) 2009 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
* 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
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include
#include "g13.h"
#include "utils.h"
/* Definition of the tuple descriptor object. */
struct tupledesc_s
{
unsigned char *data; /* The tuple data. */
size_t datalen; /* The length of the data. */
size_t pos; /* The current position as used by next_tuple. */
int refcount; /* Number of references hold. */
};
/* Append the TAG and the VALUE to the MEMBUF. There is no error
checking here; this is instead done while getting the value back
from the membuf. */
void
append_tuple (membuf_t *membuf, int tag, const void *value, size_t length)
{
unsigned char buf[2];
assert (tag >= 0 && tag <= 0xffff);
assert (length <= 0xffff);
buf[0] = tag >> 8;
buf[1] = tag;
put_membuf (membuf, buf, 2);
buf[0] = length >> 8;
buf[1] = length;
put_membuf (membuf, buf, 2);
if (length)
put_membuf (membuf, value, length);
}
/* Create a tuple object by moving the ownership of (DATA,DATALEN) to
a new object. Returns 0 on success and stores the new object at
R_TUPLEHD. The return object must be released using
destroy_tuples(). */
gpg_error_t
create_tupledesc (tupledesc_t *r_desc, void *data, size_t datalen)
{
if (datalen < 5 || memcmp (data, "\x00\x00\x00\x01\x01", 5))
return gpg_error (GPG_ERR_NOT_SUPPORTED);
*r_desc = xtrymalloc (sizeof **r_desc);
if (!*r_desc)
return gpg_error_from_syserror ();
(*r_desc)->data = data;
(*r_desc)->datalen = datalen;
(*r_desc)->pos = 0;
(*r_desc)->refcount++;
return 0;
}
/* Unref a tuple descriptor and if the refcount is down to 0 release
its allocated storage. */
void
destroy_tupledesc (tupledesc_t tupledesc)
{
if (!tupledesc)
return;
if (!--tupledesc->refcount)
{
xfree (tupledesc->data);
xfree (tupledesc);
}
}
tupledesc_t
ref_tupledesc (tupledesc_t tupledesc)
{
if (tupledesc)
tupledesc->refcount++;
return tupledesc;
}
/* Find the first tuple with tag TAG. On success return a pointer to
its value and store the length of the value at R_LENGTH. If no
tuple was return NULL. For future use by next_tupe, the last
position is stored in the descriptor. */
const void *
find_tuple (tupledesc_t tupledesc, unsigned int tag, size_t *r_length)
{
const unsigned char *s;
const unsigned char *s_end; /* Points right behind the data. */
unsigned int t;
size_t n;
s = tupledesc->data;
if (!s)
return NULL;
s_end = s + tupledesc->datalen;
while (s < s_end)
{
if (s+3 >= s_end || s + 3 < s)
break;
t = s[0] << 8;
t |= s[1];
n = s[2] << 8;
n |= s[3];
s += 4;
if (s + n > s_end || s + n < s)
break;
if (t == tag)
{
tupledesc->pos = (s + n) - tupledesc->data;
*r_length = n;
return s;
}
s += n;
}
return NULL;
}
const void *
next_tuple (tupledesc_t tupledesc, unsigned int *r_tag, size_t *r_length)
{
const unsigned char *s;
const unsigned char *s_end; /* Points right behind the data. */
unsigned int t;
size_t n;
s = tupledesc->data;
if (!s)
return NULL;
s_end = s + tupledesc->datalen;
s += tupledesc->pos;
if (s < s_end
&& !(s+3 >= s_end || s + 3 < s))
{
t = s[0] << 8;
t |= s[1];
n = s[2] << 8;
n |= s[3];
s += 4;
if (!(s + n > s_end || s + n < s))
{
tupledesc->pos = (s + n) - tupledesc->data;
*r_tag = t;
*r_length = n;
return s;
}
}
return NULL;
-}
+}
+
+
diff --git a/g13/utils.h b/g13/utils.h
index ef718d60d..528ce16ce 100644
--- a/g13/utils.h
+++ b/g13/utils.h
@@ -1,45 +1,45 @@
/* utils.h - Defs for utility fucthe dispatcher to the various backends.ntions
* Copyright (C) 2009 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
* 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
* along with this program; if not, see .
*/
#ifndef G13_UTILS_H
#define G13_UTILS_H
#include "../common/membuf.h"
/* Append a new tuple to a memory buffer. */
void append_tuple (membuf_t *membuf,
int tag, const void *value, size_t length);
/* The tuple descriptor object. */
struct tupledesc_s;
typedef struct tupledesc_s *tupledesc_t;
gpg_error_t create_tupledesc (tupledesc_t *r_tupledesc,
void *data, size_t datalen);
void destroy_tupledesc (tupledesc_t tupledesc);
tupledesc_t ref_tupledesc (tupledesc_t tupledesc);
const void *find_tuple (tupledesc_t tupledesc,
unsigned int tag, size_t *r_length);
const void *next_tuple (tupledesc_t tupledesc,
unsigned int *r_tag, size_t *r_length);
-
+char *mpi2hex( gcry_mpi_t m );
#endif /*G13_UTILS_H*/
diff --git a/include/cipher.h b/include/cipher.h
index 8e198283d..65cd59e76 100644
--- a/include/cipher.h
+++ b/include/cipher.h
@@ -1,108 +1,110 @@
/* cipher.h - Definitions for OpenPGP
* Copyright (C) 1998, 1999, 2000, 2001, 2006,
* 2007 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
* 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
* along with this program; if not, see .
*/
#ifndef G10_CIPHER_H
#define G10_CIPHER_H
#include
/* Macros for compatibility with older libgcrypt versions. */
#ifndef GCRY_PK_USAGE_CERT
# define GCRY_PK_USAGE_CERT 4
# define GCRY_PK_USAGE_AUTH 8
# define GCRY_PK_USAGE_UNKN 128
#endif
/* Constants for OpenPGP. */
#define CIPHER_ALGO_NONE /* 0 */ GCRY_CIPHER_NONE
#define CIPHER_ALGO_IDEA /* 1 */ GCRY_CIPHER_IDEA
#define CIPHER_ALGO_3DES /* 2 */ GCRY_CIPHER_3DES
#define CIPHER_ALGO_CAST5 /* 3 */ GCRY_CIPHER_CAST5
#define CIPHER_ALGO_BLOWFISH /* 4 */ GCRY_CIPHER_BLOWFISH /* 128 bit */
/* 5 & 6 are reserved */
#define CIPHER_ALGO_AES /* 7 */ GCRY_CIPHER_AES
#define CIPHER_ALGO_AES192 /* 8 */ GCRY_CIPHER_AES192
#define CIPHER_ALGO_AES256 /* 9 */ GCRY_CIPHER_AES256
#define CIPHER_ALGO_RIJNDAEL CIPHER_ALGO_AES
#define CIPHER_ALGO_RIJNDAEL192 CIPHER_ALGO_AES192
#define CIPHER_ALGO_RIJNDAEL256 CIPHER_ALGO_AES256
#define CIPHER_ALGO_TWOFISH /* 10 */ GCRY_CIPHER_TWOFISH /* 256 bit */
/* Note: Camellia ids don't match those used by libgcrypt. */
#define CIPHER_ALGO_CAMELLIA128 11
#define CIPHER_ALGO_CAMELLIA192 12
#define CIPHER_ALGO_CAMELLIA256 13
#define CIPHER_ALGO_DUMMY 110 /* No encryption at all. */
#define PUBKEY_ALGO_RSA /* 1 */ GCRY_PK_RSA
#define PUBKEY_ALGO_RSA_E /* 2 */ GCRY_PK_RSA_E /* RSA encrypt only. */
#define PUBKEY_ALGO_RSA_S /* 3 */ GCRY_PK_RSA_S /* RSA sign only. */
#define PUBKEY_ALGO_ELGAMAL_E /* 16 */ GCRY_PK_ELG_E /* Elgamal encr only */
#define PUBKEY_ALGO_DSA /* 17 */ GCRY_PK_DSA
+#define PUBKEY_ALGO_ECDH 18 /* corresponds to GCRY_PK_ECDH ECC DH; encrypt only */
+#define PUBKEY_ALGO_ECDSA 19 /* corresponds to GCRY_PK_ECDSA ECC DSA; sign only */
#define PUBKEY_ALGO_ELGAMAL /* 20 */ GCRY_PK_ELG /* Elgamal encr+sign */
#define PUBKEY_USAGE_SIG GCRY_PK_USAGE_SIGN /* Good for signatures. */
#define PUBKEY_USAGE_ENC GCRY_PK_USAGE_ENCR /* Good for encryption. */
#define PUBKEY_USAGE_CERT GCRY_PK_USAGE_CERT /* Also good to certify keys. */
#define PUBKEY_USAGE_AUTH GCRY_PK_USAGE_AUTH /* Good for authentication. */
#define PUBKEY_USAGE_UNKNOWN GCRY_PK_USAGE_UNKN /* Unknown usage flag. */
#define DIGEST_ALGO_MD5 /* 1 */ GCRY_MD_MD5
#define DIGEST_ALGO_SHA1 /* 2 */ GCRY_MD_SHA1
#define DIGEST_ALGO_RMD160 /* 3 */ GCRY_MD_RMD160
/* 4, 5, 6, and 7 are reserved */
#define DIGEST_ALGO_SHA256 /* 8 */ GCRY_MD_SHA256
#define DIGEST_ALGO_SHA384 /* 9 */ GCRY_MD_SHA384
#define DIGEST_ALGO_SHA512 /* 10 */ GCRY_MD_SHA512
/* SHA224 is only available in libgcrypt 1.4.0; thus we
can't use the GCRY macro here. */
#define DIGEST_ALGO_SHA224 /* 11 */ 11 /* GCRY_MD_SHA224 */
#define COMPRESS_ALGO_NONE 0
#define COMPRESS_ALGO_ZIP 1
#define COMPRESS_ALGO_ZLIB 2
#define COMPRESS_ALGO_BZIP2 3
#define is_RSA(a) ((a)==PUBKEY_ALGO_RSA || (a)==PUBKEY_ALGO_RSA_E \
|| (a)==PUBKEY_ALGO_RSA_S )
#define is_ELGAMAL(a) ((a)==PUBKEY_ALGO_ELGAMAL_E)
#define is_DSA(a) ((a)==PUBKEY_ALGO_DSA)
/* The data encryption key object. */
typedef struct
{
int algo;
int keylen;
int algo_info_printed;
int use_mdc;
int symmetric;
byte key[32]; /* This is the largest used keylen (256 bit). */
char s2k_cacheid[1+16+1];
} DEK;
/* Constants to allocate static MPI arrays. */
#define PUBKEY_MAX_NPKEY 4
#define PUBKEY_MAX_NSKEY 6
#define PUBKEY_MAX_NSIG 2
#define PUBKEY_MAX_NENC 2
#endif /*G10_CIPHER_H*/
diff --git a/kbx/keybox-openpgp.c b/kbx/keybox-openpgp.c
index 0968cf8b3..6c9410e05 100644
--- a/kbx/keybox-openpgp.c
+++ b/kbx/keybox-openpgp.c
@@ -1,515 +1,520 @@
/* keybox-openpgp.c - OpenPGP key parsing
* Copyright (C) 2001, 2003 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
* 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
* along with this program; if not, see .
*/
/* This is a simple OpenPGP parser suitable for all OpenPGP key
material. It just provides the functionality required to build and
parse an KBX OpenPGP key blob. Thus it is not a complete parser.
However it is self-contained and optimized for fast in-memory
parsing. Note that we don't support old ElGamal v3 keys
anymore. */
#include
#include
#include
#include
#include
#include
#include "keybox-defs.h"
#include
enum packet_types
{
PKT_NONE =0,
PKT_PUBKEY_ENC =1, /* public key encrypted packet */
PKT_SIGNATURE =2, /* secret key encrypted packet */
PKT_SYMKEY_ENC =3, /* session key packet (OpenPGP)*/
PKT_ONEPASS_SIG =4, /* one pass sig packet (OpenPGP)*/
PKT_SECRET_KEY =5, /* secret key */
PKT_PUBLIC_KEY =6, /* public key */
PKT_SECRET_SUBKEY =7, /* secret subkey (OpenPGP) */
PKT_COMPRESSED =8, /* compressed data packet */
PKT_ENCRYPTED =9, /* conventional encrypted data */
PKT_MARKER =10, /* marker packet (OpenPGP) */
PKT_PLAINTEXT =11, /* plaintext data with filename and mode */
PKT_RING_TRUST =12, /* keyring trust packet */
PKT_USER_ID =13, /* user id packet */
PKT_PUBLIC_SUBKEY =14, /* public subkey (OpenPGP) */
PKT_OLD_COMMENT =16, /* comment packet from an OpenPGP draft */
PKT_ATTRIBUTE =17, /* PGP's attribute packet */
PKT_ENCRYPTED_MDC =18, /* integrity protected encrypted data */
PKT_MDC =19, /* manipulation detection code packet */
PKT_COMMENT =61, /* new comment packet (private) */
PKT_GPG_CONTROL =63 /* internal control packet */
};
/* Assume a valid OpenPGP packet at the address pointed to by BUFBTR
which is of amaximum length as stored at BUFLEN. Return the header
information of that packet and advance the pointer stored at BUFPTR
to the next packet; also adjust the length stored at BUFLEN to
match the remaining bytes. If there are no more packets, store NULL
at BUFPTR. Return an non-zero error code on failure or the
follwing data on success:
R_DATAPKT = Pointer to the begin of the packet data.
R_DATALEN = Length of this data. This has already been checked to fit
into the buffer.
R_PKTTYPE = The packet type.
R_NTOTAL = The total number of bytes of this packet
Note that these values are only updated on success.
*/
static gpg_error_t
next_packet (unsigned char const **bufptr, size_t *buflen,
unsigned char const **r_data, size_t *r_datalen, int *r_pkttype,
size_t *r_ntotal)
{
const unsigned char *buf = *bufptr;
size_t len = *buflen;
int c, ctb, pkttype;
unsigned long pktlen;
if (!len)
return gpg_error (GPG_ERR_NO_DATA);
ctb = *buf++; len--;
if ( !(ctb & 0x80) )
return gpg_error (GPG_ERR_INV_PACKET); /* Invalid CTB. */
pktlen = 0;
if ((ctb & 0x40)) /* New style (OpenPGP) CTB. */
{
pkttype = (ctb & 0x3f);
if (!len)
return gpg_error (GPG_ERR_INV_PACKET); /* No 1st length byte. */
c = *buf++; len--;
if (pkttype == PKT_COMPRESSED)
return gpg_error (GPG_ERR_UNEXPECTED); /* ... packet in a keyblock. */
if ( c < 192 )
pktlen = c;
else if ( c < 224 )
{
pktlen = (c - 192) * 256;
if (!len)
return gpg_error (GPG_ERR_INV_PACKET); /* No 2nd length byte. */
c = *buf++; len--;
pktlen += c + 192;
}
else if (c == 255)
{
if (len <4 )
return gpg_error (GPG_ERR_INV_PACKET); /* No length bytes. */
pktlen = (*buf++) << 24;
pktlen |= (*buf++) << 16;
pktlen |= (*buf++) << 8;
pktlen |= (*buf++);
len -= 4;
}
else /* Partial length encoding is not allowed for key packets. */
return gpg_error (GPG_ERR_UNEXPECTED);
}
else /* Old style CTB. */
{
int lenbytes;
pktlen = 0;
pkttype = (ctb>>2)&0xf;
lenbytes = ((ctb&3)==3)? 0 : (1<<(ctb & 3));
if (!lenbytes) /* Not allowed in key packets. */
return gpg_error (GPG_ERR_UNEXPECTED);
if (len < lenbytes)
return gpg_error (GPG_ERR_INV_PACKET); /* Not enough length bytes. */
for (; lenbytes; lenbytes--)
{
pktlen <<= 8;
pktlen |= *buf++; len--;
}
}
/* Do some basic sanity check. */
switch (pkttype)
{
case PKT_SIGNATURE:
case PKT_SECRET_KEY:
case PKT_PUBLIC_KEY:
case PKT_SECRET_SUBKEY:
case PKT_MARKER:
case PKT_RING_TRUST:
case PKT_USER_ID:
case PKT_PUBLIC_SUBKEY:
case PKT_OLD_COMMENT:
case PKT_ATTRIBUTE:
case PKT_COMMENT:
case PKT_GPG_CONTROL:
break; /* Okay these are allowed packets. */
default:
return gpg_error (GPG_ERR_UNEXPECTED);
}
if (pktlen == 0xffffffff)
return gpg_error (GPG_ERR_INV_PACKET);
if (pktlen > len)
return gpg_error (GPG_ERR_INV_PACKET); /* Packet length header too long. */
*r_data = buf;
*r_datalen = pktlen;
*r_pkttype = pkttype;
*r_ntotal = (buf - *bufptr) + pktlen;
*bufptr = buf + pktlen;
*buflen = len - pktlen;
if (!*buflen)
*bufptr = NULL;
return 0;
}
-/* Parse a key packet and store the ionformation in KI. */
+/* Parse a key packet and store the information in KI. */
static gpg_error_t
parse_key (const unsigned char *data, size_t datalen,
struct _keybox_openpgp_key_info *ki)
{
gpg_error_t err;
const unsigned char *data_start = data;
int i, version, algorithm;
size_t n;
unsigned long timestamp, expiredate;
int npkey;
unsigned char hashbuffer[768];
const unsigned char *mpi_n = NULL;
size_t mpi_n_len = 0, mpi_e_len = 0;
gcry_md_hd_t md;
if (datalen < 5)
return gpg_error (GPG_ERR_INV_PACKET);
version = *data++; datalen--;
if (version < 2 || version > 4 )
return gpg_error (GPG_ERR_INV_PACKET); /* Invalid version. */
timestamp = ((data[0]<<24)|(data[1]<<16)|(data[2]<<8)|(data[3]));
data +=4; datalen -=4;
if (version < 4)
{
unsigned short ndays;
if (datalen < 2)
return gpg_error (GPG_ERR_INV_PACKET);
ndays = ((data[0]<<8)|(data[1]));
data +=2; datalen -= 2;
if (ndays)
expiredate = ndays? (timestamp + ndays * 86400L) : 0;
}
else
expiredate = 0; /* This is stored in the self-signature. */
if (!datalen)
return gpg_error (GPG_ERR_INV_PACKET);
algorithm = *data++; datalen--;
switch (algorithm)
{
case 1:
case 2:
case 3: /* RSA */
npkey = 2;
break;
case 16:
case 20: /* Elgamal */
npkey = 3;
break;
case 17: /* DSA */
npkey = 4;
break;
+ case 18: /* ECDH */
+ npkey = 3;
+ case 19: /* ECDSA */
+ npkey = 2;
+ break;
default: /* Unknown algorithm. */
return gpg_error (GPG_ERR_UNKNOWN_ALGORITHM);
}
for (i=0; i < npkey; i++ )
{
unsigned int nbits, nbytes;
if (datalen < 2)
return gpg_error (GPG_ERR_INV_PACKET);
nbits = ((data[0]<<8)|(data[1]));
data += 2; datalen -=2;
nbytes = (nbits+7) / 8;
if (datalen < nbytes)
return gpg_error (GPG_ERR_INV_PACKET);
/* For use by v3 fingerprint calculation we need to know the RSA
modulus and exponent. */
if (i==0)
{
mpi_n = data;
mpi_n_len = nbytes;
}
else if (i==1)
mpi_e_len = nbytes;
data += nbytes; datalen -= nbytes;
}
n = data - data_start;
if (version < 4)
{
/* We do not support any other algorithm than RSA in v3
packets. */
if (algorithm < 1 || algorithm > 3)
return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
err = gcry_md_open (&md, GCRY_MD_MD5, 0);
if (err)
return err; /* Oops */
gcry_md_write (md, mpi_n, mpi_n_len);
gcry_md_write (md, mpi_n+mpi_n_len+2, mpi_e_len);
memcpy (ki->fpr, gcry_md_read (md, 0), 16);
gcry_md_close (md);
ki->fprlen = 16;
if (mpi_n_len < 8)
{
/* Moduli less than 64 bit are out of the specs scope. Zero
them out becuase this is what gpg does too. */
memset (ki->keyid, 0, 8);
}
else
memcpy (ki->keyid, mpi_n + mpi_n_len - 8, 8);
}
else
{
/* Its a pitty that we need to prefix the buffer with the tag
and a length header: We can't simply pass it to the fast
hashing fucntion for that reason. It might be a good idea to
have a scatter-gather enabled hash function. What we do here
is to use a static buffer if this one is large enough and
only use the regular hash fucntions if this buffer is not
large enough. */
if ( 3 + n < sizeof hashbuffer )
{
hashbuffer[0] = 0x99; /* CTB */
hashbuffer[1] = (n >> 8); /* 2 byte length header. */
hashbuffer[2] = n;
memcpy (hashbuffer + 3, data_start, n);
gcry_md_hash_buffer (GCRY_MD_SHA1, ki->fpr, hashbuffer, 3 + n);
}
else
{
err = gcry_md_open (&md, GCRY_MD_SHA1, 0);
if (err)
return err; /* Oops */
gcry_md_putc (md, 0x99 ); /* CTB */
gcry_md_putc (md, (n >> 8) ); /* 2 byte length header. */
gcry_md_putc (md, n );
gcry_md_write (md, data_start, n);
memcpy (ki->fpr, gcry_md_read (md, 0), 20);
gcry_md_close (md);
}
ki->fprlen = 20;
memcpy (ki->keyid, ki->fpr+12, 8);
}
return 0;
}
/* The caller must pass the address of an INFO structure which will
get filled on success with information pertaining to the OpenPGP
keyblock IMAGE of length IMAGELEN. Note that a caller does only
need to release this INFO structure when the function returns
success. If NPARSED is not NULL the actual number of bytes parsed
will be stored at this address. */
gpg_error_t
_keybox_parse_openpgp (const unsigned char *image, size_t imagelen,
size_t *nparsed,
keybox_openpgp_info_t info)
{
gpg_error_t err = 0;
const unsigned char *image_start, *data;
size_t n, datalen;
int pkttype;
int first = 1;
struct _keybox_openpgp_key_info *k, **ktail = NULL;
struct _keybox_openpgp_uid_info *u, **utail = NULL;
memset (info, 0, sizeof *info);
if (nparsed)
*nparsed = 0;
image_start = image;
while (image)
{
err = next_packet (&image, &imagelen, &data, &datalen, &pkttype, &n);
if (err)
break;
if (first)
{
if (pkttype == PKT_PUBLIC_KEY)
;
else if (pkttype == PKT_SECRET_KEY)
info->is_secret = 1;
else
{
err = gpg_error (GPG_ERR_UNEXPECTED);
break;
}
first = 0;
}
else if (pkttype == PKT_PUBLIC_KEY || pkttype == PKT_SECRET_KEY)
break; /* Next keyblock encountered - ready. */
if (nparsed)
*nparsed += n;
if (pkttype == PKT_SIGNATURE)
{
/* For now we only count the total number of signatures. */
info->nsigs++;
}
else if (pkttype == PKT_USER_ID)
{
info->nuids++;
if (info->nuids == 1)
{
info->uids.off = data - image_start;
info->uids.len = datalen;
utail = &info->uids.next;
}
else
{
u = xtrycalloc (1, sizeof *u);
if (!u)
{
err = gpg_error_from_syserror ();
break;
}
u->off = data - image_start;
u->len = datalen;
*utail = u;
utail = &u->next;
}
}
else if (pkttype == PKT_PUBLIC_KEY || pkttype == PKT_SECRET_KEY)
{
err = parse_key (data, datalen, &info->primary);
if (err)
break;
}
else if( pkttype == PKT_PUBLIC_SUBKEY && datalen && *data == '#' )
{
/* Early versions of GnuPG used old PGP comment packets;
* luckily all those comments are prefixed by a hash
* sign - ignore these packets. */
}
else if (pkttype == PKT_PUBLIC_SUBKEY || pkttype == PKT_SECRET_SUBKEY)
{
info->nsubkeys++;
if (info->nsubkeys == 1)
{
err = parse_key (data, datalen, &info->subkeys);
if (err)
{
info->nsubkeys--;
if (gpg_err_code (err) != GPG_ERR_UNKNOWN_ALGORITHM)
break;
/* We ignore subkeys with unknown algorithms. */
}
else
ktail = &info->subkeys.next;
}
else
{
k = xtrycalloc (1, sizeof *k);
if (!k)
{
err = gpg_error_from_syserror ();
break;
}
err = parse_key (data, datalen, k);
if (err)
{
xfree (k);
info->nsubkeys--;
if (gpg_err_code (err) != GPG_ERR_UNKNOWN_ALGORITHM)
break;
/* We ignore subkeys with unknown algorithms. */
}
else
{
*ktail = k;
ktail = &k->next;
}
}
}
}
if (err)
{
_keybox_destroy_openpgp_info (info);
if (!first
&& (gpg_err_code (err) == GPG_ERR_UNSUPPORTED_ALGORITHM
|| gpg_err_code (err) == GPG_ERR_UNKNOWN_ALGORITHM))
{
/* We are able to skip to the end of this keyblock. */
while (image)
{
if (next_packet (&image, &imagelen,
&data, &datalen, &pkttype, &n) )
break; /* Another error - stop here. */
if (pkttype == PKT_PUBLIC_KEY || pkttype == PKT_SECRET_KEY)
break; /* Next keyblock encountered - ready. */
if (nparsed)
*nparsed += n;
}
}
}
return err;
}
/* Release any malloced data in INFO but not INFO itself! */
void
_keybox_destroy_openpgp_info (keybox_openpgp_info_t info)
{
struct _keybox_openpgp_key_info *k, *k2;
struct _keybox_openpgp_uid_info *u, *u2;
assert (!info->primary.next);
for (k=info->subkeys.next; k; k = k2)
{
k2 = k->next;
xfree (k);
}
for (u=info->uids.next; u; u = u2)
{
u2 = u->next;
xfree (u);
}
}