Page MenuHome GnuPG

No OneTemporary

diff --git a/agent/trustlist.c b/agent/trustlist.c
index a19af344a..d98da0c21 100644
--- a/agent/trustlist.c
+++ b/agent/trustlist.c
@@ -1,852 +1,855 @@
/* trustlist.c - Maintain the list of trusted keys
* Copyright (C) 2002, 2004, 2006, 2007, 2009,
* 2012 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GnuPG is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <unistd.h>
#include <sys/stat.h>
#include <npth.h>
#include "agent.h"
#include <assuan.h> /* fixme: need a way to avoid assuan calls here */
#include "../common/i18n.h"
/* A structure to store the information from the trust file. */
struct trustitem_s
{
struct
{
int disabled:1; /* This entry is disabled. */
int for_pgp:1; /* Set by '*' or 'P' as first flag. */
int for_smime:1; /* Set by '*' or 'S' as first flag. */
int relax:1; /* Relax checking of root certificate
constraints. */
int cm:1; /* Use chain model for validation. */
+ int qual:1; /* Root CA for qualified signatures. */
} flags;
unsigned char fpr[20]; /* The binary fingerprint. */
};
typedef struct trustitem_s trustitem_t;
/* Malloced table and its allocated size with all trust items. */
static trustitem_t *trusttable;
static size_t trusttablesize;
/* A mutex used to protect the table. */
static npth_mutex_t trusttable_lock;
static const char headerblurb[] =
"# This is the list of trusted keys. Comment lines, like this one, as\n"
"# well as empty lines are ignored. Lines have a length limit but this\n"
"# is not a serious limitation as the format of the entries is fixed and\n"
"# checked by gpg-agent. A non-comment line starts with optional white\n"
"# space, followed by the SHA-1 fingerpint in hex, followed by a flag\n"
"# which may be one of 'P', 'S' or '*' and optionally followed by a list of\n"
"# other flags. The fingerprint may be prefixed with a '!' to mark the\n"
"# key as not trusted. You should give the gpg-agent a HUP or run the\n"
"# command \"gpgconf --reload gpg-agent\" after changing this file.\n"
"\n\n"
"# Include the default trust list\n"
"include-default\n"
"\n";
/* This function must be called once to initialize this module. This
has to be done before a second thread is spawned. We can't do the
static initialization because Pth emulation code might not be able
to do a static init; in particular, it is not possible for W32. */
void
initialize_module_trustlist (void)
{
static int initialized;
int err;
if (!initialized)
{
err = npth_mutex_init (&trusttable_lock, NULL);
if (err)
log_fatal ("failed to init mutex in %s: %s\n", __FILE__,strerror (err));
initialized = 1;
}
}
static void
lock_trusttable (void)
{
int err;
err = npth_mutex_lock (&trusttable_lock);
if (err)
log_fatal ("failed to acquire mutex in %s: %s\n", __FILE__, strerror (err));
}
static void
unlock_trusttable (void)
{
int err;
err = npth_mutex_unlock (&trusttable_lock);
if (err)
log_fatal ("failed to release mutex in %s: %s\n", __FILE__, strerror (err));
}
/* Clear the trusttable. The caller needs to make sure that the
trusttable is locked. */
static inline void
clear_trusttable (void)
{
xfree (trusttable);
trusttable = NULL;
trusttablesize = 0;
}
/* Return the name of the system trustlist. Caller must free. */
static char *
make_sys_trustlist_name (void)
{
if (opt.sys_trustlist_name
&& (strchr (opt.sys_trustlist_name, '/')
|| strchr (opt.sys_trustlist_name, '\\')
|| (*opt.sys_trustlist_name == '~'
&& opt.sys_trustlist_name[1] == '/')))
return make_absfilename (opt.sys_trustlist_name, NULL);
else
return make_filename (gnupg_sysconfdir (),
(opt.sys_trustlist_name ?
opt.sys_trustlist_name : "trustlist.txt"),
NULL);
}
static gpg_error_t
read_one_trustfile (const char *fname, int systrust,
trustitem_t **addr_of_table,
size_t *addr_of_tablesize,
int *addr_of_tableidx)
{
gpg_error_t err = 0;
estream_t fp;
int n, c;
char *p, line[256];
trustitem_t *table, *ti;
int tableidx;
size_t tablesize;
int lnr = 0;
table = *addr_of_table;
tablesize = *addr_of_tablesize;
tableidx = *addr_of_tableidx;
fp = es_fopen (fname, "r");
if (!fp)
{
err = gpg_error_from_syserror ();
log_error (_("error opening '%s': %s\n"), fname, gpg_strerror (err));
goto leave;
}
while (es_fgets (line, DIM(line)-1, fp))
{
lnr++;
n = strlen (line);
if (!n || line[n-1] != '\n')
{
/* Eat until end of line. */
while ( (c=es_getc (fp)) != EOF && c != '\n')
;
err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG
: GPG_ERR_INCOMPLETE_LINE);
log_error (_("file '%s', line %d: %s\n"),
fname, lnr, gpg_strerror (err));
continue;
}
line[--n] = 0; /* Chop the LF. */
if (n && line[n-1] == '\r')
line[--n] = 0; /* Chop an optional CR. */
/* Allow for empty lines and spaces */
for (p=line; spacep (p); p++)
;
if (!*p || *p == '#')
continue;
if (!strncmp (p, "include-default", 15)
&& (!p[15] || spacep (p+15)))
{
char *etcname;
gpg_error_t err2;
gpg_err_code_t ec;
if (systrust)
{
log_error (_("statement \"%s\" ignored in '%s', line %d\n"),
"include-default", fname, lnr);
continue;
}
/* fixme: Should check for trailing garbage. */
etcname = make_sys_trustlist_name ();
if ( !strcmp (etcname, fname) ) /* Same file. */
log_info (_("statement \"%s\" ignored in '%s', line %d\n"),
"include-default", fname, lnr);
else if ((ec=gnupg_access (etcname, F_OK)) && ec == GPG_ERR_ENOENT)
{
/* A non existent system trustlist is not an error.
Just print a note. */
log_info (_("system trustlist '%s' not available\n"), etcname);
}
else
{
err2 = read_one_trustfile (etcname, 1,
&table, &tablesize, &tableidx);
if (err2)
err = err2;
}
xfree (etcname);
continue;
}
if (tableidx == tablesize) /* Need more space. */
{
trustitem_t *tmp;
size_t tmplen;
tmplen = tablesize + 20;
tmp = xtryrealloc (table, tmplen * sizeof *table);
if (!tmp)
{
err = gpg_error_from_syserror ();
goto leave;
}
table = tmp;
tablesize = tmplen;
}
ti = table + tableidx;
memset (&ti->flags, 0, sizeof ti->flags);
if (*p == '!')
{
ti->flags.disabled = 1;
p++;
while (spacep (p))
p++;
}
n = hexcolon2bin (p, ti->fpr, 20);
if (n < 0)
{
log_error (_("bad fingerprint in '%s', line %d\n"), fname, lnr);
err = gpg_error (GPG_ERR_BAD_DATA);
continue;
}
p += n;
for (; spacep (p); p++)
;
/* Process the first flag which needs to be the first for
backward compatibility. */
if (!*p || *p == '*' )
{
ti->flags.for_smime = 1;
ti->flags.for_pgp = 1;
}
else if ( *p == 'P' || *p == 'p')
{
ti->flags.for_pgp = 1;
}
else if ( *p == 'S' || *p == 's')
{
ti->flags.for_smime = 1;
}
else
{
log_error (_("invalid keyflag in '%s', line %d\n"), fname, lnr);
err = gpg_error (GPG_ERR_BAD_DATA);
continue;
}
p++;
if ( *p && !spacep (p) )
{
log_error (_("invalid keyflag in '%s', line %d\n"), fname, lnr);
err = gpg_error (GPG_ERR_BAD_DATA);
continue;
}
/* Now check for more key-value pairs of the form NAME[=VALUE]. */
while (*p)
{
for (; spacep (p); p++)
;
if (!*p)
break;
n = strcspn (p, "= \t");
if (p[n] == '=')
{
log_error ("assigning a value to a flag is not yet supported; "
"in '%s', line %d\n", fname, lnr);
err = gpg_error (GPG_ERR_BAD_DATA);
p++;
}
else if (n == 5 && !memcmp (p, "relax", 5))
ti->flags.relax = 1;
else if (n == 2 && !memcmp (p, "cm", 2))
ti->flags.cm = 1;
+ else if (n == 4 && !memcmp (p, "qual", 4) && systrust)
+ ti->flags.qual = 1;
else
log_error ("flag '%.*s' in '%s', line %d ignored\n",
n, p, fname, lnr);
p += n;
}
tableidx++;
}
if ( !err && !es_feof (fp) )
{
err = gpg_error_from_syserror ();
log_error (_("error reading '%s', line %d: %s\n"),
fname, lnr, gpg_strerror (err));
}
leave:
es_fclose (fp);
*addr_of_table = table;
*addr_of_tablesize = tablesize;
*addr_of_tableidx = tableidx;
return err;
}
/* Read the trust files and update the global table on success. The
trusttable is assumed to be locked. */
static gpg_error_t
read_trustfiles (void)
{
gpg_error_t err;
trustitem_t *table, *ti;
int tableidx;
size_t tablesize;
char *fname;
int systrust = 0;
gpg_err_code_t ec;
tablesize = 20;
table = xtrycalloc (tablesize, sizeof *table);
if (!table)
return gpg_error_from_syserror ();
tableidx = 0;
if (opt.no_user_trustlist)
fname = NULL;
else
{
fname = make_filename_try (gnupg_homedir (), "trustlist.txt", NULL);
if (!fname)
{
err = gpg_error_from_syserror ();
xfree (table);
return err;
}
}
if (!fname || (ec = gnupg_access (fname, F_OK)))
{
if (!fname)
; /* --no-user-trustlist active. */
else if ( ec == GPG_ERR_ENOENT )
; /* Silently ignore a non-existing trustfile. */
else
{
err = gpg_error (ec);
log_error (_("error opening '%s': %s\n"), fname, gpg_strerror (err));
}
xfree (fname);
fname = make_sys_trustlist_name ();
systrust = 1;
}
err = read_one_trustfile (fname, systrust, &table, &tablesize, &tableidx);
xfree (fname);
if (err)
{
xfree (table);
if (gpg_err_code (err) == GPG_ERR_ENOENT)
{
/* Take a missing trustlist as an empty one. */
clear_trusttable ();
err = 0;
}
return err;
}
/* Fixme: we should drop duplicates and sort the table. */
ti = xtryrealloc (table, (tableidx?tableidx:1) * sizeof *table);
if (!ti)
{
err = gpg_error_from_syserror ();
xfree (table);
return err;
}
/* Replace the trusttable. */
xfree (trusttable);
trusttable = ti;
trusttablesize = tableidx;
return 0;
}
/* Check whether the given fpr is in our trustdb. We expect FPR to be
an all uppercase hexstring of 40 characters. If ALREADY_LOCKED is
true the function assumes that the trusttable is already locked. */
static gpg_error_t
istrusted_internal (ctrl_t ctrl, const char *fpr, int *r_disabled,
int already_locked)
{
gpg_error_t err = 0;
int locked = already_locked;
trustitem_t *ti;
size_t len;
unsigned char fprbin[20];
if (r_disabled)
*r_disabled = 0;
if ( hexcolon2bin (fpr, fprbin, 20) < 0 )
{
err = gpg_error (GPG_ERR_INV_VALUE);
goto leave;
}
if (!already_locked)
{
lock_trusttable ();
locked = 1;
}
if (!trusttable)
{
err = read_trustfiles ();
if (err)
{
log_error (_("error reading list of trusted root certificates\n"));
goto leave;
}
}
if (trusttable)
{
for (ti=trusttable, len = trusttablesize; len; ti++, len--)
if (!memcmp (ti->fpr, fprbin, 20))
{
if (ti->flags.disabled && r_disabled)
*r_disabled = 1;
/* Print status messages only if we have not been called
in a locked state. */
if (already_locked)
;
- else if (ti->flags.relax)
+ else if (ti->flags.relax || ti->flags.cm || ti->flags.qual)
{
unlock_trusttable ();
locked = 0;
- err = agent_write_status (ctrl, "TRUSTLISTFLAG", "relax", NULL);
- }
- else if (ti->flags.cm)
- {
- unlock_trusttable ();
- locked = 0;
- err = agent_write_status (ctrl, "TRUSTLISTFLAG", "cm", NULL);
+ err = 0;
+ if (ti->flags.relax)
+ err = agent_write_status (ctrl,"TRUSTLISTFLAG", "relax",NULL);
+ if (!err && ti->flags.cm)
+ err = agent_write_status (ctrl,"TRUSTLISTFLAG", "cm", NULL);
+ if (!err && ti->flags.qual)
+ err = agent_write_status (ctrl,"TRUSTLISTFLAG", "qual",NULL);
}
if (!err)
err = ti->flags.disabled? gpg_error (GPG_ERR_NOT_TRUSTED) : 0;
goto leave;
}
}
err = gpg_error (GPG_ERR_NOT_TRUSTED);
leave:
if (locked && !already_locked)
unlock_trusttable ();
return err;
}
/* Check whether the given fpr is in our trustdb. We expect FPR to be
an all uppercase hexstring of 40 characters. */
gpg_error_t
agent_istrusted (ctrl_t ctrl, const char *fpr, int *r_disabled)
{
return istrusted_internal (ctrl, fpr, r_disabled, 0);
}
/* Write all trust entries to FP. */
gpg_error_t
agent_listtrusted (void *assuan_context)
{
trustitem_t *ti;
char key[51];
gpg_error_t err;
size_t len;
lock_trusttable ();
if (!trusttable)
{
err = read_trustfiles ();
if (err)
{
unlock_trusttable ();
log_error (_("error reading list of trusted root certificates\n"));
return err;
}
}
if (trusttable)
{
for (ti=trusttable, len = trusttablesize; len; ti++, len--)
{
if (ti->flags.disabled)
continue;
bin2hex (ti->fpr, 20, key);
key[40] = ' ';
key[41] = ((ti->flags.for_smime && ti->flags.for_pgp)? '*'
: ti->flags.for_smime? 'S': ti->flags.for_pgp? 'P':' ');
key[42] = '\n';
assuan_send_data (assuan_context, key, 43);
assuan_send_data (assuan_context, NULL, 0); /* flush */
}
}
unlock_trusttable ();
return 0;
}
/* Create a copy of string with colons inserted after each two bytes.
Caller needs to release the string. In case of a memory failure,
NULL is returned. */
static char *
insert_colons (const char *string)
{
char *buffer, *p;
size_t n = strlen (string);
size_t nnew = n + (n+1)/2;
p = buffer = xtrymalloc ( nnew + 1 );
if (!buffer)
return NULL;
while (*string)
{
*p++ = *string++;
if (*string)
{
*p++ = *string++;
if (*string)
*p++ = ':';
}
}
*p = 0;
assert (strlen (buffer) <= nnew);
return buffer;
}
/* To pretty print DNs in the Pinentry, we replace slashes by
REPLSTRING. The caller needs to free the returned string. NULL is
returned on error with ERRNO set. */
static char *
reformat_name (const char *name, const char *replstring)
{
const char *s;
char *newname;
char *d;
size_t count;
size_t replstringlen = strlen (replstring);
/* If the name does not start with a slash it is not a preformatted
DN and thus we don't bother to reformat it. */
if (*name != '/')
return xtrystrdup (name);
/* Count the names. Note that a slash contained in a DN part is
expected to be C style escaped and thus the slashes we see here
are the actual part delimiters. */
for (s=name+1, count=0; *s; s++)
if (*s == '/')
count++;
newname = xtrymalloc (strlen (name) + count*replstringlen + 1);
if (!newname)
return NULL;
for (s=name+1, d=newname; *s; s++)
if (*s == '/')
d = stpcpy (d, replstring);
else
*d++ = *s;
*d = 0;
return newname;
}
/* Insert the given fpr into our trustdb. We expect FPR to be an all
uppercase hexstring of 40 characters. FLAG is either 'P' or 'C'.
This function does first check whether that key has already been
put into the trustdb and returns success in this case. Before a
FPR actually gets inserted, the user is asked by means of the
Pinentry whether this is actual what he wants to do. */
gpg_error_t
agent_marktrusted (ctrl_t ctrl, const char *name, const char *fpr, int flag)
{
gpg_error_t err = 0;
gpg_err_code_t ec;
char *desc;
char *fname;
estream_t fp;
char *fprformatted;
char *nameformatted;
int is_disabled;
int yes_i_trust;
/* Check whether we are at all allowed to modify the trustlist.
This is useful so that the trustlist may be a symlink to a global
trustlist with only admin privileges to modify it. Of course
this is not a secure way of denying access, but it avoids the
usual clicking on an Okay button most users are used to. */
fname = make_filename_try (gnupg_homedir (), "trustlist.txt", NULL);
if (!fname)
return gpg_error_from_syserror ();
if ((ec = gnupg_access (fname, W_OK)) && ec != GPG_ERR_ENOENT)
{
xfree (fname);
return gpg_error (GPG_ERR_EPERM);
}
xfree (fname);
if (!agent_istrusted (ctrl, fpr, &is_disabled))
{
return 0; /* We already got this fingerprint. Silently return
success. */
}
/* This feature must explicitly been enabled. */
if (!opt.allow_mark_trusted)
return gpg_error (GPG_ERR_NOT_SUPPORTED);
if (is_disabled)
{
/* There is an disabled entry in the trustlist. Return an error
so that the user won't be asked again for that one. Changing
this flag with the integrated marktrusted feature is and will
not be made possible. */
return gpg_error (GPG_ERR_NOT_TRUSTED);
}
/* Insert a new one. */
nameformatted = reformat_name (name, "%0A ");
if (!nameformatted)
return gpg_error_from_syserror ();
/* First a general question whether this is trusted. */
desc = xtryasprintf (
/* TRANSLATORS: This prompt is shown by the Pinentry
and has one special property: A "%%0A" is used by
Pinentry to insert a line break. The double
percent sign is actually needed because it is also
a printf format string. If you need to insert a
plain % sign, you need to encode it as "%%25". The
"%s" gets replaced by the name as stored in the
certificate. */
L_("Do you ultimately trust%%0A"
" \"%s\"%%0A"
"to correctly certify user certificates?"),
nameformatted);
if (!desc)
{
xfree (nameformatted);
return out_of_core ();
}
err = agent_get_confirmation (ctrl, desc, L_("Yes"), L_("No"), 1);
xfree (desc);
if (!err)
yes_i_trust = 1;
else if (gpg_err_code (err) == GPG_ERR_NOT_CONFIRMED)
yes_i_trust = 0;
else
{
xfree (nameformatted);
return err;
}
fprformatted = insert_colons (fpr);
if (!fprformatted)
{
xfree (nameformatted);
return out_of_core ();
}
/* If the user trusts this certificate he has to verify the
fingerprint of course. */
if (yes_i_trust)
{
desc = xtryasprintf
(
/* TRANSLATORS: This prompt is shown by the Pinentry and has
one special property: A "%%0A" is used by Pinentry to
insert a line break. The double percent sign is actually
needed because it is also a printf format string. If you
need to insert a plain % sign, you need to encode it as
"%%25". The second "%s" gets replaced by a hexdecimal
fingerprint string whereas the first one receives the name
as stored in the certificate. */
L_("Please verify that the certificate identified as:%%0A"
" \"%s\"%%0A"
"has the fingerprint:%%0A"
" %s"), nameformatted, fprformatted);
if (!desc)
{
xfree (fprformatted);
xfree (nameformatted);
return out_of_core ();
}
/* TRANSLATORS: "Correct" is the label of a button and intended
to be hit if the fingerprint matches the one of the CA. The
other button is "the default "Cancel" of the Pinentry. */
err = agent_get_confirmation (ctrl, desc, L_("Correct"), L_("Wrong"), 1);
xfree (desc);
if (gpg_err_code (err) == GPG_ERR_NOT_CONFIRMED)
yes_i_trust = 0;
else if (err)
{
xfree (fprformatted);
xfree (nameformatted);
return err;
}
}
/* Now check again to avoid duplicates. We take the lock to make
sure that nobody else plays with our file and force a reread. */
lock_trusttable ();
clear_trusttable ();
if (!istrusted_internal (ctrl, fpr, &is_disabled, 1) || is_disabled)
{
unlock_trusttable ();
xfree (fprformatted);
xfree (nameformatted);
return is_disabled? gpg_error (GPG_ERR_NOT_TRUSTED) : 0;
}
fname = make_filename_try (gnupg_homedir (), "trustlist.txt", NULL);
if (!fname)
{
err = gpg_error_from_syserror ();
unlock_trusttable ();
xfree (fprformatted);
xfree (nameformatted);
return err;
}
if ((ec = access (fname, F_OK)) && ec == GPG_ERR_ENOENT)
{
fp = es_fopen (fname, "wx,mode=-rw-r");
if (!fp)
{
err = gpg_error (ec);
log_error ("can't create '%s': %s\n", fname, gpg_strerror (err));
xfree (fname);
unlock_trusttable ();
xfree (fprformatted);
xfree (nameformatted);
return err;
}
es_fputs (headerblurb, fp);
es_fclose (fp);
}
fp = es_fopen (fname, "a+,mode=-rw-r");
if (!fp)
{
err = gpg_error_from_syserror ();
log_error ("can't open '%s': %s\n", fname, gpg_strerror (err));
xfree (fname);
unlock_trusttable ();
xfree (fprformatted);
xfree (nameformatted);
return err;
}
/* Append the key. */
es_fputs ("\n# ", fp);
xfree (nameformatted);
nameformatted = reformat_name (name, "\n# ");
if (!nameformatted || strchr (name, '\n'))
{
/* Note that there should never be a LF in NAME but we better
play safe and print a sanitized version in this case. */
es_write_sanitized (fp, name, strlen (name), NULL, NULL);
}
else
es_fputs (nameformatted, fp);
es_fprintf (fp, "\n%s%s %c%s\n", yes_i_trust?"":"!", fprformatted, flag,
flag == 'S'? " relax":"");
if (es_ferror (fp))
err = gpg_error_from_syserror ();
if (es_fclose (fp))
err = gpg_error_from_syserror ();
clear_trusttable ();
xfree (fname);
unlock_trusttable ();
xfree (fprformatted);
xfree (nameformatted);
if (!err)
bump_key_eventcounter ();
return err;
}
/* This function may be called to force reloading of the
trustlist. */
void
agent_reload_trustlist (void)
{
/* All we need to do is to delete the trusttable. At the next
access it will get re-read. */
lock_trusttable ();
clear_trusttable ();
unlock_trusttable ();
bump_key_eventcounter ();
}
diff --git a/doc/gpg-agent.texi b/doc/gpg-agent.texi
index a97529d54..05eb066a5 100644
--- a/doc/gpg-agent.texi
+++ b/doc/gpg-agent.texi
@@ -1,1666 +1,1672 @@
@c Copyright (C) 2002 Free Software Foundation, Inc.
@c This is part of the GnuPG manual.
@c For copying conditions, see the file gnupg.texi.
@include defs.inc
@node Invoking GPG-AGENT
@chapter Invoking GPG-AGENT
@cindex GPG-AGENT command options
@cindex command options
@cindex options, GPG-AGENT command
@manpage gpg-agent.1
@ifset manverb
.B gpg-agent
\- Secret key management for GnuPG
@end ifset
@mansect synopsis
@ifset manverb
.B gpg-agent
.RB [ \-\-homedir
.IR dir ]
.RB [ \-\-options
.IR file ]
.RI [ options ]
.br
.B gpg-agent
.RB [ \-\-homedir
.IR dir ]
.RB [ \-\-options
.IR file ]
.RI [ options ]
.B \-\-server
.br
.B gpg-agent
.RB [ \-\-homedir
.IR dir ]
.RB [ \-\-options
.IR file ]
.RI [ options ]
.B \-\-daemon
.RI [ command_line ]
@end ifset
@mansect description
@command{gpg-agent} is a daemon to manage secret (private) keys
independently from any protocol. It is used as a backend for
@command{gpg} and @command{gpgsm} as well as for a couple of other
utilities.
The agent is automatically started on demand by @command{gpg},
@command{gpgsm}, @command{gpgconf}, or @command{gpg-connect-agent}.
Thus there is no reason to start it manually. In case you want to use
the included Secure Shell Agent you may start the agent using:
@c From dkg on gnupg-devel on 2016-04-21:
@c
@c Here's an attempt at writing a short description of the goals of an
@c isolated cryptographic agent:
@c
@c A cryptographic agent should control access to secret key material.
@c The agent permits use of the secret key material by a supplicant
@c without providing a copy of the secret key material to the supplicant.
@c
@c An isolated cryptographic agent separates the request for use of
@c secret key material from permission for use of secret key material.
@c That is, the system or process requesting use of the key (the
@c "supplicant") can be denied use of the key by the owner/operator of
@c the agent (the "owner"), which the supplicant has no control over.
@c
@c One way of enforcing this split is a per-key or per-session
@c passphrase, known only by the owner, which must be supplied to the
@c agent to permit the use of the secret key material. Another way is
@c with an out-of-band permission mechanism (e.g. a button or GUI
@c interface that the owner has access to, but the supplicant does not).
@c
@c The rationale for this separation is that it allows access to the
@c secret key to be tightly controlled and audited, and it doesn't permit
@c the supplicant to either copy the key or to override the owner's
@c intentions.
@example
gpg-connect-agent /bye
@end example
@noindent
If you want to manually terminate the currently-running agent, you can
safely do so with:
@example
gpgconf --kill gpg-agent
@end example
@noindent
@efindex GPG_TTY
You should always add the following lines to your @code{.bashrc} or
whatever initialization file is used for all shell invocations:
@smallexample
GPG_TTY=$(tty)
export GPG_TTY
@end smallexample
@noindent
It is important that this environment variable always reflects the
output of the @code{tty} command. For W32 systems this option is not
required.
Please make sure that a proper pinentry program has been installed
under the default filename (which is system dependent) or use the
option @option{pinentry-program} to specify the full name of that program.
It is often useful to install a symbolic link from the actual used
pinentry (e.g. @file{@value{BINDIR}/pinentry-gtk}) to the expected
one (e.g. @file{@value{BINDIR}/pinentry}).
@manpause
@noindent
@xref{Option Index}, for an index to @command{GPG-AGENT}'s commands and options.
@mancont
@menu
* Agent Commands:: List of all commands.
* Agent Options:: List of all options.
* Agent Configuration:: Configuration files.
* Agent Signals:: Use of some signals.
* Agent Examples:: Some usage examples.
* Agent Protocol:: The protocol the agent uses.
@end menu
@mansect commands
@node Agent Commands
@section Commands
Commands are not distinguished from options except for the fact that
only one command is allowed.
@table @gnupgtabopt
@item --version
@opindex version
Print the program version and licensing information. Note that you cannot
abbreviate this command.
@item --help
@itemx -h
@opindex help
Print a usage message summarizing the most useful command-line options.
Note that you cannot abbreviate this command.
@item --dump-options
@opindex dump-options
Print a list of all available options and commands. Note that you cannot
abbreviate this command.
@item --server
@opindex server
Run in server mode and wait for commands on the @code{stdin}. The
default mode is to create a socket and listen for commands there.
@item --daemon [@var{command line}]
@opindex daemon
Start the gpg-agent as a daemon; that is, detach it from the console
and run it in the background.
As an alternative you may create a new process as a child of
gpg-agent: @code{gpg-agent --daemon /bin/sh}. This way you get a new
shell with the environment setup properly; after you exit from this
shell, gpg-agent terminates within a few seconds.
@item --supervised
@opindex supervised
Run in the foreground, sending logs by default to stderr, and
listening on provided file descriptors, which must already be bound to
listening sockets. This command is useful when running under systemd
or other similar process supervision schemes. This option is not
supported on Windows.
In --supervised mode, different file descriptors can be provided for
use as different socket types (e.g. ssh, extra) as long as they are
identified in the environment variable @code{LISTEN_FDNAMES} (see
sd_listen_fds(3) on some Linux distributions for more information on
this convention).
@end table
@mansect options
@node Agent Options
@section Option Summary
Options may either be used on the command line or, after stripping off
the two leading dashes, in the configuration file.
@table @gnupgtabopt
@anchor{option --options}
@item --options @var{file}
@opindex options
Reads configuration from @var{file} instead of from the default
per-user configuration file. The default configuration file is named
@file{gpg-agent.conf} and expected in the @file{.gnupg} directory
directly below the home directory of the user. This option is ignored
if used in an options file.
@anchor{option --homedir}
@include opt-homedir.texi
@item -v
@itemx --verbose
@opindex verbose
Outputs additional information while running.
You can increase the verbosity by giving several
verbose commands to @command{gpg-agent}, such as @samp{-vv}.
@item -q
@itemx --quiet
@opindex quiet
Try to be as quiet as possible.
@item --batch
@opindex batch
Don't invoke a pinentry or do any other thing requiring human interaction.
@item --faked-system-time @var{epoch}
@opindex faked-system-time
This option is only useful for testing; it sets the system time back or
forth to @var{epoch} which is the number of seconds elapsed since the year
1970.
@item --debug-level @var{level}
@opindex debug-level
Select the debug level for investigating problems. @var{level} may be
a numeric value or a keyword:
@table @code
@item none
No debugging at all. A value of less than 1 may be used instead of
the keyword.
@item basic
Some basic debug messages. A value between 1 and 2 may be used
instead of the keyword.
@item advanced
More verbose debug messages. A value between 3 and 5 may be used
instead of the keyword.
@item expert
Even more detailed messages. A value between 6 and 8 may be used
instead of the keyword.
@item guru
All of the debug messages you can get. A value greater than 8 may be
used instead of the keyword. The creation of hash tracing files is
only enabled if the keyword is used.
@end table
How these messages are mapped to the actual debugging flags is not
specified and may change with newer releases of this program. They are
however carefully selected to best aid in debugging.
@item --debug @var{flags}
@opindex debug
This option is only useful for debugging and the behavior may change at
any time without notice. FLAGS are bit encoded and may be given in
usual C-Syntax. The currently defined bits are:
@table @code
@item 0 (1)
X.509 or OpenPGP protocol related data
@item 1 (2)
values of big number integers
@item 2 (4)
low level crypto operations
@item 5 (32)
memory allocation
@item 6 (64)
caching
@item 7 (128)
show memory statistics
@item 9 (512)
write hashed data to files named @code{dbgmd-000*}
@item 10 (1024)
trace Assuan protocol
@item 12 (4096)
bypass all certificate validation
@end table
@item --debug-all
@opindex debug-all
Same as @code{--debug=0xffffffff}
@item --debug-wait @var{n}
@opindex debug-wait
When running in server mode, wait @var{n} seconds before entering the
actual processing loop and print the pid. This gives time to attach a
debugger.
@item --debug-quick-random
@opindex debug-quick-random
This option inhibits the use of the very secure random quality level
(Libgcrypt’s @code{GCRY_VERY_STRONG_RANDOM}) and degrades all request
down to standard random quality. It is only used for testing and
should not be used for any production quality keys. This option is
only effective when given on the command line.
On GNU/Linux, another way to quickly generate insecure keys is to use
@command{rngd} to fill the kernel's entropy pool with lower quality
random data. @command{rngd} is typically provided by the
@command{rng-tools} package. It can be run as follows: @samp{sudo
rngd -f -r /dev/urandom}.
@item --debug-pinentry
@opindex debug-pinentry
This option enables extra debug information pertaining to the
Pinentry. As of now it is only useful when used along with
@code{--debug 1024}.
@item --no-detach
@opindex no-detach
Don't detach the process from the console. This is mainly useful for
debugging.
@item --steal-socket
@opindex steal-socket
In @option{--daemon} mode, gpg-agent detects an already running
gpg-agent and does not allow to start a new instance. This option can
be used to override this check: the new gpg-agent process will try to
take over the communication sockets from the already running process
and start anyway. This option should in general not be used.
@item -s
@itemx --sh
@itemx -c
@itemx --csh
@opindex sh
@opindex csh
@efindex SHELL
Format the info output in daemon mode for use with the standard Bourne
shell or the C-shell respectively. The default is to guess it based on
the environment variable @code{SHELL} which is correct in almost all
cases.
@item --grab
@itemx --no-grab
@opindex grab
@opindex no-grab
Tell the pinentry to grab the keyboard and mouse. This option should
be used on X-Servers to avoid X-sniffing attacks. Any use of the
option @option{--grab} overrides an used option @option{--no-grab}.
The default is @option{--no-grab}.
@anchor{option --log-file}
@item --log-file @var{file}
@opindex log-file
@efindex HKCU\Software\GNU\GnuPG:DefaultLogFile
Append all logging output to @var{file}. This is very helpful in
seeing what the agent actually does. Use @file{socket://} to log to
socket. If neither a log file nor a log file descriptor has been set
on a Windows platform, the Registry entry
@code{HKCU\Software\GNU\GnuPG:DefaultLogFile}, if set, is used to
specify the logging output.
@anchor{option --no-allow-mark-trusted}
@item --no-allow-mark-trusted
@opindex no-allow-mark-trusted
Do not allow clients to mark keys as trusted, i.e. put them into the
@file{trustlist.txt} file. This makes it harder for users to inadvertently
accept Root-CA keys.
@anchor{option --no-user-trustlist}
@item --no-user-trustlist
@opindex no-user-trustlist
Entirely ignore the user trust list and consider only the global
trustlist (@file{@value{SYSCONFDIR}/trustlist.txt}). This
implies the @ref{option --no-allow-mark-trusted}.
@item --sys-trustlist-name @var{file}
@opindex sys-trustlist-name
Changes the default name for the global trustlist from "trustlist.txt"
to @var{file}. If @var{file} does not contain any slashes and does
not start with "~/" it is searched in the system configuration
directory (@file{@value{SYSCONFDIR}}).
@anchor{option --allow-preset-passphrase}
@item --allow-preset-passphrase
@opindex allow-preset-passphrase
This option allows the use of @command{gpg-preset-passphrase} to seed the
internal cache of @command{gpg-agent} with passphrases.
@anchor{option --no-allow-loopback-pinentry}
@item --no-allow-loopback-pinentry
@item --allow-loopback-pinentry
@opindex no-allow-loopback-pinentry
@opindex allow-loopback-pinentry
Disallow or allow clients to use the loopback pinentry features; see
the option @option{pinentry-mode} for details. Allow is the default.
The @option{--force} option of the Assuan command @command{DELETE_KEY}
is also controlled by this option: The option is ignored if a loopback
pinentry is disallowed.
@item --no-allow-external-cache
@opindex no-allow-external-cache
Tell Pinentry not to enable features which use an external cache for
passphrases.
Some desktop environments prefer to unlock all
credentials with one master password and may have installed a Pinentry
which employs an additional external cache to implement such a policy.
By using this option the Pinentry is advised not to make use of such a
cache and instead always ask the user for the requested passphrase.
@item --allow-emacs-pinentry
@opindex allow-emacs-pinentry
Tell Pinentry to allow features to divert the passphrase entry to a
running Emacs instance. How this is exactly handled depends on the
version of the used Pinentry.
@item --ignore-cache-for-signing
@opindex ignore-cache-for-signing
This option will let @command{gpg-agent} bypass the passphrase cache for all
signing operation. Note that there is also a per-session option to
control this behavior but this command line option takes precedence.
@item --default-cache-ttl @var{n}
@opindex default-cache-ttl
Set the time a cache entry is valid to @var{n} seconds. The default
is 600 seconds. Each time a cache entry is accessed, the entry's
timer is reset. To set an entry's maximum lifetime, use
@command{max-cache-ttl}. Note that a cached passphrase may not be
evicted immediately from memory if no client requests a cache
operation. This is due to an internal housekeeping function which is
only run every few seconds.
@item --default-cache-ttl-ssh @var{n}
@opindex default-cache-ttl
Set the time a cache entry used for SSH keys is valid to @var{n}
seconds. The default is 1800 seconds. Each time a cache entry is
accessed, the entry's timer is reset. To set an entry's maximum
lifetime, use @command{max-cache-ttl-ssh}.
@item --max-cache-ttl @var{n}
@opindex max-cache-ttl
Set the maximum time a cache entry is valid to @var{n} seconds. After
this time a cache entry will be expired even if it has been accessed
recently or has been set using @command{gpg-preset-passphrase}. The
default is 2 hours (7200 seconds).
@item --max-cache-ttl-ssh @var{n}
@opindex max-cache-ttl-ssh
Set the maximum time a cache entry used for SSH keys is valid to
@var{n} seconds. After this time a cache entry will be expired even
if it has been accessed recently or has been set using
@command{gpg-preset-passphrase}. The default is 2 hours (7200
seconds).
@item --enforce-passphrase-constraints
@opindex enforce-passphrase-constraints
Enforce the passphrase constraints by not allowing the user to bypass
them using the ``Take it anyway'' button.
@item --min-passphrase-len @var{n}
@opindex min-passphrase-len
Set the minimal length of a passphrase. When entering a new passphrase
shorter than this value a warning will be displayed. Defaults to 8.
@item --min-passphrase-nonalpha @var{n}
@opindex min-passphrase-nonalpha
Set the minimal number of digits or special characters required in a
passphrase. When entering a new passphrase with less than this number
of digits or special characters a warning will be displayed. Defaults
to 1.
@item --check-passphrase-pattern @var{file}
@itemx --check-sym-passphrase-pattern @var{file}
@opindex check-passphrase-pattern
@opindex check-sym-passphrase-pattern
Check the passphrase against the pattern given in @var{file}. When
entering a new passphrase matching one of these pattern a warning will
be displayed. If @var{file} does not contain any slashes and does not
start with "~/" it is searched in the system configuration directory
(@file{@value{SYSCONFDIR}}). The default is not to use any
pattern file. The second version of this option is only used when
creating a new symmetric key to allow the use of different patterns
for such passphrases.
Security note: It is known that checking a passphrase against a list of
pattern or even against a complete dictionary is not very effective to
enforce good passphrases. Users will soon figure up ways to bypass such
a policy. A better policy is to educate users on good security
behavior and optionally to run a passphrase cracker regularly on all
users passphrases to catch the very simple ones.
@item --max-passphrase-days @var{n}
@opindex max-passphrase-days
Ask the user to change the passphrase if @var{n} days have passed since
the last change. With @option{--enforce-passphrase-constraints} set the
user may not bypass this check.
@item --enable-passphrase-history
@opindex enable-passphrase-history
This option does nothing yet.
@item --pinentry-invisible-char @var{char}
@opindex pinentry-invisible-char
This option asks the Pinentry to use @var{char} for displaying hidden
characters. @var{char} must be one character UTF-8 string. A
Pinentry may or may not honor this request.
@item --pinentry-timeout @var{n}
@opindex pinentry-timeout
This option asks the Pinentry to timeout after @var{n} seconds with no
user input. The default value of 0 does not ask the pinentry to
timeout, however a Pinentry may use its own default timeout value in
this case. A Pinentry may or may not honor this request.
@item --pinentry-formatted-passphrase
@opindex pinentry-formatted-passphrase
This option asks the Pinentry to enable passphrase formatting when asking the
user for a new passphrase and masking of the passphrase is turned off.
If passphrase formatting is enabled, then all non-breaking space characters
are stripped from the entered passphrase. Passphrase formatting is mostly
useful in combination with passphrases generated with the GENPIN
feature of some Pinentries. Note that such a generated
passphrase, if not modified by the user, skips all passphrase
constraints checking because such constraints would actually weaken
the generated passphrase.
@item --pinentry-program @var{filename}
@opindex pinentry-program
Use program @var{filename} as the PIN entry. The default is
installation dependent. With the default configuration the name of
the default pinentry is @file{pinentry}; if that file does not exist
but a @file{pinentry-basic} exist the latter is used.
On a Windows platform the default is to use the first existing program
from this list:
@file{bin\pinentry.exe},
@file{..\Gpg4win\bin\pinentry.exe},
@file{..\Gpg4win\pinentry.exe},
@file{..\GNU\GnuPG\pinentry.exe},
@file{..\GNU\bin\pinentry.exe},
@file{bin\pinentry-basic.exe}
where the file names are relative to the GnuPG installation directory.
@item --pinentry-touch-file @var{filename}
@opindex pinentry-touch-file
By default the filename of the socket gpg-agent is listening for
requests is passed to Pinentry, so that it can touch that file before
exiting (it does this only in curses mode). This option changes the
file passed to Pinentry to @var{filename}. The special name
@code{/dev/null} may be used to completely disable this feature. Note
that Pinentry will not create that file, it will only change the
modification and access time.
@item --scdaemon-program @var{filename}
@opindex scdaemon-program
Use program @var{filename} as the Smartcard daemon. The default is
installation dependent and can be shown with the @command{gpgconf}
command.
@item --disable-scdaemon
@opindex disable-scdaemon
Do not make use of the scdaemon tool. This option has the effect of
disabling the ability to do smartcard operations. Note, that enabling
this option at runtime does not kill an already forked scdaemon.
@item --disable-check-own-socket
@opindex disable-check-own-socket
@command{gpg-agent} employs a periodic self-test to detect a stolen
socket. This usually means a second instance of @command{gpg-agent}
has taken over the socket and @command{gpg-agent} will then terminate
itself. This option may be used to disable this self-test for
debugging purposes.
@item --use-standard-socket
@itemx --no-use-standard-socket
@itemx --use-standard-socket-p
@opindex use-standard-socket
@opindex no-use-standard-socket
@opindex use-standard-socket-p
Since GnuPG 2.1 the standard socket is always used. These options
have no more effect. The command @code{gpg-agent
--use-standard-socket-p} will thus always return success.
@item --display @var{string}
@itemx --ttyname @var{string}
@itemx --ttytype @var{string}
@itemx --lc-ctype @var{string}
@itemx --lc-messages @var{string}
@itemx --xauthority @var{string}
@opindex display
@opindex ttyname
@opindex ttytype
@opindex lc-ctype
@opindex lc-messages
@opindex xauthority
These options are used with the server mode to pass localization
information.
@item --keep-tty
@itemx --keep-display
@opindex keep-tty
@opindex keep-display
Ignore requests to change the current @code{tty} or X window system's
@code{DISPLAY} variable respectively. This is useful to lock the
pinentry to pop up at the @code{tty} or display you started the agent.
@item --listen-backlog @var{n}
@opindex listen-backlog
Set the size of the queue for pending connections. The default is 64.
@anchor{option --extra-socket}
@item --extra-socket @var{name}
@opindex extra-socket
The extra socket is created by default, you may use this option to
change the name of the socket. To disable the creation of the socket
use ``none'' or ``/dev/null'' for @var{name}.
Also listen on native gpg-agent connections on the given socket. The
intended use for this extra socket is to setup a Unix domain socket
forwarding from a remote machine to this socket on the local machine.
A @command{gpg} running on the remote machine may then connect to the
local gpg-agent and use its private keys. This enables decrypting or
signing data on a remote machine without exposing the private keys to the
remote machine.
@item --enable-extended-key-format
@itemx --disable-extended-key-format
@opindex enable-extended-key-format
@opindex disable-extended-key-format
These options are obsolete and have no effect. The extended key format
is used for years now and has been supported since 2.1.12. Existing
keys in the old format are migrated to the new format as soon as they
are touched.
@anchor{option --enable-ssh-support}
@item --enable-ssh-support
@itemx --enable-putty-support
@opindex enable-ssh-support
@opindex enable-putty-support
The OpenSSH Agent protocol is always enabled, but @command{gpg-agent}
will only set the @code{SSH_AUTH_SOCK} variable if this flag is given.
In this mode of operation, the agent does not only implement the
gpg-agent protocol, but also the agent protocol used by OpenSSH
(through a separate socket). Consequently, it should be possible to use
the gpg-agent as a drop-in replacement for the well known ssh-agent.
SSH Keys, which are to be used through the agent, need to be added to
the gpg-agent initially through the ssh-add utility. When a key is
added, ssh-add will ask for the password of the provided key file and
send the unprotected key material to the agent; this causes the
gpg-agent to ask for a passphrase, which is to be used for encrypting
the newly received key and storing it in a gpg-agent specific
directory.
Once a key has been added to the gpg-agent this way, the gpg-agent
will be ready to use the key.
Note: in case the gpg-agent receives a signature request, the user might
need to be prompted for a passphrase, which is necessary for decrypting
the stored key. Since the ssh-agent protocol does not contain a
mechanism for telling the agent on which display/terminal it is running,
gpg-agent's ssh-support will use the TTY or X display where gpg-agent
has been started. To switch this display to the current one, the
following command may be used:
@smallexample
gpg-connect-agent updatestartuptty /bye
@end smallexample
Although all GnuPG components try to start the gpg-agent as needed, this
is not possible for the ssh support because ssh does not know about it.
Thus if no GnuPG tool which accesses the agent has been run, there is no
guarantee that ssh is able to use gpg-agent for authentication. To fix
this you may start gpg-agent if needed using this simple command:
@smallexample
gpg-connect-agent /bye
@end smallexample
Adding the @option{--verbose} shows the progress of starting the agent.
The @option{--enable-putty-support} is only available under Windows
and allows the use of gpg-agent with the ssh implementation
@command{putty}. This is similar to the regular ssh-agent support but
makes use of Windows message queue as required by @command{putty}.
@anchor{option --ssh-fingerprint-digest}
@item --ssh-fingerprint-digest
@opindex ssh-fingerprint-digest
Select the digest algorithm used to compute ssh fingerprints that are
communicated to the user, e.g. in pinentry dialogs. OpenSSH has
transitioned from using MD5 to the more secure SHA256.
@item --auto-expand-secmem @var{n}
@opindex auto-expand-secmem
Allow Libgcrypt to expand its secure memory area as required. The
optional value @var{n} is a non-negative integer with a suggested size
in bytes of each additionally allocated secure memory area. The value
is rounded up to the next 32 KiB; usual C style prefixes are allowed.
For an heavy loaded gpg-agent with many concurrent connection this
option avoids sign or decrypt errors due to out of secure memory error
returns.
@item --s2k-calibration @var{milliseconds}
@opindex s2k-calibration
Change the default calibration time to @var{milliseconds}. The given
value is capped at 60 seconds; a value of 0 resets to the compiled-in
default. This option is re-read on a SIGHUP (or @code{gpgconf
--reload gpg-agent}) and the S2K count is then re-calibrated.
@item --s2k-count @var{n}
@opindex s2k-count
Specify the iteration count used to protect the passphrase. This
option can be used to override the auto-calibration done by default.
The auto-calibration computes a count which requires by default 100ms
to mangle a given passphrase. See also @option{--s2k-calibration}.
To view the actually used iteration count and the milliseconds
required for an S2K operation use:
@example
gpg-connect-agent 'GETINFO s2k_count' /bye
gpg-connect-agent 'GETINFO s2k_time' /bye
@end example
To view the auto-calibrated count use:
@example
gpg-connect-agent 'GETINFO s2k_count_cal' /bye
@end example
@end table
@mansect files
@node Agent Configuration
@section Configuration
There are a few configuration files needed for the operation of the
agent. By default they may all be found in the current home directory
(@pxref{option --homedir}).
@table @file
@item gpg-agent.conf
@efindex gpg-agent.conf
This is the standard configuration file read by @command{gpg-agent} on
startup. It may contain any valid long option; the leading
two dashes may not be entered and the option may not be abbreviated.
This file is also read after a @code{SIGHUP} however only a few
options will actually have an effect. This default name may be
changed on the command line (@pxref{option --options}).
You should backup this file.
@item trustlist.txt
@efindex trustlist.txt
This is the list of trusted keys. You should backup this file.
Comment lines, indicated by a leading hash mark, as well as empty
lines are ignored. To mark a key as trusted you need to enter its
fingerprint followed by a space and a capital letter @code{S}. Colons
may optionally be used to separate the bytes of a fingerprint; this
enables cutting and pasting the fingerprint from a key listing output. If
the line is prefixed with a @code{!} the key is explicitly marked as
not trusted.
Here is an example where two keys are marked as ultimately trusted
and one as not trusted:
@cartouche
@smallexample
# CN=Wurzel ZS 3,O=Intevation GmbH,C=DE
A6935DD34EF3087973C706FC311AA2CCF733765B S
# CN=PCA-1-Verwaltung-02/O=PKI-1-Verwaltung/C=DE
DC:BD:69:25:48:BD:BB:7E:31:6E:BB:80:D3:00:80:35:D4:F8:A6:CD S
# CN=Root-CA/O=Schlapphuete/L=Pullach/C=DE
!14:56:98:D3:FE:9C:CA:5A:31:6E:BC:81:D3:11:4E:00:90:A3:44:C2 S
@end smallexample
@end cartouche
Before entering a key into this file, you need to ensure its
authenticity. How to do this depends on your organisation; your
administrator might have already entered those keys which are deemed
trustworthy enough into this file. Places where to look for the
fingerprint of a root certificate are letters received from the CA or
the website of the CA (after making 100% sure that this is indeed the
website of that CA). You may want to consider disallowing interactive
updates of this file by using the @ref{option --no-allow-mark-trusted}.
It might even be advisable to change the permissions to read-only so
that this file can't be changed inadvertently.
As a special feature a line @code{include-default} will include a global
list of trusted certificates (e.g. @file{@value{SYSCONFDIR}/trustlist.txt}).
This global list is also used if the local list is not available;
the @ref{option --no-user-trustlist} enforces the use of only
this global list.
It is possible to add further flags after the @code{S} for use by the
caller:
@table @code
@item relax
@cindex relax
Relax checking of some root certificate requirements. As of now this
flag allows the use of root certificates with a missing basicConstraints
attribute (despite that it is a MUST for CA certificates) and disables
CRL checking for the root certificate.
@item cm
If validation of a certificate finally issued by a CA with this flag set
fails, try again using the chain validation model.
+@item qual
+The CA is allowed to issue certificates for qualified signatures.
+This flag has an effect only if used in the global list. This is now
+the preferred way to mark such CA; the old way of having a separate
+file @file{qualified.txt} is still supported.
+
@end table
@item sshcontrol
@efindex sshcontrol
This file is used when support for the secure shell agent protocol has
been enabled (@pxref{option --enable-ssh-support}). Only keys present in
this file are used in the SSH protocol. You should backup this file.
The @command{ssh-add} tool may be used to add new entries to this file;
you may also add them manually. Comment lines, indicated by a leading
hash mark, as well as empty lines are ignored. An entry starts with
optional whitespace, followed by the keygrip of the key given as 40 hex
digits, optionally followed by the caching TTL in seconds and another
optional field for arbitrary flags. A non-zero TTL overrides the global
default as set by @option{--default-cache-ttl-ssh}.
The only flag support is @code{confirm}. If this flag is found for a
key, each use of the key will pop up a pinentry to confirm the use of
that key. The flag is automatically set if a new key was loaded into
@code{gpg-agent} using the option @option{-c} of the @code{ssh-add}
command.
The keygrip may be prefixed with a @code{!} to disable an entry.
The following example lists exactly one key. Note that keys available
through a OpenPGP smartcard in the active smartcard reader are
implicitly added to this list; i.e. there is no need to list them.
@cartouche
@smallexample
# Key added on: 2011-07-20 20:38:46
# Fingerprint: 5e:8d:c4:ad:e7:af:6e:27:8a:d6:13:e4:79:ad:0b:81
34B62F25E277CF13D3C6BCEBFD3F85D08F0A864B 0 confirm
@end smallexample
@end cartouche
@item private-keys-v1.d/
@efindex private-keys-v1.d
This is the directory where gpg-agent stores the private keys. Each
key is stored in a file with the name made up of the keygrip and the
suffix @file{key}. You should backup all files in this directory
and take great care to keep this backup closed away.
@end table
Note that on larger installations, it is useful to put predefined
files into the directory @file{@value{SYSCONFSKELDIR}} so that newly created
users start up with a working configuration. For existing users the
a small helper script is provided to create these files (@pxref{addgnupghome}).
@c
@c Agent Signals
@c
@mansect signals
@node Agent Signals
@section Use of some signals
A running @command{gpg-agent} may be controlled by signals, i.e. using
the @command{kill} command to send a signal to the process.
Here is a list of supported signals:
@table @gnupgtabopt
@item SIGHUP
@cpindex SIGHUP
This signal flushes all cached passphrases and if the program has been
started with a configuration file, the configuration file is read
again. Only certain options are honored: @code{quiet},
@code{verbose}, @code{debug}, @code{debug-all}, @code{debug-level},
@code{debug-pinentry},
@code{no-grab},
@code{pinentry-program},
@code{pinentry-invisible-char},
@code{default-cache-ttl},
@code{max-cache-ttl}, @code{ignore-cache-for-signing},
@code{s2k-count},
@code{no-allow-external-cache}, @code{allow-emacs-pinentry},
@code{no-allow-mark-trusted}, @code{disable-scdaemon}, and
@code{disable-check-own-socket}. @code{scdaemon-program} is also
supported but due to the current implementation, which calls the
scdaemon only once, it is not of much use unless you manually kill the
scdaemon.
@item SIGTERM
@cpindex SIGTERM
Shuts down the process but waits until all current requests are
fulfilled. If the process has received 3 of these signals and requests
are still pending, a shutdown is forced.
@item SIGINT
@cpindex SIGINT
Shuts down the process immediately.
@item SIGUSR1
@cpindex SIGUSR1
Dump internal information to the log file.
@item SIGUSR2
@cpindex SIGUSR2
This signal is used for internal purposes.
@end table
@c
@c Examples
@c
@mansect examples
@node Agent Examples
@section Examples
It is important to set the environment variable @code{GPG_TTY} in
your login shell, for example in the @file{~/.bashrc} init script:
@cartouche
@example
export GPG_TTY=$(tty)
@end example
@end cartouche
If you enabled the Ssh Agent Support, you also need to tell ssh about
it by adding this to your init script:
@cartouche
@example
unset SSH_AGENT_PID
if [ "$@{gnupg_SSH_AUTH_SOCK_by:-0@}" -ne $$ ]; then
export SSH_AUTH_SOCK="$(gpgconf --list-dirs agent-ssh-socket)"
fi
@end example
@end cartouche
@c
@c Assuan Protocol
@c
@manpause
@node Agent Protocol
@section Agent's Assuan Protocol
Note: this section does only document the protocol, which is used by
GnuPG components; it does not deal with the ssh-agent protocol. To
see the full specification of each command, use
@example
gpg-connect-agent 'help COMMAND' /bye
@end example
@noindent
or just 'help' to list all available commands.
@noindent
The @command{gpg-agent} daemon is started on demand by the GnuPG
components.
To identify a key we use a thing called keygrip which is the SHA-1 hash
of an canonical encoded S-Expression of the public key as used in
Libgcrypt. For the purpose of this interface the keygrip is given as a
hex string. The advantage of using this and not the hash of a
certificate is that it will be possible to use the same keypair for
different protocols, thereby saving space on the token used to keep the
secret keys.
The @command{gpg-agent} may send status messages during a command or when
returning from a command to inform a client about the progress or result of an
operation. For example, the @var{INQUIRE_MAXLEN} status message may be sent
during a server inquire to inform the client of the maximum usable length of
the inquired data (which should not be exceeded).
@menu
* Agent PKDECRYPT:: Decrypting a session key
* Agent PKSIGN:: Signing a Hash
* Agent GENKEY:: Generating a Key
* Agent IMPORT:: Importing a Secret Key
* Agent EXPORT:: Exporting a Secret Key
* Agent ISTRUSTED:: Importing a Root Certificate
* Agent GET_PASSPHRASE:: Ask for a passphrase
* Agent CLEAR_PASSPHRASE:: Expire a cached passphrase
* Agent PRESET_PASSPHRASE:: Set a passphrase for a keygrip
* Agent GET_CONFIRMATION:: Ask for confirmation
* Agent HAVEKEY:: Check whether a key is available
* Agent LEARN:: Register a smartcard
* Agent PASSWD:: Change a Passphrase
* Agent UPDATESTARTUPTTY:: Change the Standard Display
* Agent GETEVENTCOUNTER:: Get the Event Counters
* Agent GETINFO:: Return information about the process
* Agent OPTION:: Set options for the session
@end menu
@node Agent PKDECRYPT
@subsection Decrypting a session key
The client asks the server to decrypt a session key. The encrypted
session key should have all information needed to select the
appropriate secret key or to delegate it to a smartcard.
@example
SETKEY <keyGrip>
@end example
Tell the server about the key to be used for decryption. If this is
not used, @command{gpg-agent} may try to figure out the key by trying to
decrypt the message with each key available.
@example
PKDECRYPT
@end example
The agent checks whether this command is allowed and then does an
INQUIRY to get the ciphertext the client should then send the cipher
text.
@example
S: INQUIRE CIPHERTEXT
C: D (xxxxxx
C: D xxxx)
C: END
@end example
Please note that the server may send status info lines while reading the
data lines from the client. The data send is a SPKI like S-Exp with
this structure:
@example
(enc-val
(<algo>
(<param_name1> <mpi>)
...
(<param_namen> <mpi>)))
@end example
Where algo is a string with the name of the algorithm; see the libgcrypt
documentation for a list of valid algorithms. The number and names of
the parameters depend on the algorithm. The agent does return an error
if there is an inconsistency.
If the decryption was successful the decrypted data is returned by
means of "D" lines.
Here is an example session:
@cartouche
@smallexample
C: PKDECRYPT
S: INQUIRE CIPHERTEXT
C: D (enc-val elg (a 349324324)
C: D (b 3F444677CA)))
C: END
S: # session key follows
S: S PADDING 0
S: D (value 1234567890ABCDEF0)
S: OK decryption successful
@end smallexample
@end cartouche
The “PADDING” status line is only send if gpg-agent can tell what kind
of padding is used. As of now only the value 0 is used to indicate
that the padding has been removed.
@node Agent PKSIGN
@subsection Signing a Hash
The client asks the agent to sign a given hash value. A default key
will be chosen if no key has been set. To set a key a client first
uses:
@example
SIGKEY <keyGrip>
@end example
This can be used multiple times to create multiple signature, the list
of keys is reset with the next PKSIGN command or a RESET. The server
tests whether the key is a valid key to sign something and responds with
okay.
@example
SETHASH --hash=<name>|<algo> <hexstring>
@end example
The client can use this command to tell the server about the data <hexstring>
(which usually is a hash) to be signed. <algo> is the decimal encoded hash
algorithm number as used by Libgcrypt. Either <algo> or --hash=<name>
must be given. Valid names for <name> are:
@table @code
@item sha1
The SHA-1 hash algorithm
@item sha256
The SHA-256 hash algorithm
@item rmd160
The RIPE-MD160 hash algorithm
@item md5
The old and broken MD5 hash algorithm
@item tls-md5sha1
A combined hash algorithm as used by the TLS protocol.
@end table
@noindent
The actual signing is done using
@example
PKSIGN <options>
@end example
Options are not yet defined, but may later be used to choose among
different algorithms. The agent does then some checks, asks for the
passphrase and as a result the server returns the signature as an SPKI
like S-expression in "D" lines:
@example
(sig-val
(<algo>
(<param_name1> <mpi>)
...
(<param_namen> <mpi>)))
@end example
The operation is affected by the option
@example
OPTION use-cache-for-signing=0|1
@end example
The default of @code{1} uses the cache. Setting this option to @code{0}
will lead @command{gpg-agent} to ignore the passphrase cache. Note, that there is
also a global command line option for @command{gpg-agent} to globally disable the
caching.
Here is an example session:
@cartouche
@smallexample
C: SIGKEY <keyGrip>
S: OK key available
C: SIGKEY <keyGrip>
S: OK key available
C: PKSIGN
S: # I did ask the user whether he really wants to sign
S: # I did ask the user for the passphrase
S: INQUIRE HASHVAL
C: D ABCDEF012345678901234
C: END
S: # signature follows
S: D (sig-val rsa (s 45435453654612121212))
S: OK
@end smallexample
@end cartouche
@node Agent GENKEY
@subsection Generating a Key
This is used to create a new keypair and store the secret key inside the
active PSE --- which is in most cases a Soft-PSE. A not-yet-defined
option allows choosing the storage location. To get the secret key out
of the PSE, a special export tool has to be used.
@example
GENKEY [--no-protection] [--preset] [<cache_nonce>]
@end example
Invokes the key generation process and the server will then inquire
on the generation parameters, like:
@example
S: INQUIRE KEYPARM
C: D (genkey (rsa (nbits 1024)))
C: END
@end example
The format of the key parameters which depends on the algorithm is of
the form:
@example
(genkey
(algo
(parameter_name_1 ....)
....
(parameter_name_n ....)))
@end example
If everything succeeds, the server returns the *public key* in a SPKI
like S-Expression like this:
@example
(public-key
(rsa
(n <mpi>)
(e <mpi>)))
@end example
Here is an example session:
@cartouche
@smallexample
C: GENKEY
S: INQUIRE KEYPARM
C: D (genkey (rsa (nbits 1024)))
C: END
S: D (public-key
S: D (rsa (n 326487324683264) (e 10001)))
S OK key created
@end smallexample
@end cartouche
The @option{--no-protection} option may be used to prevent prompting for a
passphrase to protect the secret key while leaving the secret key unprotected.
The @option{--preset} option may be used to add the passphrase to the cache
using the default cache parameters.
The @option{--inq-passwd} option may be used to create the key with a
supplied passphrase. When used the agent does an inquiry with the
keyword @code{NEWPASSWD} to retrieve that passphrase. This option
takes precedence over @option{--no-protection}; however if the client
sends a empty (zero-length) passphrase, this is identical to
@option{--no-protection}.
@node Agent IMPORT
@subsection Importing a Secret Key
This operation is not yet supported by GpgAgent. Specialized tools
are to be used for this.
There is no actual need because we can expect that secret keys
created by a 3rd party are stored on a smartcard. If we have
generated the key ourselves, we do not need to import it.
@node Agent EXPORT
@subsection Export a Secret Key
Not implemented.
Should be done by an extra tool.
@node Agent ISTRUSTED
@subsection Importing a Root Certificate
Actually we do not import a Root Cert but provide a way to validate
any piece of data by storing its Hash along with a description and
an identifier in the PSE. Here is the interface description:
@example
ISTRUSTED <fingerprint>
@end example
Check whether the OpenPGP primary key or the X.509 certificate with the
given fingerprint is an ultimately trusted key or a trusted Root CA
certificate. The fingerprint should be given as a hexstring (without
any blanks or colons or whatever in between) and may be left padded with
00 in case of an MD5 fingerprint. GPGAgent will answer with:
@example
OK
@end example
The key is in the table of trusted keys.
@example
ERR 304 (Not Trusted)
@end example
The key is not in this table.
Gpg needs the entire list of trusted keys to maintain the web of
trust; the following command is therefore quite helpful:
@example
LISTTRUSTED
@end example
GpgAgent returns a list of trusted keys line by line:
@example
S: D 000000001234454556565656677878AF2F1ECCFF P
S: D 340387563485634856435645634856438576457A P
S: D FEDC6532453745367FD83474357495743757435D S
S: OK
@end example
The first item on a line is the hexified fingerprint where MD5
fingerprints are @code{00} padded to the left and the second item is a
flag to indicate the type of key (so that gpg is able to only take care
of PGP keys). P = OpenPGP, S = S/MIME. A client should ignore the rest
of the line, so that we can extend the format in the future.
Finally a client should be able to mark a key as trusted:
@example
MARKTRUSTED @var{fingerprint} "P"|"S"
@end example
The server will then pop up a window to ask the user whether she
really trusts this key. For this it will probably ask for a text to
be displayed like this:
@example
S: INQUIRE TRUSTDESC
C: D Do you trust the key with the fingerprint @@FPR@@
C: D bla fasel blurb.
C: END
S: OK
@end example
Known sequences with the pattern @@foo@@ are replaced according to this
table:
@table @code
@item @@FPR16@@
Format the fingerprint according to gpg rules for a v3 keys.
@item @@FPR20@@
Format the fingerprint according to gpg rules for a v4 keys.
@item @@FPR@@
Choose an appropriate format to format the fingerprint.
@item @@@@
Replaced by a single @code{@@}.
@end table
@node Agent GET_PASSPHRASE
@subsection Ask for a passphrase
This function is usually used to ask for a passphrase to be used for
symmetric encryption, but may also be used by programs which need
special handling of passphrases. This command uses a syntax which helps
clients to use the agent with minimum effort.
@example
GET_PASSPHRASE [--data] [--check] [--no-ask] [--repeat[=N]] \
[--qualitybar] @var{cache_id} \
[@var{error_message} @var{prompt} @var{description}]
@end example
@var{cache_id} is expected to be a string used to identify a cached
passphrase. Use a @code{X} to bypass the cache. With no other
arguments the agent returns a cached passphrase or an error. By
convention either the hexified fingerprint of the key shall be used for
@var{cache_id} or an arbitrary string prefixed with the name of the
calling application and a colon: Like @code{gpg:somestring}.
@var{error_message} is either a single @code{X} for no error message or
a string to be shown as an error message like (e.g. "invalid
passphrase"). Blanks must be percent escaped or replaced by @code{+}'.
@var{prompt} is either a single @code{X} for a default prompt or the
text to be shown as the prompt. Blanks must be percent escaped or
replaced by @code{+}.
@var{description} is a text shown above the entry field. Blanks must be
percent escaped or replaced by @code{+}.
The agent either returns with an error or with a OK followed by the hex
encoded passphrase. Note that the length of the strings is implicitly
limited by the maximum length of a command. If the option
@option{--data} is used, the passphrase is not returned on the OK line
but by regular data lines; this is the preferred method.
If the option @option{--check} is used, the standard passphrase
constraints checks are applied. A check is not done if the passphrase
has been found in the cache.
If the option @option{--no-ask} is used and the passphrase is not in the
cache the user will not be asked to enter a passphrase but the error
code @code{GPG_ERR_NO_DATA} is returned.
If the option @option{--qualitybar} is used and a minimum passphrase
length has been configured, a visual indication of the entered
passphrase quality is shown.
@example
CLEAR_PASSPHRASE @var{cache_id}
@end example
may be used to invalidate the cache entry for a passphrase. The
function returns with OK even when there is no cached passphrase.
@node Agent CLEAR_PASSPHRASE
@subsection Remove a cached passphrase
Use this command to remove a cached passphrase.
@example
CLEAR_PASSPHRASE [--mode=normal] <cache_id>
@end example
The @option{--mode=normal} option can be used to clear a @var{cache_id} that
was set by gpg-agent.
@node Agent PRESET_PASSPHRASE
@subsection Set a passphrase for a keygrip
This command adds a passphrase to the cache for the specified @var{keygrip}.
@example
PRESET_PASSPHRASE [--inquire] <string_or_keygrip> <timeout> [<hexstring>]
@end example
The passphrase is a hexadecimal string when specified. When not specified, the
passphrase will be retrieved from the pinentry module unless the
@option{--inquire} option was specified in which case the passphrase will be
retrieved from the client.
The @var{timeout} parameter keeps the passphrase cached for the specified
number of seconds. A value of @code{-1} means infinite while @code{0} means
the default (currently only a timeout of -1 is allowed, which means to never
expire it).
@node Agent GET_CONFIRMATION
@subsection Ask for confirmation
This command may be used to ask for a simple confirmation by
presenting a text and 2 buttons: Okay and Cancel.
@example
GET_CONFIRMATION @var{description}
@end example
@var{description}is displayed along with a Okay and Cancel
button. Blanks must be percent escaped or replaced by @code{+}. A
@code{X} may be used to display confirmation dialog with a default
text.
The agent either returns with an error or with a OK. Note, that the
length of @var{description} is implicitly limited by the maximum
length of a command.
@node Agent HAVEKEY
@subsection Check whether a key is available
This can be used to see whether a secret key is available. It does
not return any information on whether the key is somehow protected.
@example
HAVEKEY @var{keygrips}
@end example
The agent answers either with OK or @code{No_Secret_Key} (208). The
caller may want to check for other error codes as well. More than one
keygrip may be given. In this case the command returns success if at
least one of the keygrips corresponds to an available secret key.
@node Agent LEARN
@subsection Register a smartcard
@example
LEARN [--send]
@end example
This command is used to register a smartcard. With the @option{--send}
option given the certificates are sent back.
@node Agent PASSWD
@subsection Change a Passphrase
@example
PASSWD [--cache-nonce=<c>] [--passwd-nonce=<s>] [--preset] @var{keygrip}
@end example
This command is used to interactively change the passphrase of the key
identified by the hex string @var{keygrip}. The @option{--preset}
option may be used to add the new passphrase to the cache using the
default cache parameters.
@node Agent UPDATESTARTUPTTY
@subsection Change the standard display
@example
UPDATESTARTUPTTY
@end example
Set the startup TTY and X-DISPLAY variables to the values of this
session. This command is useful to direct future pinentry invocations
to another screen. It is only required because there is no way in the
ssh-agent protocol to convey this information.
@node Agent GETEVENTCOUNTER
@subsection Get the Event Counters
@example
GETEVENTCOUNTER
@end example
This function return one status line with the current values of the
event counters. The event counters are useful to avoid polling by
delaying a poll until something has changed. The values are decimal
numbers in the range @code{0} to @code{UINT_MAX} and wrapping around to
0. The actual values should not be relied upon; they shall only be used
to detect a change.
The currently defined counters are:
@table @code
@item ANY
Incremented with any change of any of the other counters.
@item KEY
Incremented for added or removed private keys.
@item CARD
Incremented for changes of the card readers stati.
@end table
@node Agent GETINFO
@subsection Return information about the process
This is a multipurpose function to return a variety of information.
@example
GETINFO @var{what}
@end example
The value of @var{what} specifies the kind of information returned:
@table @code
@item version
Return the version of the program.
@item pid
Return the process id of the process.
@item socket_name
Return the name of the socket used to connect the agent.
@item ssh_socket_name
Return the name of the socket used for SSH connections. If SSH support
has not been enabled the error @code{GPG_ERR_NO_DATA} will be returned.
@end table
@node Agent OPTION
@subsection Set options for the session
Here is a list of session options which are not yet described with
other commands. The general syntax for an Assuan option is:
@smallexample
OPTION @var{key}=@var{value}
@end smallexample
@noindent
Supported @var{key}s are:
@table @code
@item agent-awareness
This may be used to tell gpg-agent of which gpg-agent version the
client is aware of. gpg-agent uses this information to enable
features which might break older clients.
@item putenv
Change the session's environment to be used for the
Pinentry. Valid values are:
@table @code
@item @var{name}
Delete envvar @var{name}
@item @var{name}=
Set envvar @var{name} to the empty string
@item @var{name}=@var{value}
Set envvar @var{name} to the string @var{value}.
@end table
@item use-cache-for-signing
See Assuan command @code{PKSIGN}.
@item allow-pinentry-notify
This does not need any value. It is used to enable the
PINENTRY_LAUNCHED inquiry.
@item pinentry-mode
This option is used to change the operation mode of the pinentry. The
following values are defined:
@table @code
@item ask
This is the default mode which pops up a pinentry as needed.
@item cancel
Instead of popping up a pinentry, return the error code
@code{GPG_ERR_CANCELED}.
@item error
Instead of popping up a pinentry, return the error code
@code{GPG_ERR_NO_PIN_ENTRY}.
@item loopback
Use a loopback pinentry. This fakes a pinentry by using inquiries
back to the caller to ask for a passphrase. This option may only be
set if the agent has been configured for that.
To disable this feature use @ref{option --no-allow-loopback-pinentry}.
@end table
@item cache-ttl-opt-preset
This option sets the cache TTL for new entries created by GENKEY and
PASSWD commands when using the @option{--preset} option. It is not
used a default value is used.
@item s2k-count
Instead of using the standard S2K count (which is computed on the
fly), the given S2K count is used for new keys or when changing the
passphrase of a key. Values below 65536 are considered to be 0. This
option is valid for the entire session or until reset to 0. This
option is useful if the key is later used on boxes which are either
much slower or faster than the actual box.
@item pretend-request-origin
This option switches the connection into a restricted mode which
handles all further commands in the same way as they would be handled
when originating from the extra or browser socket. Note that this
option is not available in the restricted mode. Valid values for this
option are:
@table @code
@item none
@itemx local
This is a NOP and leaves the connection in the standard way.
@item remote
Pretend to come from a remote origin in the same way as connections
from the @option{--extra-socket}.
@item browser
Pretend to come from a local web browser in the same way as connections
from the @option{--browser-socket}.
@end table
@end table
@mansect see also
@ifset isman
@command{@gpgname}(1),
@command{gpgsm}(1),
@command{gpgconf}(1),
@command{gpg-connect-agent}(1),
@command{scdaemon}(1)
@end ifset
@include see-also-note.texi
diff --git a/sm/call-agent.c b/sm/call-agent.c
index 5b1b0a9b0..5e56371fd 100644
--- a/sm/call-agent.c
+++ b/sm/call-agent.c
@@ -1,1482 +1,1484 @@
/* call-agent.c - Divert GPGSM operations to the agent
* Copyright (C) 2001, 2002, 2003, 2005, 2007,
* 2008, 2009, 2010 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GnuPG is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>
#include <assert.h>
#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif
#include "gpgsm.h"
#include <gcrypt.h>
#include <assuan.h>
#include "../common/i18n.h"
#include "../common/asshelp.h"
#include "keydb.h" /* fixme: Move this to import.c */
#include "../common/membuf.h"
#include "../common/shareddefs.h"
#include "passphrase.h"
static assuan_context_t agent_ctx = NULL;
struct cipher_parm_s
{
ctrl_t ctrl;
assuan_context_t ctx;
const unsigned char *ciphertext;
size_t ciphertextlen;
};
struct genkey_parm_s
{
ctrl_t ctrl;
assuan_context_t ctx;
const unsigned char *sexp;
size_t sexplen;
};
struct learn_parm_s
{
int error;
ctrl_t ctrl;
assuan_context_t ctx;
membuf_t *data;
};
struct import_key_parm_s
{
ctrl_t ctrl;
assuan_context_t ctx;
const void *key;
size_t keylen;
};
struct default_inq_parm_s
{
ctrl_t ctrl;
assuan_context_t ctx;
};
/* Print a warning if the server's version number is less than our
version number. Returns an error code on a connection problem. */
static gpg_error_t
warn_version_mismatch (ctrl_t ctrl, assuan_context_t ctx,
const char *servername, int mode)
{
gpg_error_t err;
char *serverversion;
const char *myversion = strusage (13);
err = get_assuan_server_version (ctx, mode, &serverversion);
if (err)
log_error (_("error getting version from '%s': %s\n"),
servername, gpg_strerror (err));
else if (compare_version_strings (serverversion, myversion) < 0)
{
char *warn;
warn = xtryasprintf (_("server '%s' is older than us (%s < %s)"),
servername, serverversion, myversion);
if (!warn)
err = gpg_error_from_syserror ();
else
{
log_info (_("WARNING: %s\n"), warn);
if (!opt.quiet)
{
log_info (_("Note: Outdated servers may lack important"
" security fixes.\n"));
log_info (_("Note: Use the command \"%s\" to restart them.\n"),
"gpgconf --kill all");
}
gpgsm_status2 (ctrl, STATUS_WARNING, "server_version_mismatch 0",
warn, NULL);
xfree (warn);
}
}
xfree (serverversion);
return err;
}
/* Try to connect to the agent via socket or fork it off and work by
pipes. Handle the server's initial greeting */
static int
start_agent (ctrl_t ctrl)
{
int rc;
if (agent_ctx)
rc = 0; /* fixme: We need a context for each thread or
serialize the access to the agent (which is
suitable given that the agent is not MT. */
else
{
rc = start_new_gpg_agent (&agent_ctx,
GPG_ERR_SOURCE_DEFAULT,
opt.agent_program,
opt.lc_ctype, opt.lc_messages,
opt.session_env,
opt.autostart, opt.verbose, DBG_IPC,
gpgsm_status2, ctrl);
if (!opt.autostart && gpg_err_code (rc) == GPG_ERR_NO_AGENT)
{
static int shown;
if (!shown)
{
shown = 1;
log_info (_("no gpg-agent running in this session\n"));
}
}
else if (!rc && !(rc = warn_version_mismatch (ctrl, agent_ctx,
GPG_AGENT_NAME, 0)))
{
/* Tell the agent that we support Pinentry notifications. No
error checking so that it will work also with older
agents. */
assuan_transact (agent_ctx, "OPTION allow-pinentry-notify",
NULL, NULL, NULL, NULL, NULL, NULL);
/* Pass on the pinentry mode. */
if (opt.pinentry_mode)
{
char *tmp = xasprintf ("OPTION pinentry-mode=%s",
str_pinentry_mode (opt.pinentry_mode));
rc = assuan_transact (agent_ctx, tmp,
NULL, NULL, NULL, NULL, NULL, NULL);
xfree (tmp);
if (rc)
log_error ("setting pinentry mode '%s' failed: %s\n",
str_pinentry_mode (opt.pinentry_mode),
gpg_strerror (rc));
}
/* Pass on the request origin. */
if (opt.request_origin)
{
char *tmp = xasprintf ("OPTION pretend-request-origin=%s",
str_request_origin (opt.request_origin));
rc = assuan_transact (agent_ctx, tmp,
NULL, NULL, NULL, NULL, NULL, NULL);
xfree (tmp);
if (rc)
log_error ("setting request origin '%s' failed: %s\n",
str_request_origin (opt.request_origin),
gpg_strerror (rc));
}
/* In DE_VS mode under Windows we require that the JENT RNG
* is active. */
#ifdef HAVE_W32_SYSTEM
if (!rc && opt.compliance == CO_DE_VS)
{
if (assuan_transact (agent_ctx, "GETINFO jent_active",
NULL, NULL, NULL, NULL, NULL, NULL))
{
rc = gpg_error (GPG_ERR_FORBIDDEN);
log_error (_("%s is not compliant with %s mode\n"),
GPG_AGENT_NAME,
gnupg_compliance_option_string (opt.compliance));
gpgsm_status_with_error (ctrl, STATUS_ERROR,
"random-compliance", rc);
}
}
#endif /*HAVE_W32_SYSTEM*/
}
}
if (!ctrl->agent_seen)
{
ctrl->agent_seen = 1;
audit_log_ok (ctrl->audit, AUDIT_AGENT_READY, rc);
}
return rc;
}
/* This is the default inquiry callback. It mainly handles the
Pinentry notifications. */
static gpg_error_t
default_inq_cb (void *opaque, const char *line)
{
gpg_error_t err = 0;
struct default_inq_parm_s *parm = opaque;
ctrl_t ctrl = parm->ctrl;
if (has_leading_keyword (line, "PINENTRY_LAUNCHED"))
{
err = gpgsm_proxy_pinentry_notify (ctrl, line);
if (err)
log_error (_("failed to proxy %s inquiry to client\n"),
"PINENTRY_LAUNCHED");
/* We do not pass errors to avoid breaking other code. */
}
else if ((has_leading_keyword (line, "PASSPHRASE")
|| has_leading_keyword (line, "NEW_PASSPHRASE"))
&& opt.pinentry_mode == PINENTRY_MODE_LOOPBACK
&& have_static_passphrase ())
{
const char *s = get_static_passphrase ();
err = assuan_send_data (parm->ctx, s, strlen (s));
}
else
log_error ("ignoring gpg-agent inquiry '%s'\n", line);
return err;
}
/* Call the agent to do a sign operation using the key identified by
the hex string KEYGRIP. */
int
gpgsm_agent_pksign (ctrl_t ctrl, const char *keygrip, const char *desc,
unsigned char *digest, size_t digestlen, int digestalgo,
unsigned char **r_buf, size_t *r_buflen )
{
int rc, i;
char *p, line[ASSUAN_LINELENGTH];
membuf_t data;
size_t len;
struct default_inq_parm_s inq_parm;
*r_buf = NULL;
rc = start_agent (ctrl);
if (rc)
return rc;
inq_parm.ctrl = ctrl;
inq_parm.ctx = agent_ctx;
if (digestlen*2 + 50 > DIM(line))
return gpg_error (GPG_ERR_GENERAL);
rc = assuan_transact (agent_ctx, "RESET", NULL, NULL, NULL, NULL, NULL, NULL);
if (rc)
return rc;
snprintf (line, DIM(line), "SIGKEY %s", keygrip);
rc = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL);
if (rc)
return rc;
if (desc)
{
snprintf (line, DIM(line), "SETKEYDESC %s", desc);
rc = assuan_transact (agent_ctx, line,
NULL, NULL, NULL, NULL, NULL, NULL);
if (rc)
return rc;
}
sprintf (line, "SETHASH %d ", digestalgo);
p = line + strlen (line);
for (i=0; i < digestlen ; i++, p += 2 )
sprintf (p, "%02X", digest[i]);
rc = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL);
if (rc)
return rc;
init_membuf (&data, 1024);
rc = assuan_transact (agent_ctx, "PKSIGN",
put_membuf_cb, &data, default_inq_cb, &inq_parm,
NULL, NULL);
if (rc)
{
xfree (get_membuf (&data, &len));
return rc;
}
*r_buf = get_membuf (&data, r_buflen);
if (!gcry_sexp_canon_len (*r_buf, *r_buflen, NULL, NULL))
{
xfree (*r_buf); *r_buf = NULL;
return gpg_error (GPG_ERR_INV_VALUE);
}
return *r_buf? 0 : out_of_core ();
}
/* Call the scdaemon to do a sign operation using the key identified by
the hex string KEYID. */
int
gpgsm_scd_pksign (ctrl_t ctrl, const char *keyid, const char *desc,
unsigned char *digest, size_t digestlen, int digestalgo,
unsigned char **r_buf, size_t *r_buflen )
{
int rc, i, pkalgo;
char *p, line[ASSUAN_LINELENGTH];
membuf_t data;
size_t len;
const char *hashopt;
unsigned char *sigbuf;
size_t sigbuflen;
struct default_inq_parm_s inq_parm;
gcry_sexp_t sig;
(void)desc;
*r_buf = NULL;
switch(digestalgo)
{
case GCRY_MD_SHA1: hashopt = "--hash=sha1"; break;
case GCRY_MD_RMD160:hashopt = "--hash=rmd160"; break;
case GCRY_MD_MD5: hashopt = "--hash=md5"; break;
case GCRY_MD_SHA256:hashopt = "--hash=sha256"; break;
case GCRY_MD_SHA384:hashopt = "--hash=sha384"; break;
case GCRY_MD_SHA512:hashopt = "--hash=sha512"; break;
default:
return gpg_error (GPG_ERR_DIGEST_ALGO);
}
rc = start_agent (ctrl);
if (rc)
return rc;
inq_parm.ctrl = ctrl;
inq_parm.ctx = agent_ctx;
if (digestlen*2 + 50 > DIM(line))
return gpg_error (GPG_ERR_GENERAL);
/* Get the key type from the scdaemon. */
snprintf (line, DIM(line), "SCD READKEY %s", keyid);
init_membuf (&data, 1024);
rc = assuan_transact (agent_ctx, line,
put_membuf_cb, &data, NULL, NULL, NULL, NULL);
if (rc)
{
xfree (get_membuf (&data, &len));
return rc;
}
p = get_membuf (&data, &len);
pkalgo = get_pk_algo_from_canon_sexp (p, len);
xfree (p);
if (!pkalgo)
return gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
p = stpcpy (line, "SCD SETDATA " );
for (i=0; i < digestlen ; i++, p += 2 )
sprintf (p, "%02X", digest[i]);
rc = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL);
if (rc)
return rc;
init_membuf (&data, 1024);
snprintf (line, DIM(line), "SCD PKSIGN %s %s", hashopt, keyid);
rc = assuan_transact (agent_ctx, line,
put_membuf_cb, &data, default_inq_cb, &inq_parm,
NULL, NULL);
if (rc)
{
xfree (get_membuf (&data, &len));
return rc;
}
sigbuf = get_membuf (&data, &sigbuflen);
switch(pkalgo)
{
case GCRY_PK_RSA:
rc = gcry_sexp_build (&sig, NULL, "(sig-val(rsa(s%b)))",
sigbuflen, sigbuf);
break;
case GCRY_PK_ECC:
rc = gcry_sexp_build (&sig, NULL, "(sig-val(ecdsa(r%b)(s%b)))",
sigbuflen/2, sigbuf,
sigbuflen/2, sigbuf + sigbuflen/2);
break;
default:
rc = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
break;
}
xfree (sigbuf);
if (rc)
return rc;
rc = make_canon_sexp (sig, r_buf, r_buflen);
gcry_sexp_release (sig);
if (rc)
return rc;
assert (gcry_sexp_canon_len (*r_buf, *r_buflen, NULL, NULL));
return 0;
}
/* Handle a CIPHERTEXT inquiry. Note, we only send the data,
assuan_transact takes care of flushing and writing the end */
static gpg_error_t
inq_ciphertext_cb (void *opaque, const char *line)
{
struct cipher_parm_s *parm = opaque;
int rc;
if (has_leading_keyword (line, "CIPHERTEXT"))
{
assuan_begin_confidential (parm->ctx);
rc = assuan_send_data (parm->ctx, parm->ciphertext, parm->ciphertextlen);
assuan_end_confidential (parm->ctx);
}
else
{
struct default_inq_parm_s inq_parm = { parm->ctrl, parm->ctx };
rc = default_inq_cb (&inq_parm, line);
}
return rc;
}
/* Call the agent to do a decrypt operation using the key identified by
the hex string KEYGRIP. */
int
gpgsm_agent_pkdecrypt (ctrl_t ctrl, const char *keygrip, const char *desc,
ksba_const_sexp_t ciphertext,
char **r_buf, size_t *r_buflen )
{
int rc;
char line[ASSUAN_LINELENGTH];
membuf_t data;
struct cipher_parm_s cipher_parm;
size_t n, len;
char *p, *buf, *endp;
size_t ciphertextlen;
if (!keygrip || strlen(keygrip) != 40 || !ciphertext || !r_buf || !r_buflen)
return gpg_error (GPG_ERR_INV_VALUE);
*r_buf = NULL;
ciphertextlen = gcry_sexp_canon_len (ciphertext, 0, NULL, NULL);
if (!ciphertextlen)
return gpg_error (GPG_ERR_INV_VALUE);
rc = start_agent (ctrl);
if (rc)
return rc;
rc = assuan_transact (agent_ctx, "RESET", NULL, NULL, NULL, NULL, NULL, NULL);
if (rc)
return rc;
assert ( DIM(line) >= 50 );
snprintf (line, DIM(line), "SETKEY %s", keygrip);
rc = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL);
if (rc)
return rc;
if (desc)
{
snprintf (line, DIM(line), "SETKEYDESC %s", desc);
rc = assuan_transact (agent_ctx, line,
NULL, NULL, NULL, NULL, NULL, NULL);
if (rc)
return rc;
}
init_membuf (&data, 1024);
cipher_parm.ctrl = ctrl;
cipher_parm.ctx = agent_ctx;
cipher_parm.ciphertext = ciphertext;
cipher_parm.ciphertextlen = ciphertextlen;
rc = assuan_transact (agent_ctx, "PKDECRYPT",
put_membuf_cb, &data,
inq_ciphertext_cb, &cipher_parm, NULL, NULL);
if (rc)
{
xfree (get_membuf (&data, &len));
return rc;
}
/* Make sure it is 0 terminated so we can invoke strtoul safely. */
put_membuf (&data, "", 1);
buf = get_membuf (&data, &len);
if (!buf)
return gpg_error (GPG_ERR_ENOMEM);
assert (len); /* (we forced Nul termination.) */
if (*buf == '(')
{
if (len < 13 || memcmp (buf, "(5:value", 8) ) /* "(5:valueN:D)\0" */
return gpg_error (GPG_ERR_INV_SEXP);
/* Trim any spurious trailing Nuls: */
while (buf[len-1] == 0)
len--;
if (buf[len-1] != ')')
return gpg_error (GPG_ERR_INV_SEXP);
len--; /* Drop the final close-paren: */
p = buf + 8; /* Skip leading parenthesis and the value tag. */
len -= 8; /* Count only the data of the second part. */
}
else
{
/* For compatibility with older gpg-agents handle the old style
incomplete S-exps. */
len--; /* Do not count the Nul. */
p = buf;
}
n = strtoul (p, &endp, 10);
if (!n || *endp != ':')
return gpg_error (GPG_ERR_INV_SEXP);
endp++;
if (endp-p+n != len)
return gpg_error (GPG_ERR_INV_SEXP); /* Oops: Inconsistent S-Exp. */
memmove (buf, endp, n);
*r_buflen = n;
*r_buf = buf;
return 0;
}
/* Handle a KEYPARMS inquiry. Note, we only send the data,
assuan_transact takes care of flushing and writing the end */
static gpg_error_t
inq_genkey_parms (void *opaque, const char *line)
{
struct genkey_parm_s *parm = opaque;
int rc;
if (has_leading_keyword (line, "KEYPARAM"))
{
rc = assuan_send_data (parm->ctx, parm->sexp, parm->sexplen);
}
else
{
struct default_inq_parm_s inq_parm = { parm->ctrl, parm->ctx };
rc = default_inq_cb (&inq_parm, line);
}
return rc;
}
/* Call the agent to generate a new key */
int
gpgsm_agent_genkey (ctrl_t ctrl,
ksba_const_sexp_t keyparms, ksba_sexp_t *r_pubkey)
{
int rc;
struct genkey_parm_s gk_parm;
membuf_t data;
size_t len;
unsigned char *buf;
gnupg_isotime_t timebuf;
char line[ASSUAN_LINELENGTH];
*r_pubkey = NULL;
rc = start_agent (ctrl);
if (rc)
return rc;
rc = assuan_transact (agent_ctx, "RESET", NULL, NULL, NULL, NULL, NULL, NULL);
if (rc)
return rc;
init_membuf (&data, 1024);
gk_parm.ctrl = ctrl;
gk_parm.ctx = agent_ctx;
gk_parm.sexp = keyparms;
gk_parm.sexplen = gcry_sexp_canon_len (keyparms, 0, NULL, NULL);
if (!gk_parm.sexplen)
return gpg_error (GPG_ERR_INV_VALUE);
gnupg_get_isotime (timebuf);
snprintf (line, sizeof line, "GENKEY --timestamp=%s", timebuf);
rc = assuan_transact (agent_ctx, line,
put_membuf_cb, &data,
inq_genkey_parms, &gk_parm, NULL, NULL);
if (rc)
{
xfree (get_membuf (&data, &len));
return rc;
}
buf = get_membuf (&data, &len);
if (!buf)
return gpg_error (GPG_ERR_ENOMEM);
if (!gcry_sexp_canon_len (buf, len, NULL, NULL))
{
xfree (buf);
return gpg_error (GPG_ERR_INV_SEXP);
}
*r_pubkey = buf;
return 0;
}
/* Call the agent to read the public key part for a given keygrip. If
FROMCARD is true, the key is directly read from the current
smartcard. In this case HEXKEYGRIP should be the keyID
(e.g. OPENPGP.3). */
int
gpgsm_agent_readkey (ctrl_t ctrl, int fromcard, const char *hexkeygrip,
ksba_sexp_t *r_pubkey)
{
int rc;
membuf_t data;
size_t len;
unsigned char *buf;
char line[ASSUAN_LINELENGTH];
struct default_inq_parm_s inq_parm;
*r_pubkey = NULL;
rc = start_agent (ctrl);
if (rc)
return rc;
inq_parm.ctrl = ctrl;
inq_parm.ctx = agent_ctx;
rc = assuan_transact (agent_ctx, "RESET",NULL, NULL, NULL, NULL, NULL, NULL);
if (rc)
return rc;
snprintf (line, DIM(line), "%sREADKEY %s",
fromcard? "SCD ":"", hexkeygrip);
init_membuf (&data, 1024);
rc = assuan_transact (agent_ctx, line,
put_membuf_cb, &data,
default_inq_cb, &inq_parm, NULL, NULL);
if (rc)
{
xfree (get_membuf (&data, &len));
return rc;
}
buf = get_membuf (&data, &len);
if (!buf)
return gpg_error (GPG_ERR_ENOMEM);
if (!gcry_sexp_canon_len (buf, len, NULL, NULL))
{
xfree (buf);
return gpg_error (GPG_ERR_INV_SEXP);
}
*r_pubkey = buf;
return 0;
}
/* Take the serial number from LINE and return it verbatim in a newly
allocated string. We make sure that only hex characters are
returned. */
static char *
store_serialno (const char *line)
{
const char *s;
char *p;
for (s=line; hexdigitp (s); s++)
;
p = xtrymalloc (s + 1 - line);
if (p)
{
memcpy (p, line, s-line);
p[s-line] = 0;
}
return p;
}
/* Callback for the gpgsm_agent_serialno function. */
static gpg_error_t
scd_serialno_status_cb (void *opaque, const char *line)
{
char **r_serialno = opaque;
const char *keyword = line;
int keywordlen;
for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
;
while (spacep (line))
line++;
if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen))
{
xfree (*r_serialno);
*r_serialno = store_serialno (line);
}
return 0;
}
/* Call the agent to read the serial number of the current card. */
int
gpgsm_agent_scd_serialno (ctrl_t ctrl, char **r_serialno)
{
int rc;
char *serialno = NULL;
struct default_inq_parm_s inq_parm;
*r_serialno = NULL;
rc = start_agent (ctrl);
if (rc)
return rc;
inq_parm.ctrl = ctrl;
inq_parm.ctx = agent_ctx;
rc = assuan_transact (agent_ctx, "SCD SERIALNO",
NULL, NULL,
default_inq_cb, &inq_parm,
scd_serialno_status_cb, &serialno);
if (!rc && !serialno)
rc = gpg_error (GPG_ERR_INTERNAL);
if (rc)
{
xfree (serialno);
return rc;
}
*r_serialno = serialno;
return 0;
}
/* Callback for the gpgsm_agent_serialno function. */
static gpg_error_t
scd_keypairinfo_status_cb (void *opaque, const char *line)
{
strlist_t *listaddr = opaque;
const char *keyword = line;
int keywordlen;
strlist_t sl;
char *p;
for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
;
while (spacep (line))
line++;
if (keywordlen == 11 && !memcmp (keyword, "KEYPAIRINFO", keywordlen))
{
sl = append_to_strlist (listaddr, line);
p = sl->d;
/* Make sure that we only have two tokens so that future
* extensions of the format won't change the format expected by
* the caller. */
while (*p && !spacep (p))
p++;
if (*p)
{
while (spacep (p))
p++;
while (*p && !spacep (p))
p++;
if (*p)
{
*p++ = 0;
while (spacep (p))
p++;
while (*p && !spacep (p))
{
switch (*p++)
{
case 'c': sl->flags |= GCRY_PK_USAGE_CERT; break;
case 's': sl->flags |= GCRY_PK_USAGE_SIGN; break;
case 'e': sl->flags |= GCRY_PK_USAGE_ENCR; break;
case 'a': sl->flags |= GCRY_PK_USAGE_AUTH; break;
}
}
}
}
}
return 0;
}
/* Call the agent to read the keypairinfo lines of the current card.
The list is returned as a string made up of the keygrip, a space
and the keyid. The flags of the string carry the usage bits. */
int
gpgsm_agent_scd_keypairinfo (ctrl_t ctrl, strlist_t *r_list)
{
int rc;
strlist_t list = NULL;
struct default_inq_parm_s inq_parm;
*r_list = NULL;
rc = start_agent (ctrl);
if (rc)
return rc;
inq_parm.ctrl = ctrl;
inq_parm.ctx = agent_ctx;
rc = assuan_transact (agent_ctx, "SCD LEARN --keypairinfo",
NULL, NULL,
default_inq_cb, &inq_parm,
scd_keypairinfo_status_cb, &list);
if (!rc && !list)
rc = gpg_error (GPG_ERR_NO_DATA);
if (rc)
{
free_strlist (list);
return rc;
}
*r_list = list;
return 0;
}
static gpg_error_t
istrusted_status_cb (void *opaque, const char *line)
{
struct rootca_flags_s *flags = opaque;
const char *s;
if ((s = has_leading_keyword (line, "TRUSTLISTFLAG")))
{
line = s;
if (has_leading_keyword (line, "relax"))
flags->relax = 1;
else if (has_leading_keyword (line, "cm"))
flags->chain_model = 1;
+ else if (has_leading_keyword (line, "qual"))
+ flags->qualified = 1;
}
return 0;
}
/* Ask the agent whether the certificate is in the list of trusted
keys. The certificate is either specified by the CERT object or by
the fingerprint HEXFPR. ROOTCA_FLAGS is guaranteed to be cleared
on error. */
int
gpgsm_agent_istrusted (ctrl_t ctrl, ksba_cert_t cert, const char *hexfpr,
struct rootca_flags_s *rootca_flags)
{
int rc;
char line[ASSUAN_LINELENGTH];
memset (rootca_flags, 0, sizeof *rootca_flags);
if (cert && hexfpr)
return gpg_error (GPG_ERR_INV_ARG);
rc = start_agent (ctrl);
if (rc)
return rc;
if (hexfpr)
{
snprintf (line, DIM(line), "ISTRUSTED %s", hexfpr);
}
else
{
char *fpr;
fpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1);
if (!fpr)
{
log_error ("error getting the fingerprint\n");
return gpg_error (GPG_ERR_GENERAL);
}
snprintf (line, DIM(line), "ISTRUSTED %s", fpr);
xfree (fpr);
}
rc = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL,
istrusted_status_cb, rootca_flags);
if (!rc)
rootca_flags->valid = 1;
return rc;
}
/* Ask the agent to mark CERT as a trusted Root-CA one */
int
gpgsm_agent_marktrusted (ctrl_t ctrl, ksba_cert_t cert)
{
int rc;
char *fpr, *dn, *dnfmt;
char line[ASSUAN_LINELENGTH];
struct default_inq_parm_s inq_parm;
rc = start_agent (ctrl);
if (rc)
return rc;
inq_parm.ctrl = ctrl;
inq_parm.ctx = agent_ctx;
fpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1);
if (!fpr)
{
log_error ("error getting the fingerprint\n");
return gpg_error (GPG_ERR_GENERAL);
}
dn = ksba_cert_get_issuer (cert, 0);
if (!dn)
{
xfree (fpr);
return gpg_error (GPG_ERR_GENERAL);
}
dnfmt = gpgsm_format_name2 (dn, 0);
xfree (dn);
if (!dnfmt)
return gpg_error_from_syserror ();
snprintf (line, DIM(line), "MARKTRUSTED %s S %s", fpr, dnfmt);
ksba_free (dnfmt);
xfree (fpr);
rc = assuan_transact (agent_ctx, line, NULL, NULL,
default_inq_cb, &inq_parm, NULL, NULL);
return rc;
}
/* Ask the agent whether the a corresponding secret key is available
for the given keygrip */
int
gpgsm_agent_havekey (ctrl_t ctrl, const char *hexkeygrip)
{
int rc;
char line[ASSUAN_LINELENGTH];
rc = start_agent (ctrl);
if (rc)
return rc;
if (!hexkeygrip || strlen (hexkeygrip) != 40)
return gpg_error (GPG_ERR_INV_VALUE);
snprintf (line, DIM(line), "HAVEKEY %s", hexkeygrip);
rc = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL);
return rc;
}
static gpg_error_t
learn_status_cb (void *opaque, const char *line)
{
struct learn_parm_s *parm = opaque;
const char *s;
/* Pass progress data to the caller. */
if ((s = has_leading_keyword (line, "PROGRESS")))
{
line = s;
if (parm->ctrl)
{
if (gpgsm_status (parm->ctrl, STATUS_PROGRESS, line))
return gpg_error (GPG_ERR_ASS_CANCELED);
}
}
return 0;
}
static gpg_error_t
learn_cb (void *opaque, const void *buffer, size_t length)
{
struct learn_parm_s *parm = opaque;
size_t len;
char *buf;
ksba_cert_t cert;
int rc;
char *string, *p, *pend;
strlist_t sl;
if (parm->error)
return 0;
if (buffer)
{
put_membuf (parm->data, buffer, length);
return 0;
}
/* END encountered - process what we have */
buf = get_membuf (parm->data, &len);
if (!buf)
{
parm->error = gpg_error (GPG_ERR_ENOMEM);
return 0;
}
if (gpgsm_status (parm->ctrl, STATUS_PROGRESS, "learncard C 0 0"))
return gpg_error (GPG_ERR_ASS_CANCELED);
/* FIXME: this should go into import.c */
rc = ksba_cert_new (&cert);
if (rc)
{
parm->error = rc;
return 0;
}
rc = ksba_cert_init_from_mem (cert, buf, len);
if (rc)
{
log_error ("failed to parse a certificate: %s\n", gpg_strerror (rc));
ksba_cert_release (cert);
parm->error = rc;
return 0;
}
/* Ignore certificates matching certain extended usage flags. */
rc = ksba_cert_get_ext_key_usages (cert, &string);
if (!rc)
{
p = string;
while (p && (pend=strchr (p, ':')))
{
*pend++ = 0;
for (sl=opt.ignore_cert_with_oid;
sl && strcmp (sl->d, p); sl = sl->next)
;
if (sl)
{
if (opt.verbose)
log_info ("certificate ignored due to OID %s\n", sl->d);
goto leave;
}
p = pend;
if ((p = strchr (p, '\n')))
p++;
}
}
else if (gpg_err_code (rc) != GPG_ERR_NO_DATA)
log_error (_("error getting key usage information: %s\n"),
gpg_strerror (rc));
xfree (string);
string = NULL;
/* We do not store a certifciate with missing issuers as ephemeral
because we can assume that the --learn-card command has been used
on purpose. */
rc = gpgsm_basic_cert_check (parm->ctrl, cert);
if (rc && gpg_err_code (rc) != GPG_ERR_MISSING_CERT
&& gpg_err_code (rc) != GPG_ERR_MISSING_ISSUER_CERT)
log_error ("invalid certificate: %s\n", gpg_strerror (rc));
else
{
int existed;
if (!keydb_store_cert (parm->ctrl, cert, 0, &existed))
{
if (opt.verbose > 1 && existed)
log_info ("certificate already in DB\n");
else if (opt.verbose && !existed)
log_info ("certificate imported\n");
}
}
leave:
xfree (string);
string = NULL;
ksba_cert_release (cert);
init_membuf (parm->data, 4096);
return 0;
}
/* Call the agent to learn about a smartcard */
int
gpgsm_agent_learn (ctrl_t ctrl)
{
int rc;
struct learn_parm_s learn_parm;
membuf_t data;
size_t len;
rc = start_agent (ctrl);
if (rc)
return rc;
rc = warn_version_mismatch (ctrl, agent_ctx, SCDAEMON_NAME, 2);
if (rc)
return rc;
init_membuf (&data, 4096);
learn_parm.error = 0;
learn_parm.ctrl = ctrl;
learn_parm.ctx = agent_ctx;
learn_parm.data = &data;
rc = assuan_transact (agent_ctx, "LEARN --send",
learn_cb, &learn_parm,
NULL, NULL,
learn_status_cb, &learn_parm);
xfree (get_membuf (&data, &len));
if (rc)
return rc;
return learn_parm.error;
}
/* Ask the agent to change the passphrase of the key identified by
HEXKEYGRIP. If DESC is not NULL, display instead of the default
description message. */
int
gpgsm_agent_passwd (ctrl_t ctrl, const char *hexkeygrip, const char *desc)
{
int rc;
char line[ASSUAN_LINELENGTH];
struct default_inq_parm_s inq_parm;
rc = start_agent (ctrl);
if (rc)
return rc;
inq_parm.ctrl = ctrl;
inq_parm.ctx = agent_ctx;
if (!hexkeygrip || strlen (hexkeygrip) != 40)
return gpg_error (GPG_ERR_INV_VALUE);
if (desc)
{
snprintf (line, DIM(line), "SETKEYDESC %s", desc);
rc = assuan_transact (agent_ctx, line,
NULL, NULL, NULL, NULL, NULL, NULL);
if (rc)
return rc;
}
snprintf (line, DIM(line), "PASSWD %s", hexkeygrip);
rc = assuan_transact (agent_ctx, line, NULL, NULL,
default_inq_cb, &inq_parm, NULL, NULL);
return rc;
}
/* Ask the agent to pop up a confirmation dialog with the text DESC
and an okay and cancel button. */
gpg_error_t
gpgsm_agent_get_confirmation (ctrl_t ctrl, const char *desc)
{
int rc;
char line[ASSUAN_LINELENGTH];
struct default_inq_parm_s inq_parm;
rc = start_agent (ctrl);
if (rc)
return rc;
inq_parm.ctrl = ctrl;
inq_parm.ctx = agent_ctx;
snprintf (line, DIM(line), "GET_CONFIRMATION %s", desc);
rc = assuan_transact (agent_ctx, line, NULL, NULL,
default_inq_cb, &inq_parm, NULL, NULL);
return rc;
}
/* Return 0 if the agent is alive. This is useful to make sure that
an agent has been started. */
gpg_error_t
gpgsm_agent_send_nop (ctrl_t ctrl)
{
int rc;
rc = start_agent (ctrl);
if (!rc)
rc = assuan_transact (agent_ctx, "NOP",
NULL, NULL, NULL, NULL, NULL, NULL);
return rc;
}
static gpg_error_t
keyinfo_status_cb (void *opaque, const char *line)
{
char **serialno = opaque;
const char *s, *s2;
if ((s = has_leading_keyword (line, "KEYINFO")) && !*serialno)
{
s = strchr (s, ' ');
if (s && s[1] == 'T' && s[2] == ' ' && s[3])
{
s += 3;
s2 = strchr (s, ' ');
if ( s2 > s )
{
*serialno = xtrymalloc ((s2 - s)+1);
if (*serialno)
{
memcpy (*serialno, s, s2 - s);
(*serialno)[s2 - s] = 0;
}
}
}
}
return 0;
}
/* Return the serial number for a secret key. If the returned serial
number is NULL, the key is not stored on a smartcard. Caller needs
to free R_SERIALNO. */
gpg_error_t
gpgsm_agent_keyinfo (ctrl_t ctrl, const char *hexkeygrip, char **r_serialno)
{
gpg_error_t err;
char line[ASSUAN_LINELENGTH];
char *serialno = NULL;
*r_serialno = NULL;
err = start_agent (ctrl);
if (err)
return err;
if (!hexkeygrip || strlen (hexkeygrip) != 40)
return gpg_error (GPG_ERR_INV_VALUE);
snprintf (line, DIM(line), "KEYINFO %s", hexkeygrip);
err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL,
keyinfo_status_cb, &serialno);
if (!err && serialno)
{
/* Sanity check for bad characters. */
if (strpbrk (serialno, ":\n\r"))
err = GPG_ERR_INV_VALUE;
}
if (err)
xfree (serialno);
else
*r_serialno = serialno;
return err;
}
/* Ask for the passphrase (this is used for pkcs#12 import/export. On
success the caller needs to free the string stored at R_PASSPHRASE.
On error NULL will be stored at R_PASSPHRASE and an appropriate
error code returned. If REPEAT is true the agent tries to get a
new passphrase (i.e. asks the user to confirm it). */
gpg_error_t
gpgsm_agent_ask_passphrase (ctrl_t ctrl, const char *desc_msg, int repeat,
char **r_passphrase)
{
gpg_error_t err;
char line[ASSUAN_LINELENGTH];
char *arg4 = NULL;
membuf_t data;
struct default_inq_parm_s inq_parm;
*r_passphrase = NULL;
err = start_agent (ctrl);
if (err)
return err;
inq_parm.ctrl = ctrl;
inq_parm.ctx = agent_ctx;
if (desc_msg && *desc_msg && !(arg4 = percent_plus_escape (desc_msg)))
return gpg_error_from_syserror ();
snprintf (line, DIM(line), "GET_PASSPHRASE --data%s -- X X X %s",
repeat? " --repeat=1 --check":"",
arg4);
xfree (arg4);
init_membuf_secure (&data, 64);
err = assuan_transact (agent_ctx, line,
put_membuf_cb, &data,
default_inq_cb, &inq_parm, NULL, NULL);
if (err)
xfree (get_membuf (&data, NULL));
else
{
put_membuf (&data, "", 1);
*r_passphrase = get_membuf (&data, NULL);
if (!*r_passphrase)
err = gpg_error_from_syserror ();
}
return err;
}
/* Retrieve a key encryption key from the agent. With FOREXPORT true
the key shall be use for export, with false for import. On success
the new key is stored at R_KEY and its length at R_KEKLEN. */
gpg_error_t
gpgsm_agent_keywrap_key (ctrl_t ctrl, int forexport,
void **r_kek, size_t *r_keklen)
{
gpg_error_t err;
membuf_t data;
size_t len;
unsigned char *buf;
char line[ASSUAN_LINELENGTH];
struct default_inq_parm_s inq_parm;
*r_kek = NULL;
err = start_agent (ctrl);
if (err)
return err;
inq_parm.ctrl = ctrl;
inq_parm.ctx = agent_ctx;
snprintf (line, DIM(line), "KEYWRAP_KEY %s",
forexport? "--export":"--import");
init_membuf_secure (&data, 64);
err = assuan_transact (agent_ctx, line,
put_membuf_cb, &data,
default_inq_cb, &inq_parm, NULL, NULL);
if (err)
{
xfree (get_membuf (&data, &len));
return err;
}
buf = get_membuf (&data, &len);
if (!buf)
return gpg_error_from_syserror ();
*r_kek = buf;
*r_keklen = len;
return 0;
}
/* Handle the inquiry for an IMPORT_KEY command. */
static gpg_error_t
inq_import_key_parms (void *opaque, const char *line)
{
struct import_key_parm_s *parm = opaque;
gpg_error_t err;
if (has_leading_keyword (line, "KEYDATA"))
{
assuan_begin_confidential (parm->ctx);
err = assuan_send_data (parm->ctx, parm->key, parm->keylen);
assuan_end_confidential (parm->ctx);
}
else
{
struct default_inq_parm_s inq_parm = { parm->ctrl, parm->ctx };
err = default_inq_cb (&inq_parm, line);
}
return err;
}
/* Call the agent to import a key into the agent. */
gpg_error_t
gpgsm_agent_import_key (ctrl_t ctrl, const void *key, size_t keylen)
{
gpg_error_t err;
struct import_key_parm_s parm;
gnupg_isotime_t timebuf;
char line[ASSUAN_LINELENGTH];
err = start_agent (ctrl);
if (err)
return err;
parm.ctrl = ctrl;
parm.ctx = agent_ctx;
parm.key = key;
parm.keylen = keylen;
gnupg_get_isotime (timebuf);
snprintf (line, sizeof line, "IMPORT_KEY --timestamp=%s", timebuf);
err = assuan_transact (agent_ctx, line,
NULL, NULL, inq_import_key_parms, &parm, NULL, NULL);
return err;
}
/* Receive a secret key from the agent. KEYGRIP is the hexified
keygrip, DESC a prompt to be displayed with the agent's passphrase
question (needs to be plus+percent escaped). On success the key is
stored as a canonical S-expression at R_RESULT and R_RESULTLEN. */
gpg_error_t
gpgsm_agent_export_key (ctrl_t ctrl, const char *keygrip, const char *desc,
unsigned char **r_result, size_t *r_resultlen)
{
gpg_error_t err;
membuf_t data;
size_t len;
unsigned char *buf;
char line[ASSUAN_LINELENGTH];
struct default_inq_parm_s inq_parm;
*r_result = NULL;
err = start_agent (ctrl);
if (err)
return err;
inq_parm.ctrl = ctrl;
inq_parm.ctx = agent_ctx;
if (desc)
{
snprintf (line, DIM(line), "SETKEYDESC %s", desc);
err = assuan_transact (agent_ctx, line,
NULL, NULL, NULL, NULL, NULL, NULL);
if (err)
return err;
}
snprintf (line, DIM(line), "EXPORT_KEY %s", keygrip);
init_membuf_secure (&data, 1024);
err = assuan_transact (agent_ctx, line,
put_membuf_cb, &data,
default_inq_cb, &inq_parm, NULL, NULL);
if (err)
{
xfree (get_membuf (&data, &len));
return err;
}
buf = get_membuf (&data, &len);
if (!buf)
return gpg_error_from_syserror ();
*r_result = buf;
*r_resultlen = len;
return 0;
}
diff --git a/sm/certchain.c b/sm/certchain.c
index 720648e06..57de48301 100644
--- a/sm/certchain.c
+++ b/sm/certchain.c
@@ -1,2414 +1,2418 @@
/* certchain.c - certificate chain validation
* Copyright (C) 2001, 2002, 2003, 2004, 2005,
* 2006, 2007, 2008, 2011 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GnuPG is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>
#include <stdarg.h>
#include <assert.h>
#include "gpgsm.h"
#include <gcrypt.h>
#include <ksba.h>
#include "keydb.h"
#include "../kbx/keybox.h" /* for KEYBOX_FLAG_* */
#include "../common/i18n.h"
#include "../common/tlv.h"
/* The OID for the authorityInfoAccess's caIssuers. */
static const char oidstr_caIssuers[] = "1.3.6.1.5.5.7.48.2";
/* Object to keep track of certain root certificates. */
struct marktrusted_info_s
{
struct marktrusted_info_s *next;
unsigned char fpr[20];
};
static struct marktrusted_info_s *marktrusted_info;
/* While running the validation function we want to keep track of the
certificates in the chain. This type is used for that. */
struct chain_item_s
{
struct chain_item_s *next;
ksba_cert_t cert; /* The certificate. */
int is_root; /* The certificate is the root certificate. */
};
typedef struct chain_item_s *chain_item_t;
static int is_root_cert (ksba_cert_t cert,
const char *issuerdn, const char *subjectdn);
static int get_regtp_ca_info (ctrl_t ctrl, ksba_cert_t cert, int *chainlen);
/* This function returns true if we already asked during this session
whether the root certificate CERT shall be marked as trusted. */
static int
already_asked_marktrusted (ksba_cert_t cert)
{
unsigned char fpr[20];
struct marktrusted_info_s *r;
gpgsm_get_fingerprint (cert, GCRY_MD_SHA1, fpr, NULL);
/* No context switches in the loop! */
for (r=marktrusted_info; r; r= r->next)
if (!memcmp (r->fpr, fpr, 20))
return 1;
return 0;
}
/* Flag certificate CERT as already asked whether it shall be marked
as trusted. */
static void
set_already_asked_marktrusted (ksba_cert_t cert)
{
unsigned char fpr[20];
struct marktrusted_info_s *r;
gpgsm_get_fingerprint (cert, GCRY_MD_SHA1, fpr, NULL);
for (r=marktrusted_info; r; r= r->next)
if (!memcmp (r->fpr, fpr, 20))
return; /* Already marked. */
r = xtrycalloc (1, sizeof *r);
if (!r)
return;
memcpy (r->fpr, fpr, 20);
r->next = marktrusted_info;
marktrusted_info = r;
}
/* If LISTMODE is true, print FORMAT using LISTMODE to FP. If
LISTMODE is false, use the string to print an log_info or, if
IS_ERROR is true, and log_error. */
static void
do_list (int is_error, int listmode, estream_t fp, const char *format, ...)
{
va_list arg_ptr;
va_start (arg_ptr, format) ;
if (listmode)
{
if (fp)
{
es_fputs (" [", fp);
es_vfprintf (fp, format, arg_ptr);
es_fputs ("]\n", fp);
}
}
else
{
log_logv (is_error? GPGRT_LOG_ERROR: GPGRT_LOG_INFO, format, arg_ptr);
log_printf ("\n");
}
va_end (arg_ptr);
}
/* Return 0 if A and B are equal. */
static int
compare_certs (ksba_cert_t a, ksba_cert_t b)
{
const unsigned char *img_a, *img_b;
size_t len_a, len_b;
img_a = ksba_cert_get_image (a, &len_a);
if (!img_a)
return 1;
img_b = ksba_cert_get_image (b, &len_b);
if (!img_b)
return 1;
return !(len_a == len_b && !memcmp (img_a, img_b, len_a));
}
/* Return true if CERT has the validityModel extensions and defines
the use of the chain model. */
static int
has_validation_model_chain (ksba_cert_t cert, int listmode, estream_t listfp)
{
gpg_error_t err;
int idx, yes;
const char *oid;
size_t off, derlen, objlen, hdrlen;
const unsigned char *der;
int class, tag, constructed, ndef;
char *oidbuf;
for (idx=0; !(err=ksba_cert_get_extension (cert, idx,
&oid, NULL, &off, &derlen));idx++)
if (!strcmp (oid, "1.3.6.1.4.1.8301.3.5") )
break;
if (err)
return 0; /* Not found. */
der = ksba_cert_get_image (cert, NULL);
if (!der)
{
err = gpg_error (GPG_ERR_INV_OBJ); /* Oops */
goto leave;
}
der += off;
err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
&ndef, &objlen, &hdrlen);
if (!err && (objlen > derlen || tag != TAG_SEQUENCE))
err = gpg_error (GPG_ERR_INV_OBJ);
if (err)
goto leave;
derlen = objlen;
err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
&ndef, &objlen, &hdrlen);
if (!err && (objlen > derlen || tag != TAG_OBJECT_ID))
err = gpg_error (GPG_ERR_INV_OBJ);
if (err)
goto leave;
oidbuf = ksba_oid_to_str (der, objlen);
if (!oidbuf)
{
err = gpg_error_from_syserror ();
goto leave;
}
if (opt.verbose)
do_list (0, listmode, listfp,
_("validation model requested by certificate: %s"),
!strcmp (oidbuf, "1.3.6.1.4.1.8301.3.5.1")? _("chain") :
!strcmp (oidbuf, "1.3.6.1.4.1.8301.3.5.2")? _("shell") :
/* */ oidbuf);
yes = !strcmp (oidbuf, "1.3.6.1.4.1.8301.3.5.1");
ksba_free (oidbuf);
return yes;
leave:
log_error ("error parsing validityModel: %s\n", gpg_strerror (err));
return 0;
}
static int
unknown_criticals (ksba_cert_t cert, int listmode, estream_t fp)
{
static const char *known[] = {
"2.5.29.15", /* keyUsage */
"2.5.29.17", /* subjectAltName
Japanese DoCoMo certs mark them as critical. PKIX
only requires them as critical if subjectName is
empty. I don't know whether our code gracefully
handles such empry subjectNames but that is
another story. */
"2.5.29.19", /* basic Constraints */
"2.5.29.32", /* certificatePolicies */
"2.5.29.37", /* extendedKeyUsage - handled by certlist.c */
"1.3.6.1.4.1.8301.3.5", /* validityModel - handled here. */
NULL
};
int rc = 0, i, idx, crit;
const char *oid;
gpg_error_t err;
int unsupported;
strlist_t sl;
for (idx=0; !(err=ksba_cert_get_extension (cert, idx,
&oid, &crit, NULL, NULL));idx++)
{
if (!crit)
continue;
for (i=0; known[i] && strcmp (known[i],oid); i++)
;
unsupported = !known[i];
/* If this critical extension is not supported. Check the list
of to be ignored extensions to see whether we claim that it
is supported. */
if (unsupported && opt.ignored_cert_extensions)
{
for (sl=opt.ignored_cert_extensions;
sl && strcmp (sl->d, oid); sl = sl->next)
;
if (sl)
unsupported = 0;
}
if (unsupported)
{
do_list (1, listmode, fp,
_("critical certificate extension %s is not supported"),
oid);
rc = gpg_error (GPG_ERR_UNSUPPORTED_CERT);
}
}
/* We ignore the error codes EOF as well as no-value. The later will
occur for certificates with no extensions at all. */
if (err
&& gpg_err_code (err) != GPG_ERR_EOF
&& gpg_err_code (err) != GPG_ERR_NO_VALUE)
rc = err;
return rc;
}
/* Check whether CERT is an allowed certificate. This requires that
CERT matches all requirements for such a CA, i.e. the
BasicConstraints extension. The function returns 0 on success and
the allowed length of the chain at CHAINLEN. */
static int
allowed_ca (ctrl_t ctrl,
ksba_cert_t cert, int *chainlen, int listmode, estream_t fp)
{
gpg_error_t err;
int flag;
err = ksba_cert_is_ca (cert, &flag, chainlen);
if (err)
return err;
if (!flag)
{
if (get_regtp_ca_info (ctrl, cert, chainlen))
{
/* Note that dirmngr takes a different way to cope with such
certs. */
return 0; /* RegTP issued certificate. */
}
do_list (1, listmode, fp,_("issuer certificate is not marked as a CA"));
return gpg_error (GPG_ERR_BAD_CA_CERT);
}
return 0;
}
static int
check_cert_policy (ksba_cert_t cert, int listmode, estream_t fplist)
{
static int no_policy_file;
gpg_error_t err;
char *policies;
estream_t fp;
int any_critical;
err = ksba_cert_get_cert_policies (cert, &policies);
if (gpg_err_code (err) == GPG_ERR_NO_DATA)
return 0; /* No policy given. */
if (err)
return err;
/* STRING is a line delimited list of certificate policies as stored
in the certificate. The line itself is colon delimited where the
first field is the OID of the policy and the second field either
N or C for normal or critical extension */
if (opt.verbose > 1 && !listmode)
log_info ("certificate's policy list: %s\n", policies);
/* The check is very minimal but won't give false positives */
any_critical = !!strstr (policies, ":C");
if (!opt.policy_file)
{
xfree (policies);
if (any_critical)
{
do_list (1, listmode, fplist,
_("critical marked policy without configured policies"));
return gpg_error (GPG_ERR_NO_POLICY_MATCH);
}
return 0;
}
if (no_policy_file)
{
/* Avoid trying to open the policy file if we already know that
* it does not exist. */
fp = NULL;
gpg_err_set_errno (ENOENT);
}
else
fp = es_fopen (opt.policy_file, "r");
if (!fp)
{
if ((opt.verbose || errno != ENOENT) && !no_policy_file)
log_info (_("failed to open '%s': %s\n"),
opt.policy_file, strerror (errno));
if (errno == ENOENT)
no_policy_file = 1;
xfree (policies);
/* With no critical policies this is only a warning */
if (!any_critical)
{
if (opt.verbose)
do_list (0, listmode, fplist,
_("Note: non-critical certificate policy not allowed"));
return 0;
}
do_list (1, listmode, fplist,
_("certificate policy not allowed"));
return gpg_error (GPG_ERR_NO_POLICY_MATCH);
}
/* FIXME: Cache the policy file content. */
for (;;)
{
int c;
char *p, line[256];
char *haystack, *allowed;
/* read line */
do
{
if (!es_fgets (line, DIM(line)-1, fp) )
{
gpg_error_t tmperr = gpg_error_from_syserror ();
xfree (policies);
if (es_feof (fp))
{
es_fclose (fp);
/* With no critical policies this is only a warning */
if (!any_critical)
{
if (opt.verbose)
do_list (0, listmode, fplist,
_("Note: non-critical certificate policy not allowed"));
return 0;
}
do_list (1, listmode, fplist,
_("certificate policy not allowed"));
return gpg_error (GPG_ERR_NO_POLICY_MATCH);
}
es_fclose (fp);
return tmperr;
}
if (!*line || line[strlen(line)-1] != '\n')
{
/* eat until end of line */
while ((c = es_getc (fp)) != EOF && c != '\n')
;
es_fclose (fp);
xfree (policies);
return gpg_error (*line? GPG_ERR_LINE_TOO_LONG
: GPG_ERR_INCOMPLETE_LINE);
}
/* Allow for empty lines and spaces */
for (p=line; spacep (p); p++)
;
}
while (!*p || *p == '\n' || *p == '#');
/* Parse line. Note that the line has always a LF and spacep
does not consider a LF a space. Thus strpbrk will always
succeed. */
for (allowed=line; spacep (allowed); allowed++)
;
p = strpbrk (allowed, " :\n");
if (!*p || p == allowed)
{
es_fclose (fp);
xfree (policies);
return gpg_error (GPG_ERR_CONFIGURATION);
}
*p = 0; /* strip the rest of the line */
/* See whether we find ALLOWED (which is an OID) in POLICIES */
for (haystack=policies; (p=strstr (haystack, allowed)); haystack = p+1)
{
if ( !(p == policies || p[-1] == '\n') )
continue; /* Does not match the begin of a line. */
if (p[strlen (allowed)] != ':')
continue; /* The length does not match. */
/* Yep - it does match so return okay. */
es_fclose (fp);
xfree (policies);
return 0;
}
}
}
/* Helper function for find_up. This resets the key handle and search
for an issuer ISSUER with a subjectKeyIdentifier of KEYID. Returns
0 on success or -1 when not found. */
static int
find_up_search_by_keyid (ctrl_t ctrl, KEYDB_HANDLE kh,
const char *issuer, ksba_sexp_t keyid)
{
int rc;
ksba_cert_t cert = NULL;
ksba_sexp_t subj = NULL;
ksba_isotime_t not_before, not_after, last_not_before, ne_last_not_before;
ksba_cert_t found_cert = NULL;
ksba_cert_t ne_found_cert = NULL;
keydb_search_reset (kh);
while (!(rc = keydb_search_subject (ctrl, kh, issuer)))
{
ksba_cert_release (cert); cert = NULL;
rc = keydb_get_cert (kh, &cert);
if (rc)
{
log_error ("keydb_get_cert() failed: rc=%d\n", rc);
rc = gpg_error (GPG_ERR_NOT_FOUND);
goto leave;
}
xfree (subj);
if (!ksba_cert_get_subj_key_id (cert, NULL, &subj))
{
if (!cmp_simple_canon_sexp (keyid, subj))
{
/* Found matching cert. */
rc = ksba_cert_get_validity (cert, 0, not_before);
if (!rc)
rc = ksba_cert_get_validity (cert, 1, not_after);
if (rc)
{
log_error ("keydb_get_validity() failed: rc=%d\n", rc);
rc = gpg_error (GPG_ERR_NOT_FOUND);
goto leave;
}
if (!found_cert
|| strcmp (last_not_before, not_before) < 0)
{
/* This certificate is the first one found or newer
* than the previous one. This copes with
* re-issuing CA certificates while keeping the same
* key information. */
gnupg_copy_time (last_not_before, not_before);
ksba_cert_release (found_cert);
ksba_cert_ref ((found_cert = cert));
keydb_push_found_state (kh);
}
if (*not_after && strcmp (ctrl->current_time, not_after) > 0 )
; /* CERT has expired - don't consider it. */
else if (!ne_found_cert
|| strcmp (ne_last_not_before, not_before) < 0)
{
/* This certificate is the first non-expired one
* found or newer than the previous non-expired one. */
gnupg_copy_time (ne_last_not_before, not_before);
ksba_cert_release (ne_found_cert);
ksba_cert_ref ((ne_found_cert = cert));
}
}
}
}
if (!found_cert)
goto leave;
/* Take the last saved one. Note that push/pop_found_state are
* misnomers because there is no stack of states. Renaming them to
* save/restore_found_state would be better. */
keydb_pop_found_state (kh);
rc = 0; /* Ignore EOF or other error after the first cert. */
/* We need to consider some corner cases. It is possible that we
* have a long term certificate (e.g. valid from 2008 to 2033) as
* well as a re-issued (i.e. using the same key material) short term
* certificate (say from 2016 to 2019). Using the short term
* certificate is the proper solution. But we need to take care if
* there is no re-issued new short term certificate (e.g. from 2020
* to 2023) available. In that case it is better to use the long
* term certificate which is still valid. The code may run into
* minor problems in the case of the chain validation mode. Given
* that this corner case is due to non-diligent PKI management we
* ignore this problem. */
/* The most common case is that the found certificate is not expired
* and thus identical to the one found from the list of non-expired
* certs. We can stop here. */
if (found_cert == ne_found_cert)
goto leave;
/* If we do not have a non expired certificate the actual cert is
* expired and we can also stop here. */
if (!ne_found_cert)
goto leave;
/* Now we need to see whether the found certificate is expired and
* only in this case we return the certificate found in the list of
* non-expired certs. */
rc = ksba_cert_get_validity (found_cert, 1, not_after);
if (rc)
{
log_error ("keydb_get_validity() failed: rc=%d\n", rc);
rc = gpg_error (GPG_ERR_NOT_FOUND);
goto leave;
}
if (*not_after && strcmp (ctrl->current_time, not_after) > 0 )
{ /* CERT has expired. Use the NE_FOUND_CERT. Because we have no
* found state for this we need to search for it again. */
unsigned char fpr[20];
gpgsm_get_fingerprint (ne_found_cert, GCRY_MD_SHA1, fpr, NULL);
keydb_search_reset (kh);
rc = keydb_search_fpr (ctrl, kh, fpr);
if (rc)
{
log_error ("keydb_search_fpr() failed: rc=%d\n", rc);
rc = gpg_error (GPG_ERR_NOT_FOUND);
goto leave;
}
/* Ready. The NE_FOUND_CERT is availabale via keydb_get_cert. */
}
leave:
ksba_cert_release (found_cert);
ksba_cert_release (ne_found_cert);
ksba_cert_release (cert);
xfree (subj);
return rc? gpg_error (GPG_ERR_NOT_FOUND) : 0;
}
struct find_up_store_certs_s
{
ctrl_t ctrl;
int count;
unsigned int want_fpr:1;
unsigned int got_fpr:1;
unsigned char fpr[20];
};
static void
find_up_store_certs_cb (void *cb_value, ksba_cert_t cert)
{
struct find_up_store_certs_s *parm = cb_value;
if (keydb_store_cert (parm->ctrl, cert, 1, NULL))
log_error ("error storing issuer certificate as ephemeral\n");
else if (parm->want_fpr && !parm->got_fpr)
{
if (!gpgsm_get_fingerprint (cert, 0, parm->fpr, NULL))
log_error (_("failed to get the fingerprint\n"));
else
parm->got_fpr = 1;
}
parm->count++;
}
/* Helper for find_up(). Locate the certificate for ISSUER using an
external lookup. KH is the keydb context we are currently using.
On success 0 is returned and the certificate may be retrieved from
the keydb using keydb_get_cert(). KEYID is the keyIdentifier from
the AKI or NULL. */
static int
find_up_external (ctrl_t ctrl, KEYDB_HANDLE kh,
const char *issuer, ksba_sexp_t keyid)
{
int rc;
strlist_t names = NULL;
struct find_up_store_certs_s find_up_store_certs_parm;
char *pattern;
const char *s;
find_up_store_certs_parm.ctrl = ctrl;
find_up_store_certs_parm.want_fpr = 0;
find_up_store_certs_parm.got_fpr = 0;
find_up_store_certs_parm.count = 0;
if (opt.verbose)
log_info (_("looking up issuer at external location\n"));
/* The Dirmngr process is confused about unknown attributes. As a
quick and ugly hack we locate the CN and use the issuer string
starting at this attribite. Fixme: we should have far better
parsing for external lookups in the Dirmngr. */
s = strstr (issuer, "CN=");
if (!s || s == issuer || s[-1] != ',')
s = issuer;
pattern = xtrymalloc (strlen (s)+2);
if (!pattern)
return gpg_error_from_syserror ();
strcpy (stpcpy (pattern, "/"), s);
add_to_strlist (&names, pattern);
xfree (pattern);
rc = gpgsm_dirmngr_lookup (ctrl, names, NULL, 0, find_up_store_certs_cb,
&find_up_store_certs_parm);
free_strlist (names);
if (opt.verbose)
log_info (_("number of issuers matching: %d\n"),
find_up_store_certs_parm.count);
if (rc)
{
log_error ("external key lookup failed: %s\n", gpg_strerror (rc));
rc = gpg_error (GPG_ERR_NOT_FOUND);
}
else if (!find_up_store_certs_parm.count)
rc = gpg_err_code (rc) == GPG_ERR_NOT_FOUND;
else
{
int old;
/* The issuers are currently stored in the ephemeral key DB, so
we temporary switch to ephemeral mode. */
old = keydb_set_ephemeral (kh, 1);
if (keyid)
rc = find_up_search_by_keyid (ctrl, kh, issuer, keyid);
else
{
keydb_search_reset (kh);
rc = keydb_search_subject (ctrl, kh, issuer);
}
keydb_set_ephemeral (kh, old);
}
return rc;
}
/* Helper for find_up(). Locate the certificate for CERT using the
* caIssuer from the authorityInfoAccess. KH is the keydb context we
* are currently using. On success 0 is returned and the certificate
* may be retrieved from the keydb using keydb_get_cert(). If no
* suitable authorityInfoAccess is encoded in the certificate
* GPG_ERR_NOT_FOUND is returned. */
static gpg_error_t
find_up_via_auth_info_access (ctrl_t ctrl, KEYDB_HANDLE kh, ksba_cert_t cert)
{
gpg_error_t err;
struct find_up_store_certs_s find_up_store_certs_parm;
char *url, *ldapurl;
int idx, i;
char *oid;
ksba_name_t name;
find_up_store_certs_parm.ctrl = ctrl;
find_up_store_certs_parm.want_fpr = 1;
find_up_store_certs_parm.got_fpr = 0;
find_up_store_certs_parm.count = 0;
/* Find suitable URLs; if there is a http scheme we prefer that. */
url = ldapurl = NULL;
for (idx=0;
!url && !(err = ksba_cert_get_authority_info_access (cert, idx,
&oid, &name));
idx++)
{
if (!strcmp (oid, oidstr_caIssuers))
{
for (i=0; !url && ksba_name_enum (name, i); i++)
{
char *p = ksba_name_get_uri (name, i);
if (p)
{
if (!strncmp (p, "http:", 5) || !strncmp (p, "https:", 6))
url = p;
else if (ldapurl)
xfree (p); /* We already got one. */
else if (!strncmp (p, "ldap:",5) || !strncmp (p, "ldaps:",6))
ldapurl = p;
}
else
xfree (p);
}
}
ksba_name_release (name);
ksba_free (oid);
}
if (err && gpg_err_code (err) != GPG_ERR_EOF)
{
log_error (_("can't get authorityInfoAccess: %s\n"), gpg_strerror (err));
return err;
}
if (!url && ldapurl)
{
/* No HTTP scheme; fallback to LDAP if available. */
url = ldapurl;
ldapurl = NULL;
}
xfree (ldapurl);
if (!url)
return gpg_error (GPG_ERR_NOT_FOUND);
if (opt.verbose)
log_info ("looking up issuer via authorityInfoAccess.caIssuers\n");
err = gpgsm_dirmngr_lookup (ctrl, NULL, url, 0, find_up_store_certs_cb,
&find_up_store_certs_parm);
/* Although we might receive several certificates we use only the
* first one. Or more exacty the first one for which we retrieved
* the fingerprint. */
if (opt.verbose)
log_info ("number of caIssuers found: %d\n",
find_up_store_certs_parm.count);
if (err)
{
log_error ("external URL lookup failed: %s\n", gpg_strerror (err));
err = gpg_error (GPG_ERR_NOT_FOUND);
}
else if (!find_up_store_certs_parm.got_fpr)
err = gpg_error (GPG_ERR_NOT_FOUND);
else
{
int old;
/* The retrieved certificates are currently stored in the
* ephemeral key DB, so we temporary switch to ephemeral
* mode. */
old = keydb_set_ephemeral (kh, 1);
keydb_search_reset (kh);
err = keydb_search_fpr (ctrl, kh, find_up_store_certs_parm.fpr);
keydb_set_ephemeral (kh, old);
}
return err;
}
/* Helper for find_up(). Ask the dirmngr for the certificate for
ISSUER with optional SERIALNO. KH is the keydb context we are
currently using. With SUBJECT_MODE set, ISSUER is searched as the
subject. On success 0 is returned and the certificate is available
in the ephemeral DB. */
static int
find_up_dirmngr (ctrl_t ctrl, KEYDB_HANDLE kh,
ksba_sexp_t serialno, const char *issuer, int subject_mode)
{
int rc;
strlist_t names = NULL;
struct find_up_store_certs_s find_up_store_certs_parm;
char *pattern;
(void)kh;
find_up_store_certs_parm.ctrl = ctrl;
find_up_store_certs_parm.count = 0;
if (opt.verbose)
log_info (_("looking up issuer from the Dirmngr cache\n"));
if (subject_mode)
{
pattern = xtrymalloc (strlen (issuer)+2);
if (pattern)
strcpy (stpcpy (pattern, "/"), issuer);
}
else if (serialno)
pattern = gpgsm_format_sn_issuer (serialno, issuer);
else
{
pattern = xtrymalloc (strlen (issuer)+3);
if (pattern)
strcpy (stpcpy (pattern, "#/"), issuer);
}
if (!pattern)
return gpg_error_from_syserror ();
add_to_strlist (&names, pattern);
xfree (pattern);
rc = gpgsm_dirmngr_lookup (ctrl, names, NULL, 1, find_up_store_certs_cb,
&find_up_store_certs_parm);
free_strlist (names);
if (opt.verbose)
log_info (_("number of matching certificates: %d\n"),
find_up_store_certs_parm.count);
if (rc && !opt.quiet)
log_info (_("dirmngr cache-only key lookup failed: %s\n"),
gpg_strerror (rc));
return ((!rc && find_up_store_certs_parm.count)
? 0 : gpg_error (GPG_ERR_NOT_FOUND));
}
/* Locate issuing certificate for CERT. ISSUER is the name of the
issuer used as a fallback if the other methods don't work. If
FIND_NEXT is true, the function shall return the next possible
issuer. The certificate itself is not directly returned but a
keydb_get_cert on the keydb context KH will return it. Returns 0
on success, GPG_ERR_NOT_FOUND if not found or another error code. */
static gpg_error_t
find_up (ctrl_t ctrl, KEYDB_HANDLE kh,
ksba_cert_t cert, const char *issuer, int find_next)
{
ksba_name_t authid;
ksba_sexp_t authidno;
ksba_sexp_t keyid;
gpg_error_t err = gpg_error (GPG_ERR_NOT_FOUND);
if (DBG_X509)
log_debug ("looking for parent certificate\n");
if (!ksba_cert_get_auth_key_id (cert, &keyid, &authid, &authidno))
{
const char *s = ksba_name_enum (authid, 0);
if (s && *authidno)
{
err = keydb_search_issuer_sn (ctrl, kh, s, authidno);
if (err)
keydb_search_reset (kh);
if (!err && DBG_X509)
log_debug (" found via authid and sn+issuer\n");
/* In case of an error, try to get the certificate from the
dirmngr. That is done by trying to put that certificate
into the ephemeral DB and let the code below do the
actual retrieve. Thus there is no error checking.
Skipped in find_next mode as usual. */
if (gpg_err_code (err) == GPG_ERR_NOT_FOUND && !find_next)
find_up_dirmngr (ctrl, kh, authidno, s, 0);
/* In case of an error try the ephemeral DB. We can't do
that in find_next mode because we can't keep the search
state then. */
if (gpg_err_code (err) == GPG_ERR_NOT_FOUND && !find_next)
{
int old = keydb_set_ephemeral (kh, 1);
if (!old)
{
err = keydb_search_issuer_sn (ctrl, kh, s, authidno);
if (err)
keydb_search_reset (kh);
if (!err && DBG_X509)
log_debug (" found via authid and sn+issuer (ephem)\n");
}
keydb_set_ephemeral (kh, old);
}
if (err) /* Need to make sure to have this error code. */
err = gpg_error (GPG_ERR_NOT_FOUND);
}
if (gpg_err_code (err) == GPG_ERR_NOT_FOUND && keyid && !find_next)
{
/* Not found by AKI.issuer_sn. Lets try the AKI.ki
instead. Loop over all certificates with that issuer as
subject and stop for the one with a matching
subjectKeyIdentifier. */
/* Fixme: Should we also search in the dirmngr? */
err = find_up_search_by_keyid (ctrl, kh, issuer, keyid);
if (!err && DBG_X509)
log_debug (" found via authid and keyid\n");
if (err)
{
int old = keydb_set_ephemeral (kh, 1);
if (!old)
err = find_up_search_by_keyid (ctrl, kh, issuer, keyid);
if (!err && DBG_X509)
log_debug (" found via authid and keyid (ephem)\n");
keydb_set_ephemeral (kh, old);
}
if (err) /* Need to make sure to have this error code. */
err = gpg_error (GPG_ERR_NOT_FOUND);
}
/* If we still didn't found it, try to find it via the subject
from the dirmngr-cache. */
if (gpg_err_code (err) == GPG_ERR_NOT_FOUND && !find_next)
{
if (!find_up_dirmngr (ctrl, kh, NULL, issuer, 1))
{
int old = keydb_set_ephemeral (kh, 1);
if (keyid)
err = find_up_search_by_keyid (ctrl, kh, issuer, keyid);
else
{
keydb_search_reset (kh);
err = keydb_search_subject (ctrl, kh, issuer);
}
keydb_set_ephemeral (kh, old);
}
if (err) /* Need to make sure to have this error code. */
err = gpg_error (GPG_ERR_NOT_FOUND);
if (!err && DBG_X509)
log_debug (" found via authid and issuer from dirmngr cache\n");
}
/* If we still didn't found it, try an external lookup. */
if (gpg_err_code (err) == GPG_ERR_NOT_FOUND
&& !find_next && !ctrl->offline)
{
/* We allow AIA also if CRLs are enabled; both can be used
* as a web bug so it does not make sense to not use AIA if
* CRL checks are enabled. */
if ((opt.auto_issuer_key_retrieve || !opt.no_crl_check)
&& !find_up_via_auth_info_access (ctrl, kh, cert))
{
if (DBG_X509)
log_debug (" found via authorityInfoAccess.caIssuers\n");
err = 0;
}
else if (opt.auto_issuer_key_retrieve)
{
err = find_up_external (ctrl, kh, issuer, keyid);
if (!err && DBG_X509)
log_debug (" found via authid and external lookup\n");
}
}
/* Print a note so that the user does not feel too helpless when
an issuer certificate was found and gpgsm prints BAD
signature because it is not the correct one. */
if (gpg_err_code (err) == GPG_ERR_NOT_FOUND && opt.quiet)
;
else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
{
log_info ("%sissuer certificate ", find_next?"next ":"");
if (keyid)
{
log_printf ("{");
gpgsm_dump_serial (keyid);
log_printf ("} ");
}
if (authidno)
{
log_printf ("(#");
gpgsm_dump_serial (authidno);
log_printf ("/");
gpgsm_dump_string (s);
log_printf (") ");
}
log_printf ("not found using authorityKeyIdentifier\n");
}
else if (err)
log_error ("failed to find authorityKeyIdentifier: err=%d\n", err);
xfree (keyid);
ksba_name_release (authid);
xfree (authidno);
}
if (err) /* Not found via authorithyKeyIdentifier, try regular issuer name. */
err = keydb_search_subject (ctrl, kh, issuer);
if (gpg_err_code (err) == GPG_ERR_NOT_FOUND && !find_next)
{
int old;
/* Also try to get it from the Dirmngr cache. The function
merely puts it into the ephemeral database. */
find_up_dirmngr (ctrl, kh, NULL, issuer, 0);
/* Not found, let us see whether we have one in the ephemeral key DB. */
old = keydb_set_ephemeral (kh, 1);
if (!old)
{
keydb_search_reset (kh);
err = keydb_search_subject (ctrl, kh, issuer);
}
keydb_set_ephemeral (kh, old);
if (!err && DBG_X509)
log_debug (" found via issuer\n");
}
/* Still not found. If enabled, try an external lookup. */
if (gpg_err_code (err) == GPG_ERR_NOT_FOUND && !find_next && !ctrl->offline)
{
if ((opt.auto_issuer_key_retrieve || !opt.no_crl_check)
&& !find_up_via_auth_info_access (ctrl, kh, cert))
{
if (DBG_X509)
log_debug (" found via authorityInfoAccess.caIssuers\n");
err = 0;
}
else if (opt.auto_issuer_key_retrieve)
{
err = find_up_external (ctrl, kh, issuer, NULL);
if (!err && DBG_X509)
log_debug (" found via issuer and external lookup\n");
}
}
return err;
}
/* Return the next certificate up in the chain starting at START.
Returns -1 when there are no more certificates. */
int
gpgsm_walk_cert_chain (ctrl_t ctrl, ksba_cert_t start, ksba_cert_t *r_next)
{
gpg_error_t err = 0;
char *issuer = NULL;
char *subject = NULL;
KEYDB_HANDLE kh = keydb_new ();
*r_next = NULL;
if (!kh)
{
log_error (_("failed to allocate keyDB handle\n"));
err = gpg_error (GPG_ERR_GENERAL);
goto leave;
}
issuer = ksba_cert_get_issuer (start, 0);
subject = ksba_cert_get_subject (start, 0);
if (!issuer)
{
log_error ("no issuer found in certificate\n");
err = gpg_error (GPG_ERR_BAD_CERT);
goto leave;
}
if (!subject)
{
log_error ("no subject found in certificate\n");
err = gpg_error (GPG_ERR_BAD_CERT);
goto leave;
}
if (is_root_cert (start, issuer, subject))
{
err = gpg_error (GPG_ERR_NOT_FOUND); /* we are at the root */
goto leave;
}
err = find_up (ctrl, kh, start, issuer, 0);
if (err)
{
/* It is quite common not to have a certificate, so better don't
print an error here. */
if (gpg_err_code (err) != GPG_ERR_NOT_FOUND && opt.verbose > 1)
log_error ("failed to find issuer's certificate: %s <%s>\n",
gpg_strerror (err), gpg_strsource (err));
err = gpg_error (GPG_ERR_MISSING_ISSUER_CERT);
goto leave;
}
err = keydb_get_cert (kh, r_next);
if (err)
{
log_error ("keydb_get_cert() failed: %s <%s>\n",
gpg_strerror (err), gpg_strsource (err));
err = gpg_error (GPG_ERR_GENERAL);
}
leave:
xfree (issuer);
xfree (subject);
keydb_release (kh);
return err;
}
/* Helper for gpgsm_is_root_cert. This one is used if the subject and
issuer DNs are already known. */
static int
is_root_cert (ksba_cert_t cert, const char *issuerdn, const char *subjectdn)
{
gpg_error_t err;
int result = 0;
ksba_sexp_t serialno;
ksba_sexp_t ak_keyid;
ksba_name_t ak_name;
ksba_sexp_t ak_sn;
const char *ak_name_str;
ksba_sexp_t subj_keyid = NULL;
if (!issuerdn || !subjectdn)
return 0; /* No. */
if (strcmp (issuerdn, subjectdn))
return 0; /* No. */
err = ksba_cert_get_auth_key_id (cert, &ak_keyid, &ak_name, &ak_sn);
if (err)
{
if (gpg_err_code (err) == GPG_ERR_NO_DATA)
return 1; /* Yes. Without a authorityKeyIdentifier this needs
to be the Root certificate (our trust anchor). */
log_error ("error getting authorityKeyIdentifier: %s\n",
gpg_strerror (err));
return 0; /* Well, it is broken anyway. Return No. */
}
serialno = ksba_cert_get_serial (cert);
if (!serialno)
{
log_error ("error getting serialno: %s\n", gpg_strerror (err));
goto leave;
}
/* Check whether the auth name's matches the issuer name+sn. If
that is the case this is a root certificate. */
ak_name_str = ksba_name_enum (ak_name, 0);
if (ak_name_str
&& !strcmp (ak_name_str, issuerdn)
&& !cmp_simple_canon_sexp (ak_sn, serialno))
{
result = 1; /* Right, CERT is self-signed. */
goto leave;
}
/* Similar for the ak_keyid. */
if (ak_keyid && !ksba_cert_get_subj_key_id (cert, NULL, &subj_keyid)
&& !cmp_simple_canon_sexp (ak_keyid, subj_keyid))
{
result = 1; /* Right, CERT is self-signed. */
goto leave;
}
leave:
ksba_free (subj_keyid);
ksba_free (ak_keyid);
ksba_name_release (ak_name);
ksba_free (ak_sn);
ksba_free (serialno);
return result;
}
/* Check whether the CERT is a root certificate. Returns True if this
is the case. */
int
gpgsm_is_root_cert (ksba_cert_t cert)
{
char *issuer;
char *subject;
int yes;
issuer = ksba_cert_get_issuer (cert, 0);
subject = ksba_cert_get_subject (cert, 0);
yes = is_root_cert (cert, issuer, subject);
xfree (issuer);
xfree (subject);
return yes;
}
/* This is a helper for gpgsm_validate_chain. */
static gpg_error_t
is_cert_still_valid (ctrl_t ctrl, int force_ocsp, int lm, estream_t fp,
ksba_cert_t subject_cert, ksba_cert_t issuer_cert,
int *any_revoked, int *any_no_crl, int *any_crl_too_old)
{
gpg_error_t err;
if (ctrl->offline || (opt.no_crl_check && !ctrl->use_ocsp))
{
audit_log_ok (ctrl->audit, AUDIT_CRL_CHECK,
gpg_error (GPG_ERR_NOT_ENABLED));
return 0;
}
if (!(force_ocsp || ctrl->use_ocsp)
&& !opt.enable_issuer_based_crl_check)
{
err = ksba_cert_get_crl_dist_point (subject_cert, 0, NULL, NULL, NULL);
if (gpg_err_code (err) == GPG_ERR_EOF)
{
/* No DP specified in the certificate. Thus the CA does not
* consider a CRL useful and the user of the certificate
* also does not consider this to be a critical thing. In
* this case we can conclude that the certificate shall not
* be revocable. Note that we reach this point here only if
* no OCSP responder shall be used. */
audit_log_ok (ctrl->audit, AUDIT_CRL_CHECK, gpg_error (GPG_ERR_TRUE));
return 0;
}
}
err = gpgsm_dirmngr_isvalid (ctrl,
subject_cert, issuer_cert,
force_ocsp? 2 : !!ctrl->use_ocsp);
audit_log_ok (ctrl->audit, AUDIT_CRL_CHECK, err);
if (err)
{
if (!lm)
gpgsm_cert_log_name (NULL, subject_cert);
switch (gpg_err_code (err))
{
case GPG_ERR_CERT_REVOKED:
do_list (1, lm, fp, _("certificate has been revoked"));
*any_revoked = 1;
/* Store that in the keybox so that key listings are able to
return the revoked flag. We don't care about error,
though. */
keydb_set_cert_flags (ctrl, subject_cert, 1, KEYBOX_FLAG_VALIDITY, 0,
~0, VALIDITY_REVOKED);
break;
case GPG_ERR_NO_CRL_KNOWN:
do_list (1, lm, fp, _("no CRL found for certificate"));
*any_no_crl = 1;
break;
case GPG_ERR_NO_DATA:
do_list (1, lm, fp, _("the status of the certificate is unknown"));
*any_no_crl = 1;
break;
case GPG_ERR_CRL_TOO_OLD:
do_list (1, lm, fp, _("the available CRL is too old"));
if (!lm)
log_info (_("please make sure that the "
"\"dirmngr\" is properly installed\n"));
*any_crl_too_old = 1;
break;
default:
do_list (1, lm, fp, _("checking the CRL failed: %s"),
gpg_strerror (err));
return err;
}
}
return 0;
}
/* Helper for gpgsm_validate_chain to check the validity period of
SUBJECT_CERT. The caller needs to pass EXPTIME which will be
updated to the nearest expiration time seen. A DEPTH of 0 indicates
the target certificate, -1 the final root certificate and other
values intermediate certificates. */
static gpg_error_t
check_validity_period (ksba_isotime_t current_time,
ksba_cert_t subject_cert,
ksba_isotime_t exptime,
int listmode, estream_t listfp, int depth)
{
gpg_error_t err;
ksba_isotime_t not_before, not_after;
err = ksba_cert_get_validity (subject_cert, 0, not_before);
if (!err)
err = ksba_cert_get_validity (subject_cert, 1, not_after);
if (err)
{
do_list (1, listmode, listfp,
_("certificate with invalid validity: %s"), gpg_strerror (err));
return gpg_error (GPG_ERR_BAD_CERT);
}
if (*not_after)
{
if (!*exptime)
gnupg_copy_time (exptime, not_after);
else if (strcmp (not_after, exptime) < 0 )
gnupg_copy_time (exptime, not_after);
}
if (*not_before && strcmp (current_time, not_before) < 0 )
{
do_list (1, listmode, listfp,
depth == 0 ? _("certificate not yet valid") :
depth == -1 ? _("root certificate not yet valid") :
/* other */ _("intermediate certificate not yet valid"));
if (!listmode)
{
log_info (" (valid from ");
dump_isotime (not_before);
log_printf (")\n");
}
return gpg_error (GPG_ERR_CERT_TOO_YOUNG);
}
if (*not_after && strcmp (current_time, not_after) > 0 )
{
do_list (opt.ignore_expiration?0:1, listmode, listfp,
depth == 0 ? _("certificate has expired") :
depth == -1 ? _("root certificate has expired") :
/* other */ _("intermediate certificate has expired"));
if (!listmode)
{
log_info (" (expired at ");
dump_isotime (not_after);
log_printf (")\n");
}
if (opt.ignore_expiration)
log_info ("WARNING: ignoring expiration\n");
else
return gpg_error (GPG_ERR_CERT_EXPIRED);
}
return 0;
}
/* This is a variant of check_validity_period used with the chain
model. The extra contraint here is that notBefore and notAfter
must exists and if the additional argument CHECK_TIME is given this
time is used to check the validity period of SUBJECT_CERT. */
static gpg_error_t
check_validity_period_cm (ksba_isotime_t current_time,
ksba_isotime_t check_time,
ksba_cert_t subject_cert,
ksba_isotime_t exptime,
int listmode, estream_t listfp, int depth)
{
gpg_error_t err;
ksba_isotime_t not_before, not_after;
err = ksba_cert_get_validity (subject_cert, 0, not_before);
if (!err)
err = ksba_cert_get_validity (subject_cert, 1, not_after);
if (err)
{
do_list (1, listmode, listfp,
_("certificate with invalid validity: %s"), gpg_strerror (err));
return gpg_error (GPG_ERR_BAD_CERT);
}
if (!*not_before || !*not_after)
{
do_list (1, listmode, listfp,
_("required certificate attributes missing: %s%s%s"),
!*not_before? "notBefore":"",
(!*not_before && !*not_after)? ", ":"",
!*not_before? "notAfter":"");
return gpg_error (GPG_ERR_BAD_CERT);
}
if (strcmp (not_before, not_after) > 0 )
{
do_list (1, listmode, listfp,
_("certificate with invalid validity"));
log_info (" (valid from ");
dump_isotime (not_before);
log_printf (" expired at ");
dump_isotime (not_after);
log_printf (")\n");
return gpg_error (GPG_ERR_BAD_CERT);
}
if (!*exptime)
gnupg_copy_time (exptime, not_after);
else if (strcmp (not_after, exptime) < 0 )
gnupg_copy_time (exptime, not_after);
if (strcmp (current_time, not_before) < 0 )
{
do_list (1, listmode, listfp,
depth == 0 ? _("certificate not yet valid") :
depth == -1 ? _("root certificate not yet valid") :
/* other */ _("intermediate certificate not yet valid"));
if (!listmode)
{
log_info (" (valid from ");
dump_isotime (not_before);
log_printf (")\n");
}
return gpg_error (GPG_ERR_CERT_TOO_YOUNG);
}
if (*check_time
&& (strcmp (check_time, not_before) < 0
|| strcmp (check_time, not_after) > 0))
{
/* Note that we don't need a case for the root certificate
because its own consistency has already been checked. */
do_list(opt.ignore_expiration?0:1, listmode, listfp,
depth == 0 ?
_("signature not created during lifetime of certificate") :
depth == 1 ?
_("certificate not created during lifetime of issuer") :
_("intermediate certificate not created during lifetime "
"of issuer"));
if (!listmode)
{
log_info (depth== 0? _(" ( signature created at ") :
/* */ _(" (certificate created at ") );
dump_isotime (check_time);
log_printf (")\n");
log_info (depth==0? _(" (certificate valid from ") :
/* */ _(" ( issuer valid from ") );
dump_isotime (not_before);
log_info (" to ");
dump_isotime (not_after);
log_printf (")\n");
}
if (opt.ignore_expiration)
log_info ("WARNING: ignoring expiration\n");
else
return gpg_error (GPG_ERR_CERT_EXPIRED);
}
return 0;
}
/* Ask the user whether he wants to mark the certificate CERT trusted.
Returns true if the CERT is the trusted. We also check whether the
agent is at all enabled to allow marktrusted and don't call it in
this session again if it is not. */
static int
ask_marktrusted (ctrl_t ctrl, ksba_cert_t cert, int listmode)
{
static int no_more_questions;
int rc;
char *fpr;
int success = 0;
fpr = gpgsm_get_fingerprint_string (cert, GCRY_MD_SHA1);
log_info (_("fingerprint=%s\n"), fpr? fpr : "?");
xfree (fpr);
if (no_more_questions)
rc = gpg_error (GPG_ERR_NOT_SUPPORTED);
else
rc = gpgsm_agent_marktrusted (ctrl, cert);
if (!rc)
{
log_info (_("root certificate has now been marked as trusted\n"));
success = 1;
}
else if (!listmode)
{
gpgsm_dump_cert ("issuer", cert);
log_info ("after checking the fingerprint, you may want "
"to add it manually to the list of trusted certificates.\n");
}
if (gpg_err_code (rc) == GPG_ERR_NOT_SUPPORTED)
{
if (!no_more_questions)
log_info (_("interactive marking as trusted "
"not enabled in gpg-agent\n"));
no_more_questions = 1;
}
else if (gpg_err_code (rc) == GPG_ERR_CANCELED)
{
log_info (_("interactive marking as trusted "
"disabled for this session\n"));
no_more_questions = 1;
}
else
set_already_asked_marktrusted (cert);
return success;
}
/* Validate a chain and optionally return the nearest expiration time
in R_EXPTIME. With LISTMODE set to 1 a special listmode is
activated where only information about the certificate is printed
to LISTFP and no output is send to the usual log stream. If
CHECKTIME_ARG is set, it is used only in the chain model instead of the
current time.
Defined flag bits
VALIDATE_FLAG_NO_DIRMNGR - Do not do any dirmngr isvalid checks.
VALIDATE_FLAG_CHAIN_MODEL - Check according to chain model.
VALIDATE_FLAG_STEED - Check according to the STEED model.
*/
static int
do_validate_chain (ctrl_t ctrl, ksba_cert_t cert, ksba_isotime_t checktime_arg,
ksba_isotime_t r_exptime,
int listmode, estream_t listfp, unsigned int flags,
struct rootca_flags_s *rootca_flags)
{
int rc = 0, depth, maxdepth;
char *issuer = NULL;
char *subject = NULL;
KEYDB_HANDLE kh = NULL;
ksba_cert_t subject_cert = NULL, issuer_cert = NULL;
ksba_isotime_t current_time;
ksba_isotime_t check_time;
ksba_isotime_t exptime;
int any_expired = 0;
int any_revoked = 0;
int any_no_crl = 0;
int any_crl_too_old = 0;
int any_no_policy_match = 0;
int is_qualified = -1; /* Indicates whether the certificate stems
from a qualified root certificate.
-1 = unknown, 0 = no, 1 = yes. */
chain_item_t chain = NULL; /* A list of all certificates in the chain. */
gnupg_get_isotime (current_time);
gnupg_copy_time (ctrl->current_time, current_time);
if ( (flags & VALIDATE_FLAG_CHAIN_MODEL) )
{
if (!strcmp (checktime_arg, "19700101T000000"))
{
do_list (1, listmode, listfp,
_("WARNING: creation time of signature not known - "
"assuming current time"));
gnupg_copy_time (check_time, current_time);
}
else
gnupg_copy_time (check_time, checktime_arg);
}
else
*check_time = 0;
if (r_exptime)
*r_exptime = 0;
*exptime = 0;
if (opt.no_chain_validation && !listmode)
{
log_info ("WARNING: bypassing certificate chain validation\n");
return 0;
}
kh = keydb_new ();
if (!kh)
{
log_error (_("failed to allocate keyDB handle\n"));
rc = gpg_error (GPG_ERR_GENERAL);
goto leave;
}
if (DBG_X509 && !listmode)
gpgsm_dump_cert ("target", cert);
subject_cert = cert;
ksba_cert_ref (subject_cert);
maxdepth = 50;
depth = 0;
for (;;)
{
int is_root;
gpg_error_t istrusted_rc = gpg_error (GPG_ERR_NOT_TRUSTED);
/* Put the certificate on our list. */
{
chain_item_t ci;
ci = xtrycalloc (1, sizeof *ci);
if (!ci)
{
rc = gpg_error_from_syserror ();
goto leave;
}
ksba_cert_ref (subject_cert);
ci->cert = subject_cert;
ci->next = chain;
chain = ci;
}
xfree (issuer);
xfree (subject);
issuer = ksba_cert_get_issuer (subject_cert, 0);
subject = ksba_cert_get_subject (subject_cert, 0);
if (!issuer)
{
do_list (1, listmode, listfp, _("no issuer found in certificate"));
rc = gpg_error (GPG_ERR_BAD_CERT);
goto leave;
}
/* Is this a self-issued certificate (i.e. the root certificate)? */
is_root = is_root_cert (subject_cert, issuer, subject);
if (is_root)
{
chain->is_root = 1;
/* Check early whether the certificate is listed as trusted.
We used to do this only later but changed it to call the
check right here so that we can access special flags
associated with that specific root certificate. */
if (gpgsm_cert_has_well_known_private_key (subject_cert))
{
memset (rootca_flags, 0, sizeof *rootca_flags);
istrusted_rc = ((flags & VALIDATE_FLAG_STEED)
? 0 : gpg_error (GPG_ERR_NOT_TRUSTED));
}
else
istrusted_rc = gpgsm_agent_istrusted (ctrl, subject_cert, NULL,
rootca_flags);
audit_log_cert (ctrl->audit, AUDIT_ROOT_TRUSTED,
subject_cert, istrusted_rc);
/* If the chain model extended attribute is used, make sure
that our chain model flag is set. */
if (!(flags & VALIDATE_FLAG_STEED)
&& has_validation_model_chain (subject_cert, listmode, listfp))
rootca_flags->chain_model = 1;
}
/* Check the validity period. */
if ( (flags & VALIDATE_FLAG_CHAIN_MODEL) )
rc = check_validity_period_cm (current_time, check_time, subject_cert,
exptime, listmode, listfp,
(depth && is_root)? -1: depth);
else
rc = check_validity_period (current_time, subject_cert,
exptime, listmode, listfp,
(depth && is_root)? -1: depth);
if (gpg_err_code (rc) == GPG_ERR_CERT_EXPIRED)
any_expired = 1;
else if (rc)
goto leave;
/* Assert that we understand all critical extensions. */
rc = unknown_criticals (subject_cert, listmode, listfp);
if (rc)
goto leave;
/* Do a policy check. */
if (!opt.no_policy_check)
{
rc = check_cert_policy (subject_cert, listmode, listfp);
if (gpg_err_code (rc) == GPG_ERR_NO_POLICY_MATCH)
{
any_no_policy_match = 1;
rc = 1; /* Be on the safe side and set RC. */
}
else if (rc)
goto leave;
}
/* If this is the root certificate we are at the end of the chain. */
if (is_root)
{
if (!istrusted_rc)
; /* No need to check the certificate for a trusted one. */
else if (gpgsm_check_cert_sig (subject_cert, subject_cert) )
{
/* We only check the signature if the certificate is not
trusted for better diagnostics. */
do_list (1, listmode, listfp,
_("self-signed certificate has a BAD signature"));
if (DBG_X509)
{
gpgsm_dump_cert ("self-signing cert", subject_cert);
}
rc = gpg_error (depth? GPG_ERR_BAD_CERT_CHAIN
: GPG_ERR_BAD_CERT);
goto leave;
}
if (!rootca_flags->relax)
{
rc = allowed_ca (ctrl, subject_cert, NULL, listmode, listfp);
if (rc)
goto leave;
}
/* Set the flag for qualified signatures. This flag is
deduced from a list of root certificates allowed for
qualified signatures. */
if (is_qualified == -1 && !(flags & VALIDATE_FLAG_STEED))
{
gpg_error_t err;
size_t buflen;
char buf[1];
if (!ksba_cert_get_user_data (cert, "is_qualified",
&buf, sizeof (buf),
&buflen) && buflen)
{
/* We already checked this for this certificate,
thus we simply take it from the user data. */
is_qualified = !!*buf;
}
else
{
/* Need to consult the list of root certificates for
- qualified signatures. */
- err = gpgsm_is_in_qualified_list (ctrl, subject_cert, NULL);
+ qualified signatures. But first we check the
+ modern way by looking at the root ca flag. */
+ if (rootca_flags->qualified)
+ err = 0;
+ else
+ err = gpgsm_is_in_qualified_list (ctrl, subject_cert, NULL);
if (!err)
is_qualified = 1;
else if ( gpg_err_code (err) == GPG_ERR_NOT_FOUND )
is_qualified = 0;
else
log_error ("checking the list of qualified "
"root certificates failed: %s\n",
gpg_strerror (err));
if ( is_qualified != -1 )
{
/* Cache the result but don't care too much
about an error. */
buf[0] = !!is_qualified;
err = ksba_cert_set_user_data (subject_cert,
"is_qualified", buf, 1);
if (err)
log_error ("set_user_data(is_qualified) failed: %s\n",
gpg_strerror (err));
}
}
}
/* Act on the check for a trusted root certificates. */
rc = istrusted_rc;
if (!rc)
;
else if (gpg_err_code (rc) == GPG_ERR_NOT_TRUSTED)
{
do_list (0, listmode, listfp,
_("root certificate is not marked trusted"));
/* If we already figured out that the certificate is
expired it does not make much sense to ask the user
whether they want to trust the root certificate. We
should do this only if the certificate under question
will then be usable. If the certificate has a well
known private key asking the user does not make any
sense. */
if ( !any_expired
&& !gpgsm_cert_has_well_known_private_key (subject_cert)
&& (!listmode || !already_asked_marktrusted (subject_cert))
&& ask_marktrusted (ctrl, subject_cert, listmode) )
rc = 0;
}
else
{
log_error (_("checking the trust list failed: %s\n"),
gpg_strerror (rc));
}
if (rc)
goto leave;
/* Check for revocations etc. */
if ((flags & VALIDATE_FLAG_NO_DIRMNGR))
;
else if ((flags & VALIDATE_FLAG_STEED))
; /* Fixme: check revocations via DNS. */
else if (opt.no_trusted_cert_crl_check || rootca_flags->relax)
;
else
rc = is_cert_still_valid (ctrl,
(flags & VALIDATE_FLAG_CHAIN_MODEL),
listmode, listfp,
subject_cert, subject_cert,
&any_revoked, &any_no_crl,
&any_crl_too_old);
if (rc)
goto leave;
break; /* Okay: a self-signed certificate is an end-point. */
} /* End is_root. */
/* Take care that the chain does not get too long. */
if ((depth+1) > maxdepth)
{
do_list (1, listmode, listfp, _("certificate chain too long\n"));
rc = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
goto leave;
}
/* Find the next cert up the tree. */
keydb_search_reset (kh);
rc = find_up (ctrl, kh, subject_cert, issuer, 0);
if (rc)
{
if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
{
do_list (0, listmode, listfp, _("issuer certificate not found"));
if (!listmode)
{
log_info ("issuer certificate: #/");
gpgsm_dump_string (issuer);
log_printf ("\n");
}
}
else
log_error ("failed to find issuer's certificate: %s <%s>\n",
gpg_strerror (rc), gpg_strsource (rc));
rc = gpg_error (GPG_ERR_MISSING_ISSUER_CERT);
goto leave;
}
ksba_cert_release (issuer_cert); issuer_cert = NULL;
rc = keydb_get_cert (kh, &issuer_cert);
if (rc)
{
log_error ("keydb_get_cert() failed: rc=%d\n", rc);
rc = gpg_error (GPG_ERR_GENERAL);
goto leave;
}
try_another_cert:
if (DBG_X509)
{
log_debug ("got issuer's certificate:\n");
gpgsm_dump_cert ("issuer", issuer_cert);
}
rc = gpgsm_check_cert_sig (issuer_cert, subject_cert);
if (rc)
{
do_list (0, listmode, listfp, _("certificate has a BAD signature"));
if (DBG_X509)
{
gpgsm_dump_cert ("signing issuer", issuer_cert);
gpgsm_dump_cert ("signed subject", subject_cert);
}
if (gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE)
{
/* We now try to find other issuer certificates which
might have been used. This is required because some
CAs are reusing the issuer and subject DN for new
root certificates. */
/* FIXME: Do this only if we don't have an
AKI.keyIdentifier */
rc = find_up (ctrl, kh, subject_cert, issuer, 1);
if (!rc)
{
ksba_cert_t tmp_cert;
rc = keydb_get_cert (kh, &tmp_cert);
if (rc || !compare_certs (issuer_cert, tmp_cert))
{
/* The find next did not work or returned an
identical certificate. We better stop here
to avoid infinite checks. */
/* No need to set RC because it is not used:
rc = gpg_error (GPG_ERR_BAD_SIGNATURE); */
ksba_cert_release (tmp_cert);
}
else
{
do_list (0, listmode, listfp,
_("found another possible matching "
"CA certificate - trying again"));
ksba_cert_release (issuer_cert);
issuer_cert = tmp_cert;
goto try_another_cert;
}
}
}
/* We give a more descriptive error code than the one
returned from the signature checking. */
rc = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
goto leave;
}
is_root = gpgsm_is_root_cert (issuer_cert);
istrusted_rc = gpg_error (GPG_ERR_NOT_TRUSTED);
/* Check that a CA is allowed to issue certificates. */
{
int chainlen;
rc = allowed_ca (ctrl, issuer_cert, &chainlen, listmode, listfp);
if (rc)
{
/* Not allowed. Check whether this is a trusted root
certificate and whether we allow special exceptions.
We could carry the result of the test over to the
regular root check at the top of the loop but for
clarity we won't do that. Given that the majority of
certificates carry proper BasicContraints our way of
overriding an error in the way is justified for
performance reasons. */
if (is_root)
{
if (gpgsm_cert_has_well_known_private_key (issuer_cert))
{
memset (rootca_flags, 0, sizeof *rootca_flags);
istrusted_rc = ((flags & VALIDATE_FLAG_STEED)
? 0 : gpg_error (GPG_ERR_NOT_TRUSTED));
}
else
istrusted_rc = gpgsm_agent_istrusted
(ctrl, issuer_cert, NULL, rootca_flags);
if (!istrusted_rc && rootca_flags->relax)
{
/* Ignore the error due to the relax flag. */
rc = 0;
chainlen = -1;
}
}
}
if (rc)
goto leave;
if (chainlen >= 0 && depth > chainlen)
{
do_list (1, listmode, listfp,
_("certificate chain longer than allowed by CA (%d)"),
chainlen);
rc = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
goto leave;
}
}
/* Is the certificate allowed to sign other certificates. */
if (!listmode)
{
rc = gpgsm_cert_use_cert_p (issuer_cert);
if (rc)
{
char numbuf[50];
sprintf (numbuf, "%d", rc);
gpgsm_status2 (ctrl, STATUS_ERROR, "certcert.issuer.keyusage",
numbuf, NULL);
goto leave;
}
}
/* Check for revocations etc. Note that for a root certificate
this test is done a second time later. This should eventually
be fixed. */
if ((flags & VALIDATE_FLAG_NO_DIRMNGR))
rc = 0;
else if ((flags & VALIDATE_FLAG_STEED))
rc = 0; /* Fixme: XXX */
else if (is_root && (opt.no_trusted_cert_crl_check
|| (!istrusted_rc && rootca_flags->relax)))
rc = 0;
else
rc = is_cert_still_valid (ctrl,
(flags & VALIDATE_FLAG_CHAIN_MODEL),
listmode, listfp,
subject_cert, issuer_cert,
&any_revoked, &any_no_crl, &any_crl_too_old);
if (rc)
goto leave;
if (opt.verbose && !listmode)
log_info (depth == 0 ? _("certificate is good\n") :
!is_root ? _("intermediate certificate is good\n") :
/* other */ _("root certificate is good\n"));
/* Under the chain model the next check time is the creation
time of the subject certificate. */
if ( (flags & VALIDATE_FLAG_CHAIN_MODEL) )
{
rc = ksba_cert_get_validity (subject_cert, 0, check_time);
if (rc)
{
/* That will never happen as we have already checked
this above. */
BUG ();
}
}
/* For the next round the current issuer becomes the new subject. */
keydb_search_reset (kh);
ksba_cert_release (subject_cert);
subject_cert = issuer_cert;
issuer_cert = NULL;
depth++;
} /* End chain traversal. */
if (!listmode && !opt.quiet)
{
if (opt.no_policy_check)
log_info ("policies not checked due to %s option\n",
"--disable-policy-checks");
if (ctrl->offline || (opt.no_crl_check && !ctrl->use_ocsp))
log_info ("CRLs not checked due to %s option\n",
ctrl->offline ? "offline" : "--disable-crl-checks");
}
if (!rc)
{ /* If we encountered an error somewhere during the checks, set
the error code to the most critical one */
if (any_revoked)
rc = gpg_error (GPG_ERR_CERT_REVOKED);
else if (any_expired)
rc = gpg_error (GPG_ERR_CERT_EXPIRED);
else if (any_no_crl)
rc = gpg_error (GPG_ERR_NO_CRL_KNOWN);
else if (any_crl_too_old)
rc = gpg_error (GPG_ERR_CRL_TOO_OLD);
else if (any_no_policy_match)
rc = gpg_error (GPG_ERR_NO_POLICY_MATCH);
}
leave:
/* If we have traversed a complete chain up to the root we will
reset the ephemeral flag for all these certificates. This is done
regardless of any error because those errors may only be
transient. */
if (chain && chain->is_root)
{
gpg_error_t err;
chain_item_t ci;
for (ci = chain; ci; ci = ci->next)
{
/* Note that it is possible for the last certificate in the
chain (i.e. our target certificate) that it has not yet
been stored in the keybox and thus the flag can't be set.
We ignore this error because it will later be stored
anyway. */
err = keydb_set_cert_flags (ctrl, ci->cert, 1, KEYBOX_FLAG_BLOB, 0,
KEYBOX_FLAG_BLOB_EPHEMERAL, 0);
if (!ci->next && gpg_err_code (err) == GPG_ERR_NOT_FOUND)
;
else if (err)
log_error ("clearing ephemeral flag failed: %s\n",
gpg_strerror (err));
}
}
/* If we have figured something about the qualified signature
capability of the certificate under question, store the result as
user data in all certificates of the chain. We do this even if the
validation itself failed. */
if (is_qualified != -1 && !(flags & VALIDATE_FLAG_STEED))
{
gpg_error_t err;
chain_item_t ci;
char buf[1];
buf[0] = !!is_qualified;
for (ci = chain; ci; ci = ci->next)
{
err = ksba_cert_set_user_data (ci->cert, "is_qualified", buf, 1);
if (err)
{
log_error ("set_user_data(is_qualified) failed: %s\n",
gpg_strerror (err));
if (!rc)
rc = err;
}
}
}
/* If auditing has been enabled, record what is in the chain. */
if (ctrl->audit)
{
chain_item_t ci;
audit_log (ctrl->audit, AUDIT_CHAIN_BEGIN);
for (ci = chain; ci; ci = ci->next)
{
audit_log_cert (ctrl->audit,
ci->is_root? AUDIT_CHAIN_ROOTCERT : AUDIT_CHAIN_CERT,
ci->cert, 0);
}
audit_log (ctrl->audit, AUDIT_CHAIN_END);
}
if (r_exptime)
gnupg_copy_time (r_exptime, exptime);
xfree (issuer);
xfree (subject);
keydb_release (kh);
while (chain)
{
chain_item_t ci_next = chain->next;
ksba_cert_release (chain->cert);
xfree (chain);
chain = ci_next;
}
ksba_cert_release (issuer_cert);
ksba_cert_release (subject_cert);
return rc;
}
/* Validate a certificate chain. For a description see
do_validate_chain. This function is a wrapper to handle a root
certificate with the chain_model flag set. If RETFLAGS is not
NULL, flags indicating now the verification was done are stored
there. The only defined bits for RETFLAGS are
VALIDATE_FLAG_CHAIN_MODEL and VALIDATE_FLAG_STEED.
If you are verifying a signature you should set CHECKTIME to the
creation time of the signature. If your are verifying a
certificate, set it nil (i.e. the empty string). If the creation
date of the signature is not known use the special date
"19700101T000000" which is treated in a special way here. */
int
gpgsm_validate_chain (ctrl_t ctrl, ksba_cert_t cert, ksba_isotime_t checktime,
ksba_isotime_t r_exptime,
int listmode, estream_t listfp, unsigned int flags,
unsigned int *retflags)
{
int rc;
struct rootca_flags_s rootca_flags;
unsigned int dummy_retflags;
if (!retflags)
retflags = &dummy_retflags;
/* If the session requested a certain validation mode make sure the
corresponding flags are set. */
if (ctrl->validation_model == 1)
flags |= VALIDATE_FLAG_CHAIN_MODEL;
else if (ctrl->validation_model == 2)
flags |= VALIDATE_FLAG_STEED;
/* If the chain model was forced, set this immediately into
RETFLAGS. */
*retflags = (flags & VALIDATE_FLAG_CHAIN_MODEL);
memset (&rootca_flags, 0, sizeof rootca_flags);
if ((flags & VALIDATE_FLAG_BYPASS))
{
*retflags |= VALIDATE_FLAG_BYPASS;
rc = 0;
}
else
rc = do_validate_chain (ctrl, cert, checktime,
r_exptime, listmode, listfp, flags,
&rootca_flags);
if (!rc && (flags & VALIDATE_FLAG_STEED))
{
*retflags |= VALIDATE_FLAG_STEED;
}
else if (gpg_err_code (rc) == GPG_ERR_CERT_EXPIRED
&& !(flags & VALIDATE_FLAG_CHAIN_MODEL)
&& (rootca_flags.valid && rootca_flags.chain_model))
{
/* The root CA indicated that the chain model is to be used but
* we have not yet used it. Thus do the validation again using
* the chain model. */
if (opt.verbose)
do_list (0, listmode, listfp, _("switching to chain model"));
rc = do_validate_chain (ctrl, cert, checktime,
r_exptime, listmode, listfp,
(flags |= VALIDATE_FLAG_CHAIN_MODEL),
&rootca_flags);
*retflags |= VALIDATE_FLAG_CHAIN_MODEL;
}
if (opt.verbose)
do_list (0, listmode, listfp, _("validation model used: %s"),
(*retflags & VALIDATE_FLAG_BYPASS)?
"bypass" :
(*retflags & VALIDATE_FLAG_STEED)?
"steed" :
(*retflags & VALIDATE_FLAG_CHAIN_MODEL)?
_("chain"):_("shell"));
return rc;
}
/* Check that the given certificate is valid but DO NOT check any
constraints. We assume that the issuers certificate is already in
the DB and that this one is valid; which it should be because it
has been checked using this function. */
int
gpgsm_basic_cert_check (ctrl_t ctrl, ksba_cert_t cert)
{
int rc = 0;
char *issuer = NULL;
char *subject = NULL;
KEYDB_HANDLE kh;
ksba_cert_t issuer_cert = NULL;
if (opt.no_chain_validation)
{
log_info ("WARNING: bypassing basic certificate checks\n");
return 0;
}
kh = keydb_new ();
if (!kh)
{
log_error (_("failed to allocate keyDB handle\n"));
rc = gpg_error (GPG_ERR_GENERAL);
goto leave;
}
issuer = ksba_cert_get_issuer (cert, 0);
subject = ksba_cert_get_subject (cert, 0);
if (!issuer)
{
log_error ("no issuer found in certificate\n");
rc = gpg_error (GPG_ERR_BAD_CERT);
goto leave;
}
if (is_root_cert (cert, issuer, subject))
{
rc = gpgsm_check_cert_sig (cert, cert);
if (rc)
{
log_error ("self-signed certificate has a BAD signature: %s\n",
gpg_strerror (rc));
if (DBG_X509)
{
gpgsm_dump_cert ("self-signing cert", cert);
}
rc = gpg_error (GPG_ERR_BAD_CERT);
goto leave;
}
}
else
{
/* Find the next cert up the tree. */
keydb_search_reset (kh);
rc = find_up (ctrl, kh, cert, issuer, 0);
if (rc)
{
if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
{
log_info ("issuer certificate (#/");
gpgsm_dump_string (issuer);
log_printf (") not found\n");
}
else
log_error ("failed to find issuer's certificate: %s <%s>\n",
gpg_strerror (rc), gpg_strsource (rc));
rc = gpg_error (GPG_ERR_MISSING_ISSUER_CERT);
goto leave;
}
ksba_cert_release (issuer_cert); issuer_cert = NULL;
rc = keydb_get_cert (kh, &issuer_cert);
if (rc)
{
log_error ("keydb_get_cert() failed: rc=%d\n", rc);
rc = gpg_error (GPG_ERR_GENERAL);
goto leave;
}
rc = gpgsm_check_cert_sig (issuer_cert, cert);
if (rc)
{
log_error ("certificate has a BAD signature: %s\n",
gpg_strerror (rc));
if (DBG_X509)
{
gpgsm_dump_cert ("signing issuer", issuer_cert);
gpgsm_dump_cert ("signed subject", cert);
}
rc = gpg_error (GPG_ERR_BAD_CERT);
goto leave;
}
if (opt.verbose)
log_info (_("certificate is good\n"));
}
leave:
xfree (issuer);
xfree (subject);
keydb_release (kh);
ksba_cert_release (issuer_cert);
return rc;
}
/* Check whether the certificate CERT has been issued by the German
authority for qualified signature. They do not set the
basicConstraints and thus we need this workaround. It works by
looking up the root certificate and checking whether that one is
listed as a qualified certificate for Germany.
We also try to cache this data but as long as don't keep a
reference to the certificate this won't be used.
Returns: True if CERT is a RegTP issued CA cert (i.e. the root
certificate itself or one of the CAs). In that case CHAINLEN will
receive the length of the chain which is either 0 or 1.
*/
static int
get_regtp_ca_info (ctrl_t ctrl, ksba_cert_t cert, int *chainlen)
{
gpg_error_t err;
ksba_cert_t next;
int rc = 0;
int i, depth;
char country[3];
ksba_cert_t array[4];
char buf[2];
size_t buflen;
int dummy_chainlen;
if (!chainlen)
chainlen = &dummy_chainlen;
*chainlen = 0;
err = ksba_cert_get_user_data (cert, "regtp_ca_chainlen",
&buf, sizeof (buf), &buflen);
if (!err)
{
/* Got info. */
if (buflen < 2 || !*buf)
return 0; /* Nothing found. */
*chainlen = buf[1];
return 1; /* This is a regtp CA. */
}
else if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
{
log_error ("ksba_cert_get_user_data(%s) failed: %s\n",
"regtp_ca_chainlen", gpg_strerror (err));
return 0; /* Nothing found. */
}
/* Need to gather the info. This requires to walk up the chain
until we have found the root. Because we are only interested in
German Bundesnetzagentur (former RegTP) derived certificates 3
levels are enough. (The German signature law demands a 3 tier
hierarchy; thus there is only one CA between the EE and the Root
CA.) */
memset (&array, 0, sizeof array);
depth = 0;
ksba_cert_ref (cert);
array[depth++] = cert;
ksba_cert_ref (cert);
while (depth < DIM(array) && !(rc=gpgsm_walk_cert_chain (ctrl, cert, &next)))
{
ksba_cert_release (cert);
ksba_cert_ref (next);
array[depth++] = next;
cert = next;
}
ksba_cert_release (cert);
if (rc != -1 || !depth || depth == DIM(array) )
{
/* We did not reached the root. */
goto leave;
}
/* If this is a German signature law issued certificate, we store
additional information. */
if (!gpgsm_is_in_qualified_list (NULL, array[depth-1], country)
&& !strcmp (country, "de"))
{
/* Setting the pathlen for the root CA and the CA flag for the
next one is all what we need to do. */
err = ksba_cert_set_user_data (array[depth-1], "regtp_ca_chainlen",
"\x01\x01", 2);
if (!err && depth > 1)
err = ksba_cert_set_user_data (array[depth-2], "regtp_ca_chainlen",
"\x01\x00", 2);
if (err)
log_error ("ksba_set_user_data(%s) failed: %s\n",
"regtp_ca_chainlen", gpg_strerror (err));
for (i=0; i < depth; i++)
ksba_cert_release (array[i]);
*chainlen = (depth>1? 0:1);
return 1;
}
leave:
/* Nothing special with this certificate. Mark the target
certificate anyway to avoid duplicate lookups. */
err = ksba_cert_set_user_data (cert, "regtp_ca_chainlen", "", 1);
if (err)
log_error ("ksba_set_user_data(%s) failed: %s\n",
"regtp_ca_chainlen", gpg_strerror (err));
for (i=0; i < depth; i++)
ksba_cert_release (array[i]);
return 0;
}
diff --git a/sm/gpgsm.h b/sm/gpgsm.h
index 469bca33c..b826fa814 100644
--- a/sm/gpgsm.h
+++ b/sm/gpgsm.h
@@ -1,491 +1,492 @@
/* gpgsm.h - Global definitions for GpgSM
* Copyright (C) 2001, 2003, 2004, 2007, 2009,
* 2010 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GnuPG is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses/>.
*/
#ifndef GPGSM_H
#define GPGSM_H
#ifdef GPG_ERR_SOURCE_DEFAULT
#error GPG_ERR_SOURCE_DEFAULT already defined
#endif
#define GPG_ERR_SOURCE_DEFAULT GPG_ERR_SOURCE_GPGSM
#include <gpg-error.h>
#include <ksba.h>
#include "../common/util.h"
#include "../common/status.h"
#include "../common/audit.h"
#include "../common/session-env.h"
#include "../common/ksba-io-support.h"
#include "../common/compliance.h"
#define MAX_DIGEST_LEN 64
/* A large struct named "opt" to keep global flags. */
EXTERN_UNLESS_MAIN_MODULE
struct
{
unsigned int debug; /* debug flags (DBG_foo_VALUE) */
int verbose; /* verbosity level */
int quiet; /* be as quiet as possible */
int batch; /* run in batch mode, i.e w/o any user interaction */
int answer_yes; /* assume yes on most questions */
int answer_no; /* assume no on most questions */
int dry_run; /* don't change any persistent data */
int no_homedir_creation;
const char *config_filename; /* Name of the used config file. */
const char *agent_program;
session_env_t session_env;
char *lc_ctype;
char *lc_messages;
int autostart;
const char *dirmngr_program;
int disable_dirmngr; /* Do not do any dirmngr calls. */
const char *protect_tool_program;
char *outfile; /* name of output file */
int with_key_data;/* include raw key in the column delimted output */
int fingerprint; /* list fingerprints in all key listings */
int with_md5_fingerprint; /* Also print an MD5 fingerprint for
standard key listings. */
int with_keygrip; /* Option --with-keygrip active. */
int pinentry_mode;
int request_origin;
int armor; /* force base64 armoring (see also ctrl.with_base64) */
int no_armor; /* don't try to figure out whether data is base64 armored*/
const char *p12_charset; /* Use this charset for encoding the
pkcs#12 passphrase. */
const char *def_cipher_algoid; /* cipher algorithm to use if
nothing else is specified */
int def_compress_algo; /* Ditto for compress algorithm */
int forced_digest_algo; /* User forced hash algorithm. */
char *def_recipient; /* userID of the default recipient */
int def_recipient_self; /* The default recipient is the default key */
int no_encrypt_to; /* Ignore all as encrypt to marked recipients. */
char *local_user; /* NULL or argument to -u */
int extra_digest_algo; /* A digest algorithm also used for
verification of signatures. */
int skip_verify; /* do not check signatures on data */
int lock_once; /* Keep lock once they are set */
int ignore_time_conflict; /* Ignore certain time conflicts */
int no_crl_check; /* Don't do a CRL check */
int no_trusted_cert_crl_check; /* Don't run a CRL check for trusted certs. */
int force_crl_refresh; /* Force refreshing the CRL. */
int enable_issuer_based_crl_check; /* Backward compatibility hack. */
int enable_ocsp; /* Default to use OCSP checks. */
char *policy_file; /* full pathname of policy file */
int no_policy_check; /* ignore certificate policies */
int no_chain_validation; /* Bypass all cert chain validity tests */
int ignore_expiration; /* Ignore the notAfter validity checks. */
int auto_issuer_key_retrieve; /* try to retrieve a missing issuer key. */
int qualsig_approval; /* Set to true if this software has
officially been approved to create an
verify qualified signatures. This is a
runtime option in case we want to check
the integrity of the software at
runtime. */
unsigned int min_rsa_length; /* Used for compliance checks. */
strlist_t keyserver;
/* A list of certificate extension OIDs which are ignored so that
one can claim that a critical extension has been handled. One
OID per string. */
strlist_t ignored_cert_extensions;
/* A list of OIDs which will be used to ignore certificates with
* sunch an OID during --learn-card. */
strlist_t ignore_cert_with_oid;
/* The current compliance mode. */
enum gnupg_compliance_mode compliance;
/* Fail if an operation can't be done in the requested compliance
* mode. */
int require_compliance;
/* Enable always-trust mode - note that there is also server option
* for this. */
int always_trust;
/* Compatibility flags (COMPAT_FLAG_xxxx). */
unsigned int compat_flags;
} opt;
/* Debug values and macros. */
#define DBG_X509_VALUE 1 /* debug x.509 data reading/writing */
#define DBG_MPI_VALUE 2 /* debug mpi details */
#define DBG_CRYPTO_VALUE 4 /* debug low level crypto */
#define DBG_MEMORY_VALUE 32 /* debug memory allocation stuff */
#define DBG_CACHE_VALUE 64 /* debug the caching */
#define DBG_MEMSTAT_VALUE 128 /* show memory statistics */
#define DBG_HASHING_VALUE 512 /* debug hashing operations */
#define DBG_IPC_VALUE 1024 /* debug assuan communication */
#define DBG_X509 (opt.debug & DBG_X509_VALUE)
#define DBG_CRYPTO (opt.debug & DBG_CRYPTO_VALUE)
#define DBG_MEMORY (opt.debug & DBG_MEMORY_VALUE)
#define DBG_CACHE (opt.debug & DBG_CACHE_VALUE)
#define DBG_HASHING (opt.debug & DBG_HASHING_VALUE)
#define DBG_IPC (opt.debug & DBG_IPC_VALUE)
/* Compatibility flags */
/* Telesec RSA cards produced for NRW in 2022 came with only the
* keyAgreement bit set. This flag allows there use for encryption
* anyway. Example cert:
* Issuer: /CN=DOI CA 10a/OU=DOI/O=PKI-1-Verwaltung/C=DE
* key usage: digitalSignature nonRepudiation keyAgreement
* policies: 1.3.6.1.4.1.7924.1.1:N:
*/
#define COMPAT_ALLOW_KA_TO_ENCR 1
#define COMPAT_ALLOW_ECC_ENCR 2
/* Forward declaration for an object defined in server.c */
struct server_local_s;
/* Session control object. This object is passed down to most
functions. Note that the default values for it are set by
gpgsm_init_default_ctrl(). */
struct server_control_s
{
int no_server; /* We are not running under server control */
int status_fd; /* Only for non-server mode */
struct server_local_s *server_local;
audit_ctx_t audit; /* NULL or a context for the audit subsystem. */
int agent_seen; /* Flag indicating that the gpg-agent has been
accessed. */
int with_colons; /* Use column delimited output format */
int with_secret; /* Mark secret keys in a public key listing. */
int with_chain; /* Include the certifying certs in a listing */
int with_validation;/* Validate each key while listing. */
int with_ephemeral_keys; /* Include ephemeral flagged keys in the
keylisting. */
int autodetect_encoding; /* Try to detect the input encoding */
int is_pem; /* Is in PEM format */
int is_base64; /* is in plain base-64 format */
/* If > 0 a hint with the expected number of input data bytes. This
* is not necessary an exact number but intended to be used for
* progress info and to decide on how to allocate buffers. */
uint64_t input_size_hint;
int create_base64; /* Create base64 encoded output */
int create_pem; /* create PEM output */
const char *pem_name; /* PEM name to use */
int include_certs; /* -1 to send all certificates in the chain
along with a signature or the number of
certificates up the chain (0 = none, 1 = only
signer) */
int use_ocsp; /* Set to true if OCSP should be used. */
int validation_model; /* 0 := standard model (shell),
1 := chain model,
2 := STEED model. */
int offline; /* If true gpgsm won't do any network access. */
int always_trust; /* True in always-trust mode; see also
* opt.always-trust. */
/* The current time. Used as a helper in certchain.c. */
ksba_isotime_t current_time;
};
/* An object to keep a list of certificates. */
struct certlist_s
{
struct certlist_s *next;
ksba_cert_t cert;
int is_encrypt_to; /* True if the certificate has been set through
the --encrypto-to option. */
int pk_algo; /* The PK_ALGO from CERT or 0 if not yet known. */
int hash_algo; /* Used to track the hash algorithm to use. */
const char *hash_algo_oid; /* And the corresponding OID. */
};
typedef struct certlist_s *certlist_t;
/* A structure carrying information about trusted root certificates. */
struct rootca_flags_s
{
unsigned int valid:1; /* The rest of the structure has valid
information. */
unsigned int relax:1; /* Relax checking of root certificates. */
unsigned int chain_model:1; /* Root requires the use of the chain model. */
+ unsigned int qualified:1; /* Root CA used for qualfied signatures. */
};
/*-- gpgsm.c --*/
extern int gpgsm_errors_seen;
void gpgsm_exit (int rc);
void gpgsm_init_default_ctrl (struct server_control_s *ctrl);
int gpgsm_parse_validation_model (const char *model);
/*-- server.c --*/
void gpgsm_server (certlist_t default_recplist);
gpg_error_t gpgsm_status (ctrl_t ctrl, int no, const char *text);
gpg_error_t gpgsm_status2 (ctrl_t ctrl, int no, ...) GPGRT_ATTR_SENTINEL(0);
gpg_error_t gpgsm_status_with_err_code (ctrl_t ctrl, int no, const char *text,
gpg_err_code_t ec);
gpg_error_t gpgsm_status_with_error (ctrl_t ctrl, int no, const char *text,
gpg_error_t err);
gpg_error_t gpgsm_progress_cb (ctrl_t ctrl, uint64_t current, uint64_t total);
gpg_error_t gpgsm_proxy_pinentry_notify (ctrl_t ctrl,
const unsigned char *line);
/*-- fingerprint --*/
unsigned char *gpgsm_get_fingerprint (ksba_cert_t cert, int algo,
unsigned char *array, int *r_len);
char *gpgsm_get_fingerprint_string (ksba_cert_t cert, int algo);
char *gpgsm_get_fingerprint_hexstring (ksba_cert_t cert, int algo);
unsigned long gpgsm_get_short_fingerprint (ksba_cert_t cert,
unsigned long *r_high);
unsigned char *gpgsm_get_keygrip (ksba_cert_t cert, unsigned char *array);
char *gpgsm_get_keygrip_hexstring (ksba_cert_t cert);
int gpgsm_get_key_algo_info (ksba_cert_t cert, unsigned int *nbits);
int gpgsm_get_key_algo_info2 (ksba_cert_t cert, unsigned int *nbits,
char **r_curve);
int gpgsm_is_ecc_key (ksba_cert_t cert);
char *gpgsm_pubkey_algo_string (ksba_cert_t cert, int *r_algoid);
char *gpgsm_get_certid (ksba_cert_t cert);
/*-- certdump.c --*/
void gpgsm_print_serial (estream_t fp, ksba_const_sexp_t p);
void gpgsm_print_serial_decimal (estream_t fp, ksba_const_sexp_t sn);
void gpgsm_print_time (estream_t fp, ksba_isotime_t t);
void gpgsm_print_name2 (FILE *fp, const char *string, int translate);
void gpgsm_print_name (FILE *fp, const char *string);
void gpgsm_es_print_name (estream_t fp, const char *string);
void gpgsm_es_print_name2 (estream_t fp, const char *string, int translate);
void gpgsm_cert_log_name (const char *text, ksba_cert_t cert);
void gpgsm_dump_cert (const char *text, ksba_cert_t cert);
void gpgsm_dump_serial (ksba_const_sexp_t p);
void gpgsm_dump_time (ksba_isotime_t t);
void gpgsm_dump_string (const char *string);
char *gpgsm_format_serial (ksba_const_sexp_t p);
char *gpgsm_format_name2 (const char *name, int translate);
char *gpgsm_format_name (const char *name);
char *gpgsm_format_sn_issuer (ksba_sexp_t sn, const char *issuer);
char *gpgsm_fpr_and_name_for_status (ksba_cert_t cert);
char *gpgsm_format_keydesc (ksba_cert_t cert);
/*-- certcheck.c --*/
int gpgsm_check_cert_sig (ksba_cert_t issuer_cert, ksba_cert_t cert);
int gpgsm_check_cms_signature (ksba_cert_t cert, gcry_sexp_t sigval,
gcry_md_hd_t md,
int hash_algo, unsigned int pkalgoflags,
int *r_pkalgo);
/* fixme: move create functions to another file */
int gpgsm_create_cms_signature (ctrl_t ctrl,
ksba_cert_t cert, gcry_md_hd_t md, int mdalgo,
unsigned char **r_sigval);
/*-- certchain.c --*/
/* Flags used with gpgsm_validate_chain. */
#define VALIDATE_FLAG_NO_DIRMNGR 1
#define VALIDATE_FLAG_CHAIN_MODEL 2
#define VALIDATE_FLAG_STEED 4
#define VALIDATE_FLAG_BYPASS 8 /* No actual validation. */
int gpgsm_walk_cert_chain (ctrl_t ctrl,
ksba_cert_t start, ksba_cert_t *r_next);
int gpgsm_is_root_cert (ksba_cert_t cert);
int gpgsm_validate_chain (ctrl_t ctrl, ksba_cert_t cert,
ksba_isotime_t checktime,
ksba_isotime_t r_exptime,
int listmode, estream_t listfp,
unsigned int flags, unsigned int *retflags);
int gpgsm_basic_cert_check (ctrl_t ctrl, ksba_cert_t cert);
/*-- certlist.c --*/
int gpgsm_cert_use_sign_p (ksba_cert_t cert, int silent);
int gpgsm_cert_use_encrypt_p (ksba_cert_t cert);
int gpgsm_cert_use_verify_p (ksba_cert_t cert);
int gpgsm_cert_use_decrypt_p (ksba_cert_t cert);
int gpgsm_cert_use_cert_p (ksba_cert_t cert);
int gpgsm_cert_use_ocsp_p (ksba_cert_t cert);
int gpgsm_cert_has_well_known_private_key (ksba_cert_t cert);
int gpgsm_certs_identical_p (ksba_cert_t cert_a, ksba_cert_t cert_b);
int gpgsm_add_cert_to_certlist (ctrl_t ctrl, ksba_cert_t cert,
certlist_t *listaddr, int is_encrypt_to);
int gpgsm_add_to_certlist (ctrl_t ctrl, const char *name, int secret,
certlist_t *listaddr, int is_encrypt_to);
void gpgsm_release_certlist (certlist_t list);
#define FIND_CERT_ALLOW_AMBIG 1
#define FIND_CERT_WITH_EPHEM 2
int gpgsm_find_cert (ctrl_t ctrl, const char *name, ksba_sexp_t keyid,
ksba_cert_t *r_cert, unsigned int flags);
/*-- keylist.c --*/
gpg_error_t gpgsm_list_keys (ctrl_t ctrl, strlist_t names,
estream_t fp, unsigned int mode);
/*-- import.c --*/
int gpgsm_import (ctrl_t ctrl, int in_fd, int reimport_mode);
int gpgsm_import_files (ctrl_t ctrl, int nfiles, char **files,
int (*of)(const char *fname));
/*-- export.c --*/
void gpgsm_export (ctrl_t ctrl, strlist_t names, estream_t stream);
void gpgsm_p12_export (ctrl_t ctrl, const char *name, estream_t stream,
int rawmode);
/*-- delete.c --*/
int gpgsm_delete (ctrl_t ctrl, strlist_t names);
/*-- verify.c --*/
int gpgsm_verify (ctrl_t ctrl, int in_fd, int data_fd, estream_t out_fp);
/*-- sign.c --*/
int gpgsm_get_default_cert (ctrl_t ctrl, ksba_cert_t *r_cert);
int gpgsm_sign (ctrl_t ctrl, certlist_t signerlist,
int data_fd, int detached, estream_t out_fp);
/*-- encrypt.c --*/
int gpgsm_encrypt (ctrl_t ctrl, certlist_t recplist,
int in_fd, estream_t out_fp);
/*-- decrypt.c --*/
gpg_error_t hash_ecc_cms_shared_info (gcry_md_hd_t hash_hd,
const char *wrap_algo_str,
unsigned int keylen,
const void *ukm, unsigned int ukmlen);
int gpgsm_decrypt (ctrl_t ctrl, int in_fd, estream_t out_fp);
/*-- certreqgen.c --*/
int gpgsm_genkey (ctrl_t ctrl, estream_t in_stream, estream_t out_stream);
/*-- certreqgen-ui.c --*/
void gpgsm_gencertreq_tty (ctrl_t ctrl, estream_t out_stream);
/*-- qualified.c --*/
gpg_error_t gpgsm_is_in_qualified_list (ctrl_t ctrl, ksba_cert_t cert,
char *country);
gpg_error_t gpgsm_qualified_consent (ctrl_t ctrl, ksba_cert_t cert);
gpg_error_t gpgsm_not_qualified_warning (ctrl_t ctrl, ksba_cert_t cert);
/*-- call-agent.c --*/
int gpgsm_agent_pksign (ctrl_t ctrl, const char *keygrip, const char *desc,
unsigned char *digest,
size_t digestlen,
int digestalgo,
unsigned char **r_buf, size_t *r_buflen);
int gpgsm_scd_pksign (ctrl_t ctrl, const char *keyid, const char *desc,
unsigned char *digest, size_t digestlen, int digestalgo,
unsigned char **r_buf, size_t *r_buflen);
int gpgsm_agent_pkdecrypt (ctrl_t ctrl, const char *keygrip, const char *desc,
ksba_const_sexp_t ciphertext,
char **r_buf, size_t *r_buflen);
int gpgsm_agent_genkey (ctrl_t ctrl,
ksba_const_sexp_t keyparms, ksba_sexp_t *r_pubkey);
int gpgsm_agent_readkey (ctrl_t ctrl, int fromcard, const char *hexkeygrip,
ksba_sexp_t *r_pubkey);
int gpgsm_agent_scd_serialno (ctrl_t ctrl, char **r_serialno);
int gpgsm_agent_scd_keypairinfo (ctrl_t ctrl, strlist_t *r_list);
int gpgsm_agent_istrusted (ctrl_t ctrl, ksba_cert_t cert, const char *hexfpr,
struct rootca_flags_s *rootca_flags);
int gpgsm_agent_havekey (ctrl_t ctrl, const char *hexkeygrip);
int gpgsm_agent_marktrusted (ctrl_t ctrl, ksba_cert_t cert);
int gpgsm_agent_learn (ctrl_t ctrl);
int gpgsm_agent_passwd (ctrl_t ctrl, const char *hexkeygrip, const char *desc);
gpg_error_t gpgsm_agent_get_confirmation (ctrl_t ctrl, const char *desc);
gpg_error_t gpgsm_agent_send_nop (ctrl_t ctrl);
gpg_error_t gpgsm_agent_keyinfo (ctrl_t ctrl, const char *hexkeygrip,
char **r_serialno);
gpg_error_t gpgsm_agent_ask_passphrase (ctrl_t ctrl, const char *desc_msg,
int repeat, char **r_passphrase);
gpg_error_t gpgsm_agent_keywrap_key (ctrl_t ctrl, int forexport,
void **r_kek, size_t *r_keklen);
gpg_error_t gpgsm_agent_import_key (ctrl_t ctrl,
const void *key, size_t keylen);
gpg_error_t gpgsm_agent_export_key (ctrl_t ctrl, const char *keygrip,
const char *desc,
unsigned char **r_result,
size_t *r_resultlen);
/*-- call-dirmngr.c --*/
int gpgsm_dirmngr_isvalid (ctrl_t ctrl,
ksba_cert_t cert, ksba_cert_t issuer_cert,
int use_ocsp);
int gpgsm_dirmngr_lookup (ctrl_t ctrl, strlist_t names, const char *uri,
int cache_only,
void (*cb)(void*, ksba_cert_t), void *cb_value);
int gpgsm_dirmngr_run_command (ctrl_t ctrl, const char *command,
int argc, char **argv);
/*-- misc.c --*/
void setup_pinentry_env (void);
gpg_error_t transform_sigval (const unsigned char *sigval, size_t sigvallen,
int mdalgo,
unsigned char **r_newsigval,
size_t *r_newsigvallen);
gcry_sexp_t gpgsm_ksba_cms_get_sig_val (ksba_cms_t cms, int idx);
int gpgsm_get_hash_algo_from_sigval (gcry_sexp_t sigval,
unsigned int *r_pkalgo_flags);
#endif /*GPGSM_H*/

File Metadata

Mime Type
text/x-diff
Expires
Mon, Dec 23, 2:11 PM (16 h, 51 m)
Storage Engine
local-disk
Storage Format
Raw Data
Storage Handle
33/1f/6c6b71373ac04d7637e7948d1f9a

Event Timeline