diff --git a/common/sexputil.c b/common/sexputil.c
index d6860f814..89e63a765 100644
--- a/common/sexputil.c
+++ b/common/sexputil.c
@@ -1,683 +1,683 @@
/* sexputil.c - Utility functions for S-expressions.
* Copyright (C) 2005, 2007, 2009 Free Software Foundation, Inc.
* Copyright (C) 2013 Werner Koch
*
* This file is part of GnuPG.
*
* This file is free software; you can redistribute it and/or modify
* it under the terms of either
*
* - the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* or
*
* - the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* or both in parallel, as here.
*
* This file 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 file implements a few utility functions useful when working
with canonical encrypted S-expressions (i.e. not the S-exprssion
objects from libgcrypt). */
#include
#include
#include
#include
#include
#include
#ifdef HAVE_LOCALE_H
#include
#endif
#include "util.h"
#include "tlv.h"
#include "sexp-parse.h"
#include "openpgpdefs.h" /* for pubkey_algo_t */
/* Return a malloced string with the S-expression CANON in advanced
format. Returns NULL on error. */
static char *
sexp_to_string (gcry_sexp_t sexp)
{
size_t n;
char *result;
if (!sexp)
return NULL;
n = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_ADVANCED, NULL, 0);
if (!n)
return NULL;
result = xtrymalloc (n);
if (!result)
return NULL;
n = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_ADVANCED, result, n);
if (!n)
BUG ();
return result;
}
/* Return a malloced string with the S-expression CANON in advanced
format. Returns NULL on error. */
char *
canon_sexp_to_string (const unsigned char *canon, size_t canonlen)
{
size_t n;
gcry_sexp_t sexp;
char *result;
n = gcry_sexp_canon_len (canon, canonlen, NULL, NULL);
if (!n)
return NULL;
if (gcry_sexp_sscan (&sexp, NULL, canon, n))
return NULL;
result = sexp_to_string (sexp);
gcry_sexp_release (sexp);
return result;
}
/* Print the canonical encoded S-expression in SEXP in advanced
format. SEXPLEN may be passed as 0 is SEXP is known to be valid.
With TEXT of NULL print just the raw S-expression, with TEXT just
an empty string, print a trailing linefeed, otherwise print an
entire debug line. */
void
log_printcanon (const char *text, const unsigned char *sexp, size_t sexplen)
{
if (text && *text)
log_debug ("%s ", text);
if (sexp)
{
char *buf = canon_sexp_to_string (sexp, sexplen);
log_printf ("%s", buf? buf : "[invalid S-expression]");
xfree (buf);
}
if (text)
log_printf ("\n");
}
-/* Print the gcryp S-expression in SEXP in advanced format. With TEXT
+/* Print the gcrypt S-expression SEXP in advanced format. With TEXT
of NULL print just the raw S-expression, with TEXT just an empty
string, print a trailing linefeed, otherwise print an entire debug
line. */
void
log_printsexp (const char *text, gcry_sexp_t sexp)
{
if (text && *text)
log_debug ("%s ", text);
if (sexp)
{
char *buf = sexp_to_string (sexp);
log_printf ("%s", buf? buf : "[invalid S-expression]");
xfree (buf);
}
if (text)
log_printf ("\n");
}
/* Helper function to create a canonical encoded S-expression from a
Libgcrypt S-expression object. The function returns 0 on success
and the malloced canonical S-expression is stored at R_BUFFER and
the allocated length at R_BUFLEN. On error an error code is
returned and (NULL, 0) stored at R_BUFFER and R_BUFLEN. If the
allocated buffer length is not required, NULL by be used for
R_BUFLEN. */
gpg_error_t
make_canon_sexp (gcry_sexp_t sexp, unsigned char **r_buffer, size_t *r_buflen)
{
size_t len;
unsigned char *buf;
*r_buffer = NULL;
if (r_buflen)
*r_buflen = 0;;
len = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_CANON, NULL, 0);
if (!len)
return gpg_error (GPG_ERR_BUG);
buf = xtrymalloc (len);
if (!buf)
return gpg_error_from_syserror ();
len = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_CANON, buf, len);
if (!len)
return gpg_error (GPG_ERR_BUG);
*r_buffer = buf;
if (r_buflen)
*r_buflen = len;
return 0;
}
/* Same as make_canon_sexp but pad the buffer to multiple of 64
bits. If SECURE is set, secure memory will be allocated. */
gpg_error_t
make_canon_sexp_pad (gcry_sexp_t sexp, int secure,
unsigned char **r_buffer, size_t *r_buflen)
{
size_t len;
unsigned char *buf;
*r_buffer = NULL;
if (r_buflen)
*r_buflen = 0;;
len = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_CANON, NULL, 0);
if (!len)
return gpg_error (GPG_ERR_BUG);
len += (8 - len % 8) % 8;
buf = secure? xtrycalloc_secure (1, len) : xtrycalloc (1, len);
if (!buf)
return gpg_error_from_syserror ();
if (!gcry_sexp_sprint (sexp, GCRYSEXP_FMT_CANON, buf, len))
return gpg_error (GPG_ERR_BUG);
*r_buffer = buf;
if (r_buflen)
*r_buflen = len;
return 0;
}
/* Return the so called "keygrip" which is the SHA-1 hash of the
public key parameters expressed in a way depended on the algorithm.
KEY is expected to be an canonical encoded S-expression with a
public or private key. KEYLEN is the length of that buffer.
GRIP must be at least 20 bytes long. On success 0 is returned, on
error an error code. */
gpg_error_t
keygrip_from_canon_sexp (const unsigned char *key, size_t keylen,
unsigned char *grip)
{
gpg_error_t err;
gcry_sexp_t sexp;
if (!grip)
return gpg_error (GPG_ERR_INV_VALUE);
err = gcry_sexp_sscan (&sexp, NULL, (const char *)key, keylen);
if (err)
return err;
if (!gcry_pk_get_keygrip (sexp, grip))
err = gpg_error (GPG_ERR_INTERNAL);
gcry_sexp_release (sexp);
return err;
}
/* Compare two simple S-expressions like "(3:foo)". Returns 0 if they
are identical or !0 if they are not. Note that this function can't
be used for sorting. */
int
cmp_simple_canon_sexp (const unsigned char *a_orig,
const unsigned char *b_orig)
{
const char *a = (const char *)a_orig;
const char *b = (const char *)b_orig;
unsigned long n1, n2;
char *endp;
if (!a && !b)
return 0; /* Both are NULL, they are identical. */
if (!a || !b)
return 1; /* One is NULL, they are not identical. */
if (*a != '(' || *b != '(')
log_bug ("invalid S-exp in cmp_simple_canon_sexp\n");
a++;
n1 = strtoul (a, &endp, 10);
a = endp;
b++;
n2 = strtoul (b, &endp, 10);
b = endp;
if (*a != ':' || *b != ':' )
log_bug ("invalid S-exp in cmp_simple_canon_sexp\n");
if (n1 != n2)
return 1; /* Not the same. */
for (a++, b++; n1; n1--, a++, b++)
if (*a != *b)
return 1; /* Not the same. */
return 0;
}
/* Create a simple S-expression from the hex string at LINE. Returns
a newly allocated buffer with that canonical encoded S-expression
or NULL in case of an error. On return the number of characters
scanned in LINE will be stored at NSCANNED. This functions stops
converting at the first character not representing a hexdigit. Odd
numbers of hex digits are allowed; a leading zero is then
assumed. If no characters have been found, NULL is returned.*/
unsigned char *
make_simple_sexp_from_hexstr (const char *line, size_t *nscanned)
{
size_t n, len;
const char *s;
unsigned char *buf;
unsigned char *p;
char numbuf[50], *numbufp;
size_t numbuflen;
for (n=0, s=line; hexdigitp (s); s++, n++)
;
if (nscanned)
*nscanned = n;
if (!n)
return NULL;
len = ((n+1) & ~0x01)/2;
numbufp = smklen (numbuf, sizeof numbuf, len, &numbuflen);
buf = xtrymalloc (1 + numbuflen + len + 1 + 1);
if (!buf)
return NULL;
buf[0] = '(';
p = (unsigned char *)stpcpy ((char *)buf+1, numbufp);
s = line;
if ((n&1))
{
*p++ = xtoi_1 (s);
s++;
n--;
}
for (; n > 1; n -=2, s += 2)
*p++ = xtoi_2 (s);
*p++ = ')';
*p = 0; /* (Not really needed.) */
return buf;
}
/* Return the hash algorithm from a KSBA sig-val. SIGVAL is a
canonical encoded S-expression. Return 0 if the hash algorithm is
not encoded in SIG-VAL or it is not supported by libgcrypt. */
int
hash_algo_from_sigval (const unsigned char *sigval)
{
const unsigned char *s = sigval;
size_t n;
int depth;
char buffer[50];
if (!s || *s != '(')
return 0; /* Invalid S-expression. */
s++;
n = snext (&s);
if (!n)
return 0; /* Invalid S-expression. */
if (!smatch (&s, n, "sig-val"))
return 0; /* Not a sig-val. */
if (*s != '(')
return 0; /* Invalid S-expression. */
s++;
/* Skip over the algo+parameter list. */
depth = 1;
if (sskip (&s, &depth) || depth)
return 0; /* Invalid S-expression. */
if (*s != '(')
return 0; /* No further list. */
/* Check whether this is (hash ALGO). */
s++;
n = snext (&s);
if (!n)
return 0; /* Invalid S-expression. */
if (!smatch (&s, n, "hash"))
return 0; /* Not a "hash" keyword. */
n = snext (&s);
if (!n || n+1 >= sizeof (buffer))
return 0; /* Algorithm string is missing or too long. */
memcpy (buffer, s, n);
buffer[n] = 0;
return gcry_md_map_name (buffer);
}
/* Create a public key S-expression for an RSA public key from the
modulus M with length MLEN and the public exponent E with length
ELEN. Returns a newly allocated buffer of NULL in case of a memory
allocation problem. If R_LEN is not NULL, the length of the
canonical S-expression is stored there. */
unsigned char *
make_canon_sexp_from_rsa_pk (const void *m_arg, size_t mlen,
const void *e_arg, size_t elen,
size_t *r_len)
{
const unsigned char *m = m_arg;
const unsigned char *e = e_arg;
int m_extra = 0;
int e_extra = 0;
char mlen_str[35];
char elen_str[35];
unsigned char *keybuf, *p;
const char part1[] = "(10:public-key(3:rsa(1:n";
const char part2[] = ")(1:e";
const char part3[] = ")))";
/* Remove leading zeroes. */
for (; mlen && !*m; mlen--, m++)
;
for (; elen && !*e; elen--, e++)
;
/* Insert a leading zero if the number would be zero or interpreted
as negative. */
if (!mlen || (m[0] & 0x80))
m_extra = 1;
if (!elen || (e[0] & 0x80))
e_extra = 1;
/* Build the S-expression. */
snprintf (mlen_str, sizeof mlen_str, "%u:", (unsigned int)mlen+m_extra);
snprintf (elen_str, sizeof elen_str, "%u:", (unsigned int)elen+e_extra);
keybuf = xtrymalloc (strlen (part1) + strlen (mlen_str) + mlen + m_extra
+ strlen (part2) + strlen (elen_str) + elen + e_extra
+ strlen (part3) + 1);
if (!keybuf)
return NULL;
p = stpcpy (keybuf, part1);
p = stpcpy (p, mlen_str);
if (m_extra)
*p++ = 0;
memcpy (p, m, mlen);
p += mlen;
p = stpcpy (p, part2);
p = stpcpy (p, elen_str);
if (e_extra)
*p++ = 0;
memcpy (p, e, elen);
p += elen;
p = stpcpy (p, part3);
if (r_len)
*r_len = p - keybuf;
return keybuf;
}
/* Return the parameters of a public RSA key expressed as an
canonical encoded S-expression. */
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 err;
const unsigned char *buf, *tok;
size_t buflen, toklen;
int depth, last_depth1, last_depth2;
const unsigned char *rsa_n = NULL;
const unsigned char *rsa_e = NULL;
size_t rsa_n_len, rsa_e_len;
*r_n = NULL;
*r_nlen = 0;
*r_e = NULL;
*r_elen = 0;
buf = keydata;
buflen = keydatalen;
depth = 0;
if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
return err;
if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
return err;
if (!tok || toklen != 10 || memcmp ("public-key", tok, toklen))
return gpg_error (GPG_ERR_BAD_PUBKEY);
if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
return err;
if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
return err;
if (!tok || toklen != 3 || memcmp ("rsa", tok, toklen))
return gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
last_depth1 = depth;
while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
&& depth && depth >= last_depth1)
{
if (tok)
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
return err;
if (tok && toklen == 1)
{
const unsigned char **mpi;
size_t *mpi_len;
switch (*tok)
{
case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break;
case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break;
default: mpi = NULL; mpi_len = NULL; break;
}
if (mpi && *mpi)
return gpg_error (GPG_ERR_DUP_VALUE);
if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
return err;
if (tok && mpi)
{
/* Strip off leading zero bytes and save. */
for (;toklen && !*tok; toklen--, tok++)
;
*mpi = tok;
*mpi_len = toklen;
}
}
/* Skip to the end of the list. */
last_depth2 = depth;
while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
&& depth && depth >= last_depth2)
;
if (err)
return err;
}
if (err)
return err;
if (!rsa_n || !rsa_n_len || !rsa_e || !rsa_e_len)
return gpg_error (GPG_ERR_BAD_PUBKEY);
*r_n = rsa_n;
*r_nlen = rsa_n_len;
*r_e = rsa_e;
*r_elen = rsa_e_len;
return 0;
}
/* Return the algo of a public KEY of SEXP. */
int
get_pk_algo_from_key (gcry_sexp_t key)
{
gcry_sexp_t list;
const char *s;
size_t n;
char algoname[6];
int algo = 0;
list = gcry_sexp_nth (key, 1);
if (!list)
goto out;
s = gcry_sexp_nth_data (list, 0, &n);
if (!s)
goto out;
if (n >= sizeof (algoname))
goto out;
memcpy (algoname, s, n);
algoname[n] = 0;
algo = gcry_pk_map_name (algoname);
if (algo == GCRY_PK_ECC)
{
gcry_sexp_t l1 = gcry_sexp_find_token (list, "flags", 0);
int i;
for (i = l1 ? gcry_sexp_length (l1)-1 : 0; i > 0; i--)
{
s = gcry_sexp_nth_data (l1, i, &n);
if (!s)
continue; /* Not a data element. */
if (n == 5 && !memcmp (s, "eddsa", 5))
{
algo = GCRY_PK_EDDSA;
break;
}
}
gcry_sexp_release (l1);
}
out:
gcry_sexp_release (list);
return algo;
}
/* This is a variant of get_pk_algo_from_key but takes an canonical
* encoded S-expression as input. Returns a GCRYPT public key
* identiier or 0 on error. */
int
get_pk_algo_from_canon_sexp (const unsigned char *keydata, size_t keydatalen)
{
gcry_sexp_t sexp;
int algo;
if (gcry_sexp_sscan (&sexp, NULL, keydata, keydatalen))
return 0;
algo = get_pk_algo_from_key (sexp);
gcry_sexp_release (sexp);
return algo;
}
/* Given the public key S_PKEY, return a new buffer with a descriptive
* string for its algorithm. This function may return NULL on memory
* error. If R_ALGOID is not NULL the gcrypt algo id is stored there. */
char *
pubkey_algo_string (gcry_sexp_t s_pkey, enum gcry_pk_algos *r_algoid)
{
const char *prefix;
gcry_sexp_t l1;
char *algoname;
int algo;
char *result;
if (r_algoid)
*r_algoid = 0;
l1 = gcry_sexp_find_token (s_pkey, "public-key", 0);
if (!l1)
return xtrystrdup ("E_no_key");
{
gcry_sexp_t l_tmp = gcry_sexp_cadr (l1);
gcry_sexp_release (l1);
l1 = l_tmp;
}
algoname = gcry_sexp_nth_string (l1, 0);
gcry_sexp_release (l1);
if (!algoname)
return xtrystrdup ("E_no_algo");
algo = gcry_pk_map_name (algoname);
switch (algo)
{
case GCRY_PK_RSA: prefix = "rsa"; break;
case GCRY_PK_ELG: prefix = "elg"; break;
case GCRY_PK_DSA: prefix = "dsa"; break;
case GCRY_PK_ECC: prefix = ""; break;
default: prefix = NULL; break;
}
if (prefix && *prefix)
result = xtryasprintf ("%s%u", prefix, gcry_pk_get_nbits (s_pkey));
else if (prefix)
{
const char *curve = gcry_pk_get_curve (s_pkey, 0, NULL);
const char *name = openpgp_oid_to_curve
(openpgp_curve_to_oid (curve, NULL, NULL), 0);
if (name)
result = xtrystrdup (name);
else if (curve)
result = xtryasprintf ("X_%s", curve);
else
result = xtrystrdup ("E_unknown");
}
else
result = xtryasprintf ("X_algo_%d", algo);
if (r_algoid)
*r_algoid = algo;
xfree (algoname);
return result;
}
/* Map a hash algo id from gcrypt to a string. This is the same as
* gcry_md_algo_name but the returned string is lower case, as
* expected by libksba and it avoids some overhead. */
const char *
hash_algo_to_string (int algo)
{
static const struct
{
const char *name;
int algo;
} hashnames[] =
{
{ "sha256", GCRY_MD_SHA256 },
{ "sha512", GCRY_MD_SHA512 },
{ "sha1", GCRY_MD_SHA1 },
{ "sha384", GCRY_MD_SHA384 },
{ "sha224", GCRY_MD_SHA224 },
{ "sha3-224", GCRY_MD_SHA3_224 },
{ "sha3-256", GCRY_MD_SHA3_256 },
{ "sha3-384", GCRY_MD_SHA3_384 },
{ "sha3-512", GCRY_MD_SHA3_512 },
{ "ripemd160", GCRY_MD_RMD160 },
{ "rmd160", GCRY_MD_RMD160 },
{ "md2", GCRY_MD_MD2 },
{ "md4", GCRY_MD_MD4 },
{ "tiger", GCRY_MD_TIGER },
{ "haval", GCRY_MD_HAVAL },
#if GCRYPT_VERSION_NUMBER >= 0x010900
{ "sm3", GCRY_MD_SM3 },
#endif
{ "md5", GCRY_MD_MD5 }
};
int i;
for (i=0; i < DIM (hashnames); i++)
if (algo == hashnames[i].algo)
return hashnames[i].name;
return "?";
}
diff --git a/g10/keylist.c b/g10/keylist.c
index c6bfbcf52..cfa90b612 100644
--- a/g10/keylist.c
+++ b/g10/keylist.c
@@ -1,2233 +1,2233 @@
/* keylist.c - Print information about OpenPGP keys
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
* 2008, 2010, 2012 Free Software Foundation, Inc.
* Copyright (C) 2013, 2014 Werner Koch
*
* 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
#ifdef HAVE_DOSISH_SYSTEM
# include /* for setmode() */
#endif
#include "gpg.h"
#include "options.h"
#include "packet.h"
#include "../common/status.h"
#include "keydb.h"
#include "photoid.h"
#include "../common/util.h"
#include "../common/ttyio.h"
#include "trustdb.h"
#include "main.h"
#include "../common/i18n.h"
#include "../common/status.h"
#include "call-agent.h"
#include "../common/mbox-util.h"
#include "../common/zb32.h"
#include "tofu.h"
#include "../common/compliance.h"
#include "../common/pkscreening.h"
static void list_all (ctrl_t, int, int);
static void list_one (ctrl_t ctrl,
strlist_t names, int secret, int mark_secret);
static void locate_one (ctrl_t ctrl, strlist_t names, int no_local);
static void print_card_serialno (const char *serialno);
struct keylist_context
{
int check_sigs; /* If set signatures shall be verified. */
int good_sigs; /* Counter used if CHECK_SIGS is set. */
int inv_sigs; /* Counter used if CHECK_SIGS is set. */
int no_key; /* Counter used if CHECK_SIGS is set. */
int oth_err; /* Counter used if CHECK_SIGS is set. */
int no_validity; /* Do not show validity. */
};
static void list_keyblock (ctrl_t ctrl,
kbnode_t keyblock, int secret, int has_secret,
int fpr, struct keylist_context *listctx);
/* The stream used to write attribute packets to. */
static estream_t attrib_fp;
/* Release resources from a keylist context. */
static void
keylist_context_release (struct keylist_context *listctx)
{
(void)listctx; /* Nothing to release. */
}
/* List the keys. If list is NULL, all available keys are listed.
* With LOCATE_MODE set the locate algorithm is used to find a key; if
* in addition NO_LOCAL is set the locate does not look into the local
* keyring. */
void
public_key_list (ctrl_t ctrl, strlist_t list, int locate_mode, int no_local)
{
#ifndef NO_TRUST_MODELS
if (opt.with_colons)
{
byte trust_model, marginals, completes, cert_depth, min_cert_level;
ulong created, nextcheck;
read_trust_options (ctrl, &trust_model, &created, &nextcheck,
&marginals, &completes, &cert_depth, &min_cert_level);
es_fprintf (es_stdout, "tru:");
if (nextcheck && nextcheck <= make_timestamp ())
es_fprintf (es_stdout, "o");
if (trust_model != opt.trust_model)
es_fprintf (es_stdout, "t");
if (opt.trust_model == TM_PGP || opt.trust_model == TM_CLASSIC
|| opt.trust_model == TM_TOFU_PGP)
{
if (marginals != opt.marginals_needed)
es_fprintf (es_stdout, "m");
if (completes != opt.completes_needed)
es_fprintf (es_stdout, "c");
if (cert_depth != opt.max_cert_depth)
es_fprintf (es_stdout, "d");
if (min_cert_level != opt.min_cert_level)
es_fprintf (es_stdout, "l");
}
es_fprintf (es_stdout, ":%d:%lu:%lu", trust_model, created, nextcheck);
/* Only show marginals, completes, and cert_depth in the classic
or PGP trust models since they are not meaningful
otherwise. */
if (trust_model == TM_PGP || trust_model == TM_CLASSIC)
es_fprintf (es_stdout, ":%d:%d:%d", marginals, completes, cert_depth);
es_fprintf (es_stdout, "\n");
}
#endif /*!NO_TRUST_MODELS*/
/* We need to do the stale check right here because it might need to
update the keyring while we already have the keyring open. This
is very bad for W32 because of a sharing violation. For real OSes
it might lead to false results if we are later listing a keyring
which is associated with the inode of a deleted file. */
check_trustdb_stale (ctrl);
#ifdef USE_TOFU
tofu_begin_batch_update (ctrl);
#endif
if (locate_mode)
locate_one (ctrl, list, no_local);
else if (!list)
list_all (ctrl, 0, opt.with_secret);
else
list_one (ctrl, list, 0, opt.with_secret);
#ifdef USE_TOFU
tofu_end_batch_update (ctrl);
#endif
}
void
secret_key_list (ctrl_t ctrl, strlist_t list)
{
(void)ctrl;
check_trustdb_stale (ctrl);
if (!list)
list_all (ctrl, 1, 0);
else /* List by user id */
list_one (ctrl, list, 1, 0);
}
/* Helper for print_key_info and print_key_info_log. */
static char *
format_key_info (ctrl_t ctrl, PKT_public_key *pk, int secret)
{
u32 keyid[2];
char *p;
char pkstrbuf[PUBKEY_STRING_SIZE];
char *result;
keyid_from_pk (pk, keyid);
/* If the pk was chosen by a particular user ID, that is the one to
print. */
if (pk->user_id)
p = utf8_to_native (pk->user_id->name, pk->user_id->len, 0);
else
p = get_user_id_native (ctrl, keyid);
result = xtryasprintf ("%s %s/%s %s %s",
secret? (pk->flags.primary? "sec":"ssb")
/* */ : (pk->flags.primary? "pub":"sub"),
pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
keystr (keyid), datestr_from_pk (pk), p);
xfree (p);
return result;
}
/* Print basic information about a public or secret key. With FP
* passed as NULL, the tty output interface is used, otherwise output
* is directed to the given stream. INDENT gives the requested
* indentation; if that is a negative value indentation is suppressed
* for the first line. SECRET tells that the PK has a secret part.
* FIXME: This is similar in use to print_key_line and thus both
* functions should eventually be united.
*/
void
print_key_info (ctrl_t ctrl, estream_t fp,
int indent, PKT_public_key *pk, int secret)
{
int indentabs = indent >= 0? indent : -indent;
char *info;
/* Note: Negative values for INDENT are not yet needed. */
info = format_key_info (ctrl, pk, secret);
if (!fp && indent >= 0)
tty_printf ("\n"); /* (Backward compatibility to old code) */
tty_fprintf (fp, "%*s%s\n", indentabs, "",
info? info : "[Ooops - out of core]");
xfree (info);
}
/* Same as print_key_info put print using the log functions at
* LOGLEVEL. */
void
print_key_info_log (ctrl_t ctrl, int loglevel,
int indent, PKT_public_key *pk, int secret)
{
int indentabs = indent >= 0? indent : -indent;
char *info;
info = format_key_info (ctrl, pk, secret);
log_log (loglevel, "%*s%s\n", indentabs, "",
info? info : "[Ooops - out of core]");
xfree (info);
}
/* Print basic information of a secret key including the card serial
number information. */
#ifdef ENABLE_CARD_SUPPORT
void
print_card_key_info (estream_t fp, kbnode_t keyblock)
{
kbnode_t node;
char *hexgrip;
char *serialno;
int s2k_char;
char pkstrbuf[PUBKEY_STRING_SIZE];
int indent;
for (node = keyblock; node; node = node->next)
{
if (node->pkt->pkttype == PKT_PUBLIC_KEY
|| node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
{
int rc;
PKT_public_key *pk = node->pkt->pkt.public_key;
serialno = NULL;
rc = hexkeygrip_from_pk (pk, &hexgrip);
if (rc)
{
log_error ("error computing a keygrip: %s\n", gpg_strerror (rc));
s2k_char = '?';
}
else if (!agent_get_keyinfo (NULL, hexgrip, &serialno, NULL))
s2k_char = serialno? '>':' ';
else
s2k_char = '#'; /* Key not found. */
tty_fprintf (fp, "%s%c %s/%s %n",
node->pkt->pkttype == PKT_PUBLIC_KEY ? "sec" : "ssb",
s2k_char,
pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
keystr_from_pk (pk),
&indent);
tty_fprintf (fp, _("created: %s"), datestr_from_pk (pk));
tty_fprintf (fp, " ");
tty_fprintf (fp, _("expires: %s"), expirestr_from_pk (pk));
if (serialno)
{
tty_fprintf (fp, "\n%*s%s", indent, "", _("card-no: "));
if (strlen (serialno) == 32
&& !strncmp (serialno, "D27600012401", 12))
{
/* This is an OpenPGP card. Print the relevant part. */
/* Example: D2760001240101010001000003470000 */
/* xxxxyyyyyyyy */
tty_fprintf (fp, "%.*s %.*s", 4, serialno+16, 8, serialno+20);
}
else
tty_fprintf (fp, "%s", serialno);
}
tty_fprintf (fp, "\n");
xfree (hexgrip);
xfree (serialno);
}
}
}
#endif /*ENABLE_CARD_SUPPORT*/
/* Flags = 0x01 hashed 0x02 critical. */
static void
status_one_subpacket (sigsubpkttype_t type, size_t len, int flags,
const byte * buf)
{
char status[40];
/* Don't print these. */
if (len > 256)
return;
snprintf (status, sizeof status,
"%d %u %u ", type, flags, (unsigned int) len);
write_status_text_and_buffer (STATUS_SIG_SUBPACKET, status, buf, len, 0);
}
/* Print a policy URL. Allowed values for MODE are:
* -1 - print to the TTY
* 0 - print to stdout.
* 1 - use log_info and emit status messages.
* 2 - emit only status messages.
*/
void
show_policy_url (PKT_signature * sig, int indent, int mode)
{
const byte *p;
size_t len;
int seq = 0, crit;
estream_t fp = mode < 0? NULL : mode ? log_get_stream () : es_stdout;
while ((p = enum_sig_subpkt (sig, 1, SIGSUBPKT_POLICY, &len, &seq, &crit)))
{
if (mode != 2)
{
const char *str;
tty_fprintf (fp, "%*s", indent, "");
if (crit)
str = _("Critical signature policy: ");
else
str = _("Signature policy: ");
if (mode > 0)
log_info ("%s", str);
else
tty_fprintf (fp, "%s", str);
tty_print_utf8_string2 (fp, p, len, 0);
tty_fprintf (fp, "\n");
}
if (mode > 0)
write_status_buffer (STATUS_POLICY_URL, p, len, 0);
}
}
/* Print a keyserver URL. Allowed values for MODE are:
* -1 - print to the TTY
* 0 - print to stdout.
* 1 - use log_info and emit status messages.
* 2 - emit only status messages.
*/
void
show_keyserver_url (PKT_signature * sig, int indent, int mode)
{
const byte *p;
size_t len;
int seq = 0, crit;
estream_t fp = mode < 0? NULL : mode ? log_get_stream () : es_stdout;
while ((p = enum_sig_subpkt (sig, 1, SIGSUBPKT_PREF_KS, &len, &seq, &crit)))
{
if (mode != 2)
{
const char *str;
tty_fprintf (fp, "%*s", indent, "");
if (crit)
str = _("Critical preferred keyserver: ");
else
str = _("Preferred keyserver: ");
if (mode > 0)
log_info ("%s", str);
else
tty_fprintf (fp, "%s", str);
tty_print_utf8_string2 (fp, p, len, 0);
tty_fprintf (fp, "\n");
}
if (mode > 0)
status_one_subpacket (SIGSUBPKT_PREF_KS, len,
(crit ? 0x02 : 0) | 0x01, p);
}
}
/* Print notation data. Allowed values for MODE are:
* -1 - print to the TTY
* 0 - print to stdout.
* 1 - use log_info and emit status messages.
* 2 - emit only status messages.
*
* Defined bits in WHICH:
* 1 - standard notations
* 2 - user notations
*/
void
show_notation (PKT_signature * sig, int indent, int mode, int which)
{
estream_t fp = mode < 0? NULL : mode ? log_get_stream () : es_stdout;
notation_t nd, notations;
if (which == 0)
which = 3;
notations = sig_to_notation (sig);
/* There may be multiple notations in the same sig. */
for (nd = notations; nd; nd = nd->next)
{
if (mode != 2)
{
int has_at = !!strchr (nd->name, '@');
if ((which & 1 && !has_at) || (which & 2 && has_at))
{
const char *str;
tty_fprintf (fp, "%*s", indent, "");
if (nd->flags.critical)
str = _("Critical signature notation: ");
else
str = _("Signature notation: ");
if (mode > 0)
log_info ("%s", str);
else
tty_fprintf (fp, "%s", str);
/* This is all UTF8 */
tty_print_utf8_string2 (fp, nd->name, strlen (nd->name), 0);
tty_fprintf (fp, "=");
tty_print_utf8_string2 (fp, nd->value, strlen (nd->value), 0);
/* (We need to use log_printf so that the next call to a
log function does not insert an extra LF.) */
if (mode > 0)
log_printf ("\n");
else
tty_fprintf (fp, "\n");
}
}
if (mode > 0)
{
write_status_buffer (STATUS_NOTATION_NAME,
nd->name, strlen (nd->name), 0);
if (nd->flags.critical || nd->flags.human)
write_status_text (STATUS_NOTATION_FLAGS,
nd->flags.critical && nd->flags.human? "1 1" :
nd->flags.critical? "1 0" : "0 1");
write_status_buffer (STATUS_NOTATION_DATA,
nd->value, strlen (nd->value), 50);
}
}
free_notation (notations);
}
static void
print_signature_stats (struct keylist_context *s)
{
if (!s->check_sigs)
return; /* Signature checking was not requested. */
/* Better flush stdout so that the stats are always printed after
* the output. */
es_fflush (es_stdout);
if (s->good_sigs)
log_info (ngettext("%d good signature\n",
"%d good signatures\n", s->good_sigs), s->good_sigs);
if (s->inv_sigs)
log_info (ngettext("%d bad signature\n",
"%d bad signatures\n", s->inv_sigs), s->inv_sigs);
if (s->no_key)
log_info (ngettext("%d signature not checked due to a missing key\n",
"%d signatures not checked due to missing keys\n",
s->no_key), s->no_key);
if (s->oth_err)
log_info (ngettext("%d signature not checked due to an error\n",
"%d signatures not checked due to errors\n",
s->oth_err), s->oth_err);
}
/* List all keys. If SECRET is true only secret keys are listed. If
MARK_SECRET is true secret keys are indicated in a public key
listing. */
static void
list_all (ctrl_t ctrl, int secret, int mark_secret)
{
KEYDB_HANDLE hd;
KBNODE keyblock = NULL;
int rc = 0;
int any_secret;
const char *lastresname, *resname;
struct keylist_context listctx;
memset (&listctx, 0, sizeof (listctx));
if (opt.check_sigs)
listctx.check_sigs = 1;
hd = keydb_new (ctrl);
if (!hd)
rc = gpg_error_from_syserror ();
else
rc = keydb_search_first (hd);
if (rc)
{
if (gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
log_error ("keydb_search_first failed: %s\n", gpg_strerror (rc));
goto leave;
}
lastresname = NULL;
do
{
if (secret)
glo_ctrl.silence_parse_warnings++;
rc = keydb_get_keyblock (hd, &keyblock);
if (secret)
glo_ctrl.silence_parse_warnings--;
if (rc)
{
if (gpg_err_code (rc) == GPG_ERR_LEGACY_KEY)
continue; /* Skip legacy keys. */
log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
goto leave;
}
if (secret || mark_secret)
any_secret = !agent_probe_any_secret_key (NULL, keyblock);
else
any_secret = 0;
if (secret && !any_secret)
; /* Secret key listing requested but this isn't one. */
else
{
if (!opt.with_colons && !(opt.list_options & LIST_SHOW_ONLY_FPR_MBOX))
{
resname = keydb_get_resource_name (hd);
if (lastresname != resname)
{
int i;
es_fprintf (es_stdout, "%s\n", resname);
for (i = strlen (resname); i; i--)
es_putc ('-', es_stdout);
es_putc ('\n', es_stdout);
lastresname = resname;
}
}
merge_keys_and_selfsig (ctrl, keyblock);
list_keyblock (ctrl, keyblock, secret, any_secret, opt.fingerprint,
&listctx);
}
release_kbnode (keyblock);
keyblock = NULL;
}
while (!(rc = keydb_search_next (hd)));
es_fflush (es_stdout);
if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
log_error ("keydb_search_next failed: %s\n", gpg_strerror (rc));
if (keydb_get_skipped_counter (hd))
log_info (ngettext("Warning: %lu key skipped due to its large size\n",
"Warning: %lu keys skipped due to their large sizes\n",
keydb_get_skipped_counter (hd)),
keydb_get_skipped_counter (hd));
if (opt.check_sigs && !opt.with_colons)
print_signature_stats (&listctx);
leave:
keylist_context_release (&listctx);
release_kbnode (keyblock);
keydb_release (hd);
}
static void
list_one (ctrl_t ctrl, strlist_t names, int secret, int mark_secret)
{
int rc = 0;
KBNODE keyblock = NULL;
GETKEY_CTX ctx;
int any_secret;
const char *resname;
const char *keyring_str = _("Keyring");
int i;
struct keylist_context listctx;
memset (&listctx, 0, sizeof (listctx));
if (!secret && opt.check_sigs)
listctx.check_sigs = 1;
/* fixme: using the bynames function has the disadvantage that we
* don't know whether one of the names given was not found. OTOH,
* this function has the advantage to list the names in the
* sequence as defined by the keyDB and does not duplicate
* outputs. A solution could be do test whether all given have
* been listed (this needs a way to use the keyDB search
* functions) or to have the search function return indicators for
* found names. Yet another way is to use the keydb search
* facilities directly. */
rc = getkey_bynames (ctrl, &ctx, NULL, names, secret, &keyblock);
if (rc)
{
log_error ("error reading key: %s\n", gpg_strerror (rc));
getkey_end (ctrl, ctx);
write_status_error ("keylist.getkey", rc);
return;
}
do
{
/* getkey_bynames makes sure that only secret keys are returned
* if requested, thus we do not need to test again. With
* MARK_SECRET set (ie. option --with-secret) we have to test
* for a secret key, though. */
if (secret)
any_secret = 1;
else if (mark_secret)
any_secret = !agent_probe_any_secret_key (NULL, keyblock);
else
any_secret = 0;
if (secret && !any_secret)
;/* Secret key listing requested but getkey_bynames failed. */
else
{
if ((opt.list_options & LIST_SHOW_KEYRING) && !opt.with_colons)
{
resname = keydb_get_resource_name (get_ctx_handle (ctx));
es_fprintf (es_stdout, "%s: %s\n", keyring_str, resname);
for (i = strlen (resname) + strlen (keyring_str) + 2; i; i--)
es_putc ('-', es_stdout);
es_putc ('\n', es_stdout);
}
list_keyblock (ctrl, keyblock, secret, any_secret,
opt.fingerprint, &listctx);
}
release_kbnode (keyblock);
}
while (!getkey_next (ctrl, ctx, NULL, &keyblock));
getkey_end (ctrl, ctx);
if (opt.check_sigs && !opt.with_colons)
print_signature_stats (&listctx);
keylist_context_release (&listctx);
}
static void
locate_one (ctrl_t ctrl, strlist_t names, int no_local)
{
int rc = 0;
strlist_t sl;
GETKEY_CTX ctx = NULL;
KBNODE keyblock = NULL;
struct keylist_context listctx;
memset (&listctx, 0, sizeof (listctx));
if (opt.check_sigs)
listctx.check_sigs = 1;
for (sl = names; sl; sl = sl->next)
{
rc = get_best_pubkey_byname (ctrl,
no_local? GET_PUBKEY_NO_LOCAL
/* */: GET_PUBKEY_NORMAL,
&ctx, NULL, sl->d, &keyblock, 1);
if (rc)
{
if (gpg_err_code (rc) != GPG_ERR_NO_PUBKEY)
log_error ("error reading key: %s\n", gpg_strerror (rc));
else if (opt.verbose)
log_info (_("key \"%s\" not found: %s\n"),
sl->d, gpg_strerror (rc));
}
else
{
do
{
list_keyblock (ctrl, keyblock, 0, 0, opt.fingerprint, &listctx);
release_kbnode (keyblock);
}
while (ctx && !getkey_next (ctrl, ctx, NULL, &keyblock));
getkey_end (ctrl, ctx);
ctx = NULL;
}
}
if (opt.check_sigs && !opt.with_colons)
print_signature_stats (&listctx);
keylist_context_release (&listctx);
}
static void
print_key_data (PKT_public_key * pk)
{
int n = pk ? pubkey_get_npkey (pk->pubkey_algo) : 0;
int i;
for (i = 0; i < n; i++)
{
es_fprintf (es_stdout, "pkd:%d:%u:", i, mpi_get_nbits (pk->pkey[i]));
mpi_print (es_stdout, pk->pkey[i], 1);
es_putc (':', es_stdout);
es_putc ('\n', es_stdout);
}
}
/* Various public key screenings. (Right now just ROCA). With
* COLON_MODE set the output is formatted for use in the compliance
* field of a colon listing.
*/
static void
print_pk_screening (PKT_public_key *pk, int colon_mode)
{
gpg_error_t err;
if (is_RSA (pk->pubkey_algo) && pubkey_get_npkey (pk->pubkey_algo))
{
err = screen_key_for_roca (pk->pkey[0]);
if (!err)
;
else if (gpg_err_code (err) == GPG_ERR_TRUE)
{
if (colon_mode)
es_fprintf (es_stdout, colon_mode > 1? " %d":"%d", 6001);
else
es_fprintf (es_stdout,
" Screening: ROCA vulnerability detected\n");
}
else if (!colon_mode)
es_fprintf (es_stdout, " Screening: [ROCA check failed: %s]\n",
gpg_strerror (err));
}
}
static void
print_capabilities (ctrl_t ctrl, PKT_public_key *pk, KBNODE keyblock)
{
unsigned int use = pk->pubkey_usage;
int c_printed = 0;
if (use & PUBKEY_USAGE_ENC)
es_putc ('e', es_stdout);
if (use & PUBKEY_USAGE_SIG)
{
es_putc ('s', es_stdout);
if (pk->flags.primary)
{
es_putc ('c', es_stdout);
/* The PUBKEY_USAGE_CERT flag was introduced later and we
used to always print 'c' for a primary key. To avoid any
regression here we better track whether we printed 'c'
already. */
c_printed = 1;
}
}
if ((use & PUBKEY_USAGE_CERT) && !c_printed)
es_putc ('c', es_stdout);
if ((use & PUBKEY_USAGE_AUTH))
es_putc ('a', es_stdout);
if ((use & PUBKEY_USAGE_UNKNOWN))
es_putc ('?', es_stdout);
if (keyblock)
{
/* Figure out the usable capabilities. */
KBNODE k;
int enc = 0, sign = 0, cert = 0, auth = 0, disabled = 0;
for (k = keyblock; k; k = k->next)
{
if (k->pkt->pkttype == PKT_PUBLIC_KEY
|| k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
{
pk = k->pkt->pkt.public_key;
if (pk->flags.primary)
disabled = pk_is_disabled (pk);
if (pk->flags.valid && !pk->flags.revoked && !pk->has_expired)
{
if (pk->pubkey_usage & PUBKEY_USAGE_ENC)
enc = 1;
if (pk->pubkey_usage & PUBKEY_USAGE_SIG)
{
sign = 1;
if (pk->flags.primary)
cert = 1;
}
if (pk->pubkey_usage & PUBKEY_USAGE_CERT)
cert = 1;
if ((pk->pubkey_usage & PUBKEY_USAGE_AUTH))
auth = 1;
}
}
}
if (enc)
es_putc ('E', es_stdout);
if (sign)
es_putc ('S', es_stdout);
if (cert)
es_putc ('C', es_stdout);
if (auth)
es_putc ('A', es_stdout);
if (disabled)
es_putc ('D', es_stdout);
}
es_putc (':', es_stdout);
}
/* FLAGS: 0x01 hashed
0x02 critical */
static void
print_one_subpacket (sigsubpkttype_t type, size_t len, int flags,
const byte * buf)
{
size_t i;
es_fprintf (es_stdout, "spk:%d:%u:%u:", type, flags, (unsigned int) len);
for (i = 0; i < len; i++)
{
/* printable ascii other than : and % */
if (buf[i] >= 32 && buf[i] <= 126 && buf[i] != ':' && buf[i] != '%')
es_fprintf (es_stdout, "%c", buf[i]);
else
es_fprintf (es_stdout, "%%%02X", buf[i]);
}
es_fprintf (es_stdout, "\n");
}
void
print_subpackets_colon (PKT_signature * sig)
{
byte *i;
log_assert (opt.show_subpackets);
for (i = opt.show_subpackets; *i; i++)
{
const byte *p;
size_t len;
int seq, crit;
seq = 0;
while ((p = enum_sig_subpkt (sig, 1, *i, &len, &seq, &crit)))
print_one_subpacket (*i, len, 0x01 | (crit ? 0x02 : 0), p);
seq = 0;
while ((p = enum_sig_subpkt (sig, 0, *i, &len, &seq, &crit)))
print_one_subpacket (*i, len, 0x00 | (crit ? 0x02 : 0), p);
}
}
void
dump_attribs (const PKT_user_id *uid, PKT_public_key *pk)
{
int i;
if (!attrib_fp)
return;
for (i = 0; i < uid->numattribs; i++)
{
if (is_status_enabled ())
{
byte array[MAX_FINGERPRINT_LEN], *p;
char buf[(MAX_FINGERPRINT_LEN * 2) + 90];
size_t j, n;
if (!pk)
BUG ();
fingerprint_from_pk (pk, array, &n);
p = array;
for (j = 0; j < n; j++, p++)
sprintf (buf + 2 * j, "%02X", *p);
sprintf (buf + strlen (buf), " %lu %u %u %u %lu %lu %u",
(ulong) uid->attribs[i].len, uid->attribs[i].type, i + 1,
uid->numattribs, (ulong) uid->created,
(ulong) uid->expiredate,
((uid->flags.primary ? 0x01 : 0) | (uid->flags.revoked ? 0x02 : 0) |
(uid->flags.expired ? 0x04 : 0)));
write_status_text (STATUS_ATTRIBUTE, buf);
}
es_fwrite (uid->attribs[i].data, uid->attribs[i].len, 1, attrib_fp);
es_fflush (attrib_fp);
}
}
static void
list_keyblock_print (ctrl_t ctrl, kbnode_t keyblock, int secret, int fpr,
struct keylist_context *listctx)
{
int rc;
KBNODE kbctx;
KBNODE node;
PKT_public_key *pk;
int skip_sigs = 0;
char *hexgrip = NULL;
char *serialno = NULL;
/* Get the keyid from the keyblock. */
node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
if (!node)
{
log_error ("Oops; key lost!\n");
dump_kbnode (keyblock);
return;
}
pk = node->pkt->pkt.public_key;
if (secret || opt.with_keygrip)
{
rc = hexkeygrip_from_pk (pk, &hexgrip);
if (rc)
log_error ("error computing a keygrip: %s\n", gpg_strerror (rc));
}
if (secret)
{
/* Encode some info about the secret key in SECRET. */
if (!agent_get_keyinfo (NULL, hexgrip, &serialno, NULL))
secret = serialno? 3 : 1;
else
secret = 2; /* Key not found. */
}
if (!listctx->no_validity)
check_trustdb_stale (ctrl);
/* Print the "pub" line and in KF_NONE mode the fingerprint. */
print_key_line (ctrl, es_stdout, pk, secret);
if (fpr)
print_fingerprint (ctrl, NULL, pk, 0);
if (opt.with_keygrip && hexgrip)
es_fprintf (es_stdout, " Keygrip = %s\n", hexgrip);
if (serialno)
print_card_serialno (serialno);
if (opt.with_key_data)
print_key_data (pk);
if (opt.with_key_screening)
print_pk_screening (pk, 0);
if (opt.with_key_origin
&& (pk->keyorg || pk->keyupdate || pk->updateurl))
{
char updatestr[MK_DATESTR_SIZE];
es_fprintf (es_stdout, " origin=%s last=%s %s",
key_origin_string (pk->keyorg),
mk_datestr (updatestr, sizeof updatestr, pk->keyupdate),
pk->updateurl? "url=":"");
if (pk->updateurl)
print_utf8_string (es_stdout, pk->updateurl);
es_putc ('\n', es_stdout);
}
for (kbctx = NULL; (node = walk_kbnode (keyblock, &kbctx, 0));)
{
if (node->pkt->pkttype == PKT_USER_ID)
{
PKT_user_id *uid = node->pkt->pkt.user_id;
int indent;
int kl = opt.keyid_format == KF_NONE? 10 : keystrlen ();
if ((uid->flags.expired || uid->flags.revoked)
&& !(opt.list_options & LIST_SHOW_UNUSABLE_UIDS))
{
skip_sigs = 1;
continue;
}
else
skip_sigs = 0;
if (attrib_fp && uid->attrib_data != NULL)
dump_attribs (uid, pk);
if ((uid->flags.revoked || uid->flags.expired)
|| ((opt.list_options & LIST_SHOW_UID_VALIDITY)
&& !listctx->no_validity))
{
const char *validity;
validity = uid_trust_string_fixed (ctrl, pk, uid);
indent = ((kl + (opt.legacy_list_mode? 9:11))
- atoi (uid_trust_string_fixed (ctrl, NULL, NULL)));
if (indent < 0 || indent > 40)
indent = 0;
es_fprintf (es_stdout, "uid%*s%s ", indent, "", validity);
}
else
{
indent = kl + (opt.legacy_list_mode? 10:12);
es_fprintf (es_stdout, "uid%*s", indent, "");
}
print_utf8_buffer (es_stdout, uid->name, uid->len);
es_putc ('\n', es_stdout);
if (opt.with_wkd_hash)
{
char *mbox, *hash, *p;
char hashbuf[32];
mbox = mailbox_from_userid (uid->name, 0);
if (mbox && (p = strchr (mbox, '@')))
{
*p++ = 0;
gcry_md_hash_buffer (GCRY_MD_SHA1, hashbuf,
mbox, strlen (mbox));
hash = zb32_encode (hashbuf, 8*20);
if (hash)
{
es_fprintf (es_stdout, " %*s%s@%s\n",
indent, "", hash, p);
xfree (hash);
}
}
xfree (mbox);
}
if (opt.with_key_origin
&& (uid->keyorg || uid->keyupdate || uid->updateurl))
{
char updatestr[MK_DATESTR_SIZE];
es_fprintf (es_stdout, " %*sorigin=%s last=%s %s",
indent, "",
key_origin_string (uid->keyorg),
mk_datestr (updatestr, sizeof updatestr,
uid->keyupdate),
uid->updateurl? "url=":"");
if (uid->updateurl)
print_utf8_string (es_stdout, uid->updateurl);
es_putc ('\n', es_stdout);
}
if ((opt.list_options & LIST_SHOW_PHOTOS) && uid->attribs != NULL)
show_photos (ctrl, uid->attribs, uid->numattribs, pk, uid);
}
else if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
{
PKT_public_key *pk2 = node->pkt->pkt.public_key;
if ((pk2->flags.revoked || pk2->has_expired)
&& !(opt.list_options & LIST_SHOW_UNUSABLE_SUBKEYS))
{
skip_sigs = 1;
continue;
}
else
skip_sigs = 0;
xfree (serialno); serialno = NULL;
xfree (hexgrip); hexgrip = NULL;
if (secret || opt.with_keygrip)
{
rc = hexkeygrip_from_pk (pk2, &hexgrip);
if (rc)
log_error ("error computing a keygrip: %s\n",
gpg_strerror (rc));
}
if (secret)
{
if (!agent_get_keyinfo (NULL, hexgrip, &serialno, NULL))
secret = serialno? 3 : 1;
else
secret = 2; /* Key not found. */
}
/* Print the "sub" line. */
print_key_line (ctrl, es_stdout, pk2, secret);
if (fpr > 1 || opt.with_subkey_fingerprint)
{
print_fingerprint (ctrl, NULL, pk2, 0);
if (serialno)
print_card_serialno (serialno);
}
if (opt.with_keygrip && hexgrip)
es_fprintf (es_stdout, " Keygrip = %s\n", hexgrip);
if (opt.with_key_data)
print_key_data (pk2);
if (opt.with_key_screening)
print_pk_screening (pk2, 0);
}
else if (opt.list_sigs
&& node->pkt->pkttype == PKT_SIGNATURE && !skip_sigs)
{
PKT_signature *sig = node->pkt->pkt.signature;
int sigrc;
char *sigstr;
char *reason_text = NULL;
char *reason_comment = NULL;
size_t reason_commentlen;
if (listctx->check_sigs)
{
rc = check_key_signature (ctrl, keyblock, node, NULL);
switch (gpg_err_code (rc))
{
case 0:
listctx->good_sigs++;
sigrc = '!';
break;
case GPG_ERR_BAD_SIGNATURE:
listctx->inv_sigs++;
sigrc = '-';
break;
case GPG_ERR_NO_PUBKEY:
case GPG_ERR_UNUSABLE_PUBKEY:
listctx->no_key++;
continue;
default:
listctx->oth_err++;
sigrc = '%';
break;
}
/* TODO: Make sure a cached sig record here still has
the pk that issued it. See also
keyedit.c:print_and_check_one_sig */
}
else
{
rc = 0;
sigrc = ' ';
}
if (sig->sig_class == 0x20 || sig->sig_class == 0x28
|| sig->sig_class == 0x30)
{
sigstr = "rev";
get_revocation_reason (sig, &reason_text,
&reason_comment, &reason_commentlen);
}
else if ((sig->sig_class & ~3) == 0x10)
sigstr = "sig";
else if (sig->sig_class == 0x18)
sigstr = "sig";
else if (sig->sig_class == 0x1F)
sigstr = "sig";
else
{
es_fprintf (es_stdout, "sig "
"[unexpected signature class 0x%02x]\n",
sig->sig_class);
continue;
}
es_fputs (sigstr, es_stdout);
es_fprintf (es_stdout, "%c%c %c%c%c%c%c%c %s %s",
sigrc, (sig->sig_class - 0x10 > 0 &&
sig->sig_class - 0x10 <
4) ? '0' + sig->sig_class - 0x10 : ' ',
sig->flags.exportable ? ' ' : 'L',
sig->flags.revocable ? ' ' : 'R',
sig->flags.policy_url ? 'P' : ' ',
sig->flags.notation ? 'N' : ' ',
sig->flags.expired ? 'X' : ' ',
(sig->trust_depth > 9) ? 'T' : (sig->trust_depth >
0) ? '0' +
sig->trust_depth : ' ', keystr (sig->keyid),
datestr_from_sig (sig));
if (opt.list_options & LIST_SHOW_SIG_EXPIRE)
es_fprintf (es_stdout, " %s", expirestr_from_sig (sig));
es_fprintf (es_stdout, " ");
if (sigrc == '%')
es_fprintf (es_stdout, "[%s] ", gpg_strerror (rc));
else if (sigrc == '?')
;
else if (!opt.fast_list_mode)
{
size_t n;
char *p = get_user_id (ctrl, sig->keyid, &n, NULL);
print_utf8_buffer (es_stdout, p, n);
xfree (p);
}
es_putc ('\n', es_stdout);
if (sig->flags.policy_url
&& (opt.list_options & LIST_SHOW_POLICY_URLS))
show_policy_url (sig, 3, 0);
if (sig->flags.notation && (opt.list_options & LIST_SHOW_NOTATIONS))
show_notation (sig, 3, 0,
((opt.
list_options & LIST_SHOW_STD_NOTATIONS) ? 1 : 0)
+
((opt.
list_options & LIST_SHOW_USER_NOTATIONS) ? 2 :
0));
if (sig->flags.pref_ks
&& (opt.list_options & LIST_SHOW_KEYSERVER_URLS))
show_keyserver_url (sig, 3, 0);
if (reason_text)
{
es_fprintf (es_stdout, " %s%s\n",
_("reason for revocation: "), reason_text);
if (reason_comment)
{
const byte *s, *s_lf;
size_t n, n_lf;
s = reason_comment;
n = reason_commentlen;
s_lf = NULL;
do
{
/* We don't want any empty lines, so we skip them. */
for (;n && *s == '\n'; s++, n--)
;
if (n)
{
s_lf = memchr (s, '\n', n);
n_lf = s_lf? s_lf - s : n;
es_fprintf (es_stdout, " %s",
_("revocation comment: "));
es_write_sanitized (es_stdout, s, n_lf, NULL, NULL);
es_putc ('\n', es_stdout);
s += n_lf; n -= n_lf;
}
} while (s_lf);
}
}
xfree (reason_text);
xfree (reason_comment);
/* fixme: check or list other sigs here */
}
}
es_putc ('\n', es_stdout);
xfree (serialno);
xfree (hexgrip);
}
/* Do a simple key listing printing only the fingerprint and the mail
* address of valid keys. */
static void
list_keyblock_simple (ctrl_t ctrl, kbnode_t keyblock)
{
gpg_err_code_t ec;
kbnode_t kbctx;
kbnode_t node;
char hexfpr[2*MAX_FINGERPRINT_LEN+1];
char *mbox;
(void)ctrl;
node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
if (!node)
{
log_error ("Oops; key lost!\n");
dump_kbnode (keyblock);
return;
}
hexfingerprint (node->pkt->pkt.public_key, hexfpr, sizeof hexfpr);
for (kbctx = NULL; (node = walk_kbnode (keyblock, &kbctx, 0));)
{
if (node->pkt->pkttype == PKT_USER_ID)
{
PKT_user_id *uid = node->pkt->pkt.user_id;
if (uid->attrib_data)
continue;
if (uid->flags.expired || uid->flags.revoked)
continue;
mbox = mailbox_from_userid (uid->name, 0);
if (!mbox)
{
ec = gpg_err_code_from_syserror ();
if (ec != GPG_ERR_EINVAL)
log_error ("error getting mailbox from user-id: %s\n",
gpg_strerror (ec));
continue;
}
es_fprintf (es_stdout, "%s %s\n", hexfpr, mbox);
xfree (mbox);
}
}
}
void
print_revokers (estream_t fp, PKT_public_key * pk)
{
/* print the revoker record */
if (!pk->revkey && pk->numrevkeys)
BUG ();
else
{
int i, j;
for (i = 0; i < pk->numrevkeys; i++)
{
byte *p;
es_fprintf (fp, "rvk:::%d::::::", pk->revkey[i].algid);
p = pk->revkey[i].fpr;
for (j = 0; j < pk->revkey[i].fprlen; j++, p++)
es_fprintf (fp, "%02X", *p);
es_fprintf (fp, ":%02x%s:\n",
pk->revkey[i].class,
(pk->revkey[i].class & 0x40) ? "s" : "");
}
}
}
/* Print the compliance flags to field 18. PK is the public key.
* KEYLENGTH is the length of the key in bits and CURVENAME is either
* NULL or the name of the curve. The latter two args are here
* merely because the caller has already computed them. */
static void
print_compliance_flags (PKT_public_key *pk,
unsigned int keylength, const char *curvename)
{
int any = 0;
if (!keylength)
keylength = nbits_from_pk (pk);
if (pk->version == 5)
{
es_fputs (gnupg_status_compliance_flag (CO_GNUPG), es_stdout);
any++;
}
if (gnupg_pk_is_compliant (CO_DE_VS, pk->pubkey_algo, pk->pkey,
keylength, curvename))
{
es_fprintf (es_stdout, any ? " %s" : "%s",
gnupg_status_compliance_flag (CO_DE_VS));
any++;
}
if (opt.with_key_screening)
print_pk_screening (pk, 1+any);
}
/* List a key in colon mode. If SECRET is true this is a secret key
record (i.e. requested via --list-secret-key). If HAS_SECRET a
secret key is available even if SECRET is not set. */
static void
list_keyblock_colon (ctrl_t ctrl, kbnode_t keyblock,
int secret, int has_secret)
{
int rc;
KBNODE kbctx;
KBNODE node;
PKT_public_key *pk;
u32 keyid[2];
int trustletter = 0;
int trustletter_print;
int ownertrust_print;
int ulti_hack = 0;
int i;
char *hexgrip_buffer = NULL;
const char *hexgrip = NULL;
char *serialno = NULL;
int stubkey;
unsigned int keylength;
char *curve = NULL;
const char *curvename = NULL;
/* Get the keyid from the keyblock. */
node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
if (!node)
{
log_error ("Oops; key lost!\n");
dump_kbnode (keyblock);
return;
}
pk = node->pkt->pkt.public_key;
if (secret || has_secret || opt.with_keygrip || opt.with_key_data)
{
rc = hexkeygrip_from_pk (pk, &hexgrip_buffer);
if (rc)
log_error ("error computing a keygrip: %s\n", gpg_strerror (rc));
/* In the error case we print an empty string so that we have a
- * "grp" record for each and subkey - even if it is empty. This
- * may help to prevent sync problems. */
+ * "grp" record for each primary and subkey - even if it is
+ * empty. This may help to prevent sync problems. */
hexgrip = hexgrip_buffer? hexgrip_buffer : "";
}
stubkey = 0;
if ((secret || has_secret)
&& agent_get_keyinfo (NULL, hexgrip, &serialno, NULL))
stubkey = 1; /* Key not found. */
keyid_from_pk (pk, keyid);
if (!pk->flags.valid)
trustletter_print = 'i';
else if (pk->flags.revoked)
trustletter_print = 'r';
else if (pk->has_expired)
trustletter_print = 'e';
else if (opt.fast_list_mode || opt.no_expensive_trust_checks)
trustletter_print = 0;
else
{
trustletter = get_validity_info (ctrl, keyblock, pk, NULL);
if (trustletter == 'u')
ulti_hack = 1;
trustletter_print = trustletter;
}
if (!opt.fast_list_mode && !opt.no_expensive_trust_checks)
ownertrust_print = get_ownertrust_info (ctrl, pk, 0);
else
ownertrust_print = 0;
keylength = nbits_from_pk (pk);
es_fputs (secret? "sec:":"pub:", es_stdout);
if (trustletter_print)
es_putc (trustletter_print, es_stdout);
es_fprintf (es_stdout, ":%u:%d:%08lX%08lX:%s:%s::",
keylength,
pk->pubkey_algo,
(ulong) keyid[0], (ulong) keyid[1],
colon_datestr_from_pk (pk), colon_strtime (pk->expiredate));
if (ownertrust_print)
es_putc (ownertrust_print, es_stdout);
es_putc (':', es_stdout);
es_putc (':', es_stdout);
es_putc (':', es_stdout);
print_capabilities (ctrl, pk, keyblock);
es_putc (':', es_stdout); /* End of field 13. */
es_putc (':', es_stdout); /* End of field 14. */
if (secret || has_secret)
{
if (stubkey)
es_putc ('#', es_stdout);
else if (serialno)
es_fputs (serialno, es_stdout);
else if (has_secret)
es_putc ('+', es_stdout);
}
es_putc (':', es_stdout); /* End of field 15. */
es_putc (':', es_stdout); /* End of field 16. */
if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA
|| pk->pubkey_algo == PUBKEY_ALGO_EDDSA
|| pk->pubkey_algo == PUBKEY_ALGO_ECDH)
{
curve = openpgp_oid_to_str (pk->pkey[0]);
curvename = openpgp_oid_to_curve (curve, 0);
if (!curvename)
curvename = curve;
es_fputs (curvename, es_stdout);
}
es_putc (':', es_stdout); /* End of field 17. */
print_compliance_flags (pk, keylength, curvename);
es_putc (':', es_stdout); /* End of field 18 (compliance). */
if (pk->keyupdate)
es_fputs (colon_strtime (pk->keyupdate), es_stdout);
es_putc (':', es_stdout); /* End of field 19 (last_update). */
es_fprintf (es_stdout, "%d%s", pk->keyorg, pk->updateurl? " ":"");
if (pk->updateurl)
es_write_sanitized (es_stdout, pk->updateurl, strlen (pk->updateurl),
":", NULL);
es_putc (':', es_stdout); /* End of field 20 (origin). */
es_putc ('\n', es_stdout);
print_revokers (es_stdout, pk);
print_fingerprint (ctrl, NULL, pk, 0);
if (hexgrip)
es_fprintf (es_stdout, "grp:::::::::%s:\n", hexgrip);
if (opt.with_key_data)
print_key_data (pk);
for (kbctx = NULL; (node = walk_kbnode (keyblock, &kbctx, 0));)
{
if (node->pkt->pkttype == PKT_USER_ID)
{
PKT_user_id *uid = node->pkt->pkt.user_id;
int uid_validity;
if (attrib_fp && uid->attrib_data != NULL)
dump_attribs (uid, pk);
if (uid->flags.revoked)
uid_validity = 'r';
else if (uid->flags.expired)
uid_validity = 'e';
else if (opt.no_expensive_trust_checks)
uid_validity = 0;
else if (ulti_hack)
uid_validity = 'u';
else
uid_validity = get_validity_info (ctrl, keyblock, pk, uid);
es_fputs (uid->attrib_data? "uat:":"uid:", es_stdout);
if (uid_validity)
es_putc (uid_validity, es_stdout);
es_fputs ("::::", es_stdout);
es_fprintf (es_stdout, "%s:", colon_strtime (uid->created));
es_fprintf (es_stdout, "%s:", colon_strtime (uid->expiredate));
namehash_from_uid (uid);
for (i = 0; i < 20; i++)
es_fprintf (es_stdout, "%02X", uid->namehash[i]);
es_fprintf (es_stdout, "::");
if (uid->attrib_data)
es_fprintf (es_stdout, "%u %lu", uid->numattribs, uid->attrib_len);
else
es_write_sanitized (es_stdout, uid->name, uid->len, ":", NULL);
es_fputs (":::::::::", es_stdout);
if (uid->keyupdate)
es_fputs (colon_strtime (uid->keyupdate), es_stdout);
es_putc (':', es_stdout); /* End of field 19 (last_update). */
es_fprintf (es_stdout, "%d%s", uid->keyorg, uid->updateurl? " ":"");
if (uid->updateurl)
es_write_sanitized (es_stdout,
uid->updateurl, strlen (uid->updateurl),
":", NULL);
es_putc (':', es_stdout); /* End of field 20 (origin). */
es_putc ('\n', es_stdout);
#ifdef USE_TOFU
if (!uid->attrib_data && opt.with_tofu_info
&& (opt.trust_model == TM_TOFU || opt.trust_model == TM_TOFU_PGP))
{
/* Print a "tfs" record. */
tofu_write_tfs_record (ctrl, es_stdout, pk, uid->name);
}
#endif /*USE_TOFU*/
}
else if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
{
u32 keyid2[2];
PKT_public_key *pk2;
int need_hexgrip = !!hexgrip;
pk2 = node->pkt->pkt.public_key;
xfree (hexgrip_buffer); hexgrip_buffer = NULL; hexgrip = NULL;
xfree (serialno); serialno = NULL;
if (need_hexgrip
|| secret || has_secret || opt.with_keygrip || opt.with_key_data)
{
rc = hexkeygrip_from_pk (pk2, &hexgrip_buffer);
if (rc)
log_error ("error computing a keygrip: %s\n",
gpg_strerror (rc));
hexgrip = hexgrip_buffer? hexgrip_buffer : "";
}
stubkey = 0;
if ((secret||has_secret)
&& agent_get_keyinfo (NULL, hexgrip, &serialno, NULL))
stubkey = 1; /* Key not found. */
keyid_from_pk (pk2, keyid2);
es_fputs (secret? "ssb:":"sub:", es_stdout);
if (!pk2->flags.valid)
es_putc ('i', es_stdout);
else if (pk2->flags.revoked)
es_putc ('r', es_stdout);
else if (pk2->has_expired)
es_putc ('e', es_stdout);
else if (opt.fast_list_mode || opt.no_expensive_trust_checks)
;
else
{
/* TRUSTLETTER should always be defined here. */
if (trustletter)
es_fprintf (es_stdout, "%c", trustletter);
}
keylength = nbits_from_pk (pk2);
es_fprintf (es_stdout, ":%u:%d:%08lX%08lX:%s:%s:::::",
keylength,
pk2->pubkey_algo,
(ulong) keyid2[0], (ulong) keyid2[1],
colon_datestr_from_pk (pk2),
colon_strtime (pk2->expiredate));
print_capabilities (ctrl, pk2, NULL);
es_putc (':', es_stdout); /* End of field 13. */
es_putc (':', es_stdout); /* End of field 14. */
if (secret || has_secret)
{
if (stubkey)
es_putc ('#', es_stdout);
else if (serialno)
es_fputs (serialno, es_stdout);
else if (has_secret)
es_putc ('+', es_stdout);
}
es_putc (':', es_stdout); /* End of field 15. */
es_putc (':', es_stdout); /* End of field 16. */
if (pk2->pubkey_algo == PUBKEY_ALGO_ECDSA
|| pk2->pubkey_algo == PUBKEY_ALGO_EDDSA
|| pk2->pubkey_algo == PUBKEY_ALGO_ECDH)
{
xfree (curve);
curve = openpgp_oid_to_str (pk2->pkey[0]);
curvename = openpgp_oid_to_curve (curve, 0);
if (!curvename)
curvename = curve;
es_fputs (curvename, es_stdout);
}
es_putc (':', es_stdout); /* End of field 17. */
print_compliance_flags (pk2, keylength, curvename);
es_putc (':', es_stdout); /* End of field 18. */
es_putc ('\n', es_stdout);
print_fingerprint (ctrl, NULL, pk2, 0);
if (hexgrip)
es_fprintf (es_stdout, "grp:::::::::%s:\n", hexgrip);
if (opt.with_key_data)
print_key_data (pk2);
}
else if (opt.list_sigs && node->pkt->pkttype == PKT_SIGNATURE)
{
PKT_signature *sig = node->pkt->pkt.signature;
int sigrc, fprokay = 0;
char *sigstr;
size_t fplen;
byte fparray[MAX_FINGERPRINT_LEN];
char *siguid;
size_t siguidlen;
char *issuer_fpr = NULL;
char *reason_text = NULL;
char *reason_comment = NULL;
size_t reason_commentlen;
int reason_code = 0; /* Init to silence compiler warning. */
if (sig->sig_class == 0x20 || sig->sig_class == 0x28
|| sig->sig_class == 0x30)
{
sigstr = "rev";
reason_code = get_revocation_reason (sig, &reason_text,
&reason_comment,
&reason_commentlen);
}
else if ((sig->sig_class & ~3) == 0x10)
sigstr = "sig";
else if (sig->sig_class == 0x18)
sigstr = "sig";
else if (sig->sig_class == 0x1F)
sigstr = "sig";
else
{
es_fprintf (es_stdout, "sig::::::::::%02x%c:\n",
sig->sig_class, sig->flags.exportable ? 'x' : 'l');
continue;
}
if (opt.check_sigs)
{
PKT_public_key *signer_pk = NULL;
es_fflush (es_stdout);
if (opt.no_sig_cache)
signer_pk = xmalloc_clear (sizeof (PKT_public_key));
rc = check_key_signature2 (ctrl, keyblock, node, NULL, signer_pk,
NULL, NULL, NULL);
switch (gpg_err_code (rc))
{
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;
}
if (opt.no_sig_cache)
{
if (!rc)
{
fingerprint_from_pk (signer_pk, fparray, &fplen);
fprokay = 1;
}
free_public_key (signer_pk);
}
}
else
{
rc = 0;
sigrc = ' '; /* Note the fix-up below in --list-sigs mode. */
}
if (sigrc != '%' && sigrc != '?' && !opt.fast_list_mode)
{
int nouid;
siguid = get_user_id (ctrl, sig->keyid, &siguidlen, &nouid);
if (!opt.check_sigs && nouid)
sigrc = '?'; /* No key in local keyring. */
}
else
{
siguid = NULL;
siguidlen = 0;
}
es_fputs (sigstr, es_stdout);
es_putc (':', es_stdout);
if (sigrc != ' ')
es_putc (sigrc, es_stdout);
es_fprintf (es_stdout, "::%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)
es_fprintf (es_stdout, "%d %d", sig->trust_depth, sig->trust_value);
es_fprintf (es_stdout, ":");
if (sig->trust_regexp)
es_write_sanitized (es_stdout, sig->trust_regexp,
strlen (sig->trust_regexp), ":", NULL);
es_fprintf (es_stdout, ":");
if (sigrc == '%')
es_fprintf (es_stdout, "[%s] ", gpg_strerror (rc));
else if (siguid)
es_write_sanitized (es_stdout, siguid, siguidlen, ":", NULL);
es_fprintf (es_stdout, ":%02x%c", sig->sig_class,
sig->flags.exportable ? 'x' : 'l');
if (reason_text)
es_fprintf (es_stdout, ",%02x", reason_code);
es_fputs ("::", es_stdout);
if (opt.no_sig_cache && opt.check_sigs && fprokay)
{
for (i = 0; i < fplen; i++)
es_fprintf (es_stdout, "%02X", fparray[i]);
}
else if ((issuer_fpr = issuer_fpr_string (sig)))
es_fputs (issuer_fpr, es_stdout);
es_fprintf (es_stdout, ":::%d:", sig->digest_algo);
if (reason_comment)
{
es_fputs ("::::", es_stdout);
es_write_sanitized (es_stdout, reason_comment, reason_commentlen,
":", NULL);
es_putc (':', es_stdout);
}
es_putc ('\n', es_stdout);
if (opt.show_subpackets)
print_subpackets_colon (sig);
/* fixme: check or list other sigs here */
xfree (reason_text);
xfree (reason_comment);
xfree (siguid);
xfree (issuer_fpr);
}
}
xfree (curve);
xfree (hexgrip_buffer);
xfree (serialno);
}
/*
* Reorder the keyblock so that the primary user ID (and not attribute
* packet) comes first. Fixme: Replace this by a generic sort
* function. */
static void
do_reorder_keyblock (KBNODE keyblock, int attr)
{
KBNODE primary = NULL, primary0 = NULL, primary2 = NULL;
KBNODE last, node;
for (node = keyblock; node; primary0 = node, node = node->next)
{
if (node->pkt->pkttype == PKT_USER_ID &&
((attr && node->pkt->pkt.user_id->attrib_data) ||
(!attr && !node->pkt->pkt.user_id->attrib_data)) &&
node->pkt->pkt.user_id->flags.primary)
{
primary = primary2 = node;
for (node = node->next; node; primary2 = node, node = node->next)
{
if (node->pkt->pkttype == PKT_USER_ID
|| node->pkt->pkttype == PKT_PUBLIC_SUBKEY
|| node->pkt->pkttype == PKT_SECRET_SUBKEY)
{
break;
}
}
break;
}
}
if (!primary)
return; /* No primary key flag found (should not happen). */
for (last = NULL, node = keyblock; node; last = node, node = node->next)
{
if (node->pkt->pkttype == PKT_USER_ID)
break;
}
log_assert (node);
log_assert (last); /* The user ID is never the first packet. */
log_assert (primary0); /* Ditto (this is the node before primary). */
if (node == primary)
return; /* Already the first one. */
last->next = primary;
primary0->next = primary2->next;
primary2->next = node;
}
void
reorder_keyblock (KBNODE keyblock)
{
do_reorder_keyblock (keyblock, 1);
do_reorder_keyblock (keyblock, 0);
}
static void
list_keyblock (ctrl_t ctrl,
KBNODE keyblock, int secret, int has_secret, int fpr,
struct keylist_context *listctx)
{
reorder_keyblock (keyblock);
if (opt.with_colons)
list_keyblock_colon (ctrl, keyblock, secret, has_secret);
else if ((opt.list_options & LIST_SHOW_ONLY_FPR_MBOX))
{
if (!listctx->no_validity)
check_trustdb_stale (ctrl);
list_keyblock_simple (ctrl, keyblock);
}
else
list_keyblock_print (ctrl, keyblock, secret, fpr, listctx);
if (secret)
es_fflush (es_stdout);
}
/* Public function used by keygen to list a keyblock. If NO_VALIDITY
* is set the validity of a key is never shown. */
void
list_keyblock_direct (ctrl_t ctrl,
kbnode_t keyblock, int secret, int has_secret, int fpr,
int no_validity)
{
struct keylist_context listctx;
memset (&listctx, 0, sizeof (listctx));
listctx.no_validity = !!no_validity;
list_keyblock (ctrl, keyblock, secret, has_secret, fpr, &listctx);
keylist_context_release (&listctx);
}
/* Print an hex digit in ICAO spelling. */
static void
print_icao_hexdigit (estream_t fp, int c)
{
static const char *list[16] = {
"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Niner", "Alfa", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot"
};
tty_fprintf (fp, "%s", list[c&15]);
}
/*
* Function to print the finperprint.
* mode 0: as used in key listings, opt.with_colons is honored
* 1: print using log_info ()
* 2: direct use of tty
* 3: direct use of tty but only primary key.
* 4: direct use of tty but only subkey.
* 10: Same as 0 but with_colons etc is ignored.
* 20: Same as 0 but using a compact format.
*
* Modes 1 and 2 will try and print both subkey and primary key
* fingerprints. A MODE with bit 7 set is used internally. If
* OVERRIDE_FP is not NULL that stream will be used in 0 instead
* of es_stdout or instead of the TTY in modes 2 and 3.
*/
void
print_fingerprint (ctrl_t ctrl, estream_t override_fp,
PKT_public_key *pk, int mode)
{
char hexfpr[2*MAX_FINGERPRINT_LEN+1];
char *p;
size_t i;
estream_t fp;
const char *text;
int primary = 0;
int with_colons = opt.with_colons;
int with_icao = opt.with_icao_spelling;
int compact = 0;
if (mode == 10)
{
mode = 0;
with_colons = 0;
with_icao = 0;
}
else if (mode == 20)
{
mode = 0;
with_colons = 0;
compact = 1;
}
if (!opt.fingerprint && !opt.with_fingerprint
&& opt.with_subkey_fingerprint)
compact = 1;
if (pk->main_keyid[0] == pk->keyid[0]
&& pk->main_keyid[1] == pk->keyid[1])
primary = 1;
/* Just to be safe */
if ((mode & 0x80) && !primary)
{
log_error ("primary key is not really primary!\n");
return;
}
mode &= ~0x80;
if (!primary && (mode == 1 || mode == 2))
{
PKT_public_key *primary_pk = xmalloc_clear (sizeof (*primary_pk));
get_pubkey (ctrl, primary_pk, pk->main_keyid);
print_fingerprint (ctrl, override_fp, primary_pk, (mode | 0x80));
free_public_key (primary_pk);
}
if (mode == 1)
{
fp = log_get_stream ();
if (primary)
text = _("Primary key fingerprint:");
else
text = _(" Subkey fingerprint:");
}
else if (mode == 2)
{
fp = override_fp; /* Use tty or given stream. */
if (primary)
/* TRANSLATORS: this should fit into 24 bytes so that the
* fingerprint data is properly aligned with the user ID */
text = _(" Primary key fingerprint:");
else
text = _(" Subkey fingerprint:");
}
else if (mode == 3)
{
fp = override_fp; /* Use tty or given stream. */
text = _(" Key fingerprint =");
}
else if (mode == 4)
{
fp = override_fp; /* Use tty or given stream. */
text = _(" Subkey fingerprint:");
}
else
{
fp = override_fp? override_fp : es_stdout;
if (opt.keyid_format == KF_NONE)
{
text = " "; /* To indent ICAO spelling. */
compact = 1;
}
else
text = _(" Key fingerprint =");
}
hexfingerprint (pk, hexfpr, sizeof hexfpr);
if (with_colons && !mode)
{
es_fprintf (fp, "fpr:::::::::%s:", hexfpr);
}
else if (compact && !opt.fingerprint && !opt.with_fingerprint)
{
tty_fprintf (fp, "%*s%s", 6, "", hexfpr);
}
else
{
char fmtfpr[MAX_FORMATTED_FINGERPRINT_LEN + 1];
format_hexfingerprint (hexfpr, fmtfpr, sizeof fmtfpr);
if (compact)
tty_fprintf (fp, "%*s%s", 6, "", fmtfpr);
else
tty_fprintf (fp, "%s %s", text, fmtfpr);
}
tty_fprintf (fp, "\n");
if (!with_colons && with_icao)
{
;
tty_fprintf (fp, "%*s\"", (int)strlen(text)+1, "");
for (i = 0, p = hexfpr; *p; i++, p++)
{
if (!i)
;
else if (!(i%10))
tty_fprintf (fp, "\n%*s ", (int)strlen(text)+1, "");
else if (!(i%5))
tty_fprintf (fp, " ");
else
tty_fprintf (fp, " ");
print_icao_hexdigit (fp, xtoi_1 (p));
}
tty_fprintf (fp, "\"\n");
}
}
/* Print the serial number of an OpenPGP card if available. */
static void
print_card_serialno (const char *serialno)
{
if (!serialno)
return;
if (opt.with_colons)
return; /* Handled elsewhere. */
es_fputs (_(" Card serial no. ="), es_stdout);
es_putc (' ', es_stdout);
if (strlen (serialno) == 32 && !strncmp (serialno, "D27600012401", 12))
{
/* This is an OpenPGP card. Print the relevant part. */
/* Example: D2760001240101010001000003470000 */
/* xxxxyyyyyyyy */
es_fprintf (es_stdout, "%.*s %.*s", 4, serialno+16, 8, serialno+20);
}
else
es_fputs (serialno, es_stdout);
es_putc ('\n', es_stdout);
}
/* Print a public or secret (sub)key line. Example:
*
* pub dsa2048 2007-12-31 [SC] [expires: 2018-12-31]
* 80615870F5BAD690333686D0F2AD85AC1E42B367
*
* pub rsa2048 2017-12-31 [SC] [expires: 2028-12-31]
* 80615870F5BAD690333686D0F2AD85AC1E42B3671122334455
*
* Some global options may result in a different output format. If
* SECRET is set, "sec" or "ssb" is used instead of "pub" or "sub" and
* depending on the value a flag character is shown:
*
* 1 := ' ' Regular secret key
* 2 := '#' Stub secret key
* 3 := '>' Secret key is on a token.
*/
void
print_key_line (ctrl_t ctrl, estream_t fp, PKT_public_key *pk, int secret)
{
char pkstrbuf[PUBKEY_STRING_SIZE];
tty_fprintf (fp, "%s%c %s",
pk->flags.primary? (secret? "sec":"pub")
/**/ : (secret? "ssb":"sub"),
secret == 2? '#' : secret == 3? '>' : ' ',
pubkey_string (pk, pkstrbuf, sizeof pkstrbuf));
if (opt.keyid_format != KF_NONE)
tty_fprintf (fp, "/%s", keystr_from_pk (pk));
tty_fprintf (fp, " %s", datestr_from_pk (pk));
if (pk->flags.primary
&& !(openpgp_pk_algo_usage (pk->pubkey_algo)
& (PUBKEY_USAGE_CERT| PUBKEY_USAGE_SIG|PUBKEY_USAGE_AUTH)))
{
/* A primary key which is really not capable to sign. */
tty_fprintf (fp, " [INVALID_ALGO]");
}
else if ((opt.list_options & LIST_SHOW_USAGE))
{
tty_fprintf (fp, " [%s]", usagestr_from_pk (pk, 0));
}
if (pk->flags.revoked)
{
tty_fprintf (fp, " [");
tty_fprintf (fp, _("revoked: %s"), revokestr_from_pk (pk));
tty_fprintf (fp, "]");
}
else if (pk->has_expired)
{
tty_fprintf (fp, " [");
tty_fprintf (fp, _("expired: %s"), expirestr_from_pk (pk));
tty_fprintf (fp, "]");
}
else if (pk->expiredate)
{
tty_fprintf (fp, " [");
tty_fprintf (fp, _("expires: %s"), expirestr_from_pk (pk));
tty_fprintf (fp, "]");
}
#if 0
/* I need to think about this some more. It's easy enough to
include, but it looks sort of confusing in the listing... */
if (opt.list_options & LIST_SHOW_VALIDITY)
{
int validity = get_validity (ctrl, pk, NULL, NULL, 0);
tty_fprintf (fp, " [%s]", trust_value_to_string (validity));
}
#endif
if (pk->pubkey_algo >= 100)
tty_fprintf (fp, " [experimental algorithm %d]", pk->pubkey_algo);
tty_fprintf (fp, "\n");
/* if the user hasn't explicitly asked for human-readable
fingerprints, show compact fpr of primary key: */
if (pk->flags.primary &&
!opt.fingerprint && !opt.with_fingerprint)
print_fingerprint (ctrl, fp, pk, 20);
}
void
set_attrib_fd (int fd)
{
static int last_fd = -1;
if (fd != -1 && last_fd == fd)
return;
/* Fixme: Do we need to check for the log stream here? */
if (attrib_fp && attrib_fp != log_get_stream ())
es_fclose (attrib_fp);
attrib_fp = NULL;
if (fd == -1)
return;
if (! gnupg_fd_valid (fd))
log_fatal ("attribute-fd is invalid: %s\n", strerror (errno));
#ifdef HAVE_DOSISH_SYSTEM
setmode (fd, O_BINARY);
#endif
if (fd == 1)
attrib_fp = es_stdout;
else if (fd == 2)
attrib_fp = es_stderr;
else
attrib_fp = es_fdopen (fd, "wb");
if (!attrib_fp)
{
log_fatal ("can't open fd %d for attribute output: %s\n",
fd, strerror (errno));
}
last_fd = fd;
}
diff --git a/sm/minip12.c b/sm/minip12.c
index 9c963d5a2..1e8a49eb5 100644
--- a/sm/minip12.c
+++ b/sm/minip12.c
@@ -1,2853 +1,2853 @@
/* minip12.c - A minimal pkcs-12 implementation.
* Copyright (C) 2002, 2003, 2004, 2006, 2011 Free Software Foundation, Inc.
* Copyright (C) 2014 Werner Koch
*
* 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 .
*/
/* References:
* RFC-7292 - PKCS #12: Personal Information Exchange Syntax v1.1
* RFC-8351 - The PKCS #8 EncryptedPrivateKeyInfo Media Type
* RFC-5958 - Asymmetric Key Packages
* RFC-3447 - PKCS #1: RSA Cryptography Specifications Version 2.1
* RFC-5915 - Elliptic Curve Private Key Structure
*/
#ifdef HAVE_CONFIG_H
#include
#endif
#include
#include
#include
#include
#include
#include
#include
#include "../common/util.h"
#include "../common/logging.h"
#include "../common/utf8conv.h"
#include "../common/tlv.h"
#include "../common/openpgpdefs.h" /* Only for openpgp_curve_to_oid. */
#include "minip12.h"
#ifndef DIM
#define DIM(v) (sizeof(v)/sizeof((v)[0]))
#endif
static unsigned char const oid_data[9] = {
0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x01 };
static unsigned char const oid_encryptedData[9] = {
0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x06 };
static unsigned char const oid_pkcs_12_keyBag[11] = {
0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x0A, 0x01, 0x01 };
static unsigned char const oid_pkcs_12_pkcs_8ShroudedKeyBag[11] = {
0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x0A, 0x01, 0x02 };
static unsigned char const oid_pkcs_12_CertBag[11] = {
0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x0A, 0x01, 0x03 };
static unsigned char const oid_pkcs_12_CrlBag[11] = {
0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x0A, 0x01, 0x04 };
static unsigned char const oid_pbeWithSHAAnd3_KeyTripleDES_CBC[10] = {
0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x01, 0x03 };
static unsigned char const oid_pbeWithSHAAnd40BitRC2_CBC[10] = {
0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x01, 0x06 };
static unsigned char const oid_x509Certificate_for_pkcs_12[10] = {
0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x16, 0x01 };
static unsigned char const oid_pkcs5PBKDF2[9] = {
0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x05, 0x0C };
static unsigned char const oid_pkcs5PBES2[9] = {
0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x05, 0x0D };
static unsigned char const oid_aes128_CBC[9] = {
0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x02 };
static unsigned char const oid_rsaEncryption[9] = {
0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01 };
static unsigned char const oid_pcPublicKey[7] = {
0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01 };
static unsigned char const data_3desiter2048[30] = {
0x30, 0x1C, 0x06, 0x0A, 0x2A, 0x86, 0x48, 0x86,
0xF7, 0x0D, 0x01, 0x0C, 0x01, 0x03, 0x30, 0x0E,
0x04, 0x08, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0x02, 0x02, 0x08, 0x00 };
#define DATA_3DESITER2048_SALT_OFF 18
static unsigned char const data_rc2iter2048[30] = {
0x30, 0x1C, 0x06, 0x0A, 0x2A, 0x86, 0x48, 0x86,
0xF7, 0x0D, 0x01, 0x0C, 0x01, 0x06, 0x30, 0x0E,
0x04, 0x08, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0x02, 0x02, 0x08, 0x00 };
#define DATA_RC2ITER2048_SALT_OFF 18
static unsigned char const data_mactemplate[51] = {
0x30, 0x31, 0x30, 0x21, 0x30, 0x09, 0x06, 0x05,
0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04,
0x14, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0x04, 0x08, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02,
0x02, 0x08, 0x00 };
#define DATA_MACTEMPLATE_MAC_OFF 17
#define DATA_MACTEMPLATE_SALT_OFF 39
static unsigned char const data_attrtemplate[106] = {
0x31, 0x7c, 0x30, 0x55, 0x06, 0x09, 0x2a, 0x86,
0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x14, 0x31,
0x48, 0x1e, 0x46, 0x00, 0x47, 0x00, 0x6e, 0x00,
0x75, 0x00, 0x50, 0x00, 0x47, 0x00, 0x20, 0x00,
0x65, 0x00, 0x78, 0x00, 0x70, 0x00, 0x6f, 0x00,
0x72, 0x00, 0x74, 0x00, 0x65, 0x00, 0x64, 0x00,
0x20, 0x00, 0x63, 0x00, 0x65, 0x00, 0x72, 0x00,
0x74, 0x00, 0x69, 0x00, 0x66, 0x00, 0x69, 0x00,
0x63, 0x00, 0x61, 0x00, 0x74, 0x00, 0x65, 0x00,
0x20, 0x00, 0x66, 0x00, 0x66, 0x00, 0x66, 0x00,
0x66, 0x00, 0x66, 0x00, 0x66, 0x00, 0x66, 0x00,
0x66, 0x30, 0x23, 0x06, 0x09, 0x2a, 0x86, 0x48,
0x86, 0xf7, 0x0d, 0x01, 0x09, 0x15, 0x31, 0x16,
0x04, 0x14 }; /* Need to append SHA-1 digest. */
#define DATA_ATTRTEMPLATE_KEYID_OFF 73
struct buffer_s
{
unsigned char *buffer;
size_t length;
};
struct tag_info
{
int class;
int is_constructed;
unsigned long tag;
unsigned long length; /* length part of the TLV */
int nhdr;
int ndef; /* It is an indefinite length */
};
/* Wrapper around tlv_builder_add_ptr to add an OID. When we
* eventually put the whole tlv_builder stuff into Libksba, we can add
* such a function there. Right now we don't do this to avoid a
* dependency on Libksba. Function return 1 on error. */
static int
builder_add_oid (tlv_builder_t tb, int class, const char *oid)
{
gpg_error_t err;
unsigned char *der;
size_t derlen;
err = ksba_oid_from_str (oid, &der, &derlen);
if (err)
{
log_error ("%s: error converting '%s' to DER: %s\n",
__func__, oid, gpg_strerror (err));
return 1;
}
tlv_builder_add_val (tb, class, TAG_OBJECT_ID, der, derlen);
ksba_free (der);
return 0;
}
-/* Wrapper around tlv_builder_add_ptr to add an MPI. TAG May either
+/* Wrapper around tlv_builder_add_ptr to add an MPI. TAG may either
* be OCTET_STRING or BIT_STRING. When we eventually put the whole
* tlv_builder stuff into Libksba, we can add such a function there.
* Right now we don't do this to avoid a dependency on Libksba.
* Function return 1 on error. STRIP is a hack to remove the first
* octet from the value. */
static int
builder_add_mpi (tlv_builder_t tb, int class, int tag, gcry_mpi_t mpi,
int strip)
{
int returncode;
gpg_error_t err;
const unsigned char *s;
unsigned char *freethis = NULL;
unsigned char *freethis2 = NULL;
unsigned int nbits;
size_t n;
if (gcry_mpi_get_flag (mpi, GCRYMPI_FLAG_OPAQUE))
{
s = gcry_mpi_get_opaque (mpi, &nbits);
n = (nbits+7)/8;
}
else
{
err = gcry_mpi_aprint (GCRYMPI_FMT_USG, &freethis, &n, mpi);
if (err)
{
log_error ("%s: error converting MPI: %s\n",
__func__, gpg_strerror (err));
returncode = 1;
goto leave;
}
s = freethis;
}
if (tag == TAG_BIT_STRING)
{
freethis2 = xtrymalloc_secure (n + 1);
if (!freethis2)
{
err = gpg_error_from_syserror ();
log_error ("%s: error converting MPI: %s\n",
__func__, gpg_strerror (err));
returncode = 1;
goto leave;
}
freethis2[0] = 0;
memcpy (freethis2+1, s, n);
s = freethis2;
n++;
}
strip = !!strip;
if (strip && n < 2)
strip = 0;
tlv_builder_add_val (tb, class, tag, s+strip, n-strip);
returncode = 0;
leave:
xfree (freethis);
xfree (freethis2);
return returncode;
}
/* Parse the buffer at the address BUFFER which is of SIZE and return
the tag and the length part from the TLV triplet. Update BUFFER
and SIZE on success. Checks that the encoded length does not
exhaust the length of the provided buffer. */
static int
parse_tag (unsigned char const **buffer, size_t *size, struct tag_info *ti)
{
int c;
unsigned long tag;
const unsigned char *buf = *buffer;
size_t length = *size;
ti->length = 0;
ti->ndef = 0;
ti->nhdr = 0;
/* Get the tag */
if (!length)
return -1; /* premature eof */
c = *buf++; length--;
ti->nhdr++;
ti->class = (c & 0xc0) >> 6;
ti->is_constructed = !!(c & 0x20);
tag = c & 0x1f;
if (tag == 0x1f)
{
tag = 0;
do
{
tag <<= 7;
if (!length)
return -1; /* premature eof */
c = *buf++; length--;
ti->nhdr++;
tag |= c & 0x7f;
}
while (c & 0x80);
}
ti->tag = tag;
/* Get the length */
if (!length)
return -1; /* prematureeof */
c = *buf++; length--;
ti->nhdr++;
if ( !(c & 0x80) )
ti->length = c;
else if (c == 0x80)
ti->ndef = 1;
else if (c == 0xff)
return -1; /* forbidden length value */
else
{
unsigned long len = 0;
int count = c & 0x7f;
for (; count; count--)
{
len <<= 8;
if (!length)
return -1; /* premature_eof */
c = *buf++; length--;
ti->nhdr++;
len |= c & 0xff;
}
ti->length = len;
}
if (ti->class == CLASS_UNIVERSAL && !ti->tag)
ti->length = 0;
if (ti->length > length)
return -1; /* data larger than buffer. */
*buffer = buf;
*size = length;
return 0;
}
/* Given an ASN.1 chunk of a structure like:
24 NDEF: OCTET STRING -- This is not passed to us
04 1: OCTET STRING -- INPUT point s to here
: 30
04 1: OCTET STRING
: 80
[...]
04 2: OCTET STRING
: 00 00
: } -- This denotes a Null tag and are the last
-- two bytes in INPUT.
Create a new buffer with the content of that octet string. INPUT
is the original buffer with a length as stored at LENGTH. Returns
NULL on error or a new malloced buffer with the length of this new
buffer stored at LENGTH and the number of bytes parsed from input
are added to the value stored at INPUT_CONSUMED. INPUT_CONSUMED is
allowed to be passed as NULL if the caller is not interested in
this value. */
static unsigned char *
cram_octet_string (const unsigned char *input, size_t *length,
size_t *input_consumed)
{
const unsigned char *s = input;
size_t n = *length;
unsigned char *output, *d;
struct tag_info ti;
/* Allocate output buf. We know that it won't be longer than the
input buffer. */
d = output = gcry_malloc (n);
if (!output)
goto bailout;
for (;;)
{
if (parse_tag (&s, &n, &ti))
goto bailout;
if (ti.class == CLASS_UNIVERSAL && ti.tag == TAG_OCTET_STRING
&& !ti.ndef && !ti.is_constructed)
{
memcpy (d, s, ti.length);
s += ti.length;
d += ti.length;
n -= ti.length;
}
else if (ti.class == CLASS_UNIVERSAL && !ti.tag && !ti.is_constructed)
break; /* Ready */
else
goto bailout;
}
*length = d - output;
if (input_consumed)
*input_consumed += s - input;
return output;
bailout:
if (input_consumed)
*input_consumed += s - input;
gcry_free (output);
return NULL;
}
static int
string_to_key (int id, char *salt, size_t saltlen, int iter, const char *pw,
int req_keylen, unsigned char *keybuf)
{
int rc, i, j;
gcry_md_hd_t md;
gcry_mpi_t num_b1 = NULL;
int pwlen;
unsigned char hash[20], buf_b[64], buf_i[128], *p;
size_t cur_keylen;
size_t n;
cur_keylen = 0;
pwlen = strlen (pw);
if (pwlen > 63/2)
{
log_error ("password too long\n");
return -1;
}
if (saltlen < 8)
{
log_error ("salt too short\n");
return -1;
}
/* Store salt and password in BUF_I */
p = buf_i;
for(i=0; i < 64; i++)
*p++ = salt [i%saltlen];
for(i=j=0; i < 64; i += 2)
{
*p++ = 0;
*p++ = pw[j];
if (++j > pwlen) /* Note, that we include the trailing zero */
j = 0;
}
for (;;)
{
rc = gcry_md_open (&md, GCRY_MD_SHA1, 0);
if (rc)
{
log_error ( "gcry_md_open failed: %s\n", gpg_strerror (rc));
return rc;
}
for(i=0; i < 64; i++)
gcry_md_putc (md, id);
gcry_md_write (md, buf_i, 128);
memcpy (hash, gcry_md_read (md, 0), 20);
gcry_md_close (md);
for (i=1; i < iter; i++)
gcry_md_hash_buffer (GCRY_MD_SHA1, hash, hash, 20);
for (i=0; i < 20 && cur_keylen < req_keylen; i++)
keybuf[cur_keylen++] = hash[i];
if (cur_keylen == req_keylen)
{
gcry_mpi_release (num_b1);
return 0; /* ready */
}
/* need more bytes. */
for(i=0; i < 64; i++)
buf_b[i] = hash[i % 20];
rc = gcry_mpi_scan (&num_b1, GCRYMPI_FMT_USG, buf_b, 64, &n);
if (rc)
{
log_error ( "gcry_mpi_scan failed: %s\n", gpg_strerror (rc));
return -1;
}
gcry_mpi_add_ui (num_b1, num_b1, 1);
for (i=0; i < 128; i += 64)
{
gcry_mpi_t num_ij;
rc = gcry_mpi_scan (&num_ij, GCRYMPI_FMT_USG, buf_i + i, 64, &n);
if (rc)
{
log_error ( "gcry_mpi_scan failed: %s\n",
gpg_strerror (rc));
return -1;
}
gcry_mpi_add (num_ij, num_ij, num_b1);
gcry_mpi_clear_highbit (num_ij, 64*8);
rc = gcry_mpi_print (GCRYMPI_FMT_USG, buf_i + i, 64, &n, num_ij);
if (rc)
{
log_error ( "gcry_mpi_print failed: %s\n",
gpg_strerror (rc));
return -1;
}
gcry_mpi_release (num_ij);
}
}
}
static int
set_key_iv (gcry_cipher_hd_t chd, char *salt, size_t saltlen, int iter,
const char *pw, int keybytes)
{
unsigned char keybuf[24];
int rc;
assert (keybytes == 5 || keybytes == 24);
if (string_to_key (1, salt, saltlen, iter, pw, keybytes, keybuf))
return -1;
rc = gcry_cipher_setkey (chd, keybuf, keybytes);
if (rc)
{
log_error ( "gcry_cipher_setkey failed: %s\n", gpg_strerror (rc));
return -1;
}
if (string_to_key (2, salt, saltlen, iter, pw, 8, keybuf))
return -1;
rc = gcry_cipher_setiv (chd, keybuf, 8);
if (rc)
{
log_error ("gcry_cipher_setiv failed: %s\n", gpg_strerror (rc));
return -1;
}
return 0;
}
static int
set_key_iv_pbes2 (gcry_cipher_hd_t chd, char *salt, size_t saltlen, int iter,
const void *iv, size_t ivlen, const char *pw, int algo)
{
unsigned char *keybuf;
size_t keylen;
int rc;
keylen = gcry_cipher_get_algo_keylen (algo);
if (!keylen)
return -1;
keybuf = gcry_malloc_secure (keylen);
if (!keybuf)
return -1;
rc = gcry_kdf_derive (pw, strlen (pw),
GCRY_KDF_PBKDF2, GCRY_MD_SHA1,
salt, saltlen, iter, keylen, keybuf);
if (rc)
{
log_error ("gcry_kdf_derive failed: %s\n", gpg_strerror (rc));
gcry_free (keybuf);
return -1;
}
rc = gcry_cipher_setkey (chd, keybuf, keylen);
gcry_free (keybuf);
if (rc)
{
log_error ("gcry_cipher_setkey failed: %s\n", gpg_strerror (rc));
return -1;
}
rc = gcry_cipher_setiv (chd, iv, ivlen);
if (rc)
{
log_error ("gcry_cipher_setiv failed: %s\n", gpg_strerror (rc));
return -1;
}
return 0;
}
static void
crypt_block (unsigned char *buffer, size_t length, char *salt, size_t saltlen,
int iter, const void *iv, size_t ivlen,
const char *pw, int cipher_algo, int encrypt)
{
gcry_cipher_hd_t chd;
int rc;
rc = gcry_cipher_open (&chd, cipher_algo, GCRY_CIPHER_MODE_CBC, 0);
if (rc)
{
log_error ( "gcry_cipher_open failed: %s\n", gpg_strerror(rc));
wipememory (buffer, length);
return;
}
if (cipher_algo == GCRY_CIPHER_AES128
? set_key_iv_pbes2 (chd, salt, saltlen, iter, iv, ivlen, pw, cipher_algo)
: set_key_iv (chd, salt, saltlen, iter, pw,
cipher_algo == GCRY_CIPHER_RFC2268_40? 5:24))
{
wipememory (buffer, length);
goto leave;
}
rc = encrypt? gcry_cipher_encrypt (chd, buffer, length, NULL, 0)
: gcry_cipher_decrypt (chd, buffer, length, NULL, 0);
if (rc)
{
wipememory (buffer, length);
log_error ("%scrytion failed (%zu bytes): %s\n",
encrypt?"en":"de", length, gpg_strerror (rc));
goto leave;
}
leave:
gcry_cipher_close (chd);
}
/* Decrypt a block of data and try several encodings of the key.
CIPHERTEXT is the encrypted data of size LENGTH bytes; PLAINTEXT is
a buffer of the same size to receive the decryption result. SALT,
SALTLEN, ITER and PW are the information required for decryption
and CIPHER_ALGO is the algorithm id to use. CHECK_FNC is a
function called with the plaintext and used to check whether the
decryption succeeded; i.e. that a correct passphrase has been
given. That function shall return true if the decryption has likely
succeeded. */
static void
decrypt_block (const void *ciphertext, unsigned char *plaintext, size_t length,
char *salt, size_t saltlen,
int iter, const void *iv, size_t ivlen,
const char *pw, int cipher_algo,
int (*check_fnc) (const void *, size_t))
{
static const char * const charsets[] = {
"", /* No conversion - use the UTF-8 passphrase direct. */
"ISO-8859-1",
"ISO-8859-15",
"ISO-8859-2",
"ISO-8859-3",
"ISO-8859-4",
"ISO-8859-5",
"ISO-8859-6",
"ISO-8859-7",
"ISO-8859-8",
"ISO-8859-9",
"KOI8-R",
"IBM437",
"IBM850",
"EUC-JP",
"BIG5",
NULL
};
int charsetidx = 0;
char *convertedpw = NULL; /* Malloced and converted password or NULL. */
size_t convertedpwsize = 0; /* Allocated length. */
for (charsetidx=0; charsets[charsetidx]; charsetidx++)
{
if (*charsets[charsetidx])
{
jnlib_iconv_t cd;
const char *inptr;
char *outptr;
size_t inbytes, outbytes;
if (!convertedpw)
{
/* We assume one byte encodings. Thus we can allocate
the buffer of the same size as the original
passphrase; the result will actually be shorter
then. */
convertedpwsize = strlen (pw) + 1;
convertedpw = gcry_malloc_secure (convertedpwsize);
if (!convertedpw)
{
log_info ("out of secure memory while"
" converting passphrase\n");
break; /* Give up. */
}
}
cd = jnlib_iconv_open (charsets[charsetidx], "utf-8");
if (cd == (jnlib_iconv_t)(-1))
continue;
inptr = pw;
inbytes = strlen (pw);
outptr = convertedpw;
outbytes = convertedpwsize - 1;
if ( jnlib_iconv (cd, (const char **)&inptr, &inbytes,
&outptr, &outbytes) == (size_t)-1)
{
jnlib_iconv_close (cd);
continue;
}
*outptr = 0;
jnlib_iconv_close (cd);
log_info ("decryption failed; trying charset '%s'\n",
charsets[charsetidx]);
}
memcpy (plaintext, ciphertext, length);
crypt_block (plaintext, length, salt, saltlen, iter, iv, ivlen,
convertedpw? convertedpw:pw, cipher_algo, 0);
if (check_fnc (plaintext, length))
break; /* Decryption succeeded. */
}
gcry_free (convertedpw);
}
/* Return true if the decryption of an bag_encrypted_data object has
likely succeeded. */
static int
bag_decrypted_data_p (const void *plaintext, size_t length)
{
struct tag_info ti;
const unsigned char *p = plaintext;
size_t n = length;
/* { */
/* # warning debug code is enabled */
/* FILE *fp = fopen ("tmp-minip12-plain-data.der", "wb"); */
/* if (!fp || fwrite (p, n, 1, fp) != 1) */
/* exit (2); */
/* fclose (fp); */
/* } */
if (parse_tag (&p, &n, &ti))
return 0;
if (ti.class || ti.tag != TAG_SEQUENCE)
return 0;
if (parse_tag (&p, &n, &ti))
return 0;
return 1;
}
/* Note: If R_RESULT is passed as NULL, a key object as already be
processed and thus we need to skip it here. */
static int
parse_bag_encrypted_data (const unsigned char *buffer, size_t length,
int startoffset, size_t *r_consumed, const char *pw,
void (*certcb)(void*, const unsigned char*, size_t),
void *certcbarg, gcry_mpi_t **r_result,
int *r_badpass)
{
struct tag_info ti;
const unsigned char *p = buffer;
const unsigned char *p_start = buffer;
size_t n = length;
const char *where;
char salt[20];
size_t saltlen;
char iv[16];
unsigned int iter;
unsigned char *plain = NULL;
int bad_pass = 0;
unsigned char *cram_buffer = NULL;
size_t consumed = 0; /* Number of bytes consumed from the original buffer. */
int is_3des = 0;
int is_pbes2 = 0;
gcry_mpi_t *result = NULL;
int result_count;
if (r_result)
*r_result = NULL;
where = "start";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class != CLASS_CONTEXT || ti.tag)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.tag != TAG_SEQUENCE)
goto bailout;
where = "bag.encryptedData.version";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.tag != TAG_INTEGER || ti.length != 1 || *p != 0)
goto bailout;
p++; n--;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.tag != TAG_SEQUENCE)
goto bailout;
where = "bag.encryptedData.data";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.tag != TAG_OBJECT_ID || ti.length != DIM(oid_data)
|| memcmp (p, oid_data, DIM(oid_data)))
goto bailout;
p += DIM(oid_data);
n -= DIM(oid_data);
where = "bag.encryptedData.keyinfo";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (!ti.class && ti.tag == TAG_OBJECT_ID
&& ti.length == DIM(oid_pbeWithSHAAnd40BitRC2_CBC)
&& !memcmp (p, oid_pbeWithSHAAnd40BitRC2_CBC,
DIM(oid_pbeWithSHAAnd40BitRC2_CBC)))
{
p += DIM(oid_pbeWithSHAAnd40BitRC2_CBC);
n -= DIM(oid_pbeWithSHAAnd40BitRC2_CBC);
}
else if (!ti.class && ti.tag == TAG_OBJECT_ID
&& ti.length == DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC)
&& !memcmp (p, oid_pbeWithSHAAnd3_KeyTripleDES_CBC,
DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC)))
{
p += DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC);
n -= DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC);
is_3des = 1;
}
else if (!ti.class && ti.tag == TAG_OBJECT_ID
&& ti.length == DIM(oid_pkcs5PBES2)
&& !memcmp (p, oid_pkcs5PBES2, ti.length))
{
p += ti.length;
n -= ti.length;
is_pbes2 = 1;
}
else
goto bailout;
if (is_pbes2)
{
where = "pkcs5PBES2-params";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (!(!ti.class && ti.tag == TAG_OBJECT_ID
&& ti.length == DIM(oid_pkcs5PBKDF2)
&& !memcmp (p, oid_pkcs5PBKDF2, ti.length)))
goto bailout; /* Not PBKDF2. */
p += ti.length;
n -= ti.length;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (!(!ti.class && ti.tag == TAG_OCTET_STRING
&& ti.length >= 8 && ti.length < sizeof salt))
goto bailout; /* No salt or unsupported length. */
saltlen = ti.length;
memcpy (salt, p, saltlen);
p += saltlen;
n -= saltlen;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (!(!ti.class && ti.tag == TAG_INTEGER && ti.length))
goto bailout; /* No valid iteration count. */
for (iter=0; ti.length; ti.length--)
{
iter <<= 8;
iter |= (*p++) & 0xff;
n--;
}
/* Note: We don't support the optional parameters but assume
that the algorithmIdentifier follows. */
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (!(!ti.class && ti.tag == TAG_OBJECT_ID
&& ti.length == DIM(oid_aes128_CBC)
&& !memcmp (p, oid_aes128_CBC, ti.length)))
goto bailout; /* Not AES-128. */
p += ti.length;
n -= ti.length;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (!(!ti.class && ti.tag == TAG_OCTET_STRING && ti.length == sizeof iv))
goto bailout; /* Bad IV. */
memcpy (iv, p, sizeof iv);
p += sizeof iv;
n -= sizeof iv;
}
else
{
where = "rc2or3des-params";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_OCTET_STRING
|| ti.length < 8 || ti.length > 20 )
goto bailout;
saltlen = ti.length;
memcpy (salt, p, saltlen);
p += saltlen;
n -= saltlen;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_INTEGER || !ti.length )
goto bailout;
for (iter=0; ti.length; ti.length--)
{
iter <<= 8;
iter |= (*p++) & 0xff;
n--;
}
}
where = "rc2or3desoraes-ciphertext";
if (parse_tag (&p, &n, &ti))
goto bailout;
consumed = p - p_start;
if (ti.class == CLASS_CONTEXT && ti.tag == 0 && ti.is_constructed && ti.ndef)
{
/* Mozilla exported certs now come with single byte chunks of
octet strings. (Mozilla Firefox 1.0.4). Arghh. */
where = "cram-rc2or3des-ciphertext";
cram_buffer = cram_octet_string ( p, &n, &consumed);
if (!cram_buffer)
goto bailout;
p = p_start = cram_buffer;
if (r_consumed)
*r_consumed = consumed;
r_consumed = NULL; /* Ugly hack to not update that value any further. */
ti.length = n;
}
else if (ti.class == CLASS_CONTEXT && ti.tag == 0 && ti.length )
;
else
goto bailout;
log_info ("%lu bytes of %s encrypted text\n",ti.length,
is_pbes2?"AES128":is_3des?"3DES":"RC2");
plain = gcry_malloc_secure (ti.length);
if (!plain)
{
log_error ("error allocating decryption buffer\n");
goto bailout;
}
decrypt_block (p, plain, ti.length, salt, saltlen, iter,
iv, is_pbes2?16:0, pw,
is_pbes2 ? GCRY_CIPHER_AES128 :
is_3des ? GCRY_CIPHER_3DES : GCRY_CIPHER_RFC2268_40,
bag_decrypted_data_p);
n = ti.length;
startoffset = 0;
p_start = p = plain;
where = "outer.outer.seq";
if (parse_tag (&p, &n, &ti))
{
bad_pass = 1;
goto bailout;
}
if (ti.class || ti.tag != TAG_SEQUENCE)
{
bad_pass = 1;
goto bailout;
}
if (parse_tag (&p, &n, &ti))
{
bad_pass = 1;
goto bailout;
}
/* Loop over all certificates inside the bag. */
while (n)
{
int iscrlbag = 0;
int iskeybag = 0;
where = "certbag.nextcert";
if (ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
where = "certbag.objectidentifier";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_OBJECT_ID)
goto bailout;
if ( ti.length == DIM(oid_pkcs_12_CertBag)
&& !memcmp (p, oid_pkcs_12_CertBag, DIM(oid_pkcs_12_CertBag)))
{
p += DIM(oid_pkcs_12_CertBag);
n -= DIM(oid_pkcs_12_CertBag);
}
else if ( ti.length == DIM(oid_pkcs_12_CrlBag)
&& !memcmp (p, oid_pkcs_12_CrlBag, DIM(oid_pkcs_12_CrlBag)))
{
p += DIM(oid_pkcs_12_CrlBag);
n -= DIM(oid_pkcs_12_CrlBag);
iscrlbag = 1;
}
else if ( ti.length == DIM(oid_pkcs_12_keyBag)
&& !memcmp (p, oid_pkcs_12_keyBag, DIM(oid_pkcs_12_keyBag)))
{
/* The TrustedMIME plugin for MS Outlook started to create
files with just one outer 3DES encrypted container and
inside the certificates as well as the key. */
p += DIM(oid_pkcs_12_keyBag);
n -= DIM(oid_pkcs_12_keyBag);
iskeybag = 1;
}
else
goto bailout;
where = "certbag.before.certheader";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class != CLASS_CONTEXT || ti.tag)
goto bailout;
if (iscrlbag)
{
log_info ("skipping unsupported crlBag\n");
p += ti.length;
n -= ti.length;
}
else if (iskeybag && (result || !r_result))
{
log_info ("one keyBag already processed; skipping this one\n");
p += ti.length;
n -= ti.length;
}
else if (iskeybag)
{
int len;
log_info ("processing simple keyBag\n");
/* Fixme: This code is duplicated from parse_bag_data. */
if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_INTEGER
|| ti.length != 1 || *p)
goto bailout;
p++; n--;
if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
len = ti.length;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (len < ti.nhdr)
goto bailout;
len -= ti.nhdr;
if (ti.class || ti.tag != TAG_OBJECT_ID
|| ti.length != DIM(oid_rsaEncryption)
|| memcmp (p, oid_rsaEncryption,
DIM(oid_rsaEncryption)))
goto bailout;
p += DIM (oid_rsaEncryption);
n -= DIM (oid_rsaEncryption);
if (len < ti.length)
goto bailout;
len -= ti.length;
if (n < len)
goto bailout;
p += len;
n -= len;
if ( parse_tag (&p, &n, &ti)
|| ti.class || ti.tag != TAG_OCTET_STRING)
goto bailout;
if ( parse_tag (&p, &n, &ti)
|| ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
len = ti.length;
result = gcry_calloc (10, sizeof *result);
if (!result)
{
log_error ( "error allocating result array\n");
goto bailout;
}
result_count = 0;
where = "reading.keybag.key-parameters";
for (result_count = 0; len && result_count < 9;)
{
if ( parse_tag (&p, &n, &ti)
|| ti.class || ti.tag != TAG_INTEGER)
goto bailout;
if (len < ti.nhdr)
goto bailout;
len -= ti.nhdr;
if (len < ti.length)
goto bailout;
len -= ti.length;
if (!result_count && ti.length == 1 && !*p)
; /* ignore the very first one if it is a 0 */
else
{
int rc;
rc = gcry_mpi_scan (result+result_count, GCRYMPI_FMT_USG, p,
ti.length, NULL);
if (rc)
{
log_error ("error parsing key parameter: %s\n",
gpg_strerror (rc));
goto bailout;
}
result_count++;
}
p += ti.length;
n -= ti.length;
}
if (len)
goto bailout;
}
else
{
log_info ("processing certBag\n");
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_OBJECT_ID
|| ti.length != DIM(oid_x509Certificate_for_pkcs_12)
|| memcmp (p, oid_x509Certificate_for_pkcs_12,
DIM(oid_x509Certificate_for_pkcs_12)))
goto bailout;
p += DIM(oid_x509Certificate_for_pkcs_12);
n -= DIM(oid_x509Certificate_for_pkcs_12);
where = "certbag.before.octetstring";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class != CLASS_CONTEXT || ti.tag)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_OCTET_STRING || ti.ndef)
goto bailout;
/* Return the certificate. */
if (certcb)
certcb (certcbarg, p, ti.length);
p += ti.length;
n -= ti.length;
}
/* Ugly hack to cope with the padding: Forget about the rest if
that is less or equal to the cipher's block length. We can
reasonable assume that all valid data will be longer than
just one block. */
if (n <= (is_pbes2? 16:8))
n = 0;
/* Skip the optional SET with the pkcs12 cert attributes. */
if (n)
{
where = "bag.attributes";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (!ti.class && ti.tag == TAG_SEQUENCE)
; /* No attributes. */
else if (!ti.class && ti.tag == TAG_SET && !ti.ndef)
{ /* The optional SET. */
p += ti.length;
n -= ti.length;
if (n <= (is_pbes2?16:8))
n = 0;
if (n && parse_tag (&p, &n, &ti))
goto bailout;
}
else
goto bailout;
}
}
if (r_consumed)
*r_consumed = consumed;
gcry_free (plain);
gcry_free (cram_buffer);
if (r_result)
*r_result = result;
return 0;
bailout:
if (result)
{
int i;
for (i=0; result[i]; i++)
gcry_mpi_release (result[i]);
gcry_free (result);
}
if (r_consumed)
*r_consumed = consumed;
gcry_free (plain);
gcry_free (cram_buffer);
log_error ("encryptedData error at \"%s\", offset %u\n",
where, (unsigned int)((p - p_start)+startoffset));
if (bad_pass)
{
/* Note, that the following string might be used by other programs
to check for a bad passphrase; it should therefore not be
translated or changed. */
log_error ("possibly bad passphrase given\n");
*r_badpass = 1;
}
return -1;
}
/* Return true if the decryption of a bag_data object has likely
succeeded. */
static int
bag_data_p (const void *plaintext, size_t length)
{
struct tag_info ti;
const unsigned char *p = plaintext;
size_t n = length;
/* { */
/* # warning debug code is enabled */
/* FILE *fp = fopen ("tmp-minip12-plain-key.der", "wb"); */
/* if (!fp || fwrite (p, n, 1, fp) != 1) */
/* exit (2); */
/* fclose (fp); */
/* } */
if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_SEQUENCE)
return 0;
if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_INTEGER
|| ti.length != 1 || *p)
return 0;
return 1;
}
static gcry_mpi_t *
parse_bag_data (const unsigned char *buffer, size_t length, int startoffset,
size_t *r_consumed, char **r_curve, const char *pw)
{
int rc;
struct tag_info ti;
const unsigned char *p = buffer;
const unsigned char *p_start = buffer;
size_t n = length;
const char *where;
char salt[20];
size_t saltlen;
char iv[16];
unsigned int iter;
int len;
unsigned char *plain = NULL;
gcry_mpi_t *result = NULL;
int result_count, i;
unsigned char *cram_buffer = NULL;
size_t consumed = 0; /* Number of bytes consumed from the original buffer. */
int is_pbes2 = 0;
char *curve = NULL;
where = "start";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class != CLASS_CONTEXT || ti.tag)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_OCTET_STRING)
goto bailout;
consumed = p - p_start;
if (ti.is_constructed && ti.ndef)
{
/* Mozilla exported certs now come with single byte chunks of
octet strings. (Mozilla Firefox 1.0.4). Arghh. */
where = "cram-data.outersegs";
cram_buffer = cram_octet_string ( p, &n, &consumed);
if (!cram_buffer)
goto bailout;
p = p_start = cram_buffer;
if (r_consumed)
*r_consumed = consumed;
r_consumed = NULL; /* Ugly hack to not update that value any further. */
}
where = "data.outerseqs";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
where = "data.objectidentifier";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_OBJECT_ID
|| ti.length != DIM(oid_pkcs_12_pkcs_8ShroudedKeyBag)
|| memcmp (p, oid_pkcs_12_pkcs_8ShroudedKeyBag,
DIM(oid_pkcs_12_pkcs_8ShroudedKeyBag)))
goto bailout;
p += DIM(oid_pkcs_12_pkcs_8ShroudedKeyBag);
n -= DIM(oid_pkcs_12_pkcs_8ShroudedKeyBag);
where = "shrouded,outerseqs";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class != CLASS_CONTEXT || ti.tag)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class == 0 && ti.tag == TAG_OBJECT_ID
&& ti.length == DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC)
&& !memcmp (p, oid_pbeWithSHAAnd3_KeyTripleDES_CBC,
DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC)))
{
p += DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC);
n -= DIM(oid_pbeWithSHAAnd3_KeyTripleDES_CBC);
}
else if (ti.class == 0 && ti.tag == TAG_OBJECT_ID
&& ti.length == DIM(oid_pkcs5PBES2)
&& !memcmp (p, oid_pkcs5PBES2, DIM(oid_pkcs5PBES2)))
{
p += DIM(oid_pkcs5PBES2);
n -= DIM(oid_pkcs5PBES2);
is_pbes2 = 1;
}
else
goto bailout;
if (is_pbes2)
{
where = "pkcs5PBES2-params";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (!(!ti.class && ti.tag == TAG_OBJECT_ID
&& ti.length == DIM(oid_pkcs5PBKDF2)
&& !memcmp (p, oid_pkcs5PBKDF2, ti.length)))
goto bailout; /* Not PBKDF2. */
p += ti.length;
n -= ti.length;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (!(!ti.class && ti.tag == TAG_OCTET_STRING
&& ti.length >= 8 && ti.length < sizeof salt))
goto bailout; /* No salt or unsupported length. */
saltlen = ti.length;
memcpy (salt, p, saltlen);
p += saltlen;
n -= saltlen;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (!(!ti.class && ti.tag == TAG_INTEGER && ti.length))
goto bailout; /* No valid iteration count. */
for (iter=0; ti.length; ti.length--)
{
iter <<= 8;
iter |= (*p++) & 0xff;
n--;
}
/* Note: We don't support the optional parameters but assume
that the algorithmIdentifier follows. */
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (!(!ti.class && ti.tag == TAG_OBJECT_ID
&& ti.length == DIM(oid_aes128_CBC)
&& !memcmp (p, oid_aes128_CBC, ti.length)))
goto bailout; /* Not AES-128. */
p += ti.length;
n -= ti.length;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (!(!ti.class && ti.tag == TAG_OCTET_STRING && ti.length == sizeof iv))
goto bailout; /* Bad IV. */
memcpy (iv, p, sizeof iv);
p += sizeof iv;
n -= sizeof iv;
}
else
{
where = "3des-params";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_OCTET_STRING
|| ti.length < 8 || ti.length > 20)
goto bailout;
saltlen = ti.length;
memcpy (salt, p, saltlen);
p += saltlen;
n -= saltlen;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_INTEGER || !ti.length )
goto bailout;
for (iter=0; ti.length; ti.length--)
{
iter <<= 8;
iter |= (*p++) & 0xff;
n--;
}
}
where = "3desoraes-ciphertext";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class || ti.tag != TAG_OCTET_STRING || !ti.length )
goto bailout;
log_info ("%lu bytes of %s encrypted text\n",
ti.length, is_pbes2? "AES128":"3DES");
plain = gcry_malloc_secure (ti.length);
if (!plain)
{
log_error ("error allocating decryption buffer\n");
goto bailout;
}
consumed += p - p_start + ti.length;
decrypt_block (p, plain, ti.length, salt, saltlen, iter,
iv, is_pbes2? 16:0, pw,
is_pbes2? GCRY_CIPHER_AES128 : GCRY_CIPHER_3DES,
bag_data_p);
n = ti.length;
startoffset = 0;
p_start = p = plain;
where = "decrypted-text";
if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_INTEGER
|| ti.length != 1 || *p)
goto bailout;
p++; n--;
if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
len = ti.length;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (len < ti.nhdr)
goto bailout;
len -= ti.nhdr;
if (ti.class || ti.tag != TAG_OBJECT_ID)
goto bailout;
/* gpgrt_log_printhex (p, ti.length, "OID:"); */
if (ti.length == DIM(oid_rsaEncryption)
&& !memcmp (p, oid_rsaEncryption, DIM(oid_rsaEncryption)))
{
p += DIM (oid_rsaEncryption);
n -= DIM (oid_rsaEncryption);
}
else if (ti.length == DIM(oid_pcPublicKey)
&& !memcmp (p, oid_pcPublicKey, DIM(oid_pcPublicKey)))
{
/* See RFC-5915 for the format. */
p += DIM (oid_pcPublicKey);
n -= DIM (oid_pcPublicKey);
if (len < ti.length)
goto bailout;
len -= ti.length;
if (n < len)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
/* gpgrt_log_debug ("ti=%d/%lu len=%lu\n",ti.class,ti.tag,ti.length); */
if (len < ti.nhdr)
goto bailout;
len -= ti.nhdr;
if (ti.class || ti.tag != TAG_OBJECT_ID)
goto bailout;
curve = ksba_oid_to_str (p, ti.length);
if (!curve)
goto bailout;
/* log_debug ("OID of curve is: %s\n", curve); */
p += ti.length;
n -= ti.length;
}
else
goto bailout;
if (len < ti.length)
goto bailout;
len -= ti.length;
if (n < len)
goto bailout;
p += len;
n -= len;
if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_OCTET_STRING)
goto bailout;
if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_SEQUENCE)
goto bailout;
len = ti.length;
result = gcry_calloc (10, sizeof *result);
if (!result)
{
log_error ( "error allocating result array\n");
goto bailout;
}
result_count = 0;
where = "reading.key-parameters";
if (curve) /* ECC case. */
{
if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_INTEGER)
goto bailout;
if (len < ti.nhdr)
goto bailout;
len -= ti.nhdr;
if (len < ti.length)
goto bailout;
len -= ti.length;
if (ti.length != 1 && *p != 1)
{
log_error ("error parsing private ecPublicKey parameter: %s\n",
"bad version");
goto bailout;
}
p += ti.length;
n -= ti.length;
if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_OCTET_STRING)
goto bailout;
if (len < ti.nhdr)
goto bailout;
len -= ti.nhdr;
if (len < ti.length)
goto bailout;
len -= ti.length;
/* log_printhex (p, ti.length, "ecc q="); */
rc = gcry_mpi_scan (result, GCRYMPI_FMT_USG, p, ti.length, NULL);
if (rc)
{
log_error ("error parsing key parameter: %s\n", gpg_strerror (rc));
goto bailout;
}
p += ti.length;
n -= ti.length;
len = 0; /* Skip the rest. */
}
else /* RSA case */
{
for (result_count=0; len && result_count < 9;)
{
if (parse_tag (&p, &n, &ti) || ti.class || ti.tag != TAG_INTEGER)
goto bailout;
if (len < ti.nhdr)
goto bailout;
len -= ti.nhdr;
if (len < ti.length)
goto bailout;
len -= ti.length;
if (!result_count && ti.length == 1 && !*p)
; /* ignore the very first one if it is a 0 */
else
{
rc = gcry_mpi_scan (result+result_count, GCRYMPI_FMT_USG, p,
ti.length, NULL);
if (rc)
{
log_error ("error parsing key parameter: %s\n",
gpg_strerror (rc));
goto bailout;
}
result_count++;
}
p += ti.length;
n -= ti.length;
}
}
if (len)
goto bailout;
goto leave;
bailout:
gcry_free (plain);
if (result)
{
for (i=0; result[i]; i++)
gcry_mpi_release (result[i]);
gcry_free (result);
}
log_error ( "data error at \"%s\", offset %u\n",
where, (unsigned int)((p - buffer) + startoffset));
result = NULL;
leave:
if (r_curve && result)
{
*r_curve = curve;
curve = NULL;
}
else if (r_curve)
*r_curve = NULL;
ksba_free (curve);
gcry_free (cram_buffer);
if (r_consumed)
*r_consumed = consumed;
return result;
}
/* Parse a PKCS12 object and return an array of MPI representing the
secret key parameters. This is a very limited implementation in
that it is only able to look for 3DES encoded encryptedData and
tries to extract the first private key object it finds. In case of
an error NULL is returned. CERTCB and CERRTCBARG are used to pass
X.509 certificates back to the caller. */
gcry_mpi_t *
p12_parse (const unsigned char *buffer, size_t length, const char *pw,
void (*certcb)(void*, const unsigned char*, size_t),
void *certcbarg, int *r_badpass, char **r_curve)
{
struct tag_info ti;
const unsigned char *p = buffer;
const unsigned char *p_start = buffer;
size_t n = length;
const char *where;
int bagseqlength, len;
int bagseqndef, lenndef;
gcry_mpi_t *result = NULL;
unsigned char *cram_buffer = NULL;
char *curve = NULL;
*r_badpass = 0;
where = "pfx";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.tag != TAG_SEQUENCE)
goto bailout;
where = "pfxVersion";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.tag != TAG_INTEGER || ti.length != 1 || *p != 3)
goto bailout;
p++; n--;
where = "authSave";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.tag != TAG_SEQUENCE)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.tag != TAG_OBJECT_ID || ti.length != DIM(oid_data)
|| memcmp (p, oid_data, DIM(oid_data)))
goto bailout;
p += DIM(oid_data);
n -= DIM(oid_data);
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class != CLASS_CONTEXT || ti.tag)
goto bailout;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class != CLASS_UNIVERSAL || ti.tag != TAG_OCTET_STRING)
goto bailout;
if (ti.is_constructed && ti.ndef)
{
/* Mozilla exported certs now come with single byte chunks of
octet strings. (Mozilla Firefox 1.0.4). Arghh. */
where = "cram-bags";
cram_buffer = cram_octet_string ( p, &n, NULL);
if (!cram_buffer)
goto bailout;
p = p_start = cram_buffer;
}
where = "bags";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (ti.class != CLASS_UNIVERSAL || ti.tag != TAG_SEQUENCE)
goto bailout;
bagseqndef = ti.ndef;
bagseqlength = ti.length;
while (bagseqlength || bagseqndef)
{
/* log_debug ( "at offset %u\n", (p - p_start)); */
where = "bag-sequence";
if (parse_tag (&p, &n, &ti))
goto bailout;
if (bagseqndef && ti.class == CLASS_UNIVERSAL
&& !ti.tag && !ti.is_constructed)
break; /* Ready */
if (ti.class != CLASS_UNIVERSAL || ti.tag != TAG_SEQUENCE)
goto bailout;
if (!bagseqndef)
{
if (bagseqlength < ti.nhdr)
goto bailout;
bagseqlength -= ti.nhdr;
if (bagseqlength < ti.length)
goto bailout;
bagseqlength -= ti.length;
}
lenndef = ti.ndef;
len = ti.length;
if (parse_tag (&p, &n, &ti))
goto bailout;
if (lenndef)
len = ti.nhdr;
else
len -= ti.nhdr;
if (ti.tag == TAG_OBJECT_ID && ti.length == DIM(oid_encryptedData)
&& !memcmp (p, oid_encryptedData, DIM(oid_encryptedData)))
{
size_t consumed = 0;
p += DIM(oid_encryptedData);
n -= DIM(oid_encryptedData);
if (!lenndef)
len -= DIM(oid_encryptedData);
where = "bag.encryptedData";
if (parse_bag_encrypted_data (p, n, (p - p_start), &consumed, pw,
certcb, certcbarg,
result? NULL : &result, r_badpass))
goto bailout;
if (lenndef)
len += consumed;
}
else if (ti.tag == TAG_OBJECT_ID && ti.length == DIM(oid_data)
&& !memcmp (p, oid_data, DIM(oid_data)))
{
if (result)
{
log_info ("already got an key object, skipping this one\n");
p += ti.length;
n -= ti.length;
}
else
{
size_t consumed = 0;
p += DIM(oid_data);
n -= DIM(oid_data);
if (!lenndef)
len -= DIM(oid_data);
result = parse_bag_data (p, n, (p - p_start),
&consumed, &curve, pw);
if (!result)
goto bailout;
if (lenndef)
len += consumed;
}
}
else
{
log_info ("unknown bag type - skipped\n");
p += ti.length;
n -= ti.length;
}
if (len < 0 || len > n)
goto bailout;
p += len;
n -= len;
if (lenndef)
{
/* Need to skip the Null Tag. */
if (parse_tag (&p, &n, &ti))
goto bailout;
if (!(ti.class == CLASS_UNIVERSAL && !ti.tag && !ti.is_constructed))
goto bailout;
}
}
gcry_free (cram_buffer);
*r_curve = curve;
return result;
bailout:
log_error ("error at \"%s\", offset %u\n",
where, (unsigned int)(p - p_start));
if (result)
{
int i;
for (i=0; result[i]; i++)
gcry_mpi_release (result[i]);
gcry_free (result);
}
gcry_free (cram_buffer);
gcry_free (curve);
*r_curve = NULL;
return NULL;
}
static size_t
compute_tag_length (size_t n)
{
int needed = 0;
if (n < 128)
needed += 2; /* tag and one length byte */
else if (n < 256)
needed += 3; /* tag, number of length bytes, 1 length byte */
else if (n < 65536)
needed += 4; /* tag, number of length bytes, 2 length bytes */
else
{
log_error ("object too larger to encode\n");
return 0;
}
return needed;
}
static unsigned char *
store_tag_length (unsigned char *p, int tag, size_t n)
{
if (tag == TAG_SEQUENCE)
tag |= 0x20; /* constructed */
*p++ = tag;
if (n < 128)
*p++ = n;
else if (n < 256)
{
*p++ = 0x81;
*p++ = n;
}
else if (n < 65536)
{
*p++ = 0x82;
*p++ = n >> 8;
*p++ = n;
}
return p;
}
/* Create the final PKCS-12 object from the sequences contained in
SEQLIST. PW is the password. That array is terminated with an NULL
object. */
static unsigned char *
create_final (struct buffer_s *sequences, const char *pw, size_t *r_length)
{
int i;
size_t needed = 0;
size_t len[8], n;
unsigned char *macstart;
size_t maclen;
unsigned char *result, *p;
size_t resultlen;
char salt[8];
unsigned char keybuf[20];
gcry_md_hd_t md;
int rc;
int with_mac = 1;
/* 9 steps to create the pkcs#12 Krampf. */
/* 8. The MAC. */
/* We add this at step 0. */
/* 7. All the buffers. */
for (i=0; sequences[i].buffer; i++)
needed += sequences[i].length;
/* 6. This goes into a sequences. */
len[6] = needed;
n = compute_tag_length (needed);
needed += n;
/* 5. Encapsulate all in an octet string. */
len[5] = needed;
n = compute_tag_length (needed);
needed += n;
/* 4. And tag it with [0]. */
len[4] = needed;
n = compute_tag_length (needed);
needed += n;
/* 3. Prepend an data OID. */
needed += 2 + DIM (oid_data);
/* 2. Put all into a sequences. */
len[2] = needed;
n = compute_tag_length (needed);
needed += n;
/* 1. Prepend the version integer 3. */
needed += 3;
/* 0. And the final outer sequence. */
if (with_mac)
needed += DIM (data_mactemplate);
len[0] = needed;
n = compute_tag_length (needed);
needed += n;
/* Allocate a buffer. */
result = gcry_malloc (needed);
if (!result)
{
log_error ("error allocating buffer\n");
return NULL;
}
p = result;
/* 0. Store the very outer sequence. */
p = store_tag_length (p, TAG_SEQUENCE, len[0]);
/* 1. Store the version integer 3. */
*p++ = TAG_INTEGER;
*p++ = 1;
*p++ = 3;
/* 2. Store another sequence. */
p = store_tag_length (p, TAG_SEQUENCE, len[2]);
/* 3. Store the data OID. */
p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_data));
memcpy (p, oid_data, DIM (oid_data));
p += DIM (oid_data);
/* 4. Next comes a context tag. */
p = store_tag_length (p, 0xa0, len[4]);
/* 5. And an octet string. */
p = store_tag_length (p, TAG_OCTET_STRING, len[5]);
/* 6. And the inner sequence. */
macstart = p;
p = store_tag_length (p, TAG_SEQUENCE, len[6]);
/* 7. Append all the buffers. */
for (i=0; sequences[i].buffer; i++)
{
memcpy (p, sequences[i].buffer, sequences[i].length);
p += sequences[i].length;
}
if (with_mac)
{
/* Intermezzo to compute the MAC. */
maclen = p - macstart;
gcry_randomize (salt, 8, GCRY_STRONG_RANDOM);
if (string_to_key (3, salt, 8, 2048, pw, 20, keybuf))
{
gcry_free (result);
return NULL;
}
rc = gcry_md_open (&md, GCRY_MD_SHA1, GCRY_MD_FLAG_HMAC);
if (rc)
{
log_error ("gcry_md_open failed: %s\n", gpg_strerror (rc));
gcry_free (result);
return NULL;
}
rc = gcry_md_setkey (md, keybuf, 20);
if (rc)
{
log_error ("gcry_md_setkey failed: %s\n", gpg_strerror (rc));
gcry_md_close (md);
gcry_free (result);
return NULL;
}
gcry_md_write (md, macstart, maclen);
/* 8. Append the MAC template and fix it up. */
memcpy (p, data_mactemplate, DIM (data_mactemplate));
memcpy (p + DATA_MACTEMPLATE_SALT_OFF, salt, 8);
memcpy (p + DATA_MACTEMPLATE_MAC_OFF, gcry_md_read (md, 0), 20);
p += DIM (data_mactemplate);
gcry_md_close (md);
}
/* Ready. */
resultlen = p - result;
if (needed != resultlen)
log_debug ("length mismatch: %lu, %lu\n",
(unsigned long)needed, (unsigned long)resultlen);
*r_length = resultlen;
return result;
}
/* Build a DER encoded SEQUENCE with the key:
*
* SEQUENCE { -- OneAsymmetricKey (RFC-5958)
* INTEGER 0
* SEQUENCE {
* OBJECT IDENTIFIER rsaEncryption (1 2 840 113549 1 1 1)
* NULL
* }
* OCTET STRING, encapsulates {
* SEQUENCE { -- RSAPrivateKey (RFC-3447)
* INTEGER 0 -- Version
* INTEGER -- n
* INTEGER -- e
* INTEGER -- d
* INTEGER -- p
* INTEGER -- q
* INTEGER -- d mod (p-1)
* INTEGER -- d mod (q-1)
* INTEGER -- q^-1 mod p
* }
* }
* }
*
* MODE controls what is being generated:
* 0 - As described above
* 1 - Ditto but without the padding
* 2 - Only the inner part (pkcs#1)
*/
static unsigned char *
build_rsa_key_sequence (gcry_mpi_t *kparms, int mode, size_t *r_length)
{
int rc, i;
size_t needed, n;
unsigned char *plain, *p;
size_t plainlen;
size_t outseqlen, oidseqlen, octstrlen, inseqlen;
needed = 3; /* The version integer with value 0. */
for (i=0; kparms[i]; i++)
{
n = 0;
rc = gcry_mpi_print (GCRYMPI_FMT_STD, NULL, 0, &n, kparms[i]);
if (rc)
{
log_error ("error formatting parameter: %s\n", gpg_strerror (rc));
return NULL;
}
needed += n;
n = compute_tag_length (n);
if (!n)
return NULL;
needed += n;
}
if (i != 8)
{
log_error ("invalid parameters for p12_build\n");
return NULL;
}
/* Now this all goes into a sequence. */
inseqlen = needed;
n = compute_tag_length (needed);
if (!n)
return NULL;
needed += n;
if (mode != 2)
{
/* Encapsulate all into an octet string. */
octstrlen = needed;
n = compute_tag_length (needed);
if (!n)
return NULL;
needed += n;
/* Prepend the object identifier sequence. */
oidseqlen = 2 + DIM (oid_rsaEncryption) + 2;
needed += 2 + oidseqlen;
/* The version number. */
needed += 3;
/* And finally put the whole thing into a sequence. */
outseqlen = needed;
n = compute_tag_length (needed);
if (!n)
return NULL;
needed += n;
}
/* allocate 8 extra bytes for padding */
plain = gcry_malloc_secure (needed+8);
if (!plain)
{
log_error ("error allocating encryption buffer\n");
return NULL;
}
/* And now fill the plaintext buffer. */
p = plain;
if (mode != 2)
{
p = store_tag_length (p, TAG_SEQUENCE, outseqlen);
/* Store version. */
*p++ = TAG_INTEGER;
*p++ = 1;
*p++ = 0;
/* Store object identifier sequence. */
p = store_tag_length (p, TAG_SEQUENCE, oidseqlen);
p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_rsaEncryption));
memcpy (p, oid_rsaEncryption, DIM (oid_rsaEncryption));
p += DIM (oid_rsaEncryption);
*p++ = TAG_NULL;
*p++ = 0;
/* Start with the octet string. */
p = store_tag_length (p, TAG_OCTET_STRING, octstrlen);
}
p = store_tag_length (p, TAG_SEQUENCE, inseqlen);
/* Store the key parameters. */
*p++ = TAG_INTEGER;
*p++ = 1;
*p++ = 0;
for (i=0; kparms[i]; i++)
{
n = 0;
rc = gcry_mpi_print (GCRYMPI_FMT_STD, NULL, 0, &n, kparms[i]);
if (rc)
{
log_error ("oops: error formatting parameter: %s\n",
gpg_strerror (rc));
gcry_free (plain);
return NULL;
}
p = store_tag_length (p, TAG_INTEGER, n);
n = plain + needed - p;
rc = gcry_mpi_print (GCRYMPI_FMT_STD, p, n, &n, kparms[i]);
if (rc)
{
log_error ("oops: error storing parameter: %s\n",
gpg_strerror (rc));
gcry_free (plain);
return NULL;
}
p += n;
}
plainlen = p - plain;
assert (needed == plainlen);
if (!mode)
{
/* Append some pad characters; we already allocated extra space. */
n = 8 - plainlen % 8;
for (i=0; i < n; i++, plainlen++)
*p++ = n;
}
*r_length = plainlen;
return plain;
}
/* Build a DER encoded SEQUENCE for an ECC key:
*
* SEQUENCE { -- OneAsymmetricKey (RFC-5958)
* INTEGER 0
* SEQUENCE {
* OBJECT IDENTIFIER ecPublicKey (1 2 840 10045 2 1)
* OBJECT IDENTIFIER -- curvename
* }
* OCTET STRING, encapsulates {
* SEQUENCE { -- ECPrivateKey
* INTEGER 1 -- version
* OCTET STRING -- privateKey
* [1] {
* BIT STRING - publicKey
* }
* }
* }
* }
*
* For details see RFC-5480 and RFC-5915 (ECparameters are not created).
*
* KPARMS[0] := Opaque MPI with the curve name as dotted-decimal string.
* KPARMS[1] := Opaque MPI with the pgublic key (q)
* KPARMS[2] := Opaque MPI with the private key (d)
* MODE controls what is being generated:
* 0 - As described above
* 1 - Ditto but without the extra padding needed for pcsk#12
* 2 - Only the octet string (ECPrivateKey)
*/
static unsigned char *
build_ecc_key_sequence (gcry_mpi_t *kparms, int mode, size_t *r_length)
{
gpg_error_t err;
unsigned int nbits, n;
const unsigned char *s;
char *p;
tlv_builder_t tb;
void *result;
size_t resultlen;
const char *curve;
unsigned int curvebits;
int e;
int i;
int strip_one;
for (i=0; kparms[i]; i++)
;
if (i != 3)
{
log_error ("%s: invalid number of parameters\n", __func__);
return NULL;
}
s = gcry_mpi_get_opaque (kparms[0], &nbits);
n = (nbits+7)/8;
p = xtrymalloc (n + 1);
if (!p)
{
err = gpg_error_from_syserror ();
log_error ("%s:%d: error getting parameter: %s\n",
__func__, __LINE__, gpg_strerror (err));
return NULL;
}
memcpy (p, s, n);
p[n] = 0;
/* We need to use our OpenPGP mapping to turn a curve name into its
* canonical numerical OID. We should have a Libgcrypt function to
* do this; see bug report #4926. */
curve = openpgp_curve_to_oid (p, &curvebits, NULL);
xfree (p);
if (!curve)
{
err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
log_error ("%s:%d: error getting parameter: %s\n",
__func__, __LINE__, gpg_strerror (err));
return NULL;
}
/* Unfortunately the private key D may come with a single leading
* zero byte. This is becuase at some point it was treated as
* signed MPI and the code made sure that it is always interpreted
* as unsigned. Fortunately we got the size of the curve and can
* detect such a case reliable. */
s = gcry_mpi_get_opaque (kparms[2], &nbits);
n = (nbits+7)/8;
strip_one = (n == (curvebits+7)/8 + 1 && !*s);
tb = tlv_builder_new (1);
if (!tb)
{
err = gpg_error_from_syserror ();
log_error ("%s:%d: error creating new TLV builder: %s\n",
__func__, __LINE__, gpg_strerror (err));
return NULL;
}
e = 0;
tlv_builder_add_tag (tb, 0, TAG_SEQUENCE);
tlv_builder_add_ptr (tb, 0, TAG_INTEGER, "\0", 1);
tlv_builder_add_tag (tb, 0, TAG_SEQUENCE);
e|= builder_add_oid (tb, 0, "1.2.840.10045.2.1");
e|= builder_add_oid (tb, 0, curve);
tlv_builder_add_end (tb);
tlv_builder_add_tag (tb, 0, TAG_OCTET_STRING);
tlv_builder_add_tag (tb, 0, TAG_SEQUENCE);
tlv_builder_add_ptr (tb, 0, TAG_INTEGER, "\x01", 1);
e|= builder_add_mpi (tb, 0, TAG_OCTET_STRING, kparms[2], strip_one);
tlv_builder_add_tag (tb, CLASS_CONTEXT, 1);
e|= builder_add_mpi (tb, 0, TAG_BIT_STRING, kparms[1], 0);
tlv_builder_add_end (tb);
tlv_builder_add_end (tb);
tlv_builder_add_end (tb);
tlv_builder_add_end (tb);
err = tlv_builder_finalize (tb, &result, &resultlen);
if (err || e)
{
if (!err)
err = gpg_error (GPG_ERR_GENERAL);
log_error ("%s:%d: tlv building failed: %s\n",
__func__, __LINE__, gpg_strerror (err));
return NULL;
}
/* Append some pad characters if needed. */
if (!mode && (n = 8 - resultlen % 8))
{
p = xtrymalloc_secure (resultlen + n);
if (!p)
{
err = gpg_error_from_syserror ();
log_error ("%s:%d: error allocating buffer: %s\n",
__func__, __LINE__, gpg_strerror (err));
xfree (result);
return NULL;
}
memcpy (p, result, resultlen);
xfree (result);
result = p;
p = (unsigned char*)result + resultlen;
for (i=0; i < n; i++, resultlen++)
*p++ = n;
}
*r_length = resultlen;
return result;
}
static unsigned char *
build_key_bag (unsigned char *buffer, size_t buflen, char *salt,
const unsigned char *sha1hash, const char *keyidstr,
size_t *r_length)
{
size_t len[11], needed;
unsigned char *p, *keybag;
size_t keybaglen;
/* Walk 11 steps down to collect the info: */
/* 10. The data goes into an octet string. */
needed = compute_tag_length (buflen);
needed += buflen;
/* 9. Prepend the algorithm identifier. */
needed += DIM (data_3desiter2048);
/* 8. Put a sequence around. */
len[8] = needed;
needed += compute_tag_length (needed);
/* 7. Prepend a [0] tag. */
len[7] = needed;
needed += compute_tag_length (needed);
/* 6b. The attributes which are appended at the end. */
if (sha1hash)
needed += DIM (data_attrtemplate) + 20;
/* 6. Prepend the shroudedKeyBag OID. */
needed += 2 + DIM (oid_pkcs_12_pkcs_8ShroudedKeyBag);
/* 5+4. Put all into two sequences. */
len[5] = needed;
needed += compute_tag_length ( needed);
len[4] = needed;
needed += compute_tag_length (needed);
/* 3. This all goes into an octet string. */
len[3] = needed;
needed += compute_tag_length (needed);
/* 2. Prepend another [0] tag. */
len[2] = needed;
needed += compute_tag_length (needed);
/* 1. Prepend the data OID. */
needed += 2 + DIM (oid_data);
/* 0. Prepend another sequence. */
len[0] = needed;
needed += compute_tag_length (needed);
/* Now that we have all length information, allocate a buffer. */
p = keybag = gcry_malloc (needed);
if (!keybag)
{
log_error ("error allocating buffer\n");
return NULL;
}
/* Walk 11 steps up to store the data. */
/* 0. Store the first sequence. */
p = store_tag_length (p, TAG_SEQUENCE, len[0]);
/* 1. Store the data OID. */
p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_data));
memcpy (p, oid_data, DIM (oid_data));
p += DIM (oid_data);
/* 2. Store a [0] tag. */
p = store_tag_length (p, 0xa0, len[2]);
/* 3. And an octet string. */
p = store_tag_length (p, TAG_OCTET_STRING, len[3]);
/* 4+5. Two sequences. */
p = store_tag_length (p, TAG_SEQUENCE, len[4]);
p = store_tag_length (p, TAG_SEQUENCE, len[5]);
/* 6. Store the shroudedKeyBag OID. */
p = store_tag_length (p, TAG_OBJECT_ID,
DIM (oid_pkcs_12_pkcs_8ShroudedKeyBag));
memcpy (p, oid_pkcs_12_pkcs_8ShroudedKeyBag,
DIM (oid_pkcs_12_pkcs_8ShroudedKeyBag));
p += DIM (oid_pkcs_12_pkcs_8ShroudedKeyBag);
/* 7. Store a [0] tag. */
p = store_tag_length (p, 0xa0, len[7]);
/* 8. Store a sequence. */
p = store_tag_length (p, TAG_SEQUENCE, len[8]);
/* 9. Now for the pre-encoded algorithm identifier and the salt. */
memcpy (p, data_3desiter2048, DIM (data_3desiter2048));
memcpy (p + DATA_3DESITER2048_SALT_OFF, salt, 8);
p += DIM (data_3desiter2048);
/* 10. And the octet string with the encrypted data. */
p = store_tag_length (p, TAG_OCTET_STRING, buflen);
memcpy (p, buffer, buflen);
p += buflen;
/* Append the attributes whose length we calculated at step 2b. */
if (sha1hash)
{
int i;
memcpy (p, data_attrtemplate, DIM (data_attrtemplate));
for (i=0; i < 8; i++)
p[DATA_ATTRTEMPLATE_KEYID_OFF+2*i+1] = keyidstr[i];
p += DIM (data_attrtemplate);
memcpy (p, sha1hash, 20);
p += 20;
}
keybaglen = p - keybag;
if (needed != keybaglen)
log_debug ("length mismatch: %lu, %lu\n",
(unsigned long)needed, (unsigned long)keybaglen);
*r_length = keybaglen;
return keybag;
}
static unsigned char *
build_cert_bag (unsigned char *buffer, size_t buflen, char *salt,
size_t *r_length)
{
size_t len[9], needed;
unsigned char *p, *certbag;
size_t certbaglen;
/* Walk 9 steps down to collect the info: */
/* 8. The data goes into an octet string. */
needed = compute_tag_length (buflen);
needed += buflen;
/* 7. The algorithm identifier. */
needed += DIM (data_rc2iter2048);
/* 6. The data OID. */
needed += 2 + DIM (oid_data);
/* 5. A sequence. */
len[5] = needed;
needed += compute_tag_length ( needed);
/* 4. An integer. */
needed += 3;
/* 3. A sequence. */
len[3] = needed;
needed += compute_tag_length (needed);
/* 2. A [0] tag. */
len[2] = needed;
needed += compute_tag_length (needed);
/* 1. The encryptedData OID. */
needed += 2 + DIM (oid_encryptedData);
/* 0. The first sequence. */
len[0] = needed;
needed += compute_tag_length (needed);
/* Now that we have all length information, allocate a buffer. */
p = certbag = gcry_malloc (needed);
if (!certbag)
{
log_error ("error allocating buffer\n");
return NULL;
}
/* Walk 9 steps up to store the data. */
/* 0. Store the first sequence. */
p = store_tag_length (p, TAG_SEQUENCE, len[0]);
/* 1. Store the encryptedData OID. */
p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_encryptedData));
memcpy (p, oid_encryptedData, DIM (oid_encryptedData));
p += DIM (oid_encryptedData);
/* 2. Store a [0] tag. */
p = store_tag_length (p, 0xa0, len[2]);
/* 3. Store a sequence. */
p = store_tag_length (p, TAG_SEQUENCE, len[3]);
/* 4. Store the integer 0. */
*p++ = TAG_INTEGER;
*p++ = 1;
*p++ = 0;
/* 5. Store a sequence. */
p = store_tag_length (p, TAG_SEQUENCE, len[5]);
/* 6. Store the data OID. */
p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_data));
memcpy (p, oid_data, DIM (oid_data));
p += DIM (oid_data);
/* 7. Now for the pre-encoded algorithm identifier and the salt. */
memcpy (p, data_rc2iter2048, DIM (data_rc2iter2048));
memcpy (p + DATA_RC2ITER2048_SALT_OFF, salt, 8);
p += DIM (data_rc2iter2048);
/* 8. And finally the [0] tag with the encrypted data. */
p = store_tag_length (p, 0x80, buflen);
memcpy (p, buffer, buflen);
p += buflen;
certbaglen = p - certbag;
if (needed != certbaglen)
log_debug ("length mismatch: %lu, %lu\n",
(unsigned long)needed, (unsigned long)certbaglen);
*r_length = certbaglen;
return certbag;
}
static unsigned char *
build_cert_sequence (const unsigned char *buffer, size_t buflen,
const unsigned char *sha1hash, const char *keyidstr,
size_t *r_length)
{
size_t len[8], needed, n;
unsigned char *p, *certseq;
size_t certseqlen;
int i;
assert (strlen (keyidstr) == 8);
/* Walk 8 steps down to collect the info: */
/* 7. The data goes into an octet string. */
needed = compute_tag_length (buflen);
needed += buflen;
/* 6. A [0] tag. */
len[6] = needed;
needed += compute_tag_length (needed);
/* 5. An OID. */
needed += 2 + DIM (oid_x509Certificate_for_pkcs_12);
/* 4. A sequence. */
len[4] = needed;
needed += compute_tag_length (needed);
/* 3. A [0] tag. */
len[3] = needed;
needed += compute_tag_length (needed);
/* 2b. The attributes which are appended at the end. */
if (sha1hash)
needed += DIM (data_attrtemplate) + 20;
/* 2. An OID. */
needed += 2 + DIM (oid_pkcs_12_CertBag);
/* 1. A sequence. */
len[1] = needed;
needed += compute_tag_length (needed);
/* 0. The first sequence. */
len[0] = needed;
needed += compute_tag_length (needed);
/* Now that we have all length information, allocate a buffer. */
p = certseq = gcry_malloc (needed + 8 /*(for padding)*/);
if (!certseq)
{
log_error ("error allocating buffer\n");
return NULL;
}
/* Walk 8 steps up to store the data. */
/* 0. Store the first sequence. */
p = store_tag_length (p, TAG_SEQUENCE, len[0]);
/* 1. Store the second sequence. */
p = store_tag_length (p, TAG_SEQUENCE, len[1]);
/* 2. Store the pkcs12-cert-bag OID. */
p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_pkcs_12_CertBag));
memcpy (p, oid_pkcs_12_CertBag, DIM (oid_pkcs_12_CertBag));
p += DIM (oid_pkcs_12_CertBag);
/* 3. Store a [0] tag. */
p = store_tag_length (p, 0xa0, len[3]);
/* 4. Store a sequence. */
p = store_tag_length (p, TAG_SEQUENCE, len[4]);
/* 5. Store the x509Certificate OID. */
p = store_tag_length (p, TAG_OBJECT_ID,
DIM (oid_x509Certificate_for_pkcs_12));
memcpy (p, oid_x509Certificate_for_pkcs_12,
DIM (oid_x509Certificate_for_pkcs_12));
p += DIM (oid_x509Certificate_for_pkcs_12);
/* 6. Store a [0] tag. */
p = store_tag_length (p, 0xa0, len[6]);
/* 7. And the octet string with the actual certificate. */
p = store_tag_length (p, TAG_OCTET_STRING, buflen);
memcpy (p, buffer, buflen);
p += buflen;
/* Append the attributes whose length we calculated at step 2b. */
if (sha1hash)
{
memcpy (p, data_attrtemplate, DIM (data_attrtemplate));
for (i=0; i < 8; i++)
p[DATA_ATTRTEMPLATE_KEYID_OFF+2*i+1] = keyidstr[i];
p += DIM (data_attrtemplate);
memcpy (p, sha1hash, 20);
p += 20;
}
certseqlen = p - certseq;
if (needed != certseqlen)
log_debug ("length mismatch: %lu, %lu\n",
(unsigned long)needed, (unsigned long)certseqlen);
/* Append some pad characters; we already allocated extra space. */
n = 8 - certseqlen % 8;
for (i=0; i < n; i++, certseqlen++)
*p++ = n;
*r_length = certseqlen;
return certseq;
}
/* Expect the RSA key parameters in KPARMS and a password in PW.
Create a PKCS structure from it and return it as well as the length
in R_LENGTH; return NULL in case of an error. If CHARSET is not
NULL, re-encode PW to that character set. */
unsigned char *
p12_build (gcry_mpi_t *kparms, const void *cert, size_t certlen,
const char *pw, const char *charset, size_t *r_length)
{
unsigned char *buffer = NULL;
size_t n, buflen;
char salt[8];
struct buffer_s seqlist[3];
int seqlistidx = 0;
unsigned char sha1hash[20];
char keyidstr[8+1];
char *pwbuf = NULL;
size_t pwbufsize = 0;
n = buflen = 0; /* (avoid compiler warning). */
memset (sha1hash, 0, 20);
*keyidstr = 0;
if (charset && pw && *pw)
{
jnlib_iconv_t cd;
const char *inptr;
char *outptr;
size_t inbytes, outbytes;
/* We assume that the converted passphrase is at max 2 times
longer than its utf-8 encoding. */
pwbufsize = strlen (pw)*2 + 1;
pwbuf = gcry_malloc_secure (pwbufsize);
if (!pwbuf)
{
log_error ("out of secure memory while converting passphrase\n");
goto failure;
}
cd = jnlib_iconv_open (charset, "utf-8");
if (cd == (jnlib_iconv_t)(-1))
{
log_error ("can't convert passphrase to"
" requested charset '%s': %s\n",
charset, strerror (errno));
goto failure;
}
inptr = pw;
inbytes = strlen (pw);
outptr = pwbuf;
outbytes = pwbufsize - 1;
if ( jnlib_iconv (cd, (const char **)&inptr, &inbytes,
&outptr, &outbytes) == (size_t)-1)
{
log_error ("error converting passphrase to"
" requested charset '%s': %s\n",
charset, strerror (errno));
jnlib_iconv_close (cd);
goto failure;
}
*outptr = 0;
jnlib_iconv_close (cd);
pw = pwbuf;
}
if (cert && certlen)
{
/* Calculate the hash value we need for the bag attributes. */
gcry_md_hash_buffer (GCRY_MD_SHA1, sha1hash, cert, certlen);
sprintf (keyidstr, "%02x%02x%02x%02x",
sha1hash[16], sha1hash[17], sha1hash[18], sha1hash[19]);
/* Encode the certificate. */
buffer = build_cert_sequence (cert, certlen, sha1hash, keyidstr,
&buflen);
if (!buffer)
goto failure;
/* Encrypt it. */
gcry_randomize (salt, 8, GCRY_STRONG_RANDOM);
crypt_block (buffer, buflen, salt, 8, 2048, NULL, 0, pw,
GCRY_CIPHER_RFC2268_40, 1);
/* Encode the encrypted stuff into a bag. */
seqlist[seqlistidx].buffer = build_cert_bag (buffer, buflen, salt, &n);
seqlist[seqlistidx].length = n;
gcry_free (buffer);
buffer = NULL;
if (!seqlist[seqlistidx].buffer)
goto failure;
seqlistidx++;
}
if (kparms)
{
/* Encode the key. */
int i;
/* Right, that is a stupid way to distinguish ECC from RSA. */
for (i=0; kparms[i]; i++)
;
if (i == 3 && gcry_mpi_get_flag (kparms[0], GCRYMPI_FLAG_OPAQUE))
buffer = build_ecc_key_sequence (kparms, 0, &buflen);
else
buffer = build_rsa_key_sequence (kparms, 0, &buflen);
if (!buffer)
goto failure;
/* Encrypt it. */
gcry_randomize (salt, 8, GCRY_STRONG_RANDOM);
crypt_block (buffer, buflen, salt, 8, 2048, NULL, 0,
pw, GCRY_CIPHER_3DES, 1);
/* Encode the encrypted stuff into a bag. */
if (cert && certlen)
seqlist[seqlistidx].buffer = build_key_bag (buffer, buflen, salt,
sha1hash, keyidstr, &n);
else
seqlist[seqlistidx].buffer = build_key_bag (buffer, buflen, salt,
NULL, NULL, &n);
seqlist[seqlistidx].length = n;
gcry_free (buffer);
buffer = NULL;
if (!seqlist[seqlistidx].buffer)
goto failure;
seqlistidx++;
}
seqlist[seqlistidx].buffer = NULL;
seqlist[seqlistidx].length = 0;
buffer = create_final (seqlist, pw, &buflen);
failure:
if (pwbuf)
{
/* Note that wipememory is not really needed due to the use of
gcry_malloc_secure. */
wipememory (pwbuf, pwbufsize);
gcry_free (pwbuf);
}
for ( ; seqlistidx; seqlistidx--)
gcry_free (seqlist[seqlistidx].buffer);
*r_length = buffer? buflen : 0;
return buffer;
}
/* This is actually not a pkcs#12 function but one which creates an
unencrypted a pkcs#1 private key. */
unsigned char *
p12_raw_build (gcry_mpi_t *kparms, int rawmode, size_t *r_length)
{
unsigned char *buffer;
size_t buflen;
int i;
log_assert (rawmode == 1 || rawmode == 2);
/* Right, that is a stupid way to distinguish ECC from RSA. */
for (i=0; kparms[i]; i++)
;
if (gcry_mpi_get_flag (kparms[0], GCRYMPI_FLAG_OPAQUE))
buffer = build_ecc_key_sequence (kparms, rawmode, &buflen);
else
buffer = build_rsa_key_sequence (kparms, rawmode, &buflen);
if (!buffer)
return NULL;
*r_length = buflen;
return buffer;
}