diff --git a/dirmngr/ks-action.c b/dirmngr/ks-action.c index 0c547947f..c2d8c374d 100644 --- a/dirmngr/ks-action.c +++ b/dirmngr/ks-action.c @@ -1,412 +1,415 @@ /* ks-action.c - OpenPGP keyserver actions * Copyright (C) 2011 Free Software Foundation, Inc. * Copyright (C) 2011, 2014 Werner Koch * Copyright (C) 2015 g10 Code GmbH * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include "dirmngr.h" #include "misc.h" #include "ks-engine.h" #include "ks-action.h" #if USE_LDAP # include "ldap-parse-uri.h" #endif /* Called by the engine's help functions to print the actual help. */ gpg_error_t ks_print_help (ctrl_t ctrl, const char *text) { return dirmngr_status_help (ctrl, text); } /* Called by the engine's help functions to print the actual help. */ gpg_error_t ks_printf_help (ctrl_t ctrl, const char *format, ...) { va_list arg_ptr; gpg_error_t err; char *buf; va_start (arg_ptr, format); buf = es_vbsprintf (format, arg_ptr); err = buf? 0 : gpg_error_from_syserror (); va_end (arg_ptr); if (!err) err = dirmngr_status_help (ctrl, buf); es_free (buf); return err; } /* Run the help command for the engine responsible for URI. */ gpg_error_t ks_action_help (ctrl_t ctrl, const char *url) { gpg_error_t err; parsed_uri_t parsed_uri; /* The broken down URI. */ if (!url || !*url) { ks_print_help (ctrl, "Known schemata:\n"); parsed_uri = NULL; } else { #if USE_LDAP if (ldap_uri_p (url)) err = ldap_parse_uri (&parsed_uri, url); else #endif { err = http_parse_uri (&parsed_uri, url, 1); } if (err) return err; } /* Call all engines to give them a chance to print a help string. */ err = ks_hkp_help (ctrl, parsed_uri); if (!err) err = ks_http_help (ctrl, parsed_uri); if (!err) err = ks_finger_help (ctrl, parsed_uri); if (!err) err = ks_kdns_help (ctrl, parsed_uri); #if USE_LDAP if (!err) err = ks_ldap_help (ctrl, parsed_uri); #endif if (!parsed_uri) ks_print_help (ctrl, "(Use an URL for engine specific help.)"); else http_release_parsed_uri (parsed_uri); return err; } /* Resolve all host names. This is useful for looking at the status of configured keyservers. */ gpg_error_t ks_action_resolve (ctrl_t ctrl, uri_item_t keyservers) { gpg_error_t err = 0; int any_server = 0; uri_item_t uri; for (uri = keyservers; !err && uri; uri = uri->next) { if (uri->parsed_uri->is_http) { any_server = 1; err = ks_hkp_resolve (ctrl, uri->parsed_uri); if (err) break; } } if (!any_server) err = gpg_error (GPG_ERR_NO_KEYSERVER); return err; } /* Search all configured keyservers for keys matching PATTERNS and write the result to the provided output stream. */ gpg_error_t ks_action_search (ctrl_t ctrl, uri_item_t keyservers, strlist_t patterns, estream_t outfp) { gpg_error_t err = 0; int any_server = 0; int any_results = 0; uri_item_t uri; estream_t infp; if (!patterns) return gpg_error (GPG_ERR_NO_USER_ID); /* FIXME: We only take care of the first pattern. To fully support multiple patterns we might either want to run several queries in parallel and merge them. We also need to decide what to do with errors - it might not be the best idea to ignore an error from one server and silently continue with another server. For now we stop at the first error, unless the server responds with '404 Not Found', in which case we try the next server. */ for (uri = keyservers; !err && uri; uri = uri->next) { int is_http = uri->parsed_uri->is_http; int is_ldap = 0; unsigned int http_status = 0; #if USE_LDAP is_ldap = (strcmp (uri->parsed_uri->scheme, "ldap") == 0 || strcmp (uri->parsed_uri->scheme, "ldaps") == 0 || strcmp (uri->parsed_uri->scheme, "ldapi") == 0); #endif if (is_http || is_ldap) { any_server = 1; #if USE_LDAP if (is_ldap) err = ks_ldap_search (ctrl, uri->parsed_uri, patterns->d, &infp); else #endif { err = ks_hkp_search (ctrl, uri->parsed_uri, patterns->d, &infp, &http_status); } if (err == gpg_error (GPG_ERR_NO_DATA) && http_status == 404 /* not found */) { /* No record found. Clear error and try next server. */ err = 0; continue; } if (!err) { err = copy_stream (infp, outfp); es_fclose (infp); any_results = 1; break; } } } if (!any_server) err = gpg_error (GPG_ERR_NO_KEYSERVER); else if (err == 0 && !any_results) err = gpg_error (GPG_ERR_NO_DATA); return err; } /* Get the requested keys (matching PATTERNS) using all configured keyservers and write the result to the provided output stream. */ gpg_error_t ks_action_get (ctrl_t ctrl, uri_item_t keyservers, - strlist_t patterns, estream_t outfp) + strlist_t patterns, int ldap_only, estream_t outfp) { gpg_error_t err = 0; gpg_error_t first_err = 0; int any_server = 0; int any_data = 0; strlist_t sl; uri_item_t uri; estream_t infp; if (!patterns) return gpg_error (GPG_ERR_NO_USER_ID); /* FIXME: We only take care of the first keyserver. To fully support multiple keyservers we need to track the result for each pattern and use the next keyserver if one key was not found. The keyservers might not all be fully synced thus it is not clear whether the first keyserver has the freshest copy of the key. Need to think about a better strategy. */ for (uri = keyservers; !err && uri; uri = uri->next) { int is_hkp_s = (strcmp (uri->parsed_uri->scheme, "hkp") == 0 || strcmp (uri->parsed_uri->scheme, "hkps") == 0); int is_http_s = (strcmp (uri->parsed_uri->scheme, "http") == 0 || strcmp (uri->parsed_uri->scheme, "https") == 0); int is_ldap = 0; + if (ldap_only) + is_hkp_s = is_http_s = 0; + #if USE_LDAP is_ldap = (strcmp (uri->parsed_uri->scheme, "ldap") == 0 || strcmp (uri->parsed_uri->scheme, "ldaps") == 0 || strcmp (uri->parsed_uri->scheme, "ldapi") == 0); #endif if (is_hkp_s || is_http_s || is_ldap) { any_server = 1; for (sl = patterns; !err && sl; sl = sl->next) { #if USE_LDAP if (is_ldap) err = ks_ldap_get (ctrl, uri->parsed_uri, sl->d, &infp); else #endif if (is_hkp_s) err = ks_hkp_get (ctrl, uri->parsed_uri, sl->d, &infp); else if (is_http_s) err = ks_http_fetch (ctrl, uri->parsed_uri->original, KS_HTTP_FETCH_NOCACHE, &infp); else BUG (); if (err) { /* It is possible that a server does not carry a key, thus we only save the error and continue with the next pattern. FIXME: It is an open question how to return such an error condition to the caller. */ first_err = err; err = 0; } else { err = copy_stream (infp, outfp); /* Reading from the keyserver should never fail, thus return this error. */ if (!err) any_data = 1; es_fclose (infp); infp = NULL; } } } if (any_data) break; /* Stop loop after a keyserver returned something. */ } if (!any_server) err = gpg_error (GPG_ERR_NO_KEYSERVER); else if (!err && first_err && !any_data) err = first_err; return err; } /* Retrieve keys from URL and write the result to the provided output * stream OUTFP. If OUTFP is NULL the data is written to the bit * bucket. */ gpg_error_t ks_action_fetch (ctrl_t ctrl, const char *url, estream_t outfp) { gpg_error_t err = 0; estream_t infp; parsed_uri_t parsed_uri; /* The broken down URI. */ if (!url) return gpg_error (GPG_ERR_INV_URI); err = http_parse_uri (&parsed_uri, url, 1); if (err) return err; if (parsed_uri->is_http) { err = ks_http_fetch (ctrl, url, KS_HTTP_FETCH_NOCACHE, &infp); if (!err) { err = copy_stream (infp, outfp); es_fclose (infp); } } else if (!parsed_uri->opaque) { err = gpg_error (GPG_ERR_INV_URI); } else if (!strcmp (parsed_uri->scheme, "finger")) { err = ks_finger_fetch (ctrl, parsed_uri, &infp); if (!err) { err = copy_stream (infp, outfp); es_fclose (infp); } } else if (!strcmp (parsed_uri->scheme, "kdns")) { err = ks_kdns_fetch (ctrl, parsed_uri, &infp); if (!err) { err = copy_stream (infp, outfp); es_fclose (infp); } } else err = gpg_error (GPG_ERR_INV_URI); http_release_parsed_uri (parsed_uri); return err; } /* Send an OpenPGP key to all keyservers. The key in {DATA,DATALEN} is expected to be in OpenPGP binary transport format. The metadata in {INFO,INFOLEN} is in colon-separated format (concretely, it is the output of 'gpg --list-keys --with-colons KEYID'). This function may modify DATA and INFO. If this is a problem, then the caller should create a copy. */ gpg_error_t ks_action_put (ctrl_t ctrl, uri_item_t keyservers, void *data, size_t datalen, void *info, size_t infolen) { gpg_error_t err = 0; gpg_error_t first_err = 0; int any_server = 0; uri_item_t uri; (void) info; (void) infolen; for (uri = keyservers; !err && uri; uri = uri->next) { int is_http = uri->parsed_uri->is_http; int is_ldap = 0; #if USE_LDAP is_ldap = (strcmp (uri->parsed_uri->scheme, "ldap") == 0 || strcmp (uri->parsed_uri->scheme, "ldaps") == 0 || strcmp (uri->parsed_uri->scheme, "ldapi") == 0); #endif if (is_http || is_ldap) { any_server = 1; #if USE_LDAP if (is_ldap) err = ks_ldap_put (ctrl, uri->parsed_uri, data, datalen, info, infolen); else #endif { err = ks_hkp_put (ctrl, uri->parsed_uri, data, datalen); } if (err) { first_err = err; err = 0; } } } if (!any_server) err = gpg_error (GPG_ERR_NO_KEYSERVER); else if (!err && first_err) err = first_err; return err; } diff --git a/dirmngr/ks-action.h b/dirmngr/ks-action.h index d576ef00f..36e0cf05e 100644 --- a/dirmngr/ks-action.h +++ b/dirmngr/ks-action.h @@ -1,36 +1,36 @@ /* ks-action.h - OpenPGP keyserver actions definitions * Copyright (C) 2011 Free Software Foundation, Inc. * 2015 g10 Code GmbH * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #ifndef DIRMNGR_KS_ACTION_H #define DIRMNGR_KS_ACTION_H 1 gpg_error_t ks_action_help (ctrl_t ctrl, const char *url); gpg_error_t ks_action_resolve (ctrl_t ctrl, uri_item_t keyservers); gpg_error_t ks_action_search (ctrl_t ctrl, uri_item_t keyservers, strlist_t patterns, estream_t outfp); gpg_error_t ks_action_get (ctrl_t ctrl, uri_item_t keyservers, - strlist_t patterns, estream_t outfp); + strlist_t patterns, int ldap_only, estream_t outfp); gpg_error_t ks_action_fetch (ctrl_t ctrl, const char *url, estream_t outfp); gpg_error_t ks_action_put (ctrl_t ctrl, uri_item_t keyservers, void *data, size_t datalen, void *info, size_t infolen); #endif /*DIRMNGR_KS_ACTION_H*/ diff --git a/dirmngr/server.c b/dirmngr/server.c index f6c2c45f1..0ccba2987 100644 --- a/dirmngr/server.c +++ b/dirmngr/server.c @@ -1,3103 +1,3107 @@ /* server.c - LDAP and Keyserver access server * Copyright (C) 2002 Klarälvdalens Datakonsult AB * Copyright (C) 2003, 2004, 2005, 2007, 2008, 2009, 2011, 2015 g10 Code GmbH * Copyright (C) 2014, 2015, 2016 Werner Koch * Copyright (C) 2016 Bundesamt für Sicherheit in der Informationstechnik * * 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 . * * SPDX-License-Identifier: GPL-3.0+ */ #include #include #include #include #include #include #include #include #include #include #include "dirmngr.h" #include #include "crlcache.h" #include "crlfetch.h" #if USE_LDAP # include "ldapserver.h" #endif #include "ocsp.h" #include "certcache.h" #include "validate.h" #include "misc.h" #if USE_LDAP # include "ldap-wrapper.h" #endif #include "ks-action.h" #include "ks-engine.h" /* (ks_hkp_print_hosttable) */ #if USE_LDAP # include "ldap-parse-uri.h" #endif #include "dns-stuff.h" #include "../common/mbox-util.h" #include "../common/zb32.h" #include "../common/server-help.h" /* To avoid DoS attacks we limit the size of a certificate to something reasonable. The DoS was actually only an issue back when Dirmngr was a system service and not a user service. */ #define MAX_CERT_LENGTH (16*1024) /* The limit for the CERTLIST inquiry. We allow for up to 20 * certificates but also take PEM encoding into account. */ #define MAX_CERTLIST_LENGTH ((MAX_CERT_LENGTH * 20 * 4)/3) /* The same goes for OpenPGP keyblocks, but here we need to allow for much longer blocks; a 200k keyblock is not too unusual for keys with a lot of signatures (e.g. 0x5b0358a2). 9C31503C6D866396 even has 770 KiB as of 2015-08-23. To avoid adding a runtime option we now use 20MiB which should really be enough. Well, a key with several pictures could be larger (the parser as a 18MiB limit for attribute packets) but it won't be nice to the keyservers to send them such large blobs. */ #define MAX_KEYBLOCK_LENGTH (20*1024*1024) #define PARM_ERROR(t) assuan_set_error (ctx, \ gpg_error (GPG_ERR_ASS_PARAMETER), (t)) #define set_error(e,t) (ctx ? assuan_set_error (ctx, gpg_error (e), (t)) \ /**/: gpg_error (e)) /* Control structure per connection. */ struct server_local_s { /* Data used to associate an Assuan context with local server data */ assuan_context_t assuan_ctx; /* The session id (a counter). */ unsigned int session_id; /* Per-session LDAP servers. */ ldap_server_t ldapservers; /* Per-session list of keyservers. */ uri_item_t keyservers; /* If this flag is set to true this dirmngr process will be terminated after the end of this session. */ int stopme; /* State variable private to is_tor_running. */ int tor_state; /* If the first both flags are set the assuan logging of data lines * is suppressed. The count variable is used to show the number of * non-logged bytes. */ size_t inhibit_data_logging_count; unsigned int inhibit_data_logging : 1; unsigned int inhibit_data_logging_now : 1; }; /* Cookie definition for assuan data line output. */ static gpgrt_ssize_t data_line_cookie_write (void *cookie, const void *buffer, size_t size); static int data_line_cookie_close (void *cookie); static es_cookie_io_functions_t data_line_cookie_functions = { NULL, data_line_cookie_write, NULL, data_line_cookie_close }; /* Local prototypes */ static const char *task_check_wkd_support (ctrl_t ctrl, const char *domain); /* Accessor for the local ldapservers variable. */ ldap_server_t get_ldapservers_from_ctrl (ctrl_t ctrl) { if (ctrl && ctrl->server_local) return ctrl->server_local->ldapservers; else return NULL; } /* Release an uri_item_t list. */ static void release_uri_item_list (uri_item_t list) { while (list) { uri_item_t tmp = list->next; http_release_parsed_uri (list->parsed_uri); xfree (list); list = tmp; } } /* Release all configured keyserver info from CTRL. */ void release_ctrl_keyservers (ctrl_t ctrl) { if (! ctrl->server_local) return; release_uri_item_list (ctrl->server_local->keyservers); ctrl->server_local->keyservers = NULL; } /* Helper to print a message while leaving a command. */ static gpg_error_t leave_cmd (assuan_context_t ctx, gpg_error_t err) { if (err) { const char *name = assuan_get_command_name (ctx); if (!name) name = "?"; if (gpg_err_source (err) == GPG_ERR_SOURCE_DEFAULT) log_error ("command '%s' failed: %s\n", name, gpg_strerror (err)); else log_error ("command '%s' failed: %s <%s>\n", name, gpg_strerror (err), gpg_strsource (err)); } return err; } /* This is a wrapper around assuan_send_data which makes debugging the output in verbose mode easier. */ static gpg_error_t data_line_write (assuan_context_t ctx, const void *buffer_arg, size_t size) { ctrl_t ctrl = assuan_get_pointer (ctx); const char *buffer = buffer_arg; gpg_error_t err; /* If we do not want logging, enable it here. */ if (ctrl && ctrl->server_local && ctrl->server_local->inhibit_data_logging) ctrl->server_local->inhibit_data_logging_now = 1; if (opt.verbose && buffer && size) { /* Ease reading of output by sending a physical line at each LF. */ const char *p; size_t n, nbytes; nbytes = size; do { p = memchr (buffer, '\n', nbytes); n = p ? (p - buffer) + 1 : nbytes; err = assuan_send_data (ctx, buffer, n); if (err) { gpg_err_set_errno (EIO); goto leave; } buffer += n; nbytes -= n; if (nbytes && (err=assuan_send_data (ctx, NULL, 0))) /* Flush line. */ { gpg_err_set_errno (EIO); goto leave; } } while (nbytes); } else { err = assuan_send_data (ctx, buffer, size); if (err) { gpg_err_set_errno (EIO); /* For use by data_line_cookie_write. */ goto leave; } } leave: if (ctrl && ctrl->server_local && ctrl->server_local->inhibit_data_logging) { ctrl->server_local->inhibit_data_logging_now = 0; ctrl->server_local->inhibit_data_logging_count += size; } return err; } /* A write handler used by es_fopencookie to write assuan data lines. */ static gpgrt_ssize_t data_line_cookie_write (void *cookie, const void *buffer, size_t size) { assuan_context_t ctx = cookie; if (data_line_write (ctx, buffer, size)) return -1; return (gpgrt_ssize_t)size; } static int data_line_cookie_close (void *cookie) { assuan_context_t ctx = cookie; if (DBG_IPC) { ctrl_t ctrl = assuan_get_pointer (ctx); if (ctrl && ctrl->server_local && ctrl->server_local->inhibit_data_logging && ctrl->server_local->inhibit_data_logging_count) log_debug ("(%zu bytes sent via D lines not shown)\n", ctrl->server_local->inhibit_data_logging_count); } if (assuan_send_data (ctx, NULL, 0)) { gpg_err_set_errno (EIO); return -1; } return 0; } /* Copy the % and + escaped string S into the buffer D and replace the escape sequences. Note, that it is sufficient to allocate the target string D as long as the source string S, i.e.: strlen(s)+1. Note further that if S contains an escaped binary Nul the resulting string D will contain the 0 as well as all other characters but it will be impossible to know whether this is the original EOS or a copied Nul. */ static void strcpy_escaped_plus (char *d, const unsigned char *s) { while (*s) { if (*s == '%' && s[1] && s[2]) { s++; *d++ = xtoi_2 ( s); s += 2; } else if (*s == '+') *d++ = ' ', s++; else *d++ = *s++; } *d = 0; } /* This function returns true if a Tor server is running. The status * is cached for the current connection. */ static int is_tor_running (ctrl_t ctrl) { /* Check whether we can connect to the proxy. */ if (!ctrl || !ctrl->server_local) return 0; /* Ooops. */ if (!ctrl->server_local->tor_state) { assuan_fd_t sock; sock = assuan_sock_connect_byname (NULL, 0, 0, NULL, ASSUAN_SOCK_TOR); if (sock == ASSUAN_INVALID_FD) ctrl->server_local->tor_state = -1; /* Not running. */ else { assuan_sock_close (sock); ctrl->server_local->tor_state = 1; /* Running. */ } } return (ctrl->server_local->tor_state > 0); } /* Return an error if the assuan context does not belong to the owner of the process or to root. On error FAILTEXT is set as Assuan error string. */ static gpg_error_t check_owner_permission (assuan_context_t ctx, const char *failtext) { #ifdef HAVE_W32_SYSTEM /* Under Windows the dirmngr is always run under the control of the user. */ (void)ctx; (void)failtext; #else gpg_err_code_t ec; assuan_peercred_t cred; ec = gpg_err_code (assuan_get_peercred (ctx, &cred)); if (!ec && cred->uid && cred->uid != getuid ()) ec = GPG_ERR_EPERM; if (ec) return set_error (ec, failtext); #endif return 0; } /* Common code for get_cert_local and get_issuer_cert_local. */ static ksba_cert_t do_get_cert_local (ctrl_t ctrl, const char *name, const char *command) { unsigned char *value; size_t valuelen; int rc; char *buf; ksba_cert_t cert; buf = name? strconcat (command, " ", name, NULL) : xtrystrdup (command); if (!buf) rc = gpg_error_from_syserror (); else { rc = assuan_inquire (ctrl->server_local->assuan_ctx, buf, &value, &valuelen, MAX_CERT_LENGTH); xfree (buf); } if (rc) { log_error (_("assuan_inquire(%s) failed: %s\n"), command, gpg_strerror (rc)); return NULL; } if (!valuelen) { xfree (value); return NULL; } rc = ksba_cert_new (&cert); if (!rc) { rc = ksba_cert_init_from_mem (cert, value, valuelen); if (rc) { ksba_cert_release (cert); cert = NULL; } } xfree (value); return cert; } /* Ask back to return a certificate for NAME, given as a regular gpgsm * certificate identifier (e.g. fingerprint or one of the other * methods). Alternatively, NULL may be used for NAME to return the * current target certificate. Either return the certificate in a * KSBA object or NULL if it is not available. */ ksba_cert_t get_cert_local (ctrl_t ctrl, const char *name) { if (!ctrl || !ctrl->server_local || !ctrl->server_local->assuan_ctx) { if (opt.debug) log_debug ("get_cert_local called w/o context\n"); return NULL; } return do_get_cert_local (ctrl, name, "SENDCERT"); } /* Ask back to return the issuing certificate for NAME, given as a * regular gpgsm certificate identifier (e.g. fingerprint or one * of the other methods). Alternatively, NULL may be used for NAME to * return the current target certificate. Either return the certificate * in a KSBA object or NULL if it is not available. */ ksba_cert_t get_issuing_cert_local (ctrl_t ctrl, const char *name) { if (!ctrl || !ctrl->server_local || !ctrl->server_local->assuan_ctx) { if (opt.debug) log_debug ("get_issuing_cert_local called w/o context\n"); return NULL; } return do_get_cert_local (ctrl, name, "SENDISSUERCERT"); } /* Ask back to return a certificate with subject NAME and a * subjectKeyIdentifier of KEYID. */ ksba_cert_t get_cert_local_ski (ctrl_t ctrl, const char *name, ksba_sexp_t keyid) { unsigned char *value; size_t valuelen; int rc; char *buf; ksba_cert_t cert; char *hexkeyid; if (!ctrl || !ctrl->server_local || !ctrl->server_local->assuan_ctx) { if (opt.debug) log_debug ("get_cert_local_ski called w/o context\n"); return NULL; } if (!name || !keyid) { log_debug ("get_cert_local_ski called with insufficient arguments\n"); return NULL; } hexkeyid = serial_hex (keyid); if (!hexkeyid) { log_debug ("serial_hex() failed\n"); return NULL; } buf = strconcat ("SENDCERT_SKI ", hexkeyid, " /", name, NULL); if (!buf) { log_error ("can't allocate enough memory: %s\n", strerror (errno)); xfree (hexkeyid); return NULL; } xfree (hexkeyid); rc = assuan_inquire (ctrl->server_local->assuan_ctx, buf, &value, &valuelen, MAX_CERT_LENGTH); xfree (buf); if (rc) { log_error (_("assuan_inquire(%s) failed: %s\n"), "SENDCERT_SKI", gpg_strerror (rc)); return NULL; } if (!valuelen) { xfree (value); return NULL; } rc = ksba_cert_new (&cert); if (!rc) { rc = ksba_cert_init_from_mem (cert, value, valuelen); if (rc) { ksba_cert_release (cert); cert = NULL; } } xfree (value); return cert; } /* Ask the client via an inquiry to check the istrusted status of the certificate specified by the hexified fingerprint HEXFPR. Returns 0 if the certificate is trusted by the client or an error code. */ gpg_error_t get_istrusted_from_client (ctrl_t ctrl, const char *hexfpr) { unsigned char *value; size_t valuelen; int rc; char request[100]; if (!ctrl || !ctrl->server_local || !ctrl->server_local->assuan_ctx || !hexfpr) return gpg_error (GPG_ERR_INV_ARG); snprintf (request, sizeof request, "ISTRUSTED %s", hexfpr); rc = assuan_inquire (ctrl->server_local->assuan_ctx, request, &value, &valuelen, 100); if (rc) { log_error (_("assuan_inquire(%s) failed: %s\n"), request, gpg_strerror (rc)); return rc; } /* The expected data is: "1" or "1 cruft" (not a C-string). */ if (valuelen && *value == '1' && (valuelen == 1 || spacep (value+1))) rc = 0; else rc = gpg_error (GPG_ERR_NOT_TRUSTED); xfree (value); return rc; } /* Ask the client to return the certificate associated with the current command. This is sometimes needed because the client usually sends us just the cert ID, assuming that the request can be satisfied from the cache, where the cert ID is used as key. */ static int inquire_cert_and_load_crl (assuan_context_t ctx) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; unsigned char *value = NULL; size_t valuelen; ksba_cert_t cert = NULL; err = assuan_inquire( ctx, "SENDCERT", &value, &valuelen, 0); if (err) return err; /* { */ /* FILE *fp = fopen ("foo.der", "r"); */ /* value = xmalloc (2000); */ /* valuelen = fread (value, 1, 2000, fp); */ /* fclose (fp); */ /* } */ if (!valuelen) /* No data returned; return a comprehensible error. */ return gpg_error (GPG_ERR_MISSING_CERT); err = ksba_cert_new (&cert); if (err) goto leave; err = ksba_cert_init_from_mem (cert, value, valuelen); if(err) goto leave; xfree (value); value = NULL; err = crl_cache_reload_crl (ctrl, cert); leave: ksba_cert_release (cert); xfree (value); return err; } /* Handle OPTION commands. */ static gpg_error_t option_handler (assuan_context_t ctx, const char *key, const char *value) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err = 0; if (!strcmp (key, "force-crl-refresh")) { int i = *value? atoi (value) : 0; ctrl->force_crl_refresh = i; } else if (!strcmp (key, "audit-events")) { int i = *value? atoi (value) : 0; ctrl->audit_events = i; } else if (!strcmp (key, "http-proxy")) { xfree (ctrl->http_proxy); if (!*value || !strcmp (value, "none")) ctrl->http_proxy = NULL; else if (!(ctrl->http_proxy = xtrystrdup (value))) err = gpg_error_from_syserror (); } else if (!strcmp (key, "honor-keyserver-url-used")) { /* Return an error if we are running in Tor mode. */ if (dirmngr_use_tor ()) err = gpg_error (GPG_ERR_FORBIDDEN); } else if (!strcmp (key, "http-crl")) { int i = *value? atoi (value) : 0; ctrl->http_no_crl = !i; } else err = gpg_error (GPG_ERR_UNKNOWN_OPTION); return err; } static const char hlp_dns_cert[] = "DNS_CERT \n" "DNS_CERT --pka \n" "DNS_CERT --dane \n" "\n" "Return the CERT record for . is one of\n" " * Return the first record of any supported subtype\n" " PGP Return the first record of subtype PGP (3)\n" " IPGP Return the first record of subtype IPGP (6)\n" "If the content of a certificate is available (PGP) it is returned\n" "by data lines. Fingerprints and URLs are returned via status lines.\n" "In --pka mode the fingerprint and if available an URL is returned.\n" "In --dane mode the key is returned from RR type 61"; static gpg_error_t cmd_dns_cert (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err = 0; int pka_mode, dane_mode; char *mbox = NULL; char *namebuf = NULL; char *encodedhash = NULL; const char *name; int certtype; char *p; void *key = NULL; size_t keylen; unsigned char *fpr = NULL; size_t fprlen; char *url = NULL; pka_mode = has_option (line, "--pka"); dane_mode = has_option (line, "--dane"); line = skip_options (line); if (pka_mode && dane_mode) { err = PARM_ERROR ("either --pka or --dane may be given"); goto leave; } if (pka_mode || dane_mode) ; /* No need to parse here - we do this later. */ else { p = strchr (line, ' '); if (!p) { err = PARM_ERROR ("missing arguments"); goto leave; } *p++ = 0; if (!strcmp (line, "*")) certtype = DNS_CERTTYPE_ANY; else if (!strcmp (line, "IPGP")) certtype = DNS_CERTTYPE_IPGP; else if (!strcmp (line, "PGP")) certtype = DNS_CERTTYPE_PGP; else { err = PARM_ERROR ("unknown subtype"); goto leave; } while (spacep (p)) p++; line = p; if (!*line) { err = PARM_ERROR ("name missing"); goto leave; } } if (pka_mode || dane_mode) { char *domain; /* Points to mbox. */ char hashbuf[32]; /* For SHA-1 and SHA-256. */ /* We lowercase ascii characters but the DANE I-D does not allow this. FIXME: Check after the release of the RFC whether to change this. */ mbox = mailbox_from_userid (line, 0); if (!mbox || !(domain = strchr (mbox, '@'))) { err = set_error (GPG_ERR_INV_USER_ID, "no mailbox in user id"); goto leave; } *domain++ = 0; if (pka_mode) { gcry_md_hash_buffer (GCRY_MD_SHA1, hashbuf, mbox, strlen (mbox)); encodedhash = zb32_encode (hashbuf, 8*20); if (!encodedhash) { err = gpg_error_from_syserror (); goto leave; } namebuf = strconcat (encodedhash, "._pka.", domain, NULL); if (!namebuf) { err = gpg_error_from_syserror (); goto leave; } name = namebuf; certtype = DNS_CERTTYPE_IPGP; } else { /* Note: The hash is truncated to 28 bytes and we lowercase the result only for aesthetic reasons. */ gcry_md_hash_buffer (GCRY_MD_SHA256, hashbuf, mbox, strlen (mbox)); encodedhash = bin2hex (hashbuf, 28, NULL); if (!encodedhash) { err = gpg_error_from_syserror (); goto leave; } ascii_strlwr (encodedhash); namebuf = strconcat (encodedhash, "._openpgpkey.", domain, NULL); if (!namebuf) { err = gpg_error_from_syserror (); goto leave; } name = namebuf; certtype = DNS_CERTTYPE_RR61; } } else name = line; err = get_dns_cert (ctrl, name, certtype, &key, &keylen, &fpr, &fprlen, &url); if (err) goto leave; if (key) { err = data_line_write (ctx, key, keylen); if (err) goto leave; } if (fpr) { char *tmpstr; tmpstr = bin2hex (fpr, fprlen, NULL); if (!tmpstr) err = gpg_error_from_syserror (); else { err = assuan_write_status (ctx, "FPR", tmpstr); xfree (tmpstr); } if (err) goto leave; } if (url) { err = assuan_write_status (ctx, "URL", url); if (err) goto leave; } leave: xfree (key); xfree (fpr); xfree (url); xfree (mbox); xfree (namebuf); xfree (encodedhash); return leave_cmd (ctx, err); } /* Core of cmd_wkd_get and task_check_wkd_support. If CTX is NULL * this function will not write anything to the assuan output. */ static gpg_error_t proc_wkd_get (ctrl_t ctrl, assuan_context_t ctx, char *line) { gpg_error_t err = 0; char *mbox = NULL; char *domainbuf = NULL; char *domain; /* Points to mbox or domainbuf. This is used to * connect to the host. */ char *domain_orig;/* Points to mbox. This is the used for the * query; i.e. the domain part of the * addrspec. */ char sha1buf[20]; char *uri = NULL; char *encodedhash = NULL; int opt_submission_addr; int opt_policy_flags; int is_wkd_query; /* True if this is a real WKD query. */ int no_log = 0; char portstr[20] = { 0 }; int subdomain_mode = 0; opt_submission_addr = has_option (line, "--submission-address"); opt_policy_flags = has_option (line, "--policy-flags"); if (has_option (line, "--quick")) ctrl->timeout = opt.connect_quick_timeout; line = skip_options (line); is_wkd_query = !(opt_policy_flags || opt_submission_addr); mbox = mailbox_from_userid (line, 0); if (!mbox || !(domain = strchr (mbox, '@'))) { err = set_error (GPG_ERR_INV_USER_ID, "no mailbox in user id"); goto leave; } *domain++ = 0; domain_orig = domain; /* Let's check whether we already know that the domain does not * support WKD. */ if (is_wkd_query) { if (domaininfo_is_wkd_not_supported (domain_orig)) { err = gpg_error (GPG_ERR_NO_DATA); dirmngr_status_printf (ctrl, "NOTE", "wkd_cached_result %u", err); goto leave; } } /* First try the new "openpgp" subdomain. We check that the domain * is valid because it is later used as an unescaped filename part * of the URI. */ if (is_valid_domain_name (domain_orig)) { dns_addrinfo_t aibuf; domainbuf = strconcat ( "openpgpkey.", domain_orig, NULL); if (!domainbuf) { err = gpg_error_from_syserror (); goto leave; } /* FIXME: We should put a cache into dns-stuff because the same * query (with a different port and socket type, though) will be * done later by http function. */ err = resolve_dns_name (ctrl, domainbuf, 0, 0, 0, &aibuf, NULL); if (err) { err = 0; xfree (domainbuf); domainbuf = NULL; } else /* Got a subdomain. */ { free_dns_addrinfo (aibuf); subdomain_mode = 1; domain = domainbuf; } } /* Check for SRV records unless we have a subdomain. */ if (!subdomain_mode) { struct srventry *srvs; unsigned int srvscount; size_t domainlen, targetlen; int i; err = get_dns_srv (ctrl, domain, "openpgpkey", NULL, &srvs, &srvscount); if (err) goto leave; /* Check for rogue DNS names. */ for (i = 0; i < srvscount; i++) { if (!is_valid_domain_name (srvs[i].target)) { err = gpg_error (GPG_ERR_DNS_ADDRESS); log_error ("rogue openpgpkey SRV record for '%s'\n", domain); xfree (srvs); goto leave; } } /* Find the first target which also ends in DOMAIN or is equal * to DOMAIN. */ domainlen = strlen (domain); for (i = 0; i < srvscount; i++) { if (DBG_DNS) log_debug ("srv: trying '%s:%hu'\n", srvs[i].target, srvs[i].port); targetlen = strlen (srvs[i].target); if ((targetlen > domainlen + 1 && srvs[i].target[targetlen - domainlen - 1] == '.' && !ascii_strcasecmp (srvs[i].target + targetlen - domainlen, domain)) || (targetlen == domainlen && !ascii_strcasecmp (srvs[i].target, domain))) { /* found. */ domainbuf = xtrystrdup (srvs[i].target); if (!domainbuf) { err = gpg_error_from_syserror (); xfree (srvs); goto leave; } domain = domainbuf; if (srvs[i].port) snprintf (portstr, sizeof portstr, ":%hu", srvs[i].port); break; } } xfree (srvs); } /* Prepare the hash of the local part. */ gcry_md_hash_buffer (GCRY_MD_SHA1, sha1buf, mbox, strlen (mbox)); encodedhash = zb32_encode (sha1buf, 8*20); if (!encodedhash) { err = gpg_error_from_syserror (); goto leave; } if (opt_submission_addr) { uri = strconcat ("https://", domain, portstr, "/.well-known/openpgpkey/", subdomain_mode? domain_orig : "", subdomain_mode? "/" : "", "submission-address", NULL); } else if (opt_policy_flags) { uri = strconcat ("https://", domain, portstr, "/.well-known/openpgpkey/", subdomain_mode? domain_orig : "", subdomain_mode? "/" : "", "policy", NULL); } else { char *escapedmbox; escapedmbox = http_escape_string (mbox, "%;?&="); if (escapedmbox) { uri = strconcat ("https://", domain, portstr, "/.well-known/openpgpkey/", subdomain_mode? domain_orig : "", subdomain_mode? "/" : "", "hu/", encodedhash, "?l=", escapedmbox, NULL); xfree (escapedmbox); no_log = 1; if (uri) { err = dirmngr_status_printf (ctrl, "SOURCE", "https://%s%s", domain, portstr); if (err) goto leave; } } } if (!uri) { err = gpg_error_from_syserror (); goto leave; } /* Setup an output stream and perform the get. */ { estream_t outfp; outfp = ctx? es_fopencookie (ctx, "w", data_line_cookie_functions) : NULL; if (!outfp && ctx) err = set_error (GPG_ERR_ASS_GENERAL, "error setting up a data stream"); else { if (ctrl->server_local) { if (no_log) ctrl->server_local->inhibit_data_logging = 1; ctrl->server_local->inhibit_data_logging_now = 0; ctrl->server_local->inhibit_data_logging_count = 0; } err = ks_action_fetch (ctrl, uri, outfp); es_fclose (outfp); if (ctrl->server_local) ctrl->server_local->inhibit_data_logging = 0; /* Register the result under the domain name of MBOX. */ switch (gpg_err_code (err)) { case 0: domaininfo_set_wkd_supported (domain_orig); break; case GPG_ERR_NO_NAME: /* There is no such domain. */ domaininfo_set_no_name (domain_orig); break; case GPG_ERR_NO_DATA: if (is_wkd_query && ctrl->server_local) { /* Mark that and schedule a check. */ domaininfo_set_wkd_not_found (domain_orig); workqueue_add_task (task_check_wkd_support, domain_orig, ctrl->server_local->session_id, 1); } else if (opt_policy_flags) /* No policy file - no support. */ domaininfo_set_wkd_not_supported (domain_orig); break; default: /* Don't register other errors. */ break; } } } leave: xfree (uri); xfree (encodedhash); xfree (mbox); xfree (domainbuf); return err; } static const char hlp_wkd_get[] = "WKD_GET [--submission-address|--policy-flags] \n" "\n" "Return the key or other info for \n" "from the Web Key Directory."; static gpg_error_t cmd_wkd_get (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; err = proc_wkd_get (ctrl, ctx, line); return leave_cmd (ctx, err); } /* A task to check whether DOMAIN supports WKD. This is done by * checking whether the policy flags file can be read. */ static const char * task_check_wkd_support (ctrl_t ctrl, const char *domain) { char *string; if (!ctrl || !domain) return "check_wkd_support"; string = strconcat ("--policy-flags foo@", domain, NULL); if (!string) log_error ("%s: %s\n", __func__, gpg_strerror (gpg_error_from_syserror ())); else { proc_wkd_get (ctrl, NULL, string); xfree (string); } return NULL; } static const char hlp_ldapserver[] = "LDAPSERVER \n" "\n" "Add a new LDAP server to the list of configured LDAP servers.\n" "DATA is in the same format as expected in the configure file."; static gpg_error_t cmd_ldapserver (assuan_context_t ctx, char *line) { #if USE_LDAP ctrl_t ctrl = assuan_get_pointer (ctx); ldap_server_t server; ldap_server_t *last_next_p; while (spacep (line)) line++; if (*line == '\0') return leave_cmd (ctx, PARM_ERROR (_("ldapserver missing"))); server = ldapserver_parse_one (line, "", 0); if (! server) return leave_cmd (ctx, gpg_error (GPG_ERR_INV_ARG)); last_next_p = &ctrl->server_local->ldapservers; while (*last_next_p) last_next_p = &(*last_next_p)->next; *last_next_p = server; return leave_cmd (ctx, 0); #else (void)line; return leave_cmd (ctx, gpg_error (GPG_ERR_NOT_IMPLEMENTED)); #endif } static const char hlp_isvalid[] = "ISVALID [--only-ocsp] [--force-default-responder]" " []\n" "\n" "This command checks whether the certificate identified by the\n" "certificate_id is valid. This is done by consulting CRLs or\n" "whatever has been configured. Note, that the returned error codes\n" "are from gpg-error.h. The command may callback using the inquire\n" "function. See the manual for details.\n" "\n" "The CERTIFICATE_ID is a hex encoded string consisting of two parts,\n" "delimited by a single dot. The first part is the SHA-1 hash of the\n" "issuer name and the second part the serial number.\n" "\n" "If an OCSP check is desired CERTIFICATE_FPR with the hex encoded\n" "fingerprint of the certificate is required. In this case an OCSP\n" "request is done before consulting the CRL.\n" "\n" "If the option --only-ocsp is given, no fallback to a CRL check will\n" "be used.\n" "\n" "If the option --force-default-responder is given, only the default\n" "OCSP responder will be used and any other methods of obtaining an\n" "OCSP responder URL won't be used."; static gpg_error_t cmd_isvalid (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); char *issuerhash, *serialno, *fpr; gpg_error_t err; int did_inquire = 0; int ocsp_mode = 0; int only_ocsp; int force_default_responder; only_ocsp = has_option (line, "--only-ocsp"); force_default_responder = has_option (line, "--force-default-responder"); line = skip_options (line); /* We need to work on a copy of the line because that same Assuan * context may be used for an inquiry. That is because Assuan * reuses its line buffer. */ issuerhash = xstrdup (line); serialno = strchr (issuerhash, '.'); if (!serialno) { xfree (issuerhash); return leave_cmd (ctx, PARM_ERROR (_("serialno missing in cert ID"))); } *serialno++ = 0; if (strlen (issuerhash) != 40) { xfree (issuerhash); return leave_cmd (ctx, PARM_ERROR ("cert ID is too short")); } fpr = strchr (serialno, ' '); while (fpr && spacep (fpr)) fpr++; if (fpr && *fpr) { char *endp = strchr (fpr, ' '); if (endp) *endp = 0; if (strlen (fpr) != 40) { xfree (issuerhash); return leave_cmd (ctx, PARM_ERROR ("fingerprint too short")); } ocsp_mode = 1; } again: if (ocsp_mode) { /* Note, that we currently ignore the supplied fingerprint FPR; * instead ocsp_isvalid does an inquire to ask for the cert. * The fingerprint may eventually be used to lookup the * certificate in a local cache. */ if (!opt.allow_ocsp) err = gpg_error (GPG_ERR_NOT_SUPPORTED); else err = ocsp_isvalid (ctrl, NULL, NULL, force_default_responder); if (gpg_err_code (err) == GPG_ERR_CONFIGURATION && gpg_err_source (err) == GPG_ERR_SOURCE_DIRMNGR) { /* No default responder configured - fallback to CRL. */ if (!only_ocsp) log_info ("falling back to CRL check\n"); ocsp_mode = 0; goto again; } } else if (only_ocsp) err = gpg_error (GPG_ERR_NO_CRL_KNOWN); else { switch (crl_cache_isvalid (ctrl, issuerhash, serialno, ctrl->force_crl_refresh)) { case CRL_CACHE_VALID: err = 0; break; case CRL_CACHE_INVALID: err = gpg_error (GPG_ERR_CERT_REVOKED); break; case CRL_CACHE_DONTKNOW: if (did_inquire) err = gpg_error (GPG_ERR_NO_CRL_KNOWN); else if (!(err = inquire_cert_and_load_crl (ctx))) { did_inquire = 1; goto again; } break; case CRL_CACHE_CANTUSE: err = gpg_error (GPG_ERR_NO_CRL_KNOWN); break; default: log_fatal ("crl_cache_isvalid returned invalid code\n"); } } xfree (issuerhash); return leave_cmd (ctx, err); } /* If the line contains a SHA-1 fingerprint as the first argument, return the FPR vuffer on success. The function checks that the fingerprint consists of valid characters and prints and error message if it does not and returns NULL. Fingerprints are considered optional and thus no explicit error is returned. NULL is also returned if there is no fingerprint at all available. FPR must be a caller provided buffer of at least 20 bytes. Note that colons within the fingerprint are allowed to separate 2 hex digits; this allows for easier cutting and pasting using the usual fingerprint rendering. */ static unsigned char * get_fingerprint_from_line (const char *line, unsigned char *fpr) { const char *s; int i; for (s=line, i=0; *s && *s != ' '; s++ ) { if ( hexdigitp (s) && hexdigitp (s+1) ) { if ( i >= 20 ) return NULL; /* Fingerprint too long. */ fpr[i++] = xtoi_2 (s); s++; } else if ( *s != ':' ) return NULL; /* Invalid. */ } if ( i != 20 ) return NULL; /* Fingerprint to short. */ return fpr; } static const char hlp_checkcrl[] = "CHECKCRL []\n" "\n" "Check whether the certificate with FINGERPRINT (SHA-1 hash of the\n" "entire X.509 certificate blob) is valid or not by consulting the\n" "CRL responsible for this certificate. If the fingerprint has not\n" "been given or the certificate is not known, the function \n" "inquires the certificate using an\n" "\n" " INQUIRE TARGETCERT\n" "\n" "and the caller is expected to return the certificate for the\n" "request (which should match FINGERPRINT) as a binary blob.\n" "Processing then takes place without further interaction; in\n" "particular dirmngr tries to locate other required certificate by\n" "its own mechanism which includes a local certificate store as well\n" "as a list of trusted root certificates.\n" "\n" "The return value is the usual gpg-error code or 0 for ducesss;\n" "i.e. the certificate validity has been confirmed by a valid CRL."; static gpg_error_t cmd_checkcrl (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; unsigned char fprbuffer[20], *fpr; ksba_cert_t cert; fpr = get_fingerprint_from_line (line, fprbuffer); cert = fpr? get_cert_byfpr (fpr) : NULL; if (!cert) { /* We do not have this certificate yet or the fingerprint has not been given. Inquire it from the client. */ unsigned char *value = NULL; size_t valuelen; err = assuan_inquire (ctrl->server_local->assuan_ctx, "TARGETCERT", &value, &valuelen, MAX_CERT_LENGTH); if (err) { log_error (_("assuan_inquire failed: %s\n"), gpg_strerror (err)); goto leave; } if (!valuelen) /* No data returned; return a comprehensible error. */ err = gpg_error (GPG_ERR_MISSING_CERT); else { err = ksba_cert_new (&cert); if (!err) err = ksba_cert_init_from_mem (cert, value, valuelen); } xfree (value); if(err) goto leave; } assert (cert); err = crl_cache_cert_isvalid (ctrl, cert, ctrl->force_crl_refresh); if (gpg_err_code (err) == GPG_ERR_NO_CRL_KNOWN) { err = crl_cache_reload_crl (ctrl, cert); if (!err) err = crl_cache_cert_isvalid (ctrl, cert, 0); } leave: ksba_cert_release (cert); return leave_cmd (ctx, err); } static const char hlp_checkocsp[] = "CHECKOCSP [--force-default-responder] []\n" "\n" "Check whether the certificate with FINGERPRINT (SHA-1 hash of the\n" "entire X.509 certificate blob) is valid or not by asking an OCSP\n" "responder responsible for this certificate. The optional\n" "fingerprint may be used for a quick check in case an OCSP check has\n" "been done for this certificate recently (we always cache OCSP\n" "responses for a couple of minutes). If the fingerprint has not been\n" "given or there is no cached result, the function inquires the\n" "certificate using an\n" "\n" " INQUIRE TARGETCERT\n" "\n" "and the caller is expected to return the certificate for the\n" "request (which should match FINGERPRINT) as a binary blob.\n" "Processing then takes place without further interaction; in\n" "particular dirmngr tries to locate other required certificates by\n" "its own mechanism which includes a local certificate store as well\n" "as a list of trusted root certificates.\n" "\n" "If the option --force-default-responder is given, only the default\n" "OCSP responder will be used and any other methods of obtaining an\n" "OCSP responder URL won't be used.\n" "\n" "The return value is the usual gpg-error code or 0 for ducesss;\n" "i.e. the certificate validity has been confirmed by a valid CRL."; static gpg_error_t cmd_checkocsp (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; unsigned char fprbuffer[20], *fpr; ksba_cert_t cert; int force_default_responder; force_default_responder = has_option (line, "--force-default-responder"); line = skip_options (line); fpr = get_fingerprint_from_line (line, fprbuffer); cert = fpr? get_cert_byfpr (fpr) : NULL; if (!cert) { /* We do not have this certificate yet or the fingerprint has not been given. Inquire it from the client. */ unsigned char *value = NULL; size_t valuelen; err = assuan_inquire (ctrl->server_local->assuan_ctx, "TARGETCERT", &value, &valuelen, MAX_CERT_LENGTH); if (err) { log_error (_("assuan_inquire failed: %s\n"), gpg_strerror (err)); goto leave; } if (!valuelen) /* No data returned; return a comprehensible error. */ err = gpg_error (GPG_ERR_MISSING_CERT); else { err = ksba_cert_new (&cert); if (!err) err = ksba_cert_init_from_mem (cert, value, valuelen); } xfree (value); if(err) goto leave; } assert (cert); if (!opt.allow_ocsp) err = gpg_error (GPG_ERR_NOT_SUPPORTED); else err = ocsp_isvalid (ctrl, cert, NULL, force_default_responder); leave: ksba_cert_release (cert); return leave_cmd (ctx, err); } static int lookup_cert_by_url (assuan_context_t ctx, const char *url) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err = 0; unsigned char *value = NULL; size_t valuelen; /* Fetch single certificate given it's URL. */ err = fetch_cert_by_url (ctrl, url, &value, &valuelen); if (err) { log_error (_("fetch_cert_by_url failed: %s\n"), gpg_strerror (err)); goto leave; } /* Send the data, flush the buffer and then send an END. */ err = assuan_send_data (ctx, value, valuelen); if (!err) err = assuan_send_data (ctx, NULL, 0); if (!err) err = assuan_write_line (ctx, "END"); if (err) { log_error (_("error sending data: %s\n"), gpg_strerror (err)); goto leave; } leave: return err; } /* Send the certificate, flush the buffer and then send an END. */ static gpg_error_t return_one_cert (void *opaque, ksba_cert_t cert) { assuan_context_t ctx = opaque; gpg_error_t err; const unsigned char *der; size_t derlen; der = ksba_cert_get_image (cert, &derlen); if (!der) err = gpg_error (GPG_ERR_INV_CERT_OBJ); else { err = assuan_send_data (ctx, der, derlen); if (!err) err = assuan_send_data (ctx, NULL, 0); if (!err) err = assuan_write_line (ctx, "END"); } if (err) log_error (_("error sending data: %s\n"), gpg_strerror (err)); return err; } /* Lookup certificates from the internal cache or using the ldap servers. */ static int lookup_cert_by_pattern (assuan_context_t ctx, char *line, int single, int cache_only) { gpg_error_t err = 0; char *p; strlist_t sl, list = NULL; int truncated = 0, truncation_forced = 0; int count = 0; int local_count = 0; #if USE_LDAP ctrl_t ctrl = assuan_get_pointer (ctx); unsigned char *value = NULL; size_t valuelen; struct ldapserver_iter ldapserver_iter; cert_fetch_context_t fetch_context; #endif /*USE_LDAP*/ int any_no_data = 0; /* Break the line down into an STRLIST */ for (p=line; *p; line = p) { while (*p && *p != ' ') p++; if (*p) *p++ = 0; if (*line) { sl = xtrymalloc (sizeof *sl + strlen (line)); if (!sl) { err = gpg_error_from_errno (errno); goto leave; } memset (sl, 0, sizeof *sl); strcpy_escaped_plus (sl->d, line); sl->next = list; list = sl; } } /* First look through the internal cache. The certificates returned here are not counted towards the truncation limit. */ if (single && !cache_only) ; /* Do not read from the local cache in this case. */ else { for (sl=list; sl; sl = sl->next) { err = get_certs_bypattern (sl->d, return_one_cert, ctx); if (!err) local_count++; if (!err && single) goto ready; if (gpg_err_code (err) == GPG_ERR_NO_DATA) { err = 0; if (cache_only) any_no_data = 1; } else if (gpg_err_code (err) == GPG_ERR_INV_NAME && !cache_only) { /* No real fault because the internal pattern lookup can't yet cope with all types of pattern. */ err = 0; } if (err) goto ready; } } /* Loop over all configured servers unless we want only the certificates from the cache. */ #if USE_LDAP for (ldapserver_iter_begin (&ldapserver_iter, ctrl); !cache_only && !ldapserver_iter_end_p (&ldapserver_iter) && ldapserver_iter.server->host && !truncation_forced; ldapserver_iter_next (&ldapserver_iter)) { ldap_server_t ldapserver = ldapserver_iter.server; if (DBG_LOOKUP) log_debug ("cmd_lookup: trying %s:%d base=%s\n", ldapserver->host, ldapserver->port, ldapserver->base?ldapserver->base : "[default]"); /* Fetch certificates matching pattern */ err = start_cert_fetch (ctrl, &fetch_context, list, ldapserver); if ( gpg_err_code (err) == GPG_ERR_NO_DATA ) { if (DBG_LOOKUP) log_debug ("cmd_lookup: no data\n"); err = 0; any_no_data = 1; continue; } if (err) { log_error (_("start_cert_fetch failed: %s\n"), gpg_strerror (err)); goto leave; } /* Fetch the certificates for this query. */ while (!truncation_forced) { xfree (value); value = NULL; err = fetch_next_cert (fetch_context, &value, &valuelen); if (gpg_err_code (err) == GPG_ERR_NO_DATA ) { err = 0; any_no_data = 1; break; /* Ready. */ } if (gpg_err_code (err) == GPG_ERR_TRUNCATED) { truncated = 1; err = 0; break; /* Ready. */ } if (gpg_err_code (err) == GPG_ERR_EOF) { err = 0; break; /* Ready. */ } if (!err && !value) { err = gpg_error (GPG_ERR_BUG); goto leave; } if (err) { log_error (_("fetch_next_cert failed: %s\n"), gpg_strerror (err)); end_cert_fetch (fetch_context); goto leave; } if (DBG_LOOKUP) log_debug ("cmd_lookup: returning one cert%s\n", truncated? " (truncated)":""); /* Send the data, flush the buffer and then send an END line as a certificate delimiter. */ err = assuan_send_data (ctx, value, valuelen); if (!err) err = assuan_send_data (ctx, NULL, 0); if (!err) err = assuan_write_line (ctx, "END"); if (err) { log_error (_("error sending data: %s\n"), gpg_strerror (err)); end_cert_fetch (fetch_context); goto leave; } if (++count >= opt.max_replies ) { truncation_forced = 1; log_info (_("max_replies %d exceeded\n"), opt.max_replies ); } if (single) break; } end_cert_fetch (fetch_context); } #endif /*USE_LDAP*/ ready: if (truncated || truncation_forced) { char str[50]; sprintf (str, "%d", count); assuan_write_status (ctx, "TRUNCATED", str); } if (!err && !count && !local_count && any_no_data) err = gpg_error (GPG_ERR_NO_DATA); leave: free_strlist (list); return err; } static const char hlp_lookup[] = "LOOKUP [--url] [--single] [--cache-only] \n" "\n" "Lookup certificates matching PATTERN. With --url the pattern is\n" "expected to be one URL.\n" "\n" "If --url is not given: To allow for multiple patterns (which are ORed)\n" "quoting is required: Spaces are translated to \"+\" or \"%20\";\n" "obviously this requires that the usual escape quoting rules are applied.\n" "\n" "If --url is given no special escaping is required because URLs are\n" "already escaped this way.\n" "\n" "If --single is given the first and only the first match will be\n" "returned. If --cache-only is _not_ given, no local query will be\n" "done.\n" "\n" "If --cache-only is given no external lookup is done so that only\n" "certificates from the cache may get returned."; static gpg_error_t cmd_lookup (assuan_context_t ctx, char *line) { gpg_error_t err; int lookup_url, single, cache_only; lookup_url = has_leading_option (line, "--url"); single = has_leading_option (line, "--single"); cache_only = has_leading_option (line, "--cache-only"); line = skip_options (line); if (lookup_url && cache_only) err = gpg_error (GPG_ERR_NOT_FOUND); else if (lookup_url && single) err = gpg_error (GPG_ERR_NOT_IMPLEMENTED); else if (lookup_url) err = lookup_cert_by_url (ctx, line); else err = lookup_cert_by_pattern (ctx, line, single, cache_only); return leave_cmd (ctx, err); } static const char hlp_loadcrl[] = "LOADCRL [--url] \n" "\n" "Load the CRL in the file with name FILENAME into our cache. Note\n" "that FILENAME should be given with an absolute path because\n" "Dirmngrs cwd is not known. With --url the CRL is directly loaded\n" "from the given URL.\n" "\n" "This command is usually used by gpgsm using the invocation \"gpgsm\n" "--call-dirmngr loadcrl \". A direct invocation of Dirmngr\n" "is not useful because gpgsm might need to callback gpgsm to ask for\n" "the CA's certificate."; static gpg_error_t cmd_loadcrl (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err = 0; int use_url = has_leading_option (line, "--url"); line = skip_options (line); if (use_url) { ksba_reader_t reader; err = crl_fetch (ctrl, line, &reader); if (err) log_error (_("fetching CRL from '%s' failed: %s\n"), line, gpg_strerror (err)); else { err = crl_cache_insert (ctrl, line, reader); if (err) log_error (_("processing CRL from '%s' failed: %s\n"), line, gpg_strerror (err)); crl_close_reader (reader); } } else { char *buf; buf = xtrymalloc (strlen (line)+1); if (!buf) err = gpg_error_from_syserror (); else { strcpy_escaped_plus (buf, line); err = crl_cache_load (ctrl, buf); xfree (buf); } } return leave_cmd (ctx, err); } static const char hlp_listcrls[] = "LISTCRLS\n" "\n" "List the content of all CRLs in a readable format. This command is\n" "usually used by gpgsm using the invocation \"gpgsm --call-dirmngr\n" "listcrls\". It may also be used directly using \"dirmngr\n" "--list-crls\"."; static gpg_error_t cmd_listcrls (assuan_context_t ctx, char *line) { gpg_error_t err; estream_t fp; (void)line; fp = es_fopencookie (ctx, "w", data_line_cookie_functions); if (!fp) err = set_error (GPG_ERR_ASS_GENERAL, "error setting up a data stream"); else { err = crl_cache_list (fp); es_fclose (fp); } return leave_cmd (ctx, err); } static const char hlp_cachecert[] = "CACHECERT\n" "\n" "Put a certificate into the internal cache. This command might be\n" "useful if a client knows in advance certificates required for a\n" "test and wants to make sure they get added to the internal cache.\n" "It is also helpful for debugging. To get the actual certificate,\n" "this command immediately inquires it using\n" "\n" " INQUIRE TARGETCERT\n" "\n" "and the caller is expected to return the certificate for the\n" "request as a binary blob."; static gpg_error_t cmd_cachecert (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; ksba_cert_t cert = NULL; unsigned char *value = NULL; size_t valuelen; (void)line; err = assuan_inquire (ctrl->server_local->assuan_ctx, "TARGETCERT", &value, &valuelen, MAX_CERT_LENGTH); if (err) { log_error (_("assuan_inquire failed: %s\n"), gpg_strerror (err)); goto leave; } if (!valuelen) /* No data returned; return a comprehensible error. */ err = gpg_error (GPG_ERR_MISSING_CERT); else { err = ksba_cert_new (&cert); if (!err) err = ksba_cert_init_from_mem (cert, value, valuelen); } xfree (value); if(err) goto leave; err = cache_cert (cert); leave: ksba_cert_release (cert); return leave_cmd (ctx, err); } static const char hlp_validate[] = "VALIDATE [--systrust] [--tls] [--no-crl]\n" "\n" "Validate a certificate using the certificate validation function\n" "used internally by dirmngr. This command is only useful for\n" "debugging. To get the actual certificate, this command immediately\n" "inquires it using\n" "\n" " INQUIRE TARGETCERT\n" "\n" "and the caller is expected to return the certificate for the\n" "request as a binary blob. The option --tls modifies this by asking\n" "for list of certificates with\n" "\n" " INQUIRE CERTLIST\n" "\n" "Here the first certificate is the target certificate, the remaining\n" "certificates are suggested intermediary certificates. All certificates\n" "need to be PEM encoded.\n" "\n" "The option --systrust changes the behaviour to include the system\n" "provided root certificates as trust anchors. The option --no-crl\n" "skips CRL checks"; static gpg_error_t cmd_validate (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; ksba_cert_t cert = NULL; certlist_t certlist = NULL; unsigned char *value = NULL; size_t valuelen; int systrust_mode, tls_mode, no_crl; systrust_mode = has_option (line, "--systrust"); tls_mode = has_option (line, "--tls"); no_crl = has_option (line, "--no-crl"); line = skip_options (line); if (tls_mode) err = assuan_inquire (ctrl->server_local->assuan_ctx, "CERTLIST", &value, &valuelen, MAX_CERTLIST_LENGTH); else err = assuan_inquire (ctrl->server_local->assuan_ctx, "TARGETCERT", &value, &valuelen, MAX_CERT_LENGTH); if (err) { log_error (_("assuan_inquire failed: %s\n"), gpg_strerror (err)); goto leave; } if (!valuelen) /* No data returned; return a comprehensible error. */ err = gpg_error (GPG_ERR_MISSING_CERT); else if (tls_mode) { estream_t fp; fp = es_fopenmem_init (0, "rb", value, valuelen); if (!fp) err = gpg_error_from_syserror (); else { err = read_certlist_from_stream (&certlist, fp); es_fclose (fp); if (!err && !certlist) err = gpg_error (GPG_ERR_MISSING_CERT); if (!err) { /* Extract the first certificate from the list. */ cert = certlist->cert; ksba_cert_ref (cert); } } } else { err = ksba_cert_new (&cert); if (!err) err = ksba_cert_init_from_mem (cert, value, valuelen); } xfree (value); if(err) goto leave; if (!tls_mode) { /* If we have this certificate already in our cache, use the * cached version for validation because this will take care of * any cached results. We don't need to do this in tls mode * because this has already been done for certificate in a * certlist_t. */ unsigned char fpr[20]; ksba_cert_t tmpcert; cert_compute_fpr (cert, fpr); tmpcert = get_cert_byfpr (fpr); if (tmpcert) { ksba_cert_release (cert); cert = tmpcert; } } /* Quick hack to make verification work by inserting the supplied * certs into the cache. */ if (tls_mode && certlist) { certlist_t cl; for (cl = certlist->next; cl; cl = cl->next) cache_cert (cl->cert); } err = validate_cert_chain (ctrl, cert, NULL, (VALIDATE_FLAG_TRUST_CONFIG | (tls_mode ? VALIDATE_FLAG_TLS : 0) | (systrust_mode ? VALIDATE_FLAG_TRUST_SYSTEM : 0) | (no_crl ? VALIDATE_FLAG_NOCRLCHECK : 0)), NULL); leave: ksba_cert_release (cert); release_certlist (certlist); return leave_cmd (ctx, err); } /* Parse an keyserver URI and store it in a new uri item which is returned at R_ITEM. On error return an error code. */ static gpg_error_t make_keyserver_item (const char *uri, uri_item_t *r_item) { gpg_error_t err; uri_item_t item; *r_item = NULL; /* We used to have DNS CNAME redirection from the URLs below to * sks-keyserver. pools. The idea was to allow for a quick way to * switch to a different set of pools. The problem with that * approach is that TLS needs to verify the hostname and - because * DNS is not secured - it can only check the user supplied hostname * and not a hostname from a CNAME RR. Thus the final server all * need to have certificates with the actual pool name as well as * for keys.gnupg.net - that would render the advantage of * keys.gnupg.net useless and so we better give up on this. Because * the keys.gnupg.net URL are still in widespread use we do a static * mapping here. */ if (!strcmp (uri, "hkps://keys.gnupg.net") || !strcmp (uri, "keys.gnupg.net")) uri = "hkps://hkps.pool.sks-keyservers.net"; else if (!strcmp (uri, "https://keys.gnupg.net")) uri = "https://hkps.pool.sks-keyservers.net"; else if (!strcmp (uri, "hkp://keys.gnupg.net")) uri = "hkp://hkps.pool.sks-keyservers.net"; else if (!strcmp (uri, "http://keys.gnupg.net")) uri = "http://hkps.pool.sks-keyservers.net"; else if (!strcmp (uri, "hkps://http-keys.gnupg.net") || !strcmp (uri, "http-keys.gnupg.net")) uri = "hkps://ha.pool.sks-keyservers.net"; else if (!strcmp (uri, "https://http-keys.gnupg.net")) uri = "https://ha.pool.sks-keyservers.net"; else if (!strcmp (uri, "hkp://http-keys.gnupg.net")) uri = "hkp://ha.pool.sks-keyservers.net"; else if (!strcmp (uri, "http://http-keys.gnupg.net")) uri = "http://ha.pool.sks-keyservers.net"; item = xtrymalloc (sizeof *item + strlen (uri)); if (!item) return gpg_error_from_syserror (); item->next = NULL; item->parsed_uri = NULL; strcpy (item->uri, uri); #if USE_LDAP if (ldap_uri_p (item->uri)) err = ldap_parse_uri (&item->parsed_uri, uri); else #endif { err = http_parse_uri (&item->parsed_uri, uri, 1); } if (err) xfree (item); else *r_item = item; return err; } /* If no keyserver is stored in CTRL but a global keyserver has been set, put that global keyserver into CTRL. We need use this function to help migrate from the old gpg based keyserver configuration to the new dirmngr based configuration. */ static gpg_error_t ensure_keyserver (ctrl_t ctrl) { gpg_error_t err; uri_item_t item; uri_item_t onion_items = NULL; uri_item_t plain_items = NULL; uri_item_t ui; strlist_t sl; if (ctrl->server_local->keyservers) return 0; /* Already set for this session. */ if (!opt.keyserver) { /* No global option set. Fall back to default: */ return make_keyserver_item (DIRMNGR_DEFAULT_KEYSERVER, &ctrl->server_local->keyservers); } for (sl = opt.keyserver; sl; sl = sl->next) { err = make_keyserver_item (sl->d, &item); if (err) goto leave; if (item->parsed_uri->onion) { item->next = onion_items; onion_items = item; } else { item->next = plain_items; plain_items = item; } } /* Decide which to use. Note that the session has no keyservers yet set. */ if (onion_items && !onion_items->next && plain_items && !plain_items->next) { /* If there is just one onion and one plain keyserver given, we take only one depending on whether Tor is running or not. */ if (is_tor_running (ctrl)) { ctrl->server_local->keyservers = onion_items; onion_items = NULL; } else { ctrl->server_local->keyservers = plain_items; plain_items = NULL; } } else if (!is_tor_running (ctrl)) { /* Tor is not running. It does not make sense to add Onion addresses. */ ctrl->server_local->keyservers = plain_items; plain_items = NULL; } else { /* In all other cases add all keyservers. */ ctrl->server_local->keyservers = onion_items; onion_items = NULL; for (ui = ctrl->server_local->keyservers; ui && ui->next; ui = ui->next) ; if (ui) ui->next = plain_items; else ctrl->server_local->keyservers = plain_items; plain_items = NULL; } leave: release_uri_item_list (onion_items); release_uri_item_list (plain_items); return err; } static const char hlp_keyserver[] = "KEYSERVER [] [|]\n" "Options are:\n" " --help\n" " --clear Remove all configured keyservers\n" " --resolve Resolve HKP host names and rotate\n" " --hosttable Print table of known hosts and pools\n" " --dead Mark as dead\n" " --alive Mark as alive\n" "\n" "If called without arguments list all configured keyserver URLs.\n" "If called with an URI add this as keyserver. Note that keyservers\n" "are configured on a per-session base. A default keyserver may already be\n" "present, thus the \"--clear\" option must be used to get full control.\n" "If \"--clear\" and an URI are used together the clear command is\n" "obviously executed first. A RESET command does not change the list\n" "of configured keyservers."; static gpg_error_t cmd_keyserver (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err = 0; int clear_flag, add_flag, help_flag, host_flag, resolve_flag; int dead_flag, alive_flag; uri_item_t item = NULL; /* gcc 4.4.5 is not able to detect that it is always initialized. */ clear_flag = has_option (line, "--clear"); help_flag = has_option (line, "--help"); resolve_flag = has_option (line, "--resolve"); host_flag = has_option (line, "--hosttable"); dead_flag = has_option (line, "--dead"); alive_flag = has_option (line, "--alive"); line = skip_options (line); add_flag = !!*line; if (help_flag) { err = ks_action_help (ctrl, line); goto leave; } if (resolve_flag) { err = ensure_keyserver (ctrl); if (err) { assuan_set_error (ctx, err, "Bad keyserver configuration in dirmngr.conf"); goto leave; } err = ks_action_resolve (ctrl, ctrl->server_local->keyservers); if (err) goto leave; } if (alive_flag && dead_flag) { err = set_error (GPG_ERR_ASS_PARAMETER, "no support for zombies"); goto leave; } if (dead_flag) { err = check_owner_permission (ctx, "no permission to use --dead"); if (err) goto leave; } if (alive_flag || dead_flag) { if (!*line) { err = set_error (GPG_ERR_ASS_PARAMETER, "name of host missing"); goto leave; } err = ks_hkp_mark_host (ctrl, line, alive_flag); if (err) goto leave; } if (host_flag) { err = ks_hkp_print_hosttable (ctrl); if (err) goto leave; } if (resolve_flag || host_flag || alive_flag || dead_flag) goto leave; if (add_flag) { err = make_keyserver_item (line, &item); if (err) goto leave; } if (clear_flag) release_ctrl_keyservers (ctrl); if (add_flag) { item->next = ctrl->server_local->keyservers; ctrl->server_local->keyservers = item; } if (!add_flag && !clear_flag && !help_flag) { /* List configured keyservers. However, we first add a global keyserver. */ uri_item_t u; err = ensure_keyserver (ctrl); if (err) { assuan_set_error (ctx, err, "Bad keyserver configuration in dirmngr.conf"); goto leave; } for (u=ctrl->server_local->keyservers; u; u = u->next) dirmngr_status (ctrl, "KEYSERVER", u->uri, NULL); } err = 0; leave: return leave_cmd (ctx, err); } static const char hlp_ks_search[] = "KS_SEARCH {}\n" "\n" "Search the configured OpenPGP keyservers (see command KEYSERVER)\n" "for keys matching PATTERN"; static gpg_error_t cmd_ks_search (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; strlist_t list, sl; char *p; estream_t outfp; if (has_option (line, "--quick")) ctrl->timeout = opt.connect_quick_timeout; line = skip_options (line); /* Break the line down into an strlist. Each pattern is percent-plus escaped. */ list = NULL; for (p=line; *p; line = p) { while (*p && *p != ' ') p++; if (*p) *p++ = 0; if (*line) { sl = xtrymalloc (sizeof *sl + strlen (line)); if (!sl) { err = gpg_error_from_syserror (); goto leave; } sl->flags = 0; strcpy_escaped_plus (sl->d, line); sl->next = list; list = sl; } } err = ensure_keyserver (ctrl); if (err) goto leave; /* Setup an output stream and perform the search. */ outfp = es_fopencookie (ctx, "w", data_line_cookie_functions); if (!outfp) err = set_error (GPG_ERR_ASS_GENERAL, "error setting up a data stream"); else { err = ks_action_search (ctrl, ctrl->server_local->keyservers, list, outfp); es_fclose (outfp); } leave: free_strlist (list); return leave_cmd (ctx, err); } static const char hlp_ks_get[] = - "KS_GET {}\n" + "KS_GET [--quick] [--ldap] {}\n" "\n" "Get the keys matching PATTERN from the configured OpenPGP keyservers\n" "(see command KEYSERVER). Each pattern should be a keyid, a fingerprint,\n" - "or an exact name indicated by the '=' prefix."; + "or an exact name indicated by the '=' prefix. Option --quick uses a\n" + "shorter timeout; --ldap will use only ldap servers"; static gpg_error_t cmd_ks_get (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; strlist_t list, sl; char *p; estream_t outfp; + int ldap_only; if (has_option (line, "--quick")) ctrl->timeout = opt.connect_quick_timeout; + ldap_only = has_option (line, "--ldap"); line = skip_options (line); /* Break the line into a strlist. Each pattern is by definition percent-plus escaped. However we only support keyids and fingerprints and thus the client has no need to apply the escaping. */ list = NULL; for (p=line; *p; line = p) { while (*p && *p != ' ') p++; if (*p) *p++ = 0; if (*line) { sl = xtrymalloc (sizeof *sl + strlen (line)); if (!sl) { err = gpg_error_from_syserror (); goto leave; } sl->flags = 0; strcpy_escaped_plus (sl->d, line); sl->next = list; list = sl; } } err = ensure_keyserver (ctrl); if (err) goto leave; /* Setup an output stream and perform the get. */ outfp = es_fopencookie (ctx, "w", data_line_cookie_functions); if (!outfp) err = set_error (GPG_ERR_ASS_GENERAL, "error setting up a data stream"); else { ctrl->server_local->inhibit_data_logging = 1; ctrl->server_local->inhibit_data_logging_now = 0; ctrl->server_local->inhibit_data_logging_count = 0; - err = ks_action_get (ctrl, ctrl->server_local->keyservers, list, outfp); + err = ks_action_get (ctrl, ctrl->server_local->keyservers, + list, ldap_only, outfp); es_fclose (outfp); ctrl->server_local->inhibit_data_logging = 0; } leave: free_strlist (list); return leave_cmd (ctx, err); } static const char hlp_ks_fetch[] = "KS_FETCH \n" "\n" "Get the key(s) from URL."; static gpg_error_t cmd_ks_fetch (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; estream_t outfp; if (has_option (line, "--quick")) ctrl->timeout = opt.connect_quick_timeout; line = skip_options (line); err = ensure_keyserver (ctrl); /* FIXME: Why do we needs this here? */ if (err) goto leave; /* Setup an output stream and perform the get. */ outfp = es_fopencookie (ctx, "w", data_line_cookie_functions); if (!outfp) err = set_error (GPG_ERR_ASS_GENERAL, "error setting up a data stream"); else { ctrl->server_local->inhibit_data_logging = 1; ctrl->server_local->inhibit_data_logging_now = 0; ctrl->server_local->inhibit_data_logging_count = 0; err = ks_action_fetch (ctrl, line, outfp); es_fclose (outfp); ctrl->server_local->inhibit_data_logging = 0; } leave: return leave_cmd (ctx, err); } static const char hlp_ks_put[] = "KS_PUT\n" "\n" "Send a key to the configured OpenPGP keyservers. The actual key material\n" "is then requested by Dirmngr using\n" "\n" " INQUIRE KEYBLOCK\n" "\n" "The client shall respond with a binary version of the keyblock (e.g.,\n" "the output of `gpg --export KEYID'). For LDAP\n" "keyservers Dirmngr may ask for meta information of the provided keyblock\n" "using:\n" "\n" " INQUIRE KEYBLOCK_INFO\n" "\n" "The client shall respond with a colon delimited info lines (the output\n" "of 'gpg --list-keys --with-colons KEYID').\n"; static gpg_error_t cmd_ks_put (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; unsigned char *value = NULL; size_t valuelen; unsigned char *info = NULL; size_t infolen; /* No options for now. */ line = skip_options (line); err = ensure_keyserver (ctrl); if (err) goto leave; /* Ask for the key material. */ err = assuan_inquire (ctx, "KEYBLOCK", &value, &valuelen, MAX_KEYBLOCK_LENGTH); if (err) { log_error (_("assuan_inquire failed: %s\n"), gpg_strerror (err)); goto leave; } if (!valuelen) /* No data returned; return a comprehensible error. */ { err = gpg_error (GPG_ERR_MISSING_CERT); goto leave; } /* Ask for the key meta data. */ err = assuan_inquire (ctx, "KEYBLOCK_INFO", &info, &infolen, MAX_KEYBLOCK_LENGTH); if (err) { log_error (_("assuan_inquire failed: %s\n"), gpg_strerror (err)); goto leave; } /* Send the key. */ err = ks_action_put (ctrl, ctrl->server_local->keyservers, value, valuelen, info, infolen); leave: xfree (info); xfree (value); return leave_cmd (ctx, err); } static const char hlp_loadswdb[] = "LOADSWDB [--force]\n" "\n" "Load and verify the swdb.lst from the Net."; static gpg_error_t cmd_loadswdb (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; err = dirmngr_load_swdb (ctrl, has_option (line, "--force")); return leave_cmd (ctx, err); } static const char hlp_getinfo[] = "GETINFO \n" "\n" "Multi purpose command to return certain information. \n" "Supported values of WHAT are:\n" "\n" "version - Return the version of the program.\n" "pid - Return the process id of the server.\n" "tor - Return OK if running in Tor mode\n" "dnsinfo - Return info about the DNS resolver\n" "socket_name - Return the name of the socket.\n" "session_id - Return the current session_id.\n" "workqueue - Inspect the work queue\n" "getenv NAME - Return value of envvar NAME\n"; static gpg_error_t cmd_getinfo (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; char numbuf[50]; if (!strcmp (line, "version")) { const char *s = VERSION; err = assuan_send_data (ctx, s, strlen (s)); } else if (!strcmp (line, "pid")) { snprintf (numbuf, sizeof numbuf, "%lu", (unsigned long)getpid ()); err = assuan_send_data (ctx, numbuf, strlen (numbuf)); } else if (!strcmp (line, "socket_name")) { const char *s = dirmngr_get_current_socket_name (); err = assuan_send_data (ctx, s, strlen (s)); } else if (!strcmp (line, "session_id")) { snprintf (numbuf, sizeof numbuf, "%u", ctrl->server_local->session_id); err = assuan_send_data (ctx, numbuf, strlen (numbuf)); } else if (!strcmp (line, "tor")) { int use_tor; use_tor = dirmngr_use_tor (); if (use_tor) { if (!is_tor_running (ctrl)) err = assuan_write_status (ctx, "NO_TOR", "Tor not running"); else err = 0; if (!err) assuan_set_okay_line (ctx, use_tor == 1 ? "- Tor mode is enabled" /**/ : "- Tor mode is enforced"); } else err = set_error (GPG_ERR_FALSE, "Tor mode is NOT enabled"); } else if (!strcmp (line, "dnsinfo")) { if (standard_resolver_p ()) assuan_set_okay_line (ctx, "- Forced use of System resolver (w/o Tor support)"); else { #ifdef USE_LIBDNS assuan_set_okay_line (ctx, (recursive_resolver_p () ? "- Libdns recursive resolver" : "- Libdns stub resolver")); #else assuan_set_okay_line (ctx, "- System resolver (w/o Tor support)"); #endif } err = 0; } else if (!strcmp (line, "workqueue")) { workqueue_dump_queue (ctrl); err = 0; } else if (!strncmp (line, "getenv", 6) && (line[6] == ' ' || line[6] == '\t' || !line[6])) { line += 6; while (*line == ' ' || *line == '\t') line++; if (!*line) err = gpg_error (GPG_ERR_MISSING_VALUE); else { const char *s = getenv (line); if (!s) err = set_error (GPG_ERR_NOT_FOUND, "No such envvar"); else err = assuan_send_data (ctx, s, strlen (s)); } } else err = set_error (GPG_ERR_ASS_PARAMETER, "unknown value for WHAT"); return leave_cmd (ctx, err); } static const char hlp_killdirmngr[] = "KILLDIRMNGR\n" "\n" "This command allows a user - given sufficient permissions -\n" "to kill this dirmngr process.\n"; static gpg_error_t cmd_killdirmngr (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); (void)line; ctrl->server_local->stopme = 1; assuan_set_flag (ctx, ASSUAN_FORCE_CLOSE, 1); return 0; } static const char hlp_reloaddirmngr[] = "RELOADDIRMNGR\n" "\n" "This command is an alternative to SIGHUP\n" "to reload the configuration."; static gpg_error_t cmd_reloaddirmngr (assuan_context_t ctx, char *line) { (void)ctx; (void)line; dirmngr_sighup_action (); return 0; } static const char hlp_flushcrls[] = "FLUSHCRLS\n" "\n" "Remove all cached CRLs from memory and\n" "the file system."; static gpg_error_t cmd_flushcrls (assuan_context_t ctx, char *line) { (void)line; return leave_cmd (ctx, crl_cache_flush () ? GPG_ERR_GENERAL : 0); } /* Tell the assuan library about our commands. */ static int register_commands (assuan_context_t ctx) { static struct { const char *name; assuan_handler_t handler; const char * const help; } table[] = { { "DNS_CERT", cmd_dns_cert, hlp_dns_cert }, { "WKD_GET", cmd_wkd_get, hlp_wkd_get }, { "LDAPSERVER", cmd_ldapserver, hlp_ldapserver }, { "ISVALID", cmd_isvalid, hlp_isvalid }, { "CHECKCRL", cmd_checkcrl, hlp_checkcrl }, { "CHECKOCSP", cmd_checkocsp, hlp_checkocsp }, { "LOOKUP", cmd_lookup, hlp_lookup }, { "LOADCRL", cmd_loadcrl, hlp_loadcrl }, { "LISTCRLS", cmd_listcrls, hlp_listcrls }, { "CACHECERT", cmd_cachecert, hlp_cachecert }, { "VALIDATE", cmd_validate, hlp_validate }, { "KEYSERVER", cmd_keyserver, hlp_keyserver }, { "KS_SEARCH", cmd_ks_search, hlp_ks_search }, { "KS_GET", cmd_ks_get, hlp_ks_get }, { "KS_FETCH", cmd_ks_fetch, hlp_ks_fetch }, { "KS_PUT", cmd_ks_put, hlp_ks_put }, { "GETINFO", cmd_getinfo, hlp_getinfo }, { "LOADSWDB", cmd_loadswdb, hlp_loadswdb }, { "KILLDIRMNGR",cmd_killdirmngr,hlp_killdirmngr }, { "RELOADDIRMNGR",cmd_reloaddirmngr,hlp_reloaddirmngr }, { "FLUSHCRLS", cmd_flushcrls, hlp_flushcrls }, { NULL, NULL } }; int i, j, rc; for (i=j=0; table[i].name; i++) { rc = assuan_register_command (ctx, table[i].name, table[i].handler, table[i].help); if (rc) return rc; } return 0; } /* Note that we do not reset the list of configured keyservers. */ static gpg_error_t reset_notify (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); (void)line; #if USE_LDAP ldapserver_list_free (ctrl->server_local->ldapservers); #endif /*USE_LDAP*/ ctrl->server_local->ldapservers = NULL; return 0; } /* This function is called by our assuan log handler to test whether a * log message shall really be printed. The function must return * false to inhibit the logging of MSG. CAT gives the requested log * category. MSG might be NULL. */ int dirmngr_assuan_log_monitor (assuan_context_t ctx, unsigned int cat, const char *msg) { ctrl_t ctrl = assuan_get_pointer (ctx); (void)cat; (void)msg; if (!ctrl || !ctrl->server_local) return 1; /* Can't decide - allow logging. */ if (!ctrl->server_local->inhibit_data_logging) return 1; /* Not requested - allow logging. */ /* Disallow logging if *_now is true. */ return !ctrl->server_local->inhibit_data_logging_now; } /* Startup the server and run the main command loop. With FD = -1, * use stdin/stdout. SESSION_ID is either 0 or a unique number * identifying a session. */ void start_command_handler (assuan_fd_t fd, unsigned int session_id) { static const char hello[] = "Dirmngr " VERSION " at your service"; static char *hello_line; int rc; assuan_context_t ctx; ctrl_t ctrl; ctrl = xtrycalloc (1, sizeof *ctrl); if (ctrl) ctrl->server_local = xtrycalloc (1, sizeof *ctrl->server_local); if (!ctrl || !ctrl->server_local) { log_error (_("can't allocate control structure: %s\n"), strerror (errno)); xfree (ctrl); return; } dirmngr_init_default_ctrl (ctrl); rc = assuan_new (&ctx); if (rc) { log_error (_("failed to allocate assuan context: %s\n"), gpg_strerror (rc)); dirmngr_exit (2); } if (fd == ASSUAN_INVALID_FD) { assuan_fd_t filedes[2]; filedes[0] = assuan_fdopen (0); filedes[1] = assuan_fdopen (1); rc = assuan_init_pipe_server (ctx, filedes); } else { rc = assuan_init_socket_server (ctx, fd, ASSUAN_SOCKET_SERVER_ACCEPTED); } if (rc) { assuan_release (ctx); log_error (_("failed to initialize the server: %s\n"), gpg_strerror(rc)); dirmngr_exit (2); } rc = register_commands (ctx); if (rc) { log_error (_("failed to the register commands with Assuan: %s\n"), gpg_strerror(rc)); dirmngr_exit (2); } if (!hello_line) { hello_line = xtryasprintf ("Home: %s\n" "Config: %s\n" "%s", gnupg_homedir (), opt.config_filename? opt.config_filename : "[none]", hello); } ctrl->server_local->assuan_ctx = ctx; assuan_set_pointer (ctx, ctrl); assuan_set_hello_line (ctx, hello_line); assuan_register_option_handler (ctx, option_handler); assuan_register_reset_notify (ctx, reset_notify); ctrl->server_local->session_id = session_id; for (;;) { rc = assuan_accept (ctx); if (rc == -1) break; if (rc) { log_info (_("Assuan accept problem: %s\n"), gpg_strerror (rc)); break; } #ifndef HAVE_W32_SYSTEM if (opt.verbose) { assuan_peercred_t peercred; if (!assuan_get_peercred (ctx, &peercred)) log_info ("connection from process %ld (%ld:%ld)\n", (long)peercred->pid, (long)peercred->uid, (long)peercred->gid); } #endif rc = assuan_process (ctx); if (rc) { log_info (_("Assuan processing failed: %s\n"), gpg_strerror (rc)); continue; } } #if USE_LDAP ldap_wrapper_connection_cleanup (ctrl); ldapserver_list_free (ctrl->server_local->ldapservers); #endif /*USE_LDAP*/ ctrl->server_local->ldapservers = NULL; release_ctrl_keyservers (ctrl); ctrl->server_local->assuan_ctx = NULL; assuan_release (ctx); if (ctrl->server_local->stopme) dirmngr_exit (0); if (ctrl->refcount) log_error ("oops: connection control structure still referenced (%d)\n", ctrl->refcount); else { release_ctrl_ocsp_certs (ctrl); xfree (ctrl->server_local); dirmngr_deinit_default_ctrl (ctrl); xfree (ctrl); } } /* Send a status line back to the client. KEYWORD is the status keyword, the optional string arguments are blank separated added to the line, the last argument must be a NULL. */ gpg_error_t dirmngr_status (ctrl_t ctrl, const char *keyword, ...) { gpg_error_t err = 0; va_list arg_ptr; assuan_context_t ctx; va_start (arg_ptr, keyword); if (ctrl->server_local && (ctx = ctrl->server_local->assuan_ctx)) { err = vprint_assuan_status_strings (ctx, keyword, arg_ptr); } va_end (arg_ptr); return err; } /* Print a help status line. The function splits text at LFs. */ gpg_error_t dirmngr_status_help (ctrl_t ctrl, const char *text) { gpg_error_t err = 0; assuan_context_t ctx; if (ctrl->server_local && (ctx = ctrl->server_local->assuan_ctx)) { char buf[950], *p; size_t n; do { p = buf; n = 0; for ( ; *text && *text != '\n' && n < DIM (buf)-2; n++) *p++ = *text++; if (*text == '\n') text++; *p = 0; err = assuan_write_status (ctx, "#", buf); } while (!err && *text); } return err; } /* Print a help status line using a printf like format. The function * splits text at LFs. */ gpg_error_t dirmngr_status_helpf (ctrl_t ctrl, const char *format, ...) { va_list arg_ptr; gpg_error_t err; char *buf; va_start (arg_ptr, format); buf = es_vbsprintf (format, arg_ptr); err = buf? 0 : gpg_error_from_syserror (); va_end (arg_ptr); if (!err) err = dirmngr_status_help (ctrl, buf); es_free (buf); return err; } /* This function is similar to print_assuan_status but takes a CTRL * arg instead of an assuan context as first argument. */ gpg_error_t dirmngr_status_printf (ctrl_t ctrl, const char *keyword, const char *format, ...) { gpg_error_t err; va_list arg_ptr; assuan_context_t ctx; if (!ctrl || !ctrl->server_local || !(ctx = ctrl->server_local->assuan_ctx)) return 0; va_start (arg_ptr, format); err = vprint_assuan_status (ctx, keyword, format, arg_ptr); va_end (arg_ptr); return err; } /* Send a tick progress indicator back. Fixme: This is only done for the currently active channel. */ gpg_error_t dirmngr_tick (ctrl_t ctrl) { static time_t next_tick = 0; gpg_error_t err = 0; time_t now = time (NULL); if (!next_tick) { next_tick = now + 1; } else if ( now > next_tick ) { if (ctrl) { err = dirmngr_status (ctrl, "PROGRESS", "tick", "? 0 0", NULL); if (err) { /* Take this as in indication for a cancel request. */ err = gpg_error (GPG_ERR_CANCELED); } now = time (NULL); } next_tick = now + 1; } return err; } diff --git a/g10/call-dirmngr.c b/g10/call-dirmngr.c index 21edab639..434b46795 100644 --- a/g10/call-dirmngr.c +++ b/g10/call-dirmngr.c @@ -1,1324 +1,1333 @@ /* call-dirmngr.c - GPG operations to the Dirmngr. * Copyright (C) 2011 Free Software Foundation, Inc. * Copyright (C) 2015 g10 Code GmbH * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include #ifdef HAVE_LOCALE_H # include #endif #include "gpg.h" #include #include "../common/util.h" #include "../common/membuf.h" #include "options.h" #include "../common/i18n.h" #include "../common/asshelp.h" #include "../common/keyserver.h" #include "../common/status.h" +#include "keyserver-internal.h" #include "call-dirmngr.h" /* Keys retrieved from the web key directory should be small. There * is only one UID and we can expect that the number of subkeys is * reasonable. So we set a generous limit of 256 KiB. */ #define MAX_WKD_RESULT_LENGTH (256 * 1024) /* Parameter structure used to gather status info. Note that it is * also used for WKD requests. */ struct ks_status_parm_s { const char *keyword; /* Look for this keyword or NULL for "SOURCE". */ char *source; }; /* Parameter structure used with the KS_SEARCH command. */ struct ks_search_parm_s { gpg_error_t lasterr; /* Last error code. */ membuf_t saveddata; /* Buffer to build complete lines. */ char *helpbuf; /* NULL or malloced buffer. */ size_t helpbufsize; /* Allocated size of HELPBUF. */ gpg_error_t (*data_cb)(void*, int, char*); /* Callback. */ void *data_cb_value; /* First argument for DATA_CB. */ struct ks_status_parm_s *stparm; /* Link to the status parameter. */ }; /* Parameter structure used with the KS_GET command. */ struct ks_get_parm_s { estream_t memfp; }; /* Parameter structure used with the KS_PUT command. */ struct ks_put_parm_s { assuan_context_t ctx; kbnode_t keyblock; /* The optional keyblock. */ const void *data; /* The key in OpenPGP binary format. */ size_t datalen; /* The length of DATA. */ }; /* Parameter structure used with the DNS_CERT command. */ struct dns_cert_parm_s { estream_t memfp; unsigned char *fpr; size_t fprlen; char *url; }; /* Data used to associate an session with dirmngr contexts. We can't use a simple one to one mapping because we sometimes need two connections to the dirmngr; for example while doing a listing and being in a data callback we may want to retrieve a key. The local dirmngr data takes care of this. At the end of the session the function dirmngr_deinit_session_data is called by gpg.c to cleanup these resources. Note that gpg.h defines a typedef dirmngr_local_t for this structure. */ struct dirmngr_local_s { /* Link to other contexts which are used simultaneously. */ struct dirmngr_local_s *next; /* The active Assuan context. */ assuan_context_t ctx; /* Flag set when the keyserver names have been send. */ int set_keyservers_done; /* Flag set to true while an operation is running on CTX. */ int is_active; }; /* Deinitialize all session data of dirmngr pertaining to CTRL. */ void gpg_dirmngr_deinit_session_data (ctrl_t ctrl) { dirmngr_local_t dml; while ((dml = ctrl->dirmngr_local)) { ctrl->dirmngr_local = dml->next; if (dml->is_active) log_error ("oops: trying to cleanup an active dirmngr context\n"); else assuan_release (dml->ctx); xfree (dml); } } /* 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 (assuan_context_t ctx, const char *servername) { return warn_server_version_mismatch (ctx, servername, 0, write_status_strings2, NULL, !opt.quiet); } /* Try to connect to the Dirmngr via a socket or spawn it if possible. Handle the server's initial greeting and set global options. */ static gpg_error_t create_context (ctrl_t ctrl, assuan_context_t *r_ctx) { gpg_error_t err; assuan_context_t ctx; *r_ctx = NULL; if (opt.disable_dirmngr) return gpg_error (GPG_ERR_NO_DIRMNGR); err = start_new_dirmngr (&ctx, GPG_ERR_SOURCE_DEFAULT, opt.dirmngr_program, opt.autostart, opt.verbose, DBG_IPC, NULL /*gpg_status2*/, ctrl); if (!opt.autostart && gpg_err_code (err) == GPG_ERR_NO_DIRMNGR) { static int shown; if (!shown) { shown = 1; log_info (_("no dirmngr running in this session\n")); } } else if (!err && !(err = warn_version_mismatch (ctx, DIRMNGR_NAME))) { char *line; /* Tell the dirmngr that we want to collect audit event. */ /* err = assuan_transact (agent_ctx, "OPTION audit-events=1", */ /* NULL, NULL, NULL, NULL, NULL, NULL); */ if (opt.keyserver_options.http_proxy) { line = xtryasprintf ("OPTION http-proxy=%s", opt.keyserver_options.http_proxy); if (!line) err = gpg_error_from_syserror (); else { err = assuan_transact (ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); xfree (line); } } if (err) ; else if ((opt.keyserver_options.options & KEYSERVER_HONOR_KEYSERVER_URL)) { /* Tell the dirmngr that this possibly privacy invading option is in use. If Dirmngr is running in Tor mode, it will return an error. */ err = assuan_transact (ctx, "OPTION honor-keyserver-url-used", NULL, NULL, NULL, NULL, NULL, NULL); if (gpg_err_code (err) == GPG_ERR_FORBIDDEN) log_error (_("keyserver option \"honor-keyserver-url\"" " may not be used in Tor mode\n")); else if (gpg_err_code (err) == GPG_ERR_UNKNOWN_OPTION) err = 0; /* Old dirmngr versions do not support this option. */ } } if (err) assuan_release (ctx); else { /* audit_log_ok (ctrl->audit, AUDIT_DIRMNGR_READY, err); */ *r_ctx = ctx; } return err; } /* Get a context for accessing dirmngr. If no context is available a new one is created and - if required - dirmngr started. On success an assuan context is stored at R_CTX. This context may only be released by means of close_context. Note that NULL is stored at R_CTX on error. */ static gpg_error_t open_context (ctrl_t ctrl, assuan_context_t *r_ctx) { gpg_error_t err; dirmngr_local_t dml; *r_ctx = NULL; for (;;) { for (dml = ctrl->dirmngr_local; dml && dml->is_active; dml = dml->next) ; if (dml) { /* Found an inactive local session - return that. */ log_assert (!dml->is_active); /* But first do the per session init if not yet done. */ if (!dml->set_keyservers_done) { keyserver_spec_t ksi; /* Set all configured keyservers. We clear existing keyservers so that any keyserver configured in GPG overrides keyservers possibly still configured in Dirmngr for the session (Note that the keyserver list of a session in Dirmngr survives a RESET. */ for (ksi = opt.keyserver; ksi; ksi = ksi->next) { char *line; line = xtryasprintf ("KEYSERVER%s %s", ksi == opt.keyserver? " --clear":"", ksi->uri); if (!line) err = gpg_error_from_syserror (); else { err = assuan_transact (dml->ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); xfree (line); } if (err) return err; } dml->set_keyservers_done = 1; } dml->is_active = 1; *r_ctx = dml->ctx; return 0; } dml = xtrycalloc (1, sizeof *dml); if (!dml) return gpg_error_from_syserror (); err = create_context (ctrl, &dml->ctx); if (err) { xfree (dml); return err; } /* To be on the nPth thread safe site we need to add it to a list; this is far easier than to have a lock for this function. It should not happen anyway but the code is free because we need it for the is_active check above. */ dml->next = ctrl->dirmngr_local; ctrl->dirmngr_local = dml; } } /* Close the assuan context CTX or return it to a pool of unused contexts. If CTX is NULL, the function does nothing. */ static void close_context (ctrl_t ctrl, assuan_context_t ctx) { dirmngr_local_t dml; if (!ctx) return; for (dml = ctrl->dirmngr_local; dml; dml = dml->next) { if (dml->ctx == ctx) { if (!dml->is_active) log_fatal ("closing inactive dirmngr context %p\n", ctx); dml->is_active = 0; return; } } log_fatal ("closing unknown dirmngr ctx %p\n", ctx); } /* Clear the set_keyservers_done flag on context CTX. */ static void clear_context_flags (ctrl_t ctrl, assuan_context_t ctx) { dirmngr_local_t dml; if (!ctx) return; for (dml = ctrl->dirmngr_local; dml; dml = dml->next) { if (dml->ctx == ctx) { if (!dml->is_active) log_fatal ("clear_context_flags on inactive dirmngr ctx %p\n", ctx); dml->set_keyservers_done = 0; return; } } log_fatal ("clear_context_flags on unknown dirmngr ctx %p\n", ctx); } /* Status callback for ks_list, ks_get, ks_search, and wkd_get */ static gpg_error_t ks_status_cb (void *opaque, const char *line) { struct ks_status_parm_s *parm = opaque; gpg_error_t err = 0; const char *s, *s2; const char *warn = NULL; int is_note = 0; if ((s = has_leading_keyword (line, parm->keyword? parm->keyword : "SOURCE"))) { /* Note that the arg for "S SOURCE" is the URL of a keyserver. */ if (!parm->source) { parm->source = xtrystrdup (s); if (!parm->source) err = gpg_error_from_syserror (); } } else if ((s = has_leading_keyword (line, "WARNING")) || (is_note = !!(s = has_leading_keyword (line, "NOTE")))) { if ((s2 = has_leading_keyword (s, "wkd_cached_result"))) { if (opt.verbose) warn = _("WKD uses a cached result"); } else if ((s2 = has_leading_keyword (s, "tor_not_running"))) warn = _("Tor is not running"); else if ((s2 = has_leading_keyword (s, "tor_config_problem"))) warn = _("Tor is not properly configured"); else if ((s2 = has_leading_keyword (s, "dns_config_problem"))) warn = _("DNS is not properly configured"); else if ((s2 = has_leading_keyword (s, "http_redirect"))) warn = _("unacceptable HTTP redirect from server"); else if ((s2 = has_leading_keyword (s, "http_redirect_cleanup"))) warn = _("unacceptable HTTP redirect from server was cleaned up"); else if ((s2 = has_leading_keyword (s, "tls_cert_error"))) warn = _("server uses an invalid certificate"); else warn = NULL; if (warn) { if (is_note) log_info (_("Note: %s\n"), warn); else log_info (_("WARNING: %s\n"), warn); if (s2) { while (*s2 && !spacep (s2)) s2++; while (*s2 && spacep (s2)) s2++; if (*s2) print_further_info ("%s", s2); } } } return err; } /* Run the "KEYSERVER" command to return the name of the used keyserver at R_KEYSERVER. */ gpg_error_t gpg_dirmngr_ks_list (ctrl_t ctrl, char **r_keyserver) { gpg_error_t err; assuan_context_t ctx; struct ks_status_parm_s stparm; memset (&stparm, 0, sizeof stparm); stparm.keyword = "KEYSERVER"; if (r_keyserver) *r_keyserver = NULL; err = open_context (ctrl, &ctx); if (err) return err; err = assuan_transact (ctx, "KEYSERVER", NULL, NULL, NULL, NULL, ks_status_cb, &stparm); if (err) goto leave; if (!stparm.source) { err = gpg_error (GPG_ERR_NO_KEYSERVER); goto leave; } if (r_keyserver) *r_keyserver = stparm.source; else xfree (stparm.source); stparm.source = NULL; leave: xfree (stparm.source); close_context (ctrl, ctx); return err; } /* Data callback for the KS_SEARCH command. */ static gpg_error_t ks_search_data_cb (void *opaque, const void *data, size_t datalen) { gpg_error_t err = 0; struct ks_search_parm_s *parm = opaque; const char *line, *s; size_t rawlen, linelen; char fixedbuf[256]; if (parm->lasterr) return 0; if (parm->stparm->source) { err = parm->data_cb (parm->data_cb_value, 1, parm->stparm->source); if (err) { parm->lasterr = err; return err; } /* Clear it so that we won't get back here unless the server accidentally sends a second source status line. Note that will not see all accidentally sent source lines because it depends on whether data lines have been send in between. */ xfree (parm->stparm->source); parm->stparm->source = NULL; } if (!data) return 0; /* Ignore END commands. */ put_membuf (&parm->saveddata, data, datalen); again: line = peek_membuf (&parm->saveddata, &rawlen); if (!line) { parm->lasterr = gpg_error_from_syserror (); return parm->lasterr; /* Tell the server about our problem. */ } if ((s = memchr (line, '\n', rawlen))) { linelen = s - line; /* That is the length excluding the LF. */ if (linelen + 1 < sizeof fixedbuf) { /* We can use the static buffer. */ memcpy (fixedbuf, line, linelen); fixedbuf[linelen] = 0; if (linelen && fixedbuf[linelen-1] == '\r') fixedbuf[linelen-1] = 0; err = parm->data_cb (parm->data_cb_value, 0, fixedbuf); } else { if (linelen + 1 >= parm->helpbufsize) { xfree (parm->helpbuf); parm->helpbufsize = linelen + 1 + 1024; parm->helpbuf = xtrymalloc (parm->helpbufsize); if (!parm->helpbuf) { parm->lasterr = gpg_error_from_syserror (); return parm->lasterr; } } memcpy (parm->helpbuf, line, linelen); parm->helpbuf[linelen] = 0; if (linelen && parm->helpbuf[linelen-1] == '\r') parm->helpbuf[linelen-1] = 0; err = parm->data_cb (parm->data_cb_value, 0, parm->helpbuf); } if (err) parm->lasterr = err; else { clear_membuf (&parm->saveddata, linelen+1); goto again; /* There might be another complete line. */ } } return err; } /* Run the KS_SEARCH command using the search string SEARCHSTR. All data lines are passed to the CB function. That function is called with CB_VALUE as its first argument, a 0 as second argument, and the decoded data line as third argument. The callback function may modify the data line and it is guaranteed that this data line is a complete line with a terminating 0 character but without the linefeed. NULL is passed to the callback to indicate EOF. */ gpg_error_t gpg_dirmngr_ks_search (ctrl_t ctrl, const char *searchstr, gpg_error_t (*cb)(void*, int, char *), void *cb_value) { gpg_error_t err; assuan_context_t ctx; struct ks_status_parm_s stparm; struct ks_search_parm_s parm; char line[ASSUAN_LINELENGTH]; err = open_context (ctrl, &ctx); if (err) return err; { char *escsearchstr = percent_plus_escape (searchstr); if (!escsearchstr) { err = gpg_error_from_syserror (); close_context (ctrl, ctx); return err; } snprintf (line, sizeof line, "KS_SEARCH -- %s", escsearchstr); xfree (escsearchstr); } memset (&stparm, 0, sizeof stparm); memset (&parm, 0, sizeof parm); init_membuf (&parm.saveddata, 1024); parm.data_cb = cb; parm.data_cb_value = cb_value; parm.stparm = &stparm; err = assuan_transact (ctx, line, ks_search_data_cb, &parm, NULL, NULL, ks_status_cb, &stparm); if (!err) err = cb (cb_value, 0, NULL); /* Send EOF. */ else if (parm.stparm->source) { /* Error but we received a SOURCE status. Tell via callback but * ignore errors. */ parm.data_cb (parm.data_cb_value, 1, parm.stparm->source); } xfree (get_membuf (&parm.saveddata, NULL)); xfree (parm.helpbuf); xfree (stparm.source); close_context (ctrl, ctx); return err; } /* Data callback for the KS_GET and KS_FETCH commands. */ static gpg_error_t ks_get_data_cb (void *opaque, const void *data, size_t datalen) { gpg_error_t err = 0; struct ks_get_parm_s *parm = opaque; size_t nwritten; if (!data) return 0; /* Ignore END commands. */ if (es_write (parm->memfp, data, datalen, &nwritten)) err = gpg_error_from_syserror (); return err; } /* Run the KS_GET command using the patterns in the array PATTERN. On success an estream object is returned to retrieve the keys. On error an error code is returned and NULL stored at R_FP. The pattern may only use search specification which a keyserver can use to retrieve keys. Because we know the format of the pattern we don't need to escape the patterns before sending them to the server. - If QUICK is set the dirmngr is advised to use a shorter timeout. + Bit values for FLAGS are: + - KEYSERVER_IMPORT_FLAG_QUICK :: dirmngr shall use a shorter timeout. + - KEYSERVER_IMPORT_FLAG_LDAP :: dirmngr shall only use LDAP or NTDS. If R_SOURCE is not NULL the source of the data is stored as a malloced string there. If a source is not known NULL is stored. Note that this may even be returned after an error. If there are too many patterns the function returns an error. That could be fixed by issuing several search commands or by implementing a different interface. However with long keyids we are able to ask for (1000-10-1)/(2+8+1) = 90 keys at once. */ gpg_error_t gpg_dirmngr_ks_get (ctrl_t ctrl, char **pattern, - keyserver_spec_t override_keyserver, int quick, + keyserver_spec_t override_keyserver, + unsigned int flags, estream_t *r_fp, char **r_source) { gpg_error_t err; assuan_context_t ctx; struct ks_status_parm_s stparm; struct ks_get_parm_s parm; char *line = NULL; size_t linelen; membuf_t mb; int idx; memset (&stparm, 0, sizeof stparm); memset (&parm, 0, sizeof parm); *r_fp = NULL; if (r_source) *r_source = NULL; err = open_context (ctrl, &ctx); if (err) return err; /* If we have an override keyserver we first indicate that the next user of the context needs to again setup the global keyservers and them we send the override keyserver. */ if (override_keyserver) { clear_context_flags (ctrl, ctx); line = xtryasprintf ("KEYSERVER --clear %s", override_keyserver->uri); if (!line) { err = gpg_error_from_syserror (); goto leave; } err = assuan_transact (ctx, line, NULL, NULL, NULL, NULL, NULL, NULL); if (err) goto leave; xfree (line); line = NULL; } /* Lump all patterns into one string. */ init_membuf (&mb, 1024); - put_membuf_str (&mb, quick? "KS_GET --quick --" : "KS_GET --"); + put_membuf_str (&mb, "KS_GET"); + if ((flags & KEYSERVER_IMPORT_FLAG_QUICK)) + put_membuf_str (&mb, " --quick"); + if ((flags & KEYSERVER_IMPORT_FLAG_LDAP)) + put_membuf_str (&mb, " --ldap"); + put_membuf_str (&mb, " --"); for (idx=0; pattern[idx]; idx++) { put_membuf (&mb, " ", 1); /* Append Delimiter. */ put_membuf_str (&mb, pattern[idx]); } put_membuf (&mb, "", 1); /* Append Nul. */ line = get_membuf (&mb, &linelen); if (!line) { err = gpg_error_from_syserror (); goto leave; } if (linelen + 2 >= ASSUAN_LINELENGTH) { err = gpg_error (GPG_ERR_TOO_MANY); goto leave; } parm.memfp = es_fopenmem (0, "rwb"); if (!parm.memfp) { err = gpg_error_from_syserror (); goto leave; } err = assuan_transact (ctx, line, ks_get_data_cb, &parm, NULL, NULL, ks_status_cb, &stparm); if (err) goto leave; es_rewind (parm.memfp); *r_fp = parm.memfp; parm.memfp = NULL; leave: if (r_source && stparm.source) { *r_source = stparm.source; stparm.source = NULL; } es_fclose (parm.memfp); xfree (stparm.source); xfree (line); close_context (ctrl, ctx); return err; } /* Run the KS_FETCH and pass URL as argument. On success an estream object is returned to retrieve the keys. On error an error code is returned and NULL stored at R_FP. The url is expected to point to a small set of keys; in many cases only to one key. However, schemes like finger may return several keys. Note that the configured keyservers are ignored by the KS_FETCH command. */ gpg_error_t gpg_dirmngr_ks_fetch (ctrl_t ctrl, const char *url, estream_t *r_fp) { gpg_error_t err; assuan_context_t ctx; struct ks_get_parm_s parm; char *line = NULL; memset (&parm, 0, sizeof parm); *r_fp = NULL; err = open_context (ctrl, &ctx); if (err) return err; line = strconcat ("KS_FETCH -- ", url, NULL); if (!line) { err = gpg_error_from_syserror (); goto leave; } if (strlen (line) + 2 >= ASSUAN_LINELENGTH) { err = gpg_error (GPG_ERR_TOO_LARGE); goto leave; } parm.memfp = es_fopenmem (0, "rwb"); if (!parm.memfp) { err = gpg_error_from_syserror (); goto leave; } err = assuan_transact (ctx, line, ks_get_data_cb, &parm, NULL, NULL, NULL, NULL); if (err) goto leave; es_rewind (parm.memfp); *r_fp = parm.memfp; parm.memfp = NULL; leave: es_fclose (parm.memfp); xfree (line); close_context (ctrl, ctx); return err; } static void record_output (estream_t output, pkttype_t type, const char *validity, /* The public key length or -1. */ int pub_key_length, /* The public key algo or -1. */ int pub_key_algo, /* 2 ulongs or NULL. */ const u32 *keyid, /* The creation / expiration date or 0. */ u32 creation_date, u32 expiration_date, const char *userid) { const char *type_str = NULL; char *pub_key_length_str = NULL; char *pub_key_algo_str = NULL; char *keyid_str = NULL; char *creation_date_str = NULL; char *expiration_date_str = NULL; char *userid_escaped = NULL; switch (type) { case PKT_PUBLIC_KEY: type_str = "pub"; break; case PKT_PUBLIC_SUBKEY: type_str = "sub"; break; case PKT_USER_ID: type_str = "uid"; break; case PKT_SIGNATURE: type_str = "sig"; break; default: log_assert (! "Unhandled type."); } if (pub_key_length > 0) pub_key_length_str = xasprintf ("%d", pub_key_length); if (pub_key_algo != -1) pub_key_algo_str = xasprintf ("%d", pub_key_algo); if (keyid) keyid_str = xasprintf ("%08lX%08lX", (ulong) keyid[0], (ulong) keyid[1]); if (creation_date) creation_date_str = xstrdup (colon_strtime (creation_date)); if (expiration_date) expiration_date_str = xstrdup (colon_strtime (expiration_date)); /* Quote ':', '%', and any 8-bit characters. */ if (userid) { int r; int w = 0; int len = strlen (userid); /* A 100k character limit on the uid should be way more than enough. */ if (len > 100 * 1024) len = 100 * 1024; /* The minimum amount of space that we need. */ userid_escaped = xmalloc (len * 3 + 1); for (r = 0; r < len; r++) { if (userid[r] == ':' || userid[r]== '%' || (userid[r] & 0x80)) { sprintf (&userid_escaped[w], "%%%02X", (byte) userid[r]); w += 3; } else userid_escaped[w ++] = userid[r]; } userid_escaped[w] = '\0'; } es_fprintf (output, "%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s\n", type_str, validity ?: "", pub_key_length_str ?: "", pub_key_algo_str ?: "", keyid_str ?: "", creation_date_str ?: "", expiration_date_str ?: "", "" /* Certificate S/N */, "" /* Ownertrust. */, userid_escaped ?: "", "" /* Signature class. */, "" /* Key capabilities. */, "" /* Issuer certificate fingerprint. */, "" /* Flag field. */, "" /* S/N of a token. */, "" /* Hash algo. */, "" /* Curve name. */); xfree (userid_escaped); xfree (expiration_date_str); xfree (creation_date_str); xfree (keyid_str); xfree (pub_key_algo_str); xfree (pub_key_length_str); } /* Handle the KS_PUT inquiries. */ static gpg_error_t ks_put_inq_cb (void *opaque, const char *line) { struct ks_put_parm_s *parm = opaque; gpg_error_t err = 0; if (has_leading_keyword (line, "KEYBLOCK")) { if (parm->data) err = assuan_send_data (parm->ctx, parm->data, parm->datalen); } else if (has_leading_keyword (line, "KEYBLOCK_INFO")) { kbnode_t node; estream_t fp; char hexfpr[2*MAX_FINGERPRINT_LEN+1]; /* Parse the keyblock and send info lines back to the server. */ fp = es_fopenmem (0, "rw,samethread"); if (!fp) err = gpg_error_from_syserror (); /* Note: the output format for the INFO block follows the colon format as described in doc/DETAILS. We don't actually reuse the functionality from g10/keylist.c to produce the output, because we don't need all of it and some of it is quite expensive to generate. The fields are (the starred fields are the ones we need): * Field 1 - Type of record * Field 2 - Validity * Field 3 - Key length * Field 4 - Public key algorithm * Field 5 - KeyID * Field 6 - Creation date * Field 7 - Expiration date Field 8 - Certificate S/N, UID hash, trust signature info Field 9 - Ownertrust * Field 10 - User-ID Field 11 - Signature class Field 12 - Key capabilities Field 13 - Issuer certificate fingerprint or other info Field 14 - Flag field Field 15 - S/N of a token Field 16 - Hash algorithm Field 17 - Curve name */ for (node = parm->keyblock; !err && node; node=node->next) { switch (node->pkt->pkttype) { case PKT_PUBLIC_KEY: case PKT_PUBLIC_SUBKEY: { PKT_public_key *pk = node->pkt->pkt.public_key; char validity[3]; int i; i = 0; if (pk->flags.revoked) validity[i ++] = 'r'; if (pk->has_expired) validity[i ++] = 'e'; validity[i] = '\0'; keyid_from_pk (pk, NULL); record_output (fp, node->pkt->pkttype, validity, nbits_from_pk (pk), pk->pubkey_algo, pk->keyid, pk->timestamp, pk->expiredate, NULL); es_fprintf (fp, "fpr:::::::::%s:\n", hexfingerprint (pk, hexfpr, sizeof hexfpr)); } break; case PKT_USER_ID: { PKT_user_id *uid = node->pkt->pkt.user_id; if (!uid->attrib_data) { char validity[3]; int i; i = 0; if (uid->flags.revoked) validity[i ++] = 'r'; if (uid->flags.expired) validity[i ++] = 'e'; validity[i] = '\0'; record_output (fp, node->pkt->pkttype, validity, -1, -1, NULL, uid->created, uid->expiredate, uid->name); } } break; default: continue; } /* Given that the last operation was an es_fprintf we should get the correct ERRNO if ferror indicates an error. */ if (es_ferror (fp)) err = gpg_error_from_syserror (); } /* Without an error and if we have an keyblock at all, send the data back. */ if (!err && parm->keyblock) { int rc; char buffer[512]; size_t nread; es_rewind (fp); while (!(rc=es_read (fp, buffer, sizeof buffer, &nread)) && nread) { err = assuan_send_data (parm->ctx, buffer, nread); if (err) break; } if (!err && rc) err = gpg_error_from_syserror (); } es_fclose (fp); } else return gpg_error (GPG_ERR_ASS_UNKNOWN_INQUIRE); return err; } /* Send a key to the configured server. {DATA,DATLEN} contains the key in OpenPGP binary transport format. If KEYBLOCK is not NULL it has the internal representation of that key; this is for example used to convey meta data to LDAP keyservers. */ gpg_error_t gpg_dirmngr_ks_put (ctrl_t ctrl, void *data, size_t datalen, kbnode_t keyblock) { gpg_error_t err; assuan_context_t ctx; struct ks_put_parm_s parm; memset (&parm, 0, sizeof parm); /* We are going to parse the keyblock, thus we better make sure the all information is readily available. */ if (keyblock) merge_keys_and_selfsig (ctrl, keyblock); err = open_context (ctrl, &ctx); if (err) return err; parm.ctx = ctx; parm.keyblock = keyblock; parm.data = data; parm.datalen = datalen; err = assuan_transact (ctx, "KS_PUT", NULL, NULL, ks_put_inq_cb, &parm, NULL, NULL); close_context (ctrl, ctx); return err; } /* Data callback for the DNS_CERT and WKD_GET commands. */ static gpg_error_t dns_cert_data_cb (void *opaque, const void *data, size_t datalen) { struct dns_cert_parm_s *parm = opaque; gpg_error_t err = 0; size_t nwritten; if (!data) return 0; /* Ignore END commands. */ if (!parm->memfp) return 0; /* Data is not required. */ if (es_write (parm->memfp, data, datalen, &nwritten)) err = gpg_error_from_syserror (); return err; } /* Status callback for the DNS_CERT command. */ static gpg_error_t dns_cert_status_cb (void *opaque, const char *line) { struct dns_cert_parm_s *parm = opaque; gpg_error_t err = 0; const char *s; size_t nbytes; if ((s = has_leading_keyword (line, "FPR"))) { char *buf; if (!(buf = xtrystrdup (s))) err = gpg_error_from_syserror (); else if (parm->fpr) err = gpg_error (GPG_ERR_DUP_KEY); else if (!hex2str (buf, buf, strlen (buf)+1, &nbytes)) err = gpg_error_from_syserror (); else if (nbytes < 20) err = gpg_error (GPG_ERR_TOO_SHORT); else { parm->fpr = xtrymalloc (nbytes); if (!parm->fpr) err = gpg_error_from_syserror (); else memcpy (parm->fpr, buf, (parm->fprlen = nbytes)); } xfree (buf); } else if ((s = has_leading_keyword (line, "URL")) && *s) { if (parm->url) err = gpg_error (GPG_ERR_DUP_KEY); else if (!(parm->url = xtrystrdup (s))) err = gpg_error_from_syserror (); } return err; } /* Ask the dirmngr for a DNS CERT record. Depending on the found subtypes different return values are set: - For a PGP subtype a new estream with that key will be returned at R_KEY and the other return parameters are set to NULL/0. - For an IPGP subtype the fingerprint is stored as a malloced block at (R_FPR,R_FPRLEN). If an URL is available it is stored as a malloced string at R_URL; NULL is stored if there is no URL. If CERTTYPE is DNS_CERTTYPE_ANY this function returns the first CERT record found with a supported type; it is expected that only one CERT record is used. If CERTTYPE is one of the supported certtypes, only records with this certtype are considered and the first one found is returned. All R_* args are optional. If CERTTYPE is NULL the DANE method is used to fetch the key. */ gpg_error_t gpg_dirmngr_dns_cert (ctrl_t ctrl, const char *name, const char *certtype, estream_t *r_key, unsigned char **r_fpr, size_t *r_fprlen, char **r_url) { gpg_error_t err; assuan_context_t ctx; struct dns_cert_parm_s parm; char *line = NULL; memset (&parm, 0, sizeof parm); if (r_key) *r_key = NULL; if (r_fpr) *r_fpr = NULL; if (r_fprlen) *r_fprlen = 0; if (r_url) *r_url = NULL; err = open_context (ctrl, &ctx); if (err) return err; line = es_bsprintf ("DNS_CERT %s %s", certtype? certtype : "--dane", name); if (!line) { err = gpg_error_from_syserror (); goto leave; } if (strlen (line) + 2 >= ASSUAN_LINELENGTH) { err = gpg_error (GPG_ERR_TOO_LARGE); goto leave; } parm.memfp = es_fopenmem (0, "rwb"); if (!parm.memfp) { err = gpg_error_from_syserror (); goto leave; } err = assuan_transact (ctx, line, dns_cert_data_cb, &parm, NULL, NULL, dns_cert_status_cb, &parm); if (err) goto leave; if (r_key) { es_rewind (parm.memfp); *r_key = parm.memfp; parm.memfp = NULL; } if (r_fpr && parm.fpr) { *r_fpr = parm.fpr; parm.fpr = NULL; } if (r_fprlen) *r_fprlen = parm.fprlen; if (r_url && parm.url) { *r_url = parm.url; parm.url = NULL; } leave: xfree (parm.fpr); xfree (parm.url); es_fclose (parm.memfp); xfree (line); close_context (ctrl, ctx); return err; } /* Ask the dirmngr to retrieve a key via the Web Key Directory * protocol. If QUICK is set the dirmngr is advised to use a shorter * timeout. On success a new estream with the key stored at R_KEY and the * url of the lookup (if any) stored at R_URL. Note that */ gpg_error_t gpg_dirmngr_wkd_get (ctrl_t ctrl, const char *name, int quick, estream_t *r_key, char **r_url) { gpg_error_t err; assuan_context_t ctx; struct ks_status_parm_s stparm = { NULL }; struct dns_cert_parm_s parm = { NULL }; char *line = NULL; if (r_key) *r_key = NULL; if (r_url) *r_url = NULL; err = open_context (ctrl, &ctx); if (err) return err; line = es_bsprintf ("WKD_GET%s -- %s", quick?" --quick":"", name); if (!line) { err = gpg_error_from_syserror (); goto leave; } if (strlen (line) + 2 >= ASSUAN_LINELENGTH) { err = gpg_error (GPG_ERR_TOO_LARGE); goto leave; } parm.memfp = es_fopenmem (MAX_WKD_RESULT_LENGTH, "rwb"); if (!parm.memfp) { err = gpg_error_from_syserror (); goto leave; } err = assuan_transact (ctx, line, dns_cert_data_cb, &parm, NULL, NULL, ks_status_cb, &stparm); if (gpg_err_code (err) == GPG_ERR_ENOSPC) err = gpg_error (GPG_ERR_TOO_LARGE); if (err) goto leave; if (r_key) { es_rewind (parm.memfp); *r_key = parm.memfp; parm.memfp = NULL; } if (r_url) { *r_url = stparm.source; stparm.source = NULL; } leave: xfree (stparm.source); xfree (parm.fpr); xfree (parm.url); es_fclose (parm.memfp); xfree (line); close_context (ctrl, ctx); return err; } diff --git a/g10/call-dirmngr.h b/g10/call-dirmngr.h index 8679777c2..c0f1e0cec 100644 --- a/g10/call-dirmngr.h +++ b/g10/call-dirmngr.h @@ -1,44 +1,45 @@ /* call-dirmngr.h - GPG operations to the Dirmngr * Copyright (C) 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 . */ #ifndef GNUPG_G10_CALL_DIRMNGR_H #define GNUPG_G10_CALL_DIRMNGR_H void gpg_dirmngr_deinit_session_data (ctrl_t ctrl); gpg_error_t gpg_dirmngr_ks_list (ctrl_t ctrl, char **r_keyserver); gpg_error_t gpg_dirmngr_ks_search (ctrl_t ctrl, const char *searchstr, gpg_error_t (*cb)(void*, int, char *), void *cb_value); gpg_error_t gpg_dirmngr_ks_get (ctrl_t ctrl, char *pattern[], - keyserver_spec_t override_keyserver, int quick, + keyserver_spec_t override_keyserver, + unsigned int flags, estream_t *r_fp, char **r_source); gpg_error_t gpg_dirmngr_ks_fetch (ctrl_t ctrl, const char *url, estream_t *r_fp); gpg_error_t gpg_dirmngr_ks_put (ctrl_t ctrl, void *data, size_t datalen, kbnode_t keyblock); gpg_error_t gpg_dirmngr_dns_cert (ctrl_t ctrl, const char *name, const char *certtype, estream_t *r_key, unsigned char **r_fpr, size_t *r_fprlen, char **r_url); gpg_error_t gpg_dirmngr_wkd_get (ctrl_t ctrl, const char *name, int quick, estream_t *r_key, char **r_url); #endif /*GNUPG_G10_CALL_DIRMNGR_H*/ diff --git a/g10/getkey.c b/g10/getkey.c index 70405c89d..6b8d44332 100644 --- a/g10/getkey.c +++ b/g10/getkey.c @@ -1,4339 +1,4357 @@ /* getkey.c - Get a key from the database * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, * 2007, 2008, 2010 Free Software Foundation, Inc. * Copyright (C) 2015, 2016 g10 Code GmbH * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include "gpg.h" #include "../common/util.h" #include "packet.h" #include "../common/iobuf.h" #include "keydb.h" #include "options.h" #include "main.h" #include "trustdb.h" #include "../common/i18n.h" #include "keyserver-internal.h" #include "call-agent.h" #include "objcache.h" #include "../common/host2net.h" #include "../common/mbox-util.h" #include "../common/status.h" #define MAX_PK_CACHE_ENTRIES PK_UID_CACHE_SIZE #define MAX_UID_CACHE_ENTRIES PK_UID_CACHE_SIZE #if MAX_PK_CACHE_ENTRIES < 2 #error We need the cache for key creation #endif /* Flags values returned by the lookup code. Note that the values are * directly used by the KEY_CONSIDERED status line. */ #define LOOKUP_NOT_SELECTED (1<<0) #define LOOKUP_ALL_SUBKEYS_EXPIRED (1<<1) /* or revoked */ /* A context object used by the lookup functions. */ struct getkey_ctx_s { /* Part of the search criteria: whether the search is an exact search or not. A search that is exact requires that a key or subkey meet all of the specified criteria. A search that is not exact allows selecting a different key or subkey from the keyblock that matched the criteria. Further, an exact search returns the key or subkey that matched whereas a non-exact search typically returns the primary key. See finish_lookup for details. */ int exact; /* Part of the search criteria: Whether the caller only wants keys with an available secret key. This is used by getkey_next to get the next result with the same initial criteria. */ int want_secret; /* Part of the search criteria: The type of the requested key. A mask of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. If non-zero, then for a key to match, it must implement one of the required uses. */ int req_usage; /* The database handle. */ KEYDB_HANDLE kr_handle; /* Whether we should call xfree() on the context when the context is released using getkey_end()). */ int not_allocated; /* This variable is used as backing store for strings which have their address used in ITEMS. */ strlist_t extra_list; /* Hack to return the mechanism (AKL_foo) used to find the key. */ int found_via_akl; /* Part of the search criteria: The low-level search specification as passed to keydb_search. */ int nitems; /* This must be the last element in the structure. When we allocate the structure, we allocate it so that ITEMS can hold NITEMS. */ KEYDB_SEARCH_DESC items[1]; }; #if 0 static struct { int any; int okay_count; int nokey_count; int error_count; } lkup_stats[21]; #endif typedef struct keyid_list { struct keyid_list *next; byte fprlen; char fpr[MAX_FINGERPRINT_LEN]; u32 keyid[2]; } *keyid_list_t; #if MAX_PK_CACHE_ENTRIES typedef struct pk_cache_entry { struct pk_cache_entry *next; u32 keyid[2]; PKT_public_key *pk; } *pk_cache_entry_t; static pk_cache_entry_t pk_cache; static int pk_cache_entries; /* Number of entries in pk cache. */ static int pk_cache_disabled; #endif #if MAX_UID_CACHE_ENTRIES < 5 #error we really need the userid cache #endif static void merge_selfsigs (ctrl_t ctrl, kbnode_t keyblock); static int lookup (ctrl_t ctrl, getkey_ctx_t ctx, int want_secret, kbnode_t *ret_keyblock, kbnode_t *ret_found_key); static kbnode_t finish_lookup (kbnode_t keyblock, unsigned int req_usage, int want_exact, int want_secret, unsigned int *r_flags); static void print_status_key_considered (kbnode_t keyblock, unsigned int flags); #if 0 static void print_stats () { int i; for (i = 0; i < DIM (lkup_stats); i++) { if (lkup_stats[i].any) es_fprintf (es_stderr, "lookup stats: mode=%-2d ok=%-6d nokey=%-6d err=%-6d\n", i, lkup_stats[i].okay_count, lkup_stats[i].nokey_count, lkup_stats[i].error_count); } } #endif /* Cache a copy of a public key in the public key cache. PK is not * cached if caching is disabled (via getkey_disable_caches), if * PK->FLAGS.DONT_CACHE is set, we don't know how to derive a key id * from the public key (e.g., unsupported algorithm), or a key with * the key id is already in the cache. * * The public key packet is copied into the cache using * copy_public_key. Thus, any secret parts are not copied, for * instance. * * This cache is filled by get_pubkey and is read by get_pubkey and * get_pubkey_fast. */ void cache_public_key (PKT_public_key * pk) { #if MAX_PK_CACHE_ENTRIES pk_cache_entry_t ce, ce2; u32 keyid[2]; if (pk_cache_disabled) return; if (pk->flags.dont_cache) return; if (is_ELGAMAL (pk->pubkey_algo) || pk->pubkey_algo == PUBKEY_ALGO_DSA || pk->pubkey_algo == PUBKEY_ALGO_ECDSA || pk->pubkey_algo == PUBKEY_ALGO_EDDSA || pk->pubkey_algo == PUBKEY_ALGO_ECDH || is_RSA (pk->pubkey_algo)) { keyid_from_pk (pk, keyid); } else return; /* Don't know how to get the keyid. */ for (ce = pk_cache; ce; ce = ce->next) if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1]) { if (DBG_CACHE) log_debug ("cache_public_key: already in cache\n"); return; } if (pk_cache_entries >= MAX_PK_CACHE_ENTRIES) { int n; /* Remove the last 50% of the entries. */ for (ce = pk_cache, n = 0; ce && n < pk_cache_entries/2; n++) ce = ce->next; if (ce && ce != pk_cache && ce->next) { ce2 = ce->next; ce->next = NULL; ce = ce2; for (; ce; ce = ce2) { ce2 = ce->next; free_public_key (ce->pk); xfree (ce); pk_cache_entries--; } } log_assert (pk_cache_entries < MAX_PK_CACHE_ENTRIES); } pk_cache_entries++; ce = xmalloc (sizeof *ce); ce->next = pk_cache; pk_cache = ce; ce->pk = copy_public_key (NULL, pk); ce->keyid[0] = keyid[0]; ce->keyid[1] = keyid[1]; #endif } /* Return a const utf-8 string with the text "[User ID not found]". This function is required so that we don't need to switch gettext's encoding temporary. */ static const char * user_id_not_found_utf8 (void) { static char *text; if (!text) text = native_to_utf8 (_("[User ID not found]")); return text; } /* Disable and drop the public key cache (which is filled by cache_public_key and get_pubkey). Note: there is currently no way to re-enable this cache. */ void getkey_disable_caches () { #if MAX_PK_CACHE_ENTRIES { pk_cache_entry_t ce, ce2; for (ce = pk_cache; ce; ce = ce2) { ce2 = ce->next; free_public_key (ce->pk); xfree (ce); } pk_cache_disabled = 1; pk_cache_entries = 0; pk_cache = NULL; } #endif /* fixme: disable user id cache ? */ } /* Free a list of pubkey_t objects. */ void pubkeys_free (pubkey_t keys) { while (keys) { pubkey_t next = keys->next; xfree (keys->pk); release_kbnode (keys->keyblock); xfree (keys); keys = next; } } static void pk_from_block (PKT_public_key *pk, kbnode_t keyblock, kbnode_t found_key) { kbnode_t a = found_key ? found_key : keyblock; log_assert (a->pkt->pkttype == PKT_PUBLIC_KEY || a->pkt->pkttype == PKT_PUBLIC_SUBKEY); copy_public_key (pk, a->pkt->pkt.public_key); } /* Specialized version of get_pubkey which retrieves the key based on * information in SIG. In contrast to get_pubkey PK is required. IF * FORCED_PK is not NULL, this public key is used and copied to PK. */ gpg_error_t get_pubkey_for_sig (ctrl_t ctrl, PKT_public_key *pk, PKT_signature *sig, PKT_public_key *forced_pk) { const byte *fpr; size_t fprlen; if (forced_pk) { copy_public_key (pk, forced_pk); return 0; } /* First try the ISSUER_FPR info. */ fpr = issuer_fpr_raw (sig, &fprlen); if (fpr && !get_pubkey_byfprint (ctrl, pk, NULL, fpr, fprlen)) return 0; /* Fallback to use the ISSUER_KEYID. */ return get_pubkey (ctrl, pk, sig->keyid); } /* Return the public key with the key id KEYID and store it at PK. * The resources in *PK should be released using * release_public_key_parts(). This function also stores a copy of * the public key in the user id cache (see cache_public_key). * * If PK is NULL, this function just stores the public key in the * cache and returns the usual return code. * * PK->REQ_USAGE (which is a mask of PUBKEY_USAGE_SIG, * PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT) is passed through to the * lookup function. If this is non-zero, only keys with the specified * usage will be returned. As such, it is essential that * PK->REQ_USAGE be correctly initialized! * * Returns 0 on success, GPG_ERR_NO_PUBKEY if there is no public key * with the specified key id, or another error code if an error * occurs. * * If the data was not read from the cache, then the self-signed data * has definitely been merged into the public key using * merge_selfsigs. */ int get_pubkey (ctrl_t ctrl, PKT_public_key * pk, u32 * keyid) { int internal = 0; int rc = 0; #if MAX_PK_CACHE_ENTRIES if (pk) { /* Try to get it from the cache. We don't do this when pk is NULL as it does not guarantee that the user IDs are cached. */ pk_cache_entry_t ce; for (ce = pk_cache; ce; ce = ce->next) { if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1]) /* XXX: We don't check PK->REQ_USAGE here, but if we don't read from the cache, we do check it! */ { copy_public_key (pk, ce->pk); return 0; } } } #endif /* More init stuff. */ if (!pk) { internal++; pk = xtrycalloc (1, sizeof *pk); if (!pk) { rc = gpg_error_from_syserror (); goto leave; } } /* Do a lookup. */ { struct getkey_ctx_s ctx; kbnode_t kb = NULL; kbnode_t found_key = NULL; memset (&ctx, 0, sizeof ctx); ctx.exact = 1; /* Use the key ID exactly as given. */ ctx.not_allocated = 1; if (ctrl && ctrl->cached_getkey_kdb) { ctx.kr_handle = ctrl->cached_getkey_kdb; ctrl->cached_getkey_kdb = NULL; keydb_search_reset (ctx.kr_handle); } else { ctx.kr_handle = keydb_new (ctrl); if (!ctx.kr_handle) { rc = gpg_error_from_syserror (); goto leave; } } ctx.nitems = 1; ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID; ctx.items[0].u.kid[0] = keyid[0]; ctx.items[0].u.kid[1] = keyid[1]; ctx.req_usage = pk->req_usage; rc = lookup (ctrl, &ctx, 0, &kb, &found_key); if (!rc) { pk_from_block (pk, kb, found_key); } getkey_end (ctrl, &ctx); release_kbnode (kb); } if (!rc) goto leave; rc = GPG_ERR_NO_PUBKEY; leave: if (!rc) cache_public_key (pk); if (internal) free_public_key (pk); return rc; } /* Similar to get_pubkey, but it does not take PK->REQ_USAGE into * account nor does it merge in the self-signed data. This function * also only considers primary keys. It is intended to be used as a * quick check of the key to avoid recursion. It should only be used * in very certain cases. Like get_pubkey and unlike any of the other * lookup functions, this function also consults the user id cache * (see cache_public_key). * * Return the public key in *PK. The resources in *PK should be * released using release_public_key_parts(). */ int get_pubkey_fast (ctrl_t ctrl, PKT_public_key * pk, u32 * keyid) { int rc = 0; KEYDB_HANDLE hd; KBNODE keyblock; u32 pkid[2]; log_assert (pk); #if MAX_PK_CACHE_ENTRIES { /* Try to get it from the cache */ pk_cache_entry_t ce; for (ce = pk_cache; ce; ce = ce->next) { if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1] /* Only consider primary keys. */ && ce->pk->keyid[0] == ce->pk->main_keyid[0] && ce->pk->keyid[1] == ce->pk->main_keyid[1]) { if (pk) copy_public_key (pk, ce->pk); return 0; } } } #endif hd = keydb_new (ctrl); if (!hd) return gpg_error_from_syserror (); rc = keydb_search_kid (hd, keyid); if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND) { keydb_release (hd); return GPG_ERR_NO_PUBKEY; } rc = keydb_get_keyblock (hd, &keyblock); keydb_release (hd); if (rc) { log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc)); return GPG_ERR_NO_PUBKEY; } log_assert (keyblock && keyblock->pkt && keyblock->pkt->pkttype == PKT_PUBLIC_KEY); /* We return the primary key. If KEYID matched a subkey, then we return an error. */ keyid_from_pk (keyblock->pkt->pkt.public_key, pkid); if (keyid[0] == pkid[0] && keyid[1] == pkid[1]) copy_public_key (pk, keyblock->pkt->pkt.public_key); else rc = GPG_ERR_NO_PUBKEY; release_kbnode (keyblock); /* Not caching key here since it won't have all of the fields properly set. */ return rc; } /* Return the entire keyblock used to create SIG. This is a * specialized version of get_pubkeyblock. * * FIXME: This is a hack because get_pubkey_for_sig was already called * and it could have used a cache to hold the key. */ kbnode_t get_pubkeyblock_for_sig (ctrl_t ctrl, PKT_signature *sig) { const byte *fpr; size_t fprlen; kbnode_t keyblock; /* First try the ISSUER_FPR info. */ fpr = issuer_fpr_raw (sig, &fprlen); if (fpr && !get_pubkey_byfprint (ctrl, NULL, &keyblock, fpr, fprlen)) return keyblock; /* Fallback to use the ISSUER_KEYID. */ return get_pubkeyblock (ctrl, sig->keyid); } /* Return the key block for the key with key id KEYID or NULL, if an * error occurs. Use release_kbnode() to release the key block. * * The self-signed data has already been merged into the public key * using merge_selfsigs. */ kbnode_t get_pubkeyblock (ctrl_t ctrl, u32 * keyid) { struct getkey_ctx_s ctx; int rc = 0; KBNODE keyblock = NULL; memset (&ctx, 0, sizeof ctx); /* No need to set exact here because we want the entire block. */ ctx.not_allocated = 1; ctx.kr_handle = keydb_new (ctrl); if (!ctx.kr_handle) return NULL; ctx.nitems = 1; ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID; ctx.items[0].u.kid[0] = keyid[0]; ctx.items[0].u.kid[1] = keyid[1]; rc = lookup (ctrl, &ctx, 0, &keyblock, NULL); getkey_end (ctrl, &ctx); return rc ? NULL : keyblock; } /* Return the public key with the key id KEYID iff the secret key is * available and store it at PK. The resources should be released * using release_public_key_parts(). * * Unlike other lookup functions, PK may not be NULL. PK->REQ_USAGE * is passed through to the lookup function and is a mask of * PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. Thus, it * must be valid! If this is non-zero, only keys with the specified * usage will be returned. * * Returns 0 on success. If a public key with the specified key id is * not found or a secret key is not available for that public key, an * error code is returned. Note: this function ignores legacy keys. * An error code is also return if an error occurs. * * The self-signed data has already been merged into the public key * using merge_selfsigs. */ gpg_error_t get_seckey (ctrl_t ctrl, PKT_public_key *pk, u32 *keyid) { gpg_error_t err; struct getkey_ctx_s ctx; kbnode_t keyblock = NULL; kbnode_t found_key = NULL; memset (&ctx, 0, sizeof ctx); ctx.exact = 1; /* Use the key ID exactly as given. */ ctx.not_allocated = 1; ctx.kr_handle = keydb_new (ctrl); if (!ctx.kr_handle) return gpg_error_from_syserror (); ctx.nitems = 1; ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID; ctx.items[0].u.kid[0] = keyid[0]; ctx.items[0].u.kid[1] = keyid[1]; ctx.req_usage = pk->req_usage; err = lookup (ctrl, &ctx, 1, &keyblock, &found_key); if (!err) { pk_from_block (pk, keyblock, found_key); } getkey_end (ctrl, &ctx); release_kbnode (keyblock); if (!err) { if (!agent_probe_secret_key (/*ctrl*/NULL, pk)) { release_public_key_parts (pk); err = gpg_error (GPG_ERR_NO_SECKEY); } } return err; } /* Skip unusable keys. A key is unusable if it is revoked, expired or disabled or if the selected user id is revoked or expired. */ static int skip_unusable (void *opaque, u32 * keyid, int uid_no) { ctrl_t ctrl = opaque; int unusable = 0; KBNODE keyblock; PKT_public_key *pk; keyblock = get_pubkeyblock (ctrl, keyid); if (!keyblock) { log_error ("error checking usability status of %s\n", keystr (keyid)); goto leave; } pk = keyblock->pkt->pkt.public_key; /* Is the key revoked or expired? */ if (pk->flags.revoked || pk->has_expired) unusable = 1; /* Is the user ID in question revoked or expired? */ if (!unusable && uid_no) { KBNODE node; int uids_seen = 0; for (node = keyblock; node; node = node->next) { if (node->pkt->pkttype == PKT_USER_ID) { PKT_user_id *user_id = node->pkt->pkt.user_id; uids_seen ++; if (uids_seen != uid_no) continue; if (user_id->flags.revoked || user_id->flags.expired) unusable = 1; break; } } /* If UID_NO is non-zero, then the keyblock better have at least that many UIDs. */ log_assert (uids_seen == uid_no); } if (!unusable) unusable = pk_is_disabled (pk); leave: release_kbnode (keyblock); return unusable; } /* Search for keys matching some criteria. If RETCTX is not NULL, then the constructed context is returned in *RETCTX so that getpubkey_next can be used to get subsequent results. In this case, getkey_end() must be used to free the search context. If RETCTX is not NULL, then RET_KDBHD must be NULL. If NAMELIST is not NULL, then a search query is constructed using classify_user_id on each of the strings in the list. (Recall: the database does an OR of the terms, not an AND.) If NAMELIST is NULL, then all results are returned. If PK is not NULL, the public key of the first result is returned in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is set, it is used to filter the search results. See the documentation for finish_lookup to understand exactly how this is used. Note: The self-signed data has already been merged into the public key using merge_selfsigs. Free *PK by calling release_public_key_parts (or, if PK was allocated using xfree, you can use free_public_key, which calls release_public_key_parts(PK) and then xfree(PK)). If WANT_SECRET is set, then only keys with an available secret key (either locally or via key registered on a smartcard) are returned. If INCLUDE_UNUSABLE is set, then unusable keys (see the documentation for skip_unusable for an exact definition) are skipped unless they are looked up by key id or by fingerprint. If RET_KB is not NULL, the keyblock is returned in *RET_KB. This should be freed using release_kbnode(). If RET_KDBHD is not NULL, then the new database handle used to conduct the search is returned in *RET_KDBHD. This can be used to get subsequent results using keydb_search_next. Note: in this case, no advanced filtering is done for subsequent results (e.g., WANT_SECRET and PK->REQ_USAGE are not respected). This function returns 0 on success. Otherwise, an error code is returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY (if want_secret is set) is returned if the key is not found. */ static int key_byname (ctrl_t ctrl, GETKEY_CTX *retctx, strlist_t namelist, PKT_public_key *pk, int want_secret, int include_unusable, KBNODE * ret_kb, KEYDB_HANDLE * ret_kdbhd) { int rc = 0; int n; strlist_t r; strlist_t namelist_expanded = NULL; GETKEY_CTX ctx; KBNODE help_kb = NULL; KBNODE found_key = NULL; if (retctx) { /* Reset the returned context in case of error. */ log_assert (!ret_kdbhd); /* Not allowed because the handle is stored in the context. */ *retctx = NULL; } if (ret_kdbhd) *ret_kdbhd = NULL; if (!namelist) /* No search terms: iterate over the whole DB. */ { ctx = xmalloc_clear (sizeof *ctx); ctx->nitems = 1; ctx->items[0].mode = KEYDB_SEARCH_MODE_FIRST; if (!include_unusable) { ctx->items[0].skipfnc = skip_unusable; ctx->items[0].skipfncvalue = ctrl; } } else { namelist_expanded = expand_group (namelist, 1); namelist = namelist_expanded; /* Build the search context. */ for (n = 0, r = namelist; r; r = r->next) n++; /* CTX has space for a single search term at the end. Thus, we need to allocate sizeof *CTX plus (n - 1) sizeof CTX->ITEMS. */ ctx = xmalloc_clear (sizeof *ctx + (n - 1) * sizeof ctx->items); ctx->nitems = n; for (n = 0, r = namelist; r; r = r->next, n++) { gpg_error_t err; err = classify_user_id (r->d, &ctx->items[n], 1); if (ctx->items[n].exact) ctx->exact = 1; if (err) { xfree (ctx); rc = gpg_err_code (err); /* FIXME: remove gpg_err_code. */ goto leave; } if (!include_unusable && ctx->items[n].mode != KEYDB_SEARCH_MODE_SHORT_KID && ctx->items[n].mode != KEYDB_SEARCH_MODE_LONG_KID && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR) { ctx->items[n].skipfnc = skip_unusable; ctx->items[n].skipfncvalue = ctrl; } } } ctx->want_secret = want_secret; ctx->kr_handle = keydb_new (ctrl); if (!ctx->kr_handle) { rc = gpg_error_from_syserror (); getkey_end (ctrl, ctx); goto leave; } if (!ret_kb) ret_kb = &help_kb; if (pk) { ctx->req_usage = pk->req_usage; } rc = lookup (ctrl, ctx, want_secret, ret_kb, &found_key); if (!rc && pk) { pk_from_block (pk, *ret_kb, found_key); } release_kbnode (help_kb); if (retctx) /* Caller wants the context. */ { if (ctx->extra_list) { for (r=ctx->extra_list; r->next; r = r->next) ; r->next = namelist_expanded; } else ctx->extra_list = namelist_expanded; namelist_expanded = NULL; *retctx = ctx; } else { if (ret_kdbhd) { *ret_kdbhd = ctx->kr_handle; ctx->kr_handle = NULL; } getkey_end (ctrl, ctx); } leave: free_strlist (namelist_expanded); return rc; } /* Find a public key identified by NAME. * * If name appears to be a valid RFC822 mailbox (i.e., email address) * and auto key lookup is enabled (mode != GET_PUBKEY_NO_AKL), then * the specified auto key lookup methods (--auto-key-lookup) are used * to import the key into the local keyring. Otherwise, just the * local keyring is consulted. * * MODE can be one of: * GET_PUBKEY_NORMAL - The standard mode * GET_PUBKEY_NO_AKL - The auto key locate functionality is * disabled and only the local key ring is * considered. Note: the local key ring is * consulted even if local is not in the * auto-key-locate option list! * GET_PUBKEY_NO_LOCAL - Only the auto key locate functionality is * used and no local search is done. * * If RETCTX is not NULL, then the constructed context is returned in * *RETCTX so that getpubkey_next can be used to get subsequent * results. In this case, getkey_end() must be used to free the * search context. If RETCTX is not NULL, then RET_KDBHD must be * NULL. * * If PK is not NULL, the public key of the first result is returned * in *PK. Note: PK->REQ_USAGE must be valid!!! PK->REQ_USAGE is * passed through to the lookup function and is a mask of * PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. If this * is non-zero, only keys with the specified usage will be returned. * Note: The self-signed data has already been merged into the public * key using merge_selfsigs. Free *PK by calling * release_public_key_parts (or, if PK was allocated using xfree, you * can use free_public_key, which calls release_public_key_parts(PK) * and then xfree(PK)). * * NAME is a string, which is turned into a search query using * classify_user_id. * * If RET_KEYBLOCK is not NULL, the keyblock is returned in * *RET_KEYBLOCK. This should be freed using release_kbnode(). * * If RET_KDBHD is not NULL, then the new database handle used to * conduct the search is returned in *RET_KDBHD. This can be used to * get subsequent results using keydb_search_next or to modify the * returned record. Note: in this case, no advanced filtering is done * for subsequent results (e.g., PK->REQ_USAGE is not respected). * Unlike RETCTX, this is always returned. * * If INCLUDE_UNUSABLE is set, then unusable keys (see the * documentation for skip_unusable for an exact definition) are * skipped unless they are looked up by key id or by fingerprint. * * This function returns 0 on success. Otherwise, an error code is * returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY * (if want_secret is set) is returned if the key is not found. */ int get_pubkey_byname (ctrl_t ctrl, enum get_pubkey_modes mode, GETKEY_CTX * retctx, PKT_public_key * pk, const char *name, KBNODE * ret_keyblock, KEYDB_HANDLE * ret_kdbhd, int include_unusable) { int rc; strlist_t namelist = NULL; struct akl *akl; int is_mbox; int nodefault = 0; int anylocalfirst = 0; int mechanism_type = AKL_NODEFAULT; /* If RETCTX is not NULL, then RET_KDBHD must be NULL. */ log_assert (retctx == NULL || ret_kdbhd == NULL); if (retctx) *retctx = NULL; /* Does NAME appear to be a mailbox (mail address)? */ is_mbox = is_valid_mailbox (name); if (!is_mbox && *name == '<' && name[1] && name[strlen(name)-1]=='>' && name[1] != '>' && is_valid_mailbox_mem (name+1, strlen (name)-2)) { /* The mailbox is in the form "" which is not * detected by is_valid_mailbox. Set the flag but keep name as * it is because the bracketed name is actual the better * specification for a local search and the other methods * extract the mail address anyway. */ is_mbox = 1; } /* The auto-key-locate feature works as follows: there are a number * of methods to look up keys. By default, the local keyring is * tried first. Then, each method listed in the --auto-key-locate is * tried in the order it appears. * * This can be changed as follows: * * - if nodefault appears anywhere in the list of options, then * the local keyring is not tried first, or, * * - if local appears anywhere in the list of options, then the * local keyring is not tried first, but in the order in which * it was listed in the --auto-key-locate option. * * Note: we only save the search context in RETCTX if the local * method is the first method tried (either explicitly or * implicitly). */ if (mode == GET_PUBKEY_NO_LOCAL) nodefault = 1; /* Auto-key-locate but ignore "local". */ else if (mode != GET_PUBKEY_NO_AKL) { /* auto-key-locate is enabled. */ /* nodefault is true if "nodefault" or "local" appear. */ for (akl = opt.auto_key_locate; akl; akl = akl->next) if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL) { nodefault = 1; break; } /* anylocalfirst is true if "local" appears before any other search methods (except "nodefault"). */ for (akl = opt.auto_key_locate; akl; akl = akl->next) if (akl->type != AKL_NODEFAULT) { if (akl->type == AKL_LOCAL) anylocalfirst = 1; break; } } if (!nodefault) { /* "nodefault" didn't occur. Thus, "local" is implicitly the * first method to try. */ anylocalfirst = 1; } if (mode == GET_PUBKEY_NO_LOCAL) { /* Force using the AKL. If IS_MBOX is not set this is the final * error code. */ rc = GPG_ERR_NO_PUBKEY; } else if (nodefault && is_mbox) { /* Either "nodefault" or "local" (explicitly) appeared in the * auto key locate list and NAME appears to be an email address. * Don't try the local keyring. */ rc = GPG_ERR_NO_PUBKEY; } else { /* Either "nodefault" and "local" don't appear in the auto key * locate list (in which case we try the local keyring first) or * NAME does not appear to be an email address (in which case we * only try the local keyring). In this case, lookup NAME in * the local keyring. */ add_to_strlist (&namelist, name); rc = key_byname (ctrl, retctx, namelist, pk, 0, include_unusable, ret_keyblock, ret_kdbhd); } /* If the requested name resembles a valid mailbox and automatic retrieval has been enabled, we try to import the key. */ if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && mode != GET_PUBKEY_NO_AKL && is_mbox) { /* NAME wasn't present in the local keyring (or we didn't try * the local keyring). Since the auto key locate feature is * enabled and NAME appears to be an email address, try the auto * locate feature. */ for (akl = opt.auto_key_locate; akl; akl = akl->next) { unsigned char *fpr = NULL; size_t fpr_len; int did_akl_local = 0; int no_fingerprint = 0; const char *mechanism_string = "?"; mechanism_type = akl->type; switch (mechanism_type) { case AKL_NODEFAULT: /* This is a dummy mechanism. */ mechanism_string = ""; rc = GPG_ERR_NO_PUBKEY; break; case AKL_LOCAL: if (mode == GET_PUBKEY_NO_LOCAL) { mechanism_string = ""; rc = GPG_ERR_NO_PUBKEY; } else { mechanism_string = "Local"; did_akl_local = 1; if (retctx) { getkey_end (ctrl, *retctx); *retctx = NULL; } add_to_strlist (&namelist, name); rc = key_byname (ctrl, anylocalfirst ? retctx : NULL, namelist, pk, 0, include_unusable, ret_keyblock, ret_kdbhd); } break; case AKL_CERT: mechanism_string = "DNS CERT"; glo_ctrl.in_auto_key_retrieve++; rc = keyserver_import_cert (ctrl, name, 0, &fpr, &fpr_len); glo_ctrl.in_auto_key_retrieve--; break; case AKL_PKA: /* This is now obsolete. */ break; case AKL_DANE: mechanism_string = "DANE"; glo_ctrl.in_auto_key_retrieve++; rc = keyserver_import_cert (ctrl, name, 1, &fpr, &fpr_len); glo_ctrl.in_auto_key_retrieve--; break; case AKL_WKD: mechanism_string = "WKD"; glo_ctrl.in_auto_key_retrieve++; rc = keyserver_import_wkd (ctrl, name, 0, &fpr, &fpr_len); glo_ctrl.in_auto_key_retrieve--; break; case AKL_LDAP: mechanism_string = "LDAP"; glo_ctrl.in_auto_key_retrieve++; rc = keyserver_import_ldap (ctrl, name, &fpr, &fpr_len); glo_ctrl.in_auto_key_retrieve--; break; case AKL_NTDS: mechanism_string = "NTDS"; glo_ctrl.in_auto_key_retrieve++; rc = keyserver_import_ntds (ctrl, name, &fpr, &fpr_len); glo_ctrl.in_auto_key_retrieve--; break; case AKL_KEYSERVER: /* Strictly speaking, we don't need to only use a valid * mailbox for the getname search, but it helps cut down * on the problem of searching for something like "john" * and getting a whole lot of keys back. */ if (keyserver_any_configured (ctrl)) { mechanism_string = "keyserver"; glo_ctrl.in_auto_key_retrieve++; rc = keyserver_import_name (ctrl, name, &fpr, &fpr_len, opt.keyserver); glo_ctrl.in_auto_key_retrieve--; } else { mechanism_string = "Unconfigured keyserver"; rc = GPG_ERR_NO_PUBKEY; } break; case AKL_SPEC: { struct keyserver_spec *keyserver; mechanism_string = akl->spec->uri; keyserver = keyserver_match (akl->spec); glo_ctrl.in_auto_key_retrieve++; rc = keyserver_import_name (ctrl, name, &fpr, &fpr_len, keyserver); glo_ctrl.in_auto_key_retrieve--; } break; } /* Use the fingerprint of the key that we actually fetched. * This helps prevent problems where the key that we fetched * doesn't have the same name that we used to fetch it. In * the case of CERT, this is an actual security * requirement as the URL might point to a key put in by an * attacker. By forcing the use of the fingerprint, we * won't use the attacker's key here. */ if (!rc && fpr) { char fpr_string[MAX_FINGERPRINT_LEN * 2 + 1]; log_assert (fpr_len <= MAX_FINGERPRINT_LEN); free_strlist (namelist); namelist = NULL; bin2hex (fpr, fpr_len, fpr_string); if (opt.verbose) log_info ("auto-key-locate found fingerprint %s\n", fpr_string); add_to_strlist (&namelist, fpr_string); } else if (!rc && !fpr && !did_akl_local) { /* The acquisition method said no failure occurred, but * it didn't return a fingerprint. That's a failure. */ no_fingerprint = 1; rc = GPG_ERR_NO_PUBKEY; } xfree (fpr); fpr = NULL; if (!rc && !did_akl_local) { /* There was no error and we didn't do a local lookup. * This means that we imported a key into the local * keyring. Try to read the imported key from the * keyring. */ if (retctx) { getkey_end (ctrl, *retctx); *retctx = NULL; } rc = key_byname (ctrl, anylocalfirst ? retctx : NULL, namelist, pk, 0, include_unusable, ret_keyblock, ret_kdbhd); } if (!rc) { /* Key found. */ if (opt.verbose) log_info (_("automatically retrieved '%s' via %s\n"), name, mechanism_string); break; } if ((gpg_err_code (rc) != GPG_ERR_NO_PUBKEY || opt.verbose || no_fingerprint) && *mechanism_string) log_info (_("error retrieving '%s' via %s: %s\n"), name, mechanism_string, no_fingerprint ? _("No fingerprint") : gpg_strerror (rc)); } } if (rc && retctx) { getkey_end (ctrl, *retctx); *retctx = NULL; } if (retctx && *retctx) { GETKEY_CTX ctx = *retctx; strlist_t sl; if (ctx->extra_list) { for (sl=ctx->extra_list; sl->next; sl = sl->next) ; sl->next = namelist; } else ctx->extra_list = namelist; (*retctx)->found_via_akl = mechanism_type; } else free_strlist (namelist); return rc; } /* Comparison machinery for get_best_pubkey_byname. */ /* First we have a struct to cache computed information about the key * in question. */ struct pubkey_cmp_cookie { int valid; /* Is this cookie valid? */ PKT_public_key key; /* The key. */ PKT_user_id *uid; /* The matching UID packet. */ unsigned int validity; /* Computed validity of (KEY, UID). */ u32 creation_time; /* Creation time of the newest subkey capable of encryption. */ }; /* Then we have a series of helper functions. */ static int key_is_ok (const PKT_public_key *key) { return (! key->has_expired && ! key->flags.revoked && key->flags.valid && ! key->flags.disabled); } static int uid_is_ok (const PKT_public_key *key, const PKT_user_id *uid) { return key_is_ok (key) && ! uid->flags.revoked; } static int subkey_is_ok (const PKT_public_key *sub) { return ! sub->flags.revoked && sub->flags.valid && ! sub->flags.disabled; } /* Return true if KEYBLOCK has only expired encryption subkeys. Note * that the function returns false if the key has no encryption * subkeys at all or the subkeys are revoked. */ static int only_expired_enc_subkeys (kbnode_t keyblock) { kbnode_t node; PKT_public_key *sub; int any = 0; for (node = find_next_kbnode (keyblock, PKT_PUBLIC_SUBKEY); node; node = find_next_kbnode (node, PKT_PUBLIC_SUBKEY)) { sub = node->pkt->pkt.public_key; if (!(sub->pubkey_usage & PUBKEY_USAGE_ENC)) continue; if (!subkey_is_ok (sub)) continue; any = 1; if (!sub->has_expired) return 0; } return any? 1 : 0; } /* Finally this function compares a NEW key to the former candidate * OLD. Returns < 0 if the old key is worse, > 0 if the old key is * better, == 0 if it is a tie. */ static int pubkey_cmp (ctrl_t ctrl, const char *name, struct pubkey_cmp_cookie *old, struct pubkey_cmp_cookie *new, KBNODE new_keyblock) { kbnode_t n; if ((new->key.pubkey_usage & PUBKEY_USAGE_ENC) == 0) new->creation_time = 0; else new->creation_time = new->key.timestamp; for (n = find_next_kbnode (new_keyblock, PKT_PUBLIC_SUBKEY); n; n = find_next_kbnode (n, PKT_PUBLIC_SUBKEY)) { PKT_public_key *sub = n->pkt->pkt.public_key; if ((sub->pubkey_usage & PUBKEY_USAGE_ENC) == 0) continue; if (! subkey_is_ok (sub)) continue; if (sub->timestamp > new->creation_time) new->creation_time = sub->timestamp; } /* When new key has no encryption key, use OLD key. */ if (new->creation_time == 0) return 1; for (n = find_next_kbnode (new_keyblock, PKT_USER_ID); n; n = find_next_kbnode (n, PKT_USER_ID)) { PKT_user_id *uid = n->pkt->pkt.user_id; char *mbox = mailbox_from_userid (uid->name, 0); int match = mbox ? strcasecmp (name, mbox) == 0 : 0; xfree (mbox); if (! match) continue; new->uid = scopy_user_id (uid); new->validity = get_validity (ctrl, new_keyblock, &new->key, uid, NULL, 0) & TRUST_MASK; new->valid = 1; if (! old->valid) return -1; /* No OLD key. */ if (! uid_is_ok (&old->key, old->uid) && uid_is_ok (&new->key, uid)) return -1; /* Validity of the NEW key is better. */ if (new->validity != TRUST_EXPIRED && old->validity < new->validity) return -1; /* Validity of the NEW key is better. */ if (old->validity == TRUST_EXPIRED && new->validity != TRUST_EXPIRED) return -1; /* Validity of the NEW key is better. */ if (old->validity == new->validity && uid_is_ok (&new->key, uid) && old->creation_time < new->creation_time) return -1; /* Both keys are of the same validity, but the NEW key is newer. */ } /* Stick with the OLD key. */ return 1; } /* This function works like get_pubkey_byname, but if the name * resembles a mail address, the results are ranked and only the best * result is returned. */ gpg_error_t get_best_pubkey_byname (ctrl_t ctrl, enum get_pubkey_modes mode, GETKEY_CTX *retctx, PKT_public_key *pk, const char *name, KBNODE *ret_keyblock, int include_unusable) { gpg_error_t err; struct getkey_ctx_s *ctx = NULL; int is_mbox; int wkd_tried = 0; PKT_public_key pk0; log_assert (ret_keyblock != NULL); if (retctx) *retctx = NULL; memset (&pk0, 0, sizeof pk0); pk0.req_usage = pk? pk->req_usage : 0; is_mbox = is_valid_mailbox (name); if (!is_mbox && *name == '<' && name[1] && name[strlen(name)-1]=='>' && name[1] != '>' && is_valid_mailbox_mem (name+1, strlen (name)-2)) { /* The mailbox is in the form "" which is not * detected by is_valid_mailbox. Set the flag but keep name as * it is because get_pubkey_byname does an is_valid_mailbox_mem * itself. */ is_mbox = 1; } start_over: if (ctx) /* Clear in case of a start over. */ { release_kbnode (*ret_keyblock); *ret_keyblock = NULL; getkey_end (ctrl, ctx); ctx = NULL; } err = get_pubkey_byname (ctrl, mode, &ctx, &pk0, name, ret_keyblock, NULL, include_unusable); if (err) { goto leave; } /* If the keyblock was retrieved from the local database and the key * has expired, do further checks. However, we can do this only if * the caller requested a keyblock. */ if (is_mbox && ctx && ctx->found_via_akl == AKL_LOCAL) { u32 now = make_timestamp (); int found; /* If the key has expired and its origin was the WKD then try to * get a fresh key from the WKD. We also try this if the key * has any only expired encryption subkeys. In case we checked * for a fresh copy in the last 3 hours we won't do that again. * Unfortunately that does not yet work because KEYUPDATE is * only updated during import iff the key has actually changed * (see import.c:import_one). */ if (!wkd_tried && pk0.keyorg == KEYORG_WKD && (pk0.keyupdate + 3*3600) < now && (pk0.has_expired || only_expired_enc_subkeys (*ret_keyblock))) { if (opt.verbose) log_info (_("checking for a fresh copy of an expired key via %s\n"), "WKD"); wkd_tried = 1; glo_ctrl.in_auto_key_retrieve++; found = !keyserver_import_wkd (ctrl, name, 0, NULL, NULL); glo_ctrl.in_auto_key_retrieve--; if (found) { release_public_key_parts (&pk0); goto start_over; } } } if (is_mbox && ctx) { /* Rank results and return only the most relevant key for encryption. */ struct pubkey_cmp_cookie best = { 0 }; struct pubkey_cmp_cookie new = { 0 }; kbnode_t new_keyblock; copy_public_key (&new.key, &pk0); if (pubkey_cmp (ctrl, name, &best, &new, *ret_keyblock) >= 0) { release_public_key_parts (&new.key); free_user_id (new.uid); } else best = new; new.uid = NULL; while (getkey_next (ctrl, ctx, &new.key, &new_keyblock) == 0) { int diff = pubkey_cmp (ctrl, name, &best, &new, new_keyblock); release_kbnode (new_keyblock); if (diff < 0) { /* New key is better. */ release_public_key_parts (&best.key); free_user_id (best.uid); best = new; } else if (diff > 0) { /* Old key is better. */ release_public_key_parts (&new.key); free_user_id (new.uid); } else { /* A tie. Keep the old key. */ release_public_key_parts (&new.key); free_user_id (new.uid); } new.uid = NULL; } getkey_end (ctrl, ctx); ctx = NULL; free_user_id (best.uid); best.uid = NULL; if (best.valid) { ctx = xtrycalloc (1, sizeof **retctx); if (! ctx) err = gpg_error_from_syserror (); else { ctx->kr_handle = keydb_new (ctrl); if (! ctx->kr_handle) { err = gpg_error_from_syserror (); xfree (ctx); ctx = NULL; if (retctx) *retctx = NULL; } else { u32 *keyid = pk_keyid (&best.key); ctx->exact = 1; ctx->nitems = 1; ctx->items[0].mode = KEYDB_SEARCH_MODE_LONG_KID; ctx->items[0].u.kid[0] = keyid[0]; ctx->items[0].u.kid[1] = keyid[1]; release_kbnode (*ret_keyblock); *ret_keyblock = NULL; err = getkey_next (ctrl, ctx, NULL, ret_keyblock); } } if (pk) *pk = best.key; else release_public_key_parts (&best.key); release_public_key_parts (&pk0); } else { if (pk) *pk = pk0; else release_public_key_parts (&pk0); } } else { if (pk) *pk = pk0; else release_public_key_parts (&pk0); } if (err && ctx) { getkey_end (ctrl, ctx); ctx = NULL; } if (retctx && ctx) { *retctx = ctx; ctx = NULL; } leave: getkey_end (ctrl, ctx); return err; } /* Get a public key from a file. * * PK is the buffer to store the key. The caller needs to make sure * that PK->REQ_USAGE is valid. PK->REQ_USAGE is passed through to * the lookup function and is a mask of PUBKEY_USAGE_SIG, * PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT. If this is non-zero, only * keys with the specified usage will be returned. * * FNAME is the file name. That file should contain exactly one * keyblock. * * This function returns 0 on success. Otherwise, an error code is * returned. In particular, GPG_ERR_NO_PUBKEY is returned if the key * is not found. * * The self-signed data has already been merged into the public key * using merge_selfsigs. The caller must release the content of PK by * calling release_public_key_parts (or, if PK was malloced, using * free_public_key). */ gpg_error_t get_pubkey_fromfile (ctrl_t ctrl, PKT_public_key *pk, const char *fname) { gpg_error_t err; kbnode_t keyblock; kbnode_t found_key; unsigned int infoflags; err = read_key_from_file_or_buffer (ctrl, fname, NULL, 0, &keyblock); if (!err) { /* Warning: node flag bits 0 and 1 should be preserved by * merge_selfsigs. FIXME: Check whether this still holds. */ merge_selfsigs (ctrl, keyblock); found_key = finish_lookup (keyblock, pk->req_usage, 0, 0, &infoflags); print_status_key_considered (keyblock, infoflags); if (found_key) pk_from_block (pk, keyblock, found_key); else err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY); } release_kbnode (keyblock); return err; } /* Return a public key from the buffer (BUFFER, BUFLEN). The key is * onlyretruned if it matches the keyid given in WANT_KEYID. On * success the key is stored at the caller provided PKBUF structure. * The caller must release the content of PK by calling * release_public_key_parts (or, if PKBUF was malloced, using * free_public_key). If R_KEYBLOCK is not NULL the full keyblock is * also stored there. */ gpg_error_t get_pubkey_from_buffer (ctrl_t ctrl, PKT_public_key *pkbuf, const void *buffer, size_t buflen, u32 *want_keyid, kbnode_t *r_keyblock) { gpg_error_t err; kbnode_t keyblock; kbnode_t node; PKT_public_key *pk; if (r_keyblock) *r_keyblock = NULL; err = read_key_from_file_or_buffer (ctrl, NULL, buffer, buflen, &keyblock); if (!err) { merge_selfsigs (ctrl, keyblock); for (node = keyblock; node; node = node->next) { if (node->pkt->pkttype == PKT_PUBLIC_KEY || node->pkt->pkttype == PKT_PUBLIC_SUBKEY) { pk = node->pkt->pkt.public_key; keyid_from_pk (pk, NULL); if (pk->keyid[0] == want_keyid[0] && pk->keyid[1] == want_keyid[1]) break; } } if (node) copy_public_key (pkbuf, pk); else err = gpg_error (GPG_ERR_NO_PUBKEY); } if (!err && r_keyblock) *r_keyblock = keyblock; else release_kbnode (keyblock); return err; } /* Lookup a key with the specified fingerprint. * * If PK is not NULL, the public key of the first result is returned * in *PK. Note: this function does an exact search and thus the * returned public key may be a subkey rather than the primary key. * Note: The self-signed data has already been merged into the public * key using merge_selfsigs. Free *PK by calling * release_public_key_parts (or, if PK was allocated using xfree, you * can use free_public_key, which calls release_public_key_parts(PK) * and then xfree(PK)). * * If PK->REQ_USAGE is set, it is used to filter the search results. * (Thus, if PK is not NULL, PK->REQ_USAGE must be valid!!!) See the * documentation for finish_lookup to understand exactly how this is * used. * * If R_KEYBLOCK is not NULL, then the first result's keyblock is * returned in *R_KEYBLOCK. This should be freed using * release_kbnode(). * * FPRINT is a byte array whose contents is the fingerprint to use as * the search term. FPRINT_LEN specifies the length of the * fingerprint (in bytes). Currently, only 16, 20, and 32-byte * fingerprints are supported. * * FIXME: We should replace this with the _byname function. This can * be done by creating a userID conforming to the unified fingerprint * style. */ int get_pubkey_byfprint (ctrl_t ctrl, PKT_public_key *pk, kbnode_t *r_keyblock, const byte * fprint, size_t fprint_len) { int rc; if (r_keyblock) *r_keyblock = NULL; if (fprint_len == 32 || fprint_len == 20 || fprint_len == 16) { struct getkey_ctx_s ctx; KBNODE kb = NULL; KBNODE found_key = NULL; memset (&ctx, 0, sizeof ctx); ctx.exact = 1; ctx.not_allocated = 1; /* FIXME: We should get the handle from the cache like we do in * get_pubkey. */ ctx.kr_handle = keydb_new (ctrl); if (!ctx.kr_handle) return gpg_error_from_syserror (); ctx.nitems = 1; ctx.items[0].mode = KEYDB_SEARCH_MODE_FPR; memcpy (ctx.items[0].u.fpr, fprint, fprint_len); ctx.items[0].fprlen = fprint_len; if (pk) ctx.req_usage = pk->req_usage; rc = lookup (ctrl, &ctx, 0, &kb, &found_key); if (!rc && pk) pk_from_block (pk, kb, found_key); if (!rc && r_keyblock) { *r_keyblock = kb; kb = NULL; } release_kbnode (kb); getkey_end (ctrl, &ctx); } else rc = GPG_ERR_GENERAL; /* Oops */ return rc; } /* This function is similar to get_pubkey_byfprint, but it doesn't * merge the self-signed data into the public key and subkeys or into * the user ids. It also doesn't add the key to the user id cache. * Further, this function ignores PK->REQ_USAGE. * * This function is intended to avoid recursion and, as such, should * only be used in very specific situations. * * Like get_pubkey_byfprint, PK may be NULL. In that case, this * function effectively just checks for the existence of the key. */ gpg_error_t get_pubkey_byfprint_fast (ctrl_t ctrl, PKT_public_key * pk, const byte * fprint, size_t fprint_len) { gpg_error_t err; KBNODE keyblock; err = get_keyblock_byfprint_fast (ctrl, &keyblock, NULL, fprint, fprint_len, 0); if (!err) { if (pk) copy_public_key (pk, keyblock->pkt->pkt.public_key); release_kbnode (keyblock); } return err; } /* This function is similar to get_pubkey_byfprint_fast but returns a * keydb handle at R_HD and the keyblock at R_KEYBLOCK. R_KEYBLOCK or * R_HD may be NULL. If LOCK is set the handle has been opend in * locked mode and keydb_disable_caching () has been called. On error * R_KEYBLOCK is set to NULL but R_HD must be released by the caller; * it may have a value of NULL, though. This allows to do an insert * operation on a locked keydb handle. */ gpg_error_t get_keyblock_byfprint_fast (ctrl_t ctrl, kbnode_t *r_keyblock, KEYDB_HANDLE *r_hd, const byte *fprint, size_t fprint_len, int lock) { gpg_error_t err; KEYDB_HANDLE hd; kbnode_t keyblock; byte fprbuf[MAX_FINGERPRINT_LEN]; int i; if (r_keyblock) *r_keyblock = NULL; if (r_hd) *r_hd = NULL; for (i = 0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++) fprbuf[i] = fprint[i]; hd = keydb_new (ctrl); if (!hd) return gpg_error_from_syserror (); if (lock) { err = keydb_lock (hd); if (err) { /* If locking did not work, we better don't return a handle * at all - there was a reason that locking has been * requested. */ keydb_release (hd); return err; } keydb_disable_caching (hd); } /* For all other errors we return the handle. */ if (r_hd) *r_hd = hd; err = keydb_search_fpr (hd, fprbuf, fprint_len); if (gpg_err_code (err) == GPG_ERR_NOT_FOUND) { if (!r_hd) keydb_release (hd); return gpg_error (GPG_ERR_NO_PUBKEY); } err = keydb_get_keyblock (hd, &keyblock); if (err) { log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (err)); if (!r_hd) keydb_release (hd); return gpg_error (GPG_ERR_NO_PUBKEY); } log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY); /* Not caching key here since it won't have all of the fields properly set. */ if (r_keyblock) *r_keyblock = keyblock; else release_kbnode (keyblock); if (!r_hd) keydb_release (hd); return 0; } const char * parse_def_secret_key (ctrl_t ctrl) { KEYDB_HANDLE hd = NULL; strlist_t t; static int warned; for (t = opt.def_secret_key; t; t = t->next) { gpg_error_t err; KEYDB_SEARCH_DESC desc; KBNODE kb; KBNODE node; err = classify_user_id (t->d, &desc, 1); if (err) { log_error (_("secret key \"%s\" not found: %s\n"), t->d, gpg_strerror (err)); if (!opt.quiet) log_info (_("(check argument of option '%s')\n"), "--default-key"); continue; } if (! hd) { hd = keydb_new (ctrl); if (!hd) return NULL; } else keydb_search_reset (hd); err = keydb_search (hd, &desc, 1, NULL); if (gpg_err_code (err) == GPG_ERR_NOT_FOUND) continue; if (err) { log_error (_("key \"%s\" not found: %s\n"), t->d, gpg_strerror (err)); t = NULL; break; } err = keydb_get_keyblock (hd, &kb); if (err) { log_error (_("error reading keyblock: %s\n"), gpg_strerror (err)); continue; } merge_selfsigs (ctrl, kb); err = gpg_error (GPG_ERR_NO_SECKEY); node = kb; do { PKT_public_key *pk = node->pkt->pkt.public_key; /* Check if the key is valid. */ if (pk->flags.revoked) { if (DBG_LOOKUP) log_debug ("not using %s as default key, %s", keystr_from_pk (pk), "revoked"); continue; } if (pk->has_expired) { if (DBG_LOOKUP) log_debug ("not using %s as default key, %s", keystr_from_pk (pk), "expired"); continue; } if (pk_is_disabled (pk)) { if (DBG_LOOKUP) log_debug ("not using %s as default key, %s", keystr_from_pk (pk), "disabled"); continue; } if (agent_probe_secret_key (ctrl, pk)) { /* This is a valid key. */ err = 0; break; } } while ((node = find_next_kbnode (node, PKT_PUBLIC_SUBKEY))); release_kbnode (kb); if (err) { if (! warned && ! opt.quiet) { log_info (_("Warning: not using '%s' as default key: %s\n"), t->d, gpg_strerror (GPG_ERR_NO_SECKEY)); print_reported_error (err, GPG_ERR_NO_SECKEY); } } else { if (! warned && ! opt.quiet) log_info (_("using \"%s\" as default secret key for signing\n"), t->d); break; } } if (! warned && opt.def_secret_key && ! t) log_info (_("all values passed to '%s' ignored\n"), "--default-key"); warned = 1; if (hd) keydb_release (hd); if (t) return t->d; return NULL; } /* Look up a secret key. * * If PK is not NULL, the public key of the first result is returned * in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is * set, it is used to filter the search results. See the * documentation for finish_lookup to understand exactly how this is * used. Note: The self-signed data has already been merged into the * public key using merge_selfsigs. Free *PK by calling * release_public_key_parts (or, if PK was allocated using xfree, you * can use free_public_key, which calls release_public_key_parts(PK) * and then xfree(PK)). * * If --default-key was set, then the specified key is looked up. (In * this case, the default key is returned even if it is considered * unusable. See the documentation for skip_unusable for exactly what * this means.) * * Otherwise, this initiates a DB scan that returns all keys that are * usable (see previous paragraph for exactly what usable means) and * for which a secret key is available. * * This function returns the first match. Additional results can be * returned using getkey_next. */ gpg_error_t get_seckey_default (ctrl_t ctrl, PKT_public_key *pk) { gpg_error_t err; strlist_t namelist = NULL; int include_unusable = 1; const char *def_secret_key = parse_def_secret_key (ctrl); if (def_secret_key) add_to_strlist (&namelist, def_secret_key); else include_unusable = 0; err = key_byname (ctrl, NULL, namelist, pk, 1, include_unusable, NULL, NULL); free_strlist (namelist); return err; } /* Search for keys matching some criteria. * * If RETCTX is not NULL, then the constructed context is returned in * *RETCTX so that getpubkey_next can be used to get subsequent * results. In this case, getkey_end() must be used to free the * search context. If RETCTX is not NULL, then RET_KDBHD must be * NULL. * * If PK is not NULL, the public key of the first result is returned * in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is * set, it is used to filter the search results. See the * documentation for finish_lookup to understand exactly how this is * used. Note: The self-signed data has already been merged into the * public key using merge_selfsigs. Free *PK by calling * release_public_key_parts (or, if PK was allocated using xfree, you * can use free_public_key, which calls release_public_key_parts(PK) * and then xfree(PK)). * * If NAMES is not NULL, then a search query is constructed using * classify_user_id on each of the strings in the list. (Recall: the * database does an OR of the terms, not an AND.) If NAMES is * NULL, then all results are returned. * * If WANT_SECRET is set, then only keys with an available secret key * (either locally or via key registered on a smartcard) are returned. * * This function does not skip unusable keys (see the documentation * for skip_unusable for an exact definition). * * If RET_KEYBLOCK is not NULL, the keyblock is returned in * *RET_KEYBLOCK. This should be freed using release_kbnode(). * * This function returns 0 on success. Otherwise, an error code is * returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY * (if want_secret is set) is returned if the key is not found. */ gpg_error_t getkey_bynames (ctrl_t ctrl, getkey_ctx_t *retctx, PKT_public_key *pk, strlist_t names, int want_secret, kbnode_t *ret_keyblock) { return key_byname (ctrl, retctx, names, pk, want_secret, 1, ret_keyblock, NULL); } /* Search for one key matching some criteria. * * If RETCTX is not NULL, then the constructed context is returned in * *RETCTX so that getpubkey_next can be used to get subsequent * results. In this case, getkey_end() must be used to free the * search context. If RETCTX is not NULL, then RET_KDBHD must be * NULL. * * If PK is not NULL, the public key of the first result is returned * in *PK. Note: PK->REQ_USAGE must be valid!!! If PK->REQ_USAGE is * set, it is used to filter the search results. See the * documentation for finish_lookup to understand exactly how this is * used. Note: The self-signed data has already been merged into the * public key using merge_selfsigs. Free *PK by calling * release_public_key_parts (or, if PK was allocated using xfree, you * can use free_public_key, which calls release_public_key_parts(PK) * and then xfree(PK)). * * If NAME is not NULL, then a search query is constructed using * classify_user_id on the string. In this case, even unusable keys * (see the documentation for skip_unusable for an exact definition of * unusable) are returned. Otherwise, if --default-key was set, then * that key is returned (even if it is unusable). If neither of these * conditions holds, then the first usable key is returned. * * If WANT_SECRET is set, then only keys with an available secret key * (either locally or via key registered on a smartcard) are returned. * * This function does not skip unusable keys (see the documentation * for skip_unusable for an exact definition). * * If RET_KEYBLOCK is not NULL, the keyblock is returned in * *RET_KEYBLOCK. This should be freed using release_kbnode(). * * This function returns 0 on success. Otherwise, an error code is * returned. In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY * (if want_secret is set) is returned if the key is not found. * * FIXME: We also have the get_pubkey_byname function which has a * different semantic. Should be merged with this one. */ gpg_error_t getkey_byname (ctrl_t ctrl, getkey_ctx_t *retctx, PKT_public_key *pk, const char *name, int want_secret, kbnode_t *ret_keyblock) { gpg_error_t err; strlist_t namelist = NULL; int with_unusable = 1; const char *def_secret_key = NULL; if (want_secret && !name) def_secret_key = parse_def_secret_key (ctrl); if (want_secret && !name && def_secret_key) add_to_strlist (&namelist, def_secret_key); else if (name) add_to_strlist (&namelist, name); else with_unusable = 0; err = key_byname (ctrl, retctx, namelist, pk, want_secret, with_unusable, ret_keyblock, NULL); /* FIXME: Check that we really return GPG_ERR_NO_SECKEY if WANT_SECRET has been used. */ free_strlist (namelist); return err; } /* Return the next search result. * * If PK is not NULL, the public key of the next result is returned in * *PK. Note: The self-signed data has already been merged into the * public key using merge_selfsigs. Free *PK by calling * release_public_key_parts (or, if PK was allocated using xmalloc, you * can use free_public_key, which calls release_public_key_parts(PK) * and then xfree(PK)). * * RET_KEYBLOCK can be given as NULL; if it is not NULL it the entire * found keyblock is returned which must be released with * release_kbnode. If the function returns an error NULL is stored at * RET_KEYBLOCK. * * The self-signed data has already been merged into the public key * using merge_selfsigs. */ gpg_error_t getkey_next (ctrl_t ctrl, getkey_ctx_t ctx, PKT_public_key *pk, kbnode_t *ret_keyblock) { int rc; /* Fixme: Make sure this is proper gpg_error */ KBNODE keyblock = NULL; KBNODE found_key = NULL; /* We need to disable the caching so that for an exact key search we won't get the result back from the cache and thus end up in an endless loop. The endless loop can occur, because the cache is used without respecting the current file pointer! */ keydb_disable_caching (ctx->kr_handle); /* FOUND_KEY is only valid as long as RET_KEYBLOCK is. If the * caller wants PK, but not RET_KEYBLOCK, we need hand in our own * keyblock. */ if (pk && ret_keyblock == NULL) ret_keyblock = &keyblock; rc = lookup (ctrl, ctx, ctx->want_secret, ret_keyblock, pk ? &found_key : NULL); if (!rc && pk) { log_assert (found_key); pk_from_block (pk, NULL, found_key); release_kbnode (keyblock); } return rc; } /* Release any resources used by a key listing context. This must be * called on the context returned by, e.g., getkey_byname. */ void getkey_end (ctrl_t ctrl, getkey_ctx_t ctx) { if (ctx) { #ifdef HAVE_W32_SYSTEM /* FIXME: This creates a big regression for Windows because the * keyring is only released after the global ctrl is released. * So if an operation does a getkey and then tries to modify the * keyring it will fail on Windows with a sharing violation. We * need to modify all keyring write operations to also take the * ctrl and close the cached_getkey_kdb handle to make writing * work. See: GnuPG-bug-id: 3097 */ (void)ctrl; keydb_release (ctx->kr_handle); #else /*!HAVE_W32_SYSTEM*/ if (ctrl && !ctrl->cached_getkey_kdb) ctrl->cached_getkey_kdb = ctx->kr_handle; else keydb_release (ctx->kr_handle); #endif /*!HAVE_W32_SYSTEM*/ free_strlist (ctx->extra_list); if (!ctx->not_allocated) xfree (ctx); } } /************************************************ ************* Merging stuff ******************** ************************************************/ /* Set the mainkey_id fields for all keys in KEYBLOCK. This is * usually done by merge_selfsigs but at some places we only need the * main_kid not a full merge. The function also guarantees that all * pk->keyids are computed. */ void setup_main_keyids (kbnode_t keyblock) { u32 kid[2], mainkid[2]; kbnode_t kbctx, node; PKT_public_key *pk; if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY) BUG (); pk = keyblock->pkt->pkt.public_key; keyid_from_pk (pk, mainkid); for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); ) { if (!(node->pkt->pkttype == PKT_PUBLIC_KEY || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)) continue; pk = node->pkt->pkt.public_key; keyid_from_pk (pk, kid); /* Make sure pk->keyid is set. */ if (!pk->main_keyid[0] && !pk->main_keyid[1]) { pk->main_keyid[0] = mainkid[0]; pk->main_keyid[1] = mainkid[1]; } } } /* KEYBLOCK corresponds to a public key block. This function merges * much of the information from the self-signed data into the public * key, public subkey and user id data structures. If you use the * high-level search API (e.g., get_pubkey) for looking up key blocks, * then you don't need to call this function. This function is * useful, however, if you change the keyblock, e.g., by adding or * removing a self-signed data packet. */ void merge_keys_and_selfsig (ctrl_t ctrl, kbnode_t keyblock) { if (!keyblock) ; else if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY) merge_selfsigs (ctrl, keyblock); else log_debug ("FIXME: merging secret key blocks is not anymore available\n"); } static int parse_key_usage (PKT_signature * sig) { int key_usage = 0; const byte *p; size_t n; byte flags; p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_FLAGS, &n); if (p && n) { /* First octet of the keyflags. */ flags = *p; if (flags & 1) { key_usage |= PUBKEY_USAGE_CERT; flags &= ~1; } if (flags & 2) { key_usage |= PUBKEY_USAGE_SIG; flags &= ~2; } /* We do not distinguish between encrypting communications and encrypting storage. */ if (flags & (0x04 | 0x08)) { key_usage |= PUBKEY_USAGE_ENC; flags &= ~(0x04 | 0x08); } if (flags & 0x20) { key_usage |= PUBKEY_USAGE_AUTH; flags &= ~0x20; } if (flags) key_usage |= PUBKEY_USAGE_UNKNOWN; if (!key_usage) key_usage |= PUBKEY_USAGE_NONE; } else if (p) /* Key flags of length zero. */ key_usage |= PUBKEY_USAGE_NONE; /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a capability that we do not handle. This serves to distinguish between a zero key usage which we handle as the default capabilities for that algorithm, and a usage that we do not handle. Likewise we use PUBKEY_USAGE_NONE to indicate that key_flags have been given but they do not specify any usage. */ return key_usage; } /* Apply information from SIGNODE (which is the valid self-signature * associated with that UID) to the UIDNODE: * - wether the UID has been revoked * - assumed creation date of the UID * - temporary store the keyflags here * - temporary store the key expiration time here * - mark whether the primary user ID flag hat been set. * - store the preferences */ static void fixup_uidnode (KBNODE uidnode, KBNODE signode, u32 keycreated) { PKT_user_id *uid = uidnode->pkt->pkt.user_id; PKT_signature *sig = signode->pkt->pkt.signature; const byte *p, *sym, *aead, *hash, *zip; size_t n, nsym, naead, nhash, nzip; sig->flags.chosen_selfsig = 1;/* We chose this one. */ uid->created = 0; /* Not created == invalid. */ if (IS_UID_REV (sig)) { uid->flags.revoked = 1; return; /* Has been revoked. */ } else uid->flags.revoked = 0; uid->expiredate = sig->expiredate; if (sig->flags.expired) { uid->flags.expired = 1; return; /* Has expired. */ } else uid->flags.expired = 0; uid->created = sig->timestamp; /* This one is okay. */ uid->selfsigversion = sig->version; /* If we got this far, it's not expired :) */ uid->flags.expired = 0; /* Store the key flags in the helper variable for later processing. */ uid->help_key_usage = parse_key_usage (sig); /* Ditto for the key expiration. */ p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_EXPIRE, NULL); if (p && buf32_to_u32 (p)) uid->help_key_expire = keycreated + buf32_to_u32 (p); else uid->help_key_expire = 0; /* Set the primary user ID flag - we will later wipe out some * of them to only have one in our keyblock. */ uid->flags.primary = 0; p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PRIMARY_UID, NULL); if (p && *p) uid->flags.primary = 2; /* We could also query this from the unhashed area if it is not in * the hased area and then later try to decide which is the better * there should be no security problem with this. * For now we only look at the hashed one. */ /* Now build the preferences list. These must come from the hashed section so nobody can modify the ciphers a key is willing to accept. */ p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_SYM, &n); sym = p; nsym = p ? n : 0; p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_AEAD, &n); aead = p; naead = p ? n : 0; p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_HASH, &n); hash = p; nhash = p ? n : 0; p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_COMPR, &n); zip = p; nzip = p ? n : 0; if (uid->prefs) xfree (uid->prefs); n = nsym + naead + nhash + nzip; if (!n) uid->prefs = NULL; else { uid->prefs = xmalloc (sizeof (*uid->prefs) * (n + 1)); n = 0; for (; nsym; nsym--, n++) { uid->prefs[n].type = PREFTYPE_SYM; uid->prefs[n].value = *sym++; } for (; naead; naead--, n++) { uid->prefs[n].type = PREFTYPE_AEAD; uid->prefs[n].value = *aead++; } for (; nhash; nhash--, n++) { uid->prefs[n].type = PREFTYPE_HASH; uid->prefs[n].value = *hash++; } for (; nzip; nzip--, n++) { uid->prefs[n].type = PREFTYPE_ZIP; uid->prefs[n].value = *zip++; } uid->prefs[n].type = PREFTYPE_NONE; /* End of list marker */ uid->prefs[n].value = 0; } /* See whether we have the MDC feature. */ uid->flags.mdc = 0; p = parse_sig_subpkt (sig, 1, SIGSUBPKT_FEATURES, &n); if (p && n && (p[0] & 0x01)) uid->flags.mdc = 1; /* See whether we have the AEAD feature. */ uid->flags.aead = 0; p = parse_sig_subpkt (sig, 1, SIGSUBPKT_FEATURES, &n); if (p && n && (p[0] & 0x02)) uid->flags.aead = 1; /* And the keyserver modify flag. */ uid->flags.ks_modify = 1; p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KS_FLAGS, &n); if (p && n && (p[0] & 0x80)) uid->flags.ks_modify = 0; } static void sig_to_revoke_info (PKT_signature * sig, struct revoke_info *rinfo) { rinfo->date = sig->timestamp; rinfo->algo = sig->pubkey_algo; rinfo->keyid[0] = sig->keyid[0]; rinfo->keyid[1] = sig->keyid[1]; } /* Given a keyblock, parse the key block and extract various pieces of * information and save them with the primary key packet and the user * id packets. For instance, some information is stored in signature * packets. We find the latest such valid packet (since the user can * change that information) and copy its contents into the * PKT_public_key. * * Note that R_REVOKED may be set to 0, 1 or 2. * * This function fills in the following fields in the primary key's * keyblock: * * main_keyid (computed) * revkey / numrevkeys (derived from self signed key data) * flags.valid (whether we have at least 1 self-sig) * flags.maybe_revoked (whether a designed revoked the key, but * we are missing the key to check the sig) * selfsigversion (highest version of any valid self-sig) * pubkey_usage (derived from most recent self-sig or most * recent user id) * has_expired (various sources) * expiredate (various sources) * * See the documentation for fixup_uidnode for how the user id packets * are modified. In addition to that the primary user id's is_primary * field is set to 1 and the other user id's is_primary are set to 0. */ static void merge_selfsigs_main (ctrl_t ctrl, kbnode_t keyblock, int *r_revoked, struct revoke_info *rinfo) { PKT_public_key *pk = NULL; KBNODE k; u32 kid[2]; u32 sigdate, uiddate, uiddate2; KBNODE signode, uidnode, uidnode2; u32 curtime = make_timestamp (); unsigned int key_usage = 0; u32 keytimestamp = 0; /* Creation time of the key. */ u32 key_expire = 0; int key_expire_seen = 0; byte sigversion = 0; *r_revoked = 0; memset (rinfo, 0, sizeof (*rinfo)); /* Section 11.1 of RFC 4880 determines the order of packets within a * message. There are three sections, which must occur in the * following order: the public key, the user ids and user attributes * and the subkeys. Within each section, each primary packet (e.g., * a user id packet) is followed by one or more signature packets, * which modify that packet. */ /* According to Section 11.1 of RFC 4880, the public key must be the first packet. Note that parse_keyblock_image ensures that the first packet is the public key. */ if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY) BUG (); pk = keyblock->pkt->pkt.public_key; keytimestamp = pk->timestamp; keyid_from_pk (pk, kid); pk->main_keyid[0] = kid[0]; pk->main_keyid[1] = kid[1]; if (pk->version < 4) { /* Before v4 the key packet itself contains the expiration date * and there was no way to change it, so we start with the one * from the key packet. We do not support v3 keys anymore but * we keep the code in case a future key versions introduces a * hadr expire time again. */ key_expire = pk->max_expiredate; key_expire_seen = 1; } /* First pass: * * - Find the latest direct key self-signature. We assume that the * newest one overrides all others. * * - Determine whether the key has been revoked. * * - Gather all revocation keys (unlike other data, we don't just * take them from the latest self-signed packet). * * - Determine max (sig[...]->version). */ /* Reset this in case this key was already merged. */ xfree (pk->revkey); pk->revkey = NULL; pk->numrevkeys = 0; signode = NULL; sigdate = 0; /* Helper variable to find the latest signature. */ /* According to Section 11.1 of RFC 4880, the public key comes first * and is immediately followed by any signature packets that modify * it. */ for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID && k->pkt->pkttype != PKT_ATTRIBUTE && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) { if (k->pkt->pkttype == PKT_SIGNATURE) { PKT_signature *sig = k->pkt->pkt.signature; if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1]) { /* Self sig. */ if (check_key_signature (ctrl, keyblock, k, NULL)) ; /* Signature did not verify. */ else if (IS_KEY_REV (sig)) { /* Key has been revoked - there is no way to * override such a revocation, so we theoretically * can stop now. We should not cope with expiration * times for revocations here because we have to * assume that an attacker can generate all kinds of * signatures. However due to the fact that the key * has been revoked it does not harm either and by * continuing we gather some more info on that * key. */ *r_revoked = 1; sig_to_revoke_info (sig, rinfo); } else if (IS_KEY_SIG (sig)) { /* Add the indicated revocations keys from all * signatures not just the latest. We do this * because you need multiple 1F sigs to properly * handle revocation keys (PGP does it this way, and * a revocation key could be sensitive and hence in * a different signature). */ if (sig->revkey) { int i; pk->revkey = xrealloc (pk->revkey, sizeof (struct revocation_key) * (pk->numrevkeys + sig->numrevkeys)); for (i = 0; i < sig->numrevkeys; i++, pk->numrevkeys++) { pk->revkey[pk->numrevkeys].class = sig->revkey[i].class; pk->revkey[pk->numrevkeys].algid = sig->revkey[i].algid; pk->revkey[pk->numrevkeys].fprlen = sig->revkey[i].fprlen; memcpy (pk->revkey[pk->numrevkeys].fpr, sig->revkey[i].fpr, sig->revkey[i].fprlen); memset (pk->revkey[pk->numrevkeys].fpr + sig->revkey[i].fprlen, 0, sizeof (sig->revkey[i].fpr) - sig->revkey[i].fprlen); } } if (sig->timestamp >= sigdate) { /* This is the latest signature so far. */ if (sig->flags.expired) ; /* Signature has expired - ignore it. */ else { sigdate = sig->timestamp; signode = k; if (sig->version > sigversion) sigversion = sig->version; } } } } } } /* Remove dupes from the revocation keys. */ if (pk->revkey) { int i, j, x, changed = 0; for (i = 0; i < pk->numrevkeys; i++) { for (j = i + 1; j < pk->numrevkeys; j++) { if (memcmp (&pk->revkey[i], &pk->revkey[j], sizeof (struct revocation_key)) == 0) { /* remove j */ for (x = j; x < pk->numrevkeys - 1; x++) pk->revkey[x] = pk->revkey[x + 1]; pk->numrevkeys--; j--; changed = 1; } } } if (changed) pk->revkey = xrealloc (pk->revkey, pk->numrevkeys * sizeof (struct revocation_key)); } /* SIGNODE is the direct key signature packet (sigclass 0x1f) with * the latest creation time. Extract some information from it. */ if (signode) { /* Some information from a direct key signature take precedence * over the same information given in UID sigs. */ PKT_signature *sig = signode->pkt->pkt.signature; const byte *p; key_usage = parse_key_usage (sig); p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_EXPIRE, NULL); if (p && buf32_to_u32 (p)) { key_expire = keytimestamp + buf32_to_u32 (p); key_expire_seen = 1; } /* Mark that key as valid: One direct key signature should * render a key as valid. */ pk->flags.valid = 1; } /* Pass 1.5: Look for key revocation signatures that were not made * by the key (i.e. did a revocation key issue a revocation for * us?). Only bother to do this if there is a revocation key in the * first place and we're not revoked already. */ if (!*r_revoked && pk->revkey) for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next) { if (k->pkt->pkttype == PKT_SIGNATURE) { PKT_signature *sig = k->pkt->pkt.signature; if (IS_KEY_REV (sig) && (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1])) { int rc = check_revocation_keys (ctrl, pk, sig); if (rc == 0) { *r_revoked = 2; sig_to_revoke_info (sig, rinfo); /* Don't continue checking since we can't be any * more revoked than this. */ break; } else if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY) pk->flags.maybe_revoked = 1; /* A failure here means the sig did not verify, was * not issued by a revocation key, or a revocation * key loop was broken. If a revocation key isn't * findable, however, the key might be revoked and * we don't know it. */ /* Fixme: In the future handle subkey and cert * revocations? PGP doesn't, but it's in 2440. */ } } } /* Second pass: Look at the self-signature of all user IDs. */ /* According to RFC 4880 section 11.1, user id and attribute packets * are in the second section, after the public key packet and before * the subkey packets. */ signode = uidnode = NULL; sigdate = 0; /* Helper variable to find the latest signature in one UID. */ for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) { if (k->pkt->pkttype == PKT_USER_ID || k->pkt->pkttype == PKT_ATTRIBUTE) { /* New user id packet. */ /* Apply the data from the most recent self-signed packet to * the preceding user id packet. */ if (uidnode && signode) { fixup_uidnode (uidnode, signode, keytimestamp); pk->flags.valid = 1; } /* Clear SIGNODE. The only relevant self-signed data for * UIDNODE follows it. */ if (k->pkt->pkttype == PKT_USER_ID) uidnode = k; else uidnode = NULL; signode = NULL; sigdate = 0; } else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode) { PKT_signature *sig = k->pkt->pkt.signature; if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1]) { if (check_key_signature (ctrl, keyblock, k, NULL)) ; /* signature did not verify */ else if ((IS_UID_SIG (sig) || IS_UID_REV (sig)) && sig->timestamp >= sigdate) { /* Note: we allow invalidation of cert revocations * by a newer signature. An attacker can't use this * because a key should be revoked with a key revocation. * The reason why we have to allow for that is that at * one time an email address may become invalid but later * the same email address may become valid again (hired, * fired, hired again). */ sigdate = sig->timestamp; signode = k; signode->pkt->pkt.signature->flags.chosen_selfsig = 0; if (sig->version > sigversion) sigversion = sig->version; } } } } if (uidnode && signode) { fixup_uidnode (uidnode, signode, keytimestamp); pk->flags.valid = 1; } /* If the key isn't valid yet, and we have * --allow-non-selfsigned-uid set, then force it valid. */ if (!pk->flags.valid && opt.allow_non_selfsigned_uid) { if (opt.verbose) log_info (_("Invalid key %s made valid by" " --allow-non-selfsigned-uid\n"), keystr_from_pk (pk)); pk->flags.valid = 1; } /* The key STILL isn't valid, so try and find an ultimately * trusted signature. */ if (!pk->flags.valid) { uidnode = NULL; for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) { if (k->pkt->pkttype == PKT_USER_ID) uidnode = k; else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode) { PKT_signature *sig = k->pkt->pkt.signature; if (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1]) { PKT_public_key *ultimate_pk; ultimate_pk = xmalloc_clear (sizeof (*ultimate_pk)); /* We don't want to use the full get_pubkey to avoid * infinite recursion in certain cases. There is no * reason to check that an ultimately trusted key is * still valid - if it has been revoked the user * should also remove the ultimate trust flag. */ if (get_pubkey_fast (ctrl, ultimate_pk, sig->keyid) == 0 && check_key_signature2 (ctrl, keyblock, k, ultimate_pk, NULL, NULL, NULL, NULL) == 0 && get_ownertrust (ctrl, ultimate_pk) == TRUST_ULTIMATE) { free_public_key (ultimate_pk); pk->flags.valid = 1; break; } free_public_key (ultimate_pk); } } } } /* Record the highest selfsig version so we know if this is a v3 key * through and through, or a v3 key with a v4 selfsig somewhere. * This is useful in a few places to know if the key must be treated * as PGP2-style or OpenPGP-style. Note that a selfsig revocation * with a higher version number will also raise this value. This is * okay since such a revocation must be issued by the user (i.e. it * cannot be issued by someone else to modify the key behavior.) */ pk->selfsigversion = sigversion; /* Now that we had a look at all user IDs we can now get some * information from those user IDs. */ if (!key_usage) { /* Find the latest user ID with key flags set. */ uiddate = 0; /* Helper to find the latest user ID. */ for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) { if (k->pkt->pkttype == PKT_USER_ID) { PKT_user_id *uid = k->pkt->pkt.user_id; if (uid->help_key_usage && (uid->created > uiddate || (!uid->created && !uiddate))) { key_usage = uid->help_key_usage; uiddate = uid->created; } } } } if (!key_usage) { /* No key flags at all: get it from the algo. */ key_usage = openpgp_pk_algo_usage (pk->pubkey_algo); } else { /* Check that the usage matches the usage as given by the algo. */ int x = openpgp_pk_algo_usage (pk->pubkey_algo); if (x) /* Mask it down to the actual allowed usage. */ key_usage &= x; } /* Whatever happens, it's a primary key, so it can certify. */ pk->pubkey_usage = key_usage | PUBKEY_USAGE_CERT; if (!key_expire_seen) { /* Find the latest valid user ID with a key expiration set. * This may be a different one than from usage computation above * because some user IDs may have no expiration date set. */ uiddate = 0; for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) { if (k->pkt->pkttype == PKT_USER_ID) { PKT_user_id *uid = k->pkt->pkt.user_id; if (uid->help_key_expire && (uid->created > uiddate || (!uid->created && !uiddate))) { key_expire = uid->help_key_expire; uiddate = uid->created; } } } } /* Currently only the not anymore supported v3 keys have a maximum * expiration date, but future key versions may get this feature again. */ if (key_expire == 0 || (pk->max_expiredate && key_expire > pk->max_expiredate)) key_expire = pk->max_expiredate; pk->has_expired = key_expire >= curtime ? 0 : key_expire; pk->expiredate = key_expire; /* Fixme: we should see how to get rid of the expiretime fields but * this needs changes at other places too. */ /* And now find the real primary user ID and delete all others. */ uiddate = uiddate2 = 0; uidnode = uidnode2 = NULL; for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) { if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data) { PKT_user_id *uid = k->pkt->pkt.user_id; if (uid->flags.primary) { if (uid->created > uiddate) { uiddate = uid->created; uidnode = k; } else if (uid->created == uiddate && uidnode) { /* The dates are equal, so we need to do a different * (and arbitrary) comparison. This should rarely, * if ever, happen. It's good to try and guarantee * that two different GnuPG users with two different * keyrings at least pick the same primary. */ if (cmp_user_ids (uid, uidnode->pkt->pkt.user_id) > 0) uidnode = k; } } else { if (uid->created > uiddate2) { uiddate2 = uid->created; uidnode2 = k; } else if (uid->created == uiddate2 && uidnode2) { if (cmp_user_ids (uid, uidnode2->pkt->pkt.user_id) > 0) uidnode2 = k; } } } } if (uidnode) { for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) { if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data) { PKT_user_id *uid = k->pkt->pkt.user_id; if (k != uidnode) uid->flags.primary = 0; } } } else if (uidnode2) { /* None is flagged primary - use the latest user ID we have, * and disambiguate with the arbitrary packet comparison. */ uidnode2->pkt->pkt.user_id->flags.primary = 1; } else { /* None of our uids were self-signed, so pick the one that * sorts first to be the primary. This is the best we can do * here since there are no self sigs to date the uids. */ uidnode = NULL; for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) { if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data) { if (!uidnode) { uidnode = k; uidnode->pkt->pkt.user_id->flags.primary = 1; continue; } else { if (cmp_user_ids (k->pkt->pkt.user_id, uidnode->pkt->pkt.user_id) > 0) { uidnode->pkt->pkt.user_id->flags.primary = 0; uidnode = k; uidnode->pkt->pkt.user_id->flags.primary = 1; } else { /* just to be safe: */ k->pkt->pkt.user_id->flags.primary = 0; } } } } } } /* Convert a buffer to a signature. Useful for 0x19 embedded sigs. * Caller must free the signature when they are done. */ static PKT_signature * buf_to_sig (const byte * buf, size_t len) { PKT_signature *sig = xmalloc_clear (sizeof (PKT_signature)); IOBUF iobuf = iobuf_temp_with_content (buf, len); int save_mode = set_packet_list_mode (0); if (parse_signature (iobuf, PKT_SIGNATURE, len, sig) != 0) { free_seckey_enc (sig); sig = NULL; } set_packet_list_mode (save_mode); iobuf_close (iobuf); return sig; } /* Use the self-signed data to fill in various fields in subkeys. * * KEYBLOCK is the whole keyblock. SUBNODE is the subkey to fill in. * * Sets the following fields on the subkey: * * main_keyid * flags.valid if the subkey has a valid self-sig binding * flags.revoked * flags.backsig * pubkey_usage * has_expired * expired_date * * On this subkey's most revent valid self-signed packet, the * following field is set: * * flags.chosen_selfsig */ static void merge_selfsigs_subkey (ctrl_t ctrl, kbnode_t keyblock, kbnode_t subnode) { PKT_public_key *mainpk = NULL, *subpk = NULL; PKT_signature *sig; KBNODE k; u32 mainkid[2]; u32 sigdate = 0; KBNODE signode; u32 curtime = make_timestamp (); unsigned int key_usage = 0; u32 keytimestamp = 0; u32 key_expire = 0; const byte *p; if (subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY) BUG (); mainpk = keyblock->pkt->pkt.public_key; if (mainpk->version < 4) return;/* (actually this should never happen) */ keyid_from_pk (mainpk, mainkid); subpk = subnode->pkt->pkt.public_key; keytimestamp = subpk->timestamp; subpk->flags.valid = 0; subpk->flags.exact = 0; subpk->main_keyid[0] = mainpk->main_keyid[0]; subpk->main_keyid[1] = mainpk->main_keyid[1]; /* Find the latest key binding self-signature. */ signode = NULL; sigdate = 0; /* Helper to find the latest signature. */ for (k = subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) { if (k->pkt->pkttype == PKT_SIGNATURE) { sig = k->pkt->pkt.signature; if (sig->keyid[0] == mainkid[0] && sig->keyid[1] == mainkid[1]) { if (check_key_signature (ctrl, keyblock, k, NULL)) ; /* Signature did not verify. */ else if (IS_SUBKEY_REV (sig)) { /* Note that this means that the date on a * revocation sig does not matter - even if the * binding sig is dated after the revocation sig, * the subkey is still marked as revoked. This * seems ok, as it is just as easy to make new * subkeys rather than re-sign old ones as the * problem is in the distribution. Plus, PGP (7) * does this the same way. */ subpk->flags.revoked = 1; sig_to_revoke_info (sig, &subpk->revoked); /* Although we could stop now, we continue to * figure out other information like the old expiration * time. */ } else if (IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate) { if (sig->flags.expired) ; /* Signature has expired - ignore it. */ else { sigdate = sig->timestamp; signode = k; signode->pkt->pkt.signature->flags.chosen_selfsig = 0; } } } } } /* No valid key binding. */ if (!signode) return; sig = signode->pkt->pkt.signature; sig->flags.chosen_selfsig = 1; /* So we know which selfsig we chose later. */ key_usage = parse_key_usage (sig); if (!key_usage) { /* No key flags at all: get it from the algo. */ key_usage = openpgp_pk_algo_usage (subpk->pubkey_algo); } else { /* Check that the usage matches the usage as given by the algo. */ int x = openpgp_pk_algo_usage (subpk->pubkey_algo); if (x) /* Mask it down to the actual allowed usage. */ key_usage &= x; } subpk->pubkey_usage = key_usage; p = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_EXPIRE, NULL); if (p && buf32_to_u32 (p)) key_expire = keytimestamp + buf32_to_u32 (p); else key_expire = 0; subpk->has_expired = key_expire >= curtime ? 0 : key_expire; subpk->expiredate = key_expire; /* Algo doesn't exist. */ if (openpgp_pk_test_algo (subpk->pubkey_algo)) return; subpk->flags.valid = 1; /* Find the most recent 0x19 embedded signature on our self-sig. */ if (!subpk->flags.backsig) { int seq = 0; size_t n; PKT_signature *backsig = NULL; sigdate = 0; /* We do this while() since there may be other embedded * signatures in the future. We only want 0x19 here. */ while ((p = enum_sig_subpkt (sig, 1, SIGSUBPKT_SIGNATURE, &n, &seq, NULL))) if (n > 3 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19))) { PKT_signature *tempsig = buf_to_sig (p, n); if (tempsig) { if (tempsig->timestamp > sigdate) { if (backsig) free_seckey_enc (backsig); backsig = tempsig; sigdate = backsig->timestamp; } else free_seckey_enc (tempsig); } } seq = 0; /* It is safe to have this in the unhashed area since the 0x19 * is located on the selfsig for convenience, not security. */ while ((p = enum_sig_subpkt (sig, 0, SIGSUBPKT_SIGNATURE, &n, &seq, NULL))) if (n > 3 && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19))) { PKT_signature *tempsig = buf_to_sig (p, n); if (tempsig) { if (tempsig->timestamp > sigdate) { if (backsig) free_seckey_enc (backsig); backsig = tempsig; sigdate = backsig->timestamp; } else free_seckey_enc (tempsig); } } if (backsig) { /* At this point, backsig contains the most recent 0x19 sig. * Let's see if it is good. */ /* 2==valid, 1==invalid, 0==didn't check */ if (check_backsig (mainpk, subpk, backsig) == 0) subpk->flags.backsig = 2; else subpk->flags.backsig = 1; free_seckey_enc (backsig); } } } /* Merge information from the self-signatures with the public key, * subkeys and user ids to make using them more easy. * * See documentation for merge_selfsigs_main, merge_selfsigs_subkey * and fixup_uidnode for exactly which fields are updated. */ static void merge_selfsigs (ctrl_t ctrl, kbnode_t keyblock) { KBNODE k; int revoked; struct revoke_info rinfo; PKT_public_key *main_pk; prefitem_t *prefs; unsigned int mdc_feature; unsigned int aead_feature; if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY) { if (keyblock->pkt->pkttype == PKT_SECRET_KEY) { log_error ("expected public key but found secret key " "- must stop\n"); /* We better exit here because a public key is expected at * other places too. FIXME: Figure this out earlier and * don't get to here at all */ g10_exit (1); } BUG (); } merge_selfsigs_main (ctrl, keyblock, &revoked, &rinfo); /* Now merge in the data from each of the subkeys. */ for (k = keyblock; k; k = k->next) { if (k->pkt->pkttype == PKT_PUBLIC_SUBKEY) { merge_selfsigs_subkey (ctrl, keyblock, k); } } main_pk = keyblock->pkt->pkt.public_key; if (revoked || main_pk->has_expired || !main_pk->flags.valid) { /* If the primary key is revoked, expired, or invalid we * better set the appropriate flags on that key and all * subkeys. */ for (k = keyblock; k; k = k->next) { if (k->pkt->pkttype == PKT_PUBLIC_KEY || k->pkt->pkttype == PKT_PUBLIC_SUBKEY) { PKT_public_key *pk = k->pkt->pkt.public_key; if (!main_pk->flags.valid) pk->flags.valid = 0; if (revoked && !pk->flags.revoked) { pk->flags.revoked = revoked; memcpy (&pk->revoked, &rinfo, sizeof (rinfo)); } if (main_pk->has_expired) { pk->has_expired = main_pk->has_expired; if (!pk->expiredate || pk->expiredate > main_pk->expiredate) pk->expiredate = main_pk->expiredate; } } } return; } /* Set the preference list of all keys to those of the primary real * user ID. Note: we use these preferences when we don't know by * which user ID the key has been selected. * fixme: we should keep atoms of commonly used preferences or * use reference counting to optimize the preference lists storage. * FIXME: it might be better to use the intersection of * all preferences. * Do a similar thing for the MDC feature flag. */ prefs = NULL; mdc_feature = aead_feature = 0; for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) { if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data && k->pkt->pkt.user_id->flags.primary) { prefs = k->pkt->pkt.user_id->prefs; mdc_feature = k->pkt->pkt.user_id->flags.mdc; aead_feature = k->pkt->pkt.user_id->flags.aead; break; } } for (k = keyblock; k; k = k->next) { if (k->pkt->pkttype == PKT_PUBLIC_KEY || k->pkt->pkttype == PKT_PUBLIC_SUBKEY) { PKT_public_key *pk = k->pkt->pkt.public_key; if (pk->prefs) xfree (pk->prefs); pk->prefs = copy_prefs (prefs); pk->flags.mdc = mdc_feature; pk->flags.aead = aead_feature; } } } /* See whether the key satisfies any additional requirements specified * in CTX. If so, return the node of an appropriate key or subkey. * Otherwise, return NULL if there was no appropriate key. * * Note that we do not return a reference, i.e. the result must not be * freed using 'release_kbnode'. * * In case the primary key is not required, select a suitable subkey. * We need the primary key if PUBKEY_USAGE_CERT is set in REQ_USAGE or * we are in PGP7 mode and PUBKEY_USAGE_SIG is set in * REQ_USAGE. * * If any of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT * are set in REQ_USAGE, we filter by the key's function. Concretely, * if PUBKEY_USAGE_SIG and PUBKEY_USAGE_CERT are set, then we only * return a key if it is (at least) either a signing or a * certification key. * * If REQ_USAGE is set, then we reject any keys that are not good * (i.e., valid, not revoked, not expired, etc.). This allows the * getkey functions to be used for plain key listings. * * Sets the matched key's user id field (pk->user_id) to the user id * that matched the low-level search criteria or NULL. * * If R_FLAGS is not NULL set certain flags for more detailed error * reporting. Used flags are: * * - LOOKUP_ALL_SUBKEYS_EXPIRED :: All Subkeys are expired or have * been revoked. * - LOOKUP_NOT_SELECTED :: No suitable key found * * This function needs to handle several different cases: * * 1. No requested usage and no primary key requested * Examples for this case are that we have a keyID to be used * for decryption or verification. * 2. No usage but primary key requested * This is the case for all functions which work on an * entire keyblock, e.g. for editing or listing * 3. Usage and primary key requested * FIXME * 4. Usage but no primary key requested * FIXME * */ static kbnode_t finish_lookup (kbnode_t keyblock, unsigned int req_usage, int want_exact, int want_secret, unsigned int *r_flags) { kbnode_t k; /* If WANT_EXACT is set, the key or subkey that actually matched the low-level search criteria. */ kbnode_t foundk = NULL; /* The user id (if any) that matched the low-level search criteria. */ PKT_user_id *foundu = NULL; u32 latest_date; kbnode_t latest_key; PKT_public_key *pk; int req_prim; u32 curtime = make_timestamp (); if (r_flags) *r_flags = 0; #define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT) req_usage &= USAGE_MASK; /* Request the primary if we're certifying another key, and also if * signing data while --pgp7 is on since pgp 7 do * not understand signatures made by a signing subkey. PGP 8 does. */ req_prim = ((req_usage & PUBKEY_USAGE_CERT) || (PGP7 && (req_usage & PUBKEY_USAGE_SIG))); log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY); /* For an exact match mark the primary or subkey that matched the low-level search criteria. */ if (want_exact) { for (k = keyblock; k; k = k->next) { if ((k->flag & 1)) { log_assert (k->pkt->pkttype == PKT_PUBLIC_KEY || k->pkt->pkttype == PKT_PUBLIC_SUBKEY); foundk = k; pk = k->pkt->pkt.public_key; pk->flags.exact = 1; break; } } } /* Get the user id that matched that low-level search criteria. */ for (k = keyblock; k; k = k->next) { if ((k->flag & 2)) { log_assert (k->pkt->pkttype == PKT_USER_ID); foundu = k->pkt->pkt.user_id; break; } } if (DBG_LOOKUP) log_debug ("finish_lookup: checking key %08lX (%s)(req_usage=%x)\n", (ulong) keyid_from_pk (keyblock->pkt->pkt.public_key, NULL), foundk ? "one" : "all", req_usage); if (!req_usage) { latest_key = foundk ? foundk : keyblock; goto found; } latest_date = 0; latest_key = NULL; /* Set LATEST_KEY to the latest (the one with the most recent * timestamp) good (valid, not revoked, not expired, etc.) subkey. * * Don't bother if we are only looking for a primary key or we need * an exact match and the exact match is not a subkey. */ if (req_prim || (foundk && foundk->pkt->pkttype != PKT_PUBLIC_SUBKEY)) ; else { kbnode_t nextk; int n_subkeys = 0; int n_revoked_or_expired = 0; int last_secret_key_avail = 0; /* Either start a loop or check just this one subkey. */ for (k = foundk ? foundk : keyblock; k; k = nextk) { if (foundk) { /* If FOUNDK is not NULL, then only consider that exact key, i.e., don't iterate. */ nextk = NULL; } else nextk = k->next; if (k->pkt->pkttype != PKT_PUBLIC_SUBKEY) continue; pk = k->pkt->pkt.public_key; if (DBG_LOOKUP) log_debug ("\tchecking subkey %08lX\n", (ulong) keyid_from_pk (pk, NULL)); if (!pk->flags.valid) { if (DBG_LOOKUP) log_debug ("\tsubkey not valid\n"); continue; } if (!((pk->pubkey_usage & USAGE_MASK) & req_usage)) { if (DBG_LOOKUP) log_debug ("\tusage does not match: want=%x have=%x\n", req_usage, pk->pubkey_usage); continue; } n_subkeys++; if (pk->flags.revoked) { if (DBG_LOOKUP) log_debug ("\tsubkey has been revoked\n"); n_revoked_or_expired++; continue; } if (pk->has_expired) { if (DBG_LOOKUP) log_debug ("\tsubkey has expired\n"); n_revoked_or_expired++; continue; } if (pk->timestamp > curtime && !opt.ignore_valid_from) { if (DBG_LOOKUP) log_debug ("\tsubkey not yet valid\n"); continue; } if (want_secret) { int secret_key_avail = agent_probe_secret_key (NULL, pk); if (!secret_key_avail) { if (DBG_LOOKUP) log_debug ("\tno secret key\n"); continue; } if (secret_key_avail > last_secret_key_avail) { /* Use this key. */ last_secret_key_avail = secret_key_avail; latest_date = 0; } } if (DBG_LOOKUP) log_debug ("\tsubkey might be fine\n"); /* In case a key has a timestamp of 0 set, we make sure that it is used. A better change would be to compare ">=" but that might also change the selected keys and is as such a more intrusive change. */ if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date)) { latest_date = pk->timestamp; latest_key = k; } } if (n_subkeys == n_revoked_or_expired && r_flags) *r_flags |= LOOKUP_ALL_SUBKEYS_EXPIRED; } /* Check if the primary key is ok (valid, not revoke, not expire, * matches requested usage) if: * * - we didn't find an appropriate subkey and we're not doing an * exact search, * * - we're doing an exact match and the exact match was the * primary key, or, * * - we're just considering the primary key. */ if ((!latest_key && !want_exact) || foundk == keyblock || req_prim) { if (DBG_LOOKUP && !foundk && !req_prim) log_debug ("\tno suitable subkeys found - trying primary\n"); pk = keyblock->pkt->pkt.public_key; if (!pk->flags.valid) { if (DBG_LOOKUP) log_debug ("\tprimary key not valid\n"); } else if (!((pk->pubkey_usage & USAGE_MASK) & req_usage)) { if (DBG_LOOKUP) log_debug ("\tprimary key usage does not match: " "want=%x have=%x\n", req_usage, pk->pubkey_usage); } else if (pk->flags.revoked) { if (DBG_LOOKUP) log_debug ("\tprimary key has been revoked\n"); } else if (pk->has_expired) { if (DBG_LOOKUP) log_debug ("\tprimary key has expired\n"); } else /* Okay. */ { if (DBG_LOOKUP) log_debug ("\tprimary key may be used\n"); latest_key = keyblock; } } if (!latest_key) { if (DBG_LOOKUP) log_debug ("\tno suitable key found - giving up\n"); if (r_flags) *r_flags |= LOOKUP_NOT_SELECTED; return NULL; /* Not found. */ } found: if (DBG_LOOKUP) log_debug ("\tusing key %08lX\n", (ulong) keyid_from_pk (latest_key->pkt->pkt.public_key, NULL)); if (latest_key) { pk = latest_key->pkt->pkt.public_key; free_user_id (pk->user_id); pk->user_id = scopy_user_id (foundu); } if (latest_key != keyblock && opt.verbose) { char *tempkeystr = xstrdup (keystr_from_pk (latest_key->pkt->pkt.public_key)); log_info (_("using subkey %s instead of primary key %s\n"), tempkeystr, keystr_from_pk (keyblock->pkt->pkt.public_key)); xfree (tempkeystr); } cache_put_keyblock (keyblock); return latest_key ? latest_key : keyblock; /* Found. */ } /* Print a KEY_CONSIDERED status line. */ static void print_status_key_considered (kbnode_t keyblock, unsigned int flags) { char hexfpr[2*MAX_FINGERPRINT_LEN + 1]; kbnode_t node; char flagbuf[20]; if (!is_status_enabled ()) return; for (node=keyblock; node; node = node->next) if (node->pkt->pkttype == PKT_PUBLIC_KEY || node->pkt->pkttype == PKT_SECRET_KEY) break; if (!node) { log_error ("%s: keyblock w/o primary key\n", __func__); return; } hexfingerprint (node->pkt->pkt.public_key, hexfpr, sizeof hexfpr); snprintf (flagbuf, sizeof flagbuf, " %u", flags); write_status_strings (STATUS_KEY_CONSIDERED, hexfpr, flagbuf, NULL); } /* A high-level function to lookup keys. * * This function builds on top of the low-level keydb API. It first * searches the database using the description stored in CTX->ITEMS, * then it filters the results using CTX and, finally, if WANT_SECRET * is set, it ignores any keys for which no secret key is available. * * Unlike the low-level search functions, this function also merges * all of the self-signed data into the keys, subkeys and user id * packets (see the merge_selfsigs for details). * * On success the key's keyblock is stored at *RET_KEYBLOCK, and the * specific subkey is stored at *RET_FOUND_KEY. Note that we do not * return a reference in *RET_FOUND_KEY, i.e. the result must not be * freed using 'release_kbnode', and it is only valid until * *RET_KEYBLOCK is deallocated. Therefore, if RET_FOUND_KEY is not * NULL, then RET_KEYBLOCK must not be NULL. */ static int lookup (ctrl_t ctrl, getkey_ctx_t ctx, int want_secret, kbnode_t *ret_keyblock, kbnode_t *ret_found_key) { int rc; int no_suitable_key = 0; KBNODE keyblock = NULL; KBNODE found_key = NULL; unsigned int infoflags; log_assert (ret_found_key == NULL || ret_keyblock != NULL); if (ret_keyblock) *ret_keyblock = NULL; for (;;) { rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems, NULL); if (rc) break; /* If we are iterating over the entire database, then we need to * change from KEYDB_SEARCH_MODE_FIRST, which does an implicit * reset, to KEYDB_SEARCH_MODE_NEXT, which gets the next record. */ if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST) ctx->items->mode = KEYDB_SEARCH_MODE_NEXT; rc = keydb_get_keyblock (ctx->kr_handle, &keyblock); if (rc) { log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc)); goto skip; } if (want_secret) { rc = agent_probe_any_secret_key (NULL, keyblock); if (gpg_err_code(rc) == GPG_ERR_NO_SECKEY) goto skip; /* No secret key available. */ if (rc) goto found; /* Unexpected error. */ } /* Warning: node flag bits 0 and 1 should be preserved by * merge_selfsigs. */ merge_selfsigs (ctrl, keyblock); found_key = finish_lookup (keyblock, ctx->req_usage, ctx->exact, want_secret, &infoflags); print_status_key_considered (keyblock, infoflags); if (found_key) { no_suitable_key = 0; goto found; } else { no_suitable_key = 1; } skip: /* Release resources and continue search. */ release_kbnode (keyblock); keyblock = NULL; /* The keyblock cache ignores the current "file position". * Thus, if we request the next result and the cache matches * (and it will since it is what we just looked for), we'll get * the same entry back! We can avoid this infinite loop by * disabling the cache. */ keydb_disable_caching (ctx->kr_handle); } found: if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND) log_error ("keydb_search failed: %s\n", gpg_strerror (rc)); if (!rc) { if (ret_keyblock) { *ret_keyblock = keyblock; /* Return the keyblock. */ keyblock = NULL; } } else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && no_suitable_key) rc = want_secret? GPG_ERR_UNUSABLE_SECKEY : GPG_ERR_UNUSABLE_PUBKEY; else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND) rc = want_secret? GPG_ERR_NO_SECKEY : GPG_ERR_NO_PUBKEY; release_kbnode (keyblock); if (ret_found_key) { if (! rc) *ret_found_key = found_key; else *ret_found_key = NULL; } return rc; } /* If a default key has been specified, return that key. If a card * based key is also available as indicated by FPR_CARD not being * NULL, return that key if suitable. */ gpg_error_t get_seckey_default_or_card (ctrl_t ctrl, PKT_public_key *pk, const byte *fpr_card, size_t fpr_len) { gpg_error_t err; strlist_t namelist = NULL; const char *def_secret_key; def_secret_key = parse_def_secret_key (ctrl); if (def_secret_key) add_to_strlist (&namelist, def_secret_key); else if (fpr_card) { err = get_pubkey_byfprint (ctrl, pk, NULL, fpr_card, fpr_len); + if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY) + { + if (opt.debug) + log_debug ("using LDAP to find public key for current card\n"); + err = keyserver_import_fprint (ctrl, fpr_card, fpr_len, + opt.keyserver, + KEYSERVER_IMPORT_FLAG_LDAP); + if (!err) + err = get_pubkey_byfprint (ctrl, pk, NULL, fpr_card, fpr_len); + else if (gpg_err_code (err) == GPG_ERR_NO_DATA + || gpg_err_code (err) == GPG_ERR_NO_KEYSERVER) + { + /* Dirmngr returns NO DATA is the selected keyserver + * does not have the requested key. It returns NO + * KEYSERVER if no LDAP keyservers are configured. */ + err = gpg_error (GPG_ERR_NO_PUBKEY); + } + } /* The key on card can be not suitable for requested usage. */ if (gpg_err_code (err) == GPG_ERR_UNUSABLE_PUBKEY) fpr_card = NULL; /* Fallthrough as no card. */ else return err; /* Success or other error. */ } if (!fpr_card || (def_secret_key && *def_secret_key && def_secret_key[strlen (def_secret_key)-1] == '!')) { err = key_byname (ctrl, NULL, namelist, pk, 1, 0, NULL, NULL); } else { /* Default key is specified and card key is also available. */ kbnode_t k, keyblock = NULL; err = key_byname (ctrl, NULL, namelist, pk, 1, 0, &keyblock, NULL); if (err) goto leave; for (k = keyblock; k; k = k->next) { PKT_public_key *pk_candidate; char fpr[MAX_FINGERPRINT_LEN]; if (k->pkt->pkttype != PKT_PUBLIC_KEY &&k->pkt->pkttype != PKT_PUBLIC_SUBKEY) continue; pk_candidate = k->pkt->pkt.public_key; if (!pk_candidate->flags.valid) continue; if (!((pk_candidate->pubkey_usage & USAGE_MASK) & pk->req_usage)) continue; fingerprint_from_pk (pk_candidate, fpr, NULL); if (!memcmp (fpr_card, fpr, fpr_len)) { release_public_key_parts (pk); copy_public_key (pk, pk_candidate); break; } } release_kbnode (keyblock); } leave: free_strlist (namelist); return err; } /********************************************* *********** User ID printing helpers ******* *********************************************/ /* Return a string with a printable representation of the user_id. * this string must be freed by xfree. If R_NOUID is not NULL it is * set to true if a user id was not found; otherwise to false. */ static char * get_user_id_string (ctrl_t ctrl, u32 * keyid, int mode) { char *name; unsigned int namelen; char *p; log_assert (mode != 2); name = cache_get_uid_bykid (keyid, &namelen); if (!name) { /* Get it so that the cache will be filled. */ if (!get_pubkey (ctrl, NULL, keyid)) name = cache_get_uid_bykid (keyid, &namelen); } if (name) { if (mode) p = xasprintf ("%08lX%08lX %.*s", (ulong) keyid[0], (ulong) keyid[1], namelen, name); else p = xasprintf ("%s %.*s", keystr (keyid), namelen, name); xfree (name); } else { if (mode) p = xasprintf ("%08lX%08lX [?]", (ulong) keyid[0], (ulong) keyid[1]); else p = xasprintf ("%s [?]", keystr (keyid)); } return p; } char * get_user_id_string_native (ctrl_t ctrl, u32 * keyid) { char *p = get_user_id_string (ctrl, keyid, 0); char *p2 = utf8_to_native (p, strlen (p), 0); xfree (p); return p2; } char * get_long_user_id_string (ctrl_t ctrl, u32 * keyid) { return get_user_id_string (ctrl, keyid, 1); } /* Please try to use get_user_byfpr instead of this one. */ char * get_user_id (ctrl_t ctrl, u32 *keyid, size_t *rn, int *r_nouid) { char *name; unsigned int namelen; if (r_nouid) *r_nouid = 0; name = cache_get_uid_bykid (keyid, &namelen); if (!name) { /* Get it so that the cache will be filled. */ if (!get_pubkey (ctrl, NULL, keyid)) name = cache_get_uid_bykid (keyid, &namelen); } if (!name) { name = xstrdup (user_id_not_found_utf8 ()); namelen = strlen (name); if (r_nouid) *r_nouid = 1; } if (rn && name) *rn = namelen; return name; } /* Please try to use get_user_id_byfpr_native instead of this one. */ char * get_user_id_native (ctrl_t ctrl, u32 *keyid) { size_t rn; char *p = get_user_id (ctrl, keyid, &rn, NULL); char *p2 = utf8_to_native (p, rn, 0); xfree (p); return p2; } /* Return the user id for a key designated by its fingerprint, FPR, which must be MAX_FINGERPRINT_LEN bytes in size. Note: the returned string, which must be freed using xfree, may not be NUL terminated. To determine the length of the string, you must use *RN. */ static char * get_user_id_byfpr (ctrl_t ctrl, const byte *fpr, size_t fprlen, size_t *rn) { char *name; name = cache_get_uid_byfpr (fpr, fprlen, rn); if (!name) { /* Get it so that the cache will be filled. */ if (!get_pubkey_byfprint (ctrl, NULL, NULL, fpr, fprlen)) name = cache_get_uid_byfpr (fpr, fprlen, rn); } if (!name) { name = xstrdup (user_id_not_found_utf8 ()); *rn = strlen (name); } return name; } /* Like get_user_id_byfpr, but convert the string to the native encoding. The returned string needs to be freed. Unlike get_user_id_byfpr, the returned string is NUL terminated. */ char * get_user_id_byfpr_native (ctrl_t ctrl, const byte *fpr, size_t fprlen) { size_t rn; char *p = get_user_id_byfpr (ctrl, fpr, fprlen, &rn); char *p2 = utf8_to_native (p, rn, 0); xfree (p); return p2; } /* Return the database handle used by this context. The context still owns the handle. */ KEYDB_HANDLE get_ctx_handle (GETKEY_CTX ctx) { return ctx->kr_handle; } static void free_akl (struct akl *akl) { if (! akl) return; if (akl->spec) free_keyserver_spec (akl->spec); xfree (akl); } void release_akl (void) { while (opt.auto_key_locate) { struct akl *akl2 = opt.auto_key_locate; opt.auto_key_locate = opt.auto_key_locate->next; free_akl (akl2); } } /* Returns true if the AKL is empty or has only the local method * active. */ int akl_empty_or_only_local (void) { struct akl *akl; int any = 0; for (akl = opt.auto_key_locate; akl; akl = akl->next) if (akl->type != AKL_NODEFAULT && akl->type != AKL_LOCAL) { any = 1; break; } return !any; } /* Returns false on error. */ int parse_auto_key_locate (const char *options_arg) { char *tok; char *options, *options_buf; options = options_buf = xstrdup (options_arg); while ((tok = optsep (&options))) { struct akl *akl, *check, *last = NULL; int dupe = 0; if (tok[0] == '\0') continue; akl = xmalloc_clear (sizeof (*akl)); if (ascii_strcasecmp (tok, "clear") == 0) { xfree (akl); free_akl (opt.auto_key_locate); opt.auto_key_locate = NULL; continue; } else if (ascii_strcasecmp (tok, "nodefault") == 0) akl->type = AKL_NODEFAULT; else if (ascii_strcasecmp (tok, "local") == 0) akl->type = AKL_LOCAL; else if (ascii_strcasecmp (tok, "ldap") == 0) akl->type = AKL_LDAP; else if (ascii_strcasecmp (tok, "keyserver") == 0) akl->type = AKL_KEYSERVER; else if (ascii_strcasecmp (tok, "cert") == 0) akl->type = AKL_CERT; else if (ascii_strcasecmp (tok, "pka") == 0) akl->type = AKL_PKA; else if (ascii_strcasecmp (tok, "dane") == 0) akl->type = AKL_DANE; else if (ascii_strcasecmp (tok, "wkd") == 0) akl->type = AKL_WKD; else if (ascii_strcasecmp (tok, "ntds") == 0) akl->type = AKL_NTDS; else if ((akl->spec = parse_keyserver_uri (tok, 1))) akl->type = AKL_SPEC; else { free_akl (akl); xfree (options_buf); return 0; } /* We must maintain the order the user gave us */ for (check = opt.auto_key_locate; check; last = check, check = check->next) { /* Check for duplicates */ if (check->type == akl->type && (akl->type != AKL_SPEC || (akl->type == AKL_SPEC && strcmp (check->spec->uri, akl->spec->uri) == 0))) { dupe = 1; free_akl (akl); break; } } if (!dupe) { if (last) last->next = akl; else opt.auto_key_locate = akl; } } xfree (options_buf); return 1; } /* The list of key origins. */ static struct { const char *name; int origin; } key_origin_list[] = { { "self", KEYORG_SELF }, { "file", KEYORG_FILE }, { "url", KEYORG_URL }, { "wkd", KEYORG_WKD }, { "dane", KEYORG_DANE }, { "ks-pref", KEYORG_KS_PREF }, { "ks", KEYORG_KS }, { "unknown", KEYORG_UNKNOWN } }; /* Parse the argument for --key-origin. Return false on error. */ int parse_key_origin (char *string) { int i; char *comma; comma = strchr (string, ','); if (comma) *comma = 0; if (!ascii_strcasecmp (string, "help")) { log_info (_("valid values for option '%s':\n"), "--key-origin"); for (i=0; i < DIM (key_origin_list); i++) log_info (" %s\n", key_origin_list[i].name); g10_exit (1); } for (i=0; i < DIM (key_origin_list); i++) if (!ascii_strcasecmp (string, key_origin_list[i].name)) { opt.key_origin = key_origin_list[i].origin; xfree (opt.key_origin_url); opt.key_origin_url = NULL; if (comma && comma[1]) { opt.key_origin_url = xstrdup (comma+1); trim_spaces (opt.key_origin_url); } return 1; } if (comma) *comma = ','; return 0; } /* Return a string or "?" for the key ORIGIN. */ const char * key_origin_string (int origin) { int i; for (i=0; i < DIM (key_origin_list); i++) if (key_origin_list[i].origin == origin) return key_origin_list[i].name; return "?"; } /* Returns true if a secret key is available for the public key with key id KEYID; returns false if not. This function ignores legacy keys. Note: this is just a fast check and does not tell us whether the secret key is valid; this check merely indicates whether there is some secret key with the specified key id. */ int have_secret_key_with_kid (ctrl_t ctrl, u32 *keyid) { gpg_error_t err; KEYDB_HANDLE kdbhd; KEYDB_SEARCH_DESC desc; kbnode_t keyblock; kbnode_t node; int result = 0; kdbhd = keydb_new (ctrl); if (!kdbhd) return 0; memset (&desc, 0, sizeof desc); desc.mode = KEYDB_SEARCH_MODE_LONG_KID; desc.u.kid[0] = keyid[0]; desc.u.kid[1] = keyid[1]; while (!result) { err = keydb_search (kdbhd, &desc, 1, NULL); if (err) break; err = keydb_get_keyblock (kdbhd, &keyblock); if (err) { log_error (_("error reading keyblock: %s\n"), gpg_strerror (err)); break; } for (node = keyblock; node; node = node->next) { /* Bit 0 of the flags is set if the search found the key using that key or subkey. Note: a search will only ever match a single key or subkey. */ if ((node->flag & 1)) { log_assert (node->pkt->pkttype == PKT_PUBLIC_KEY || node->pkt->pkttype == PKT_PUBLIC_SUBKEY); if (agent_probe_secret_key (NULL, node->pkt->pkt.public_key)) result = 1; /* Secret key available. */ else result = 0; break; } } release_kbnode (keyblock); } keydb_release (kdbhd); return result; } diff --git a/g10/gpgv.c b/g10/gpgv.c index 82fbf8fce..09c694c6a 100644 --- a/g10/gpgv.c +++ b/g10/gpgv.c @@ -1,801 +1,801 @@ /* gpgv.c - The GnuPG signature verify utility * Copyright (C) 1998-2020 Free Software Foundation, Inc. * Copyright (C) 1997-2019 Werner Koch * Copyright (C) 2015-2020 g10 Code GmbH * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . * SPDX-License-Identifier: GPL-3.0-or-later */ #include #include #include #include #include #include #include #ifdef HAVE_DOSISH_SYSTEM #include /* for setmode() */ #endif #ifdef HAVE_LIBREADLINE #define GNUPG_LIBREADLINE_H_INCLUDED #include #endif #define INCLUDED_BY_MAIN_MODULE 1 #include "gpg.h" #include "../common/util.h" #include "packet.h" #include "../common/iobuf.h" #include "main.h" #include "options.h" #include "keydb.h" #include "trustdb.h" #include "filter.h" #include "../common/ttyio.h" #include "../common/i18n.h" #include "../common/sysutils.h" #include "../common/status.h" #include "call-agent.h" #include "../common/init.h" enum cmd_and_opt_values { aNull = 0, oQuiet = 'q', oVerbose = 'v', oOutput = 'o', oBatch = 500, oKeyring, oIgnoreTimeConflict, oStatusFD, oLoggerFD, oLoggerFile, oHomedir, oWeakDigest, oEnableSpecialFilenames, oDebug, aTest }; static gpgrt_opt_t opts[] = { ARGPARSE_group (300, N_("@\nOptions:\n ")), ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")), ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")), ARGPARSE_s_s (oKeyring, "keyring", N_("|FILE|take the keys from the keyring FILE")), ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")), ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", N_("make timestamp conflicts only a warning")), ARGPARSE_s_i (oStatusFD, "status-fd", N_("|FD|write status info to this FD")), ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"), ARGPARSE_s_s (oLoggerFile, "log-file", "@"), ARGPARSE_s_s (oHomedir, "homedir", "@"), ARGPARSE_s_s (oWeakDigest, "weak-digest", N_("|ALGO|reject signatures made with ALGO")), ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"), ARGPARSE_s_s (oDebug, "debug", "@"), ARGPARSE_end () }; /* The list of supported debug flags. */ static struct debug_flags_s debug_flags [] = { { DBG_PACKET_VALUE , "packet" }, { DBG_MPI_VALUE , "mpi" }, { DBG_CRYPTO_VALUE , "crypto" }, { DBG_FILTER_VALUE , "filter" }, { DBG_IOBUF_VALUE , "iobuf" }, { DBG_MEMORY_VALUE , "memory" }, { DBG_CACHE_VALUE , "cache" }, { DBG_MEMSTAT_VALUE, "memstat" }, { DBG_TRUST_VALUE , "trust" }, { DBG_HASHING_VALUE, "hashing" }, { DBG_IPC_VALUE , "ipc" }, { DBG_CLOCK_VALUE , "clock" }, { DBG_LOOKUP_VALUE , "lookup" }, { DBG_EXTPROG_VALUE, "extprog" }, { 0, NULL } }; int g10_errors_seen = 0; static char * make_libversion (const char *libname, const char *(*getfnc)(const char*)) { const char *s; char *result; s = getfnc (NULL); result = xmalloc (strlen (libname) + 1 + strlen (s) + 1); strcpy (stpcpy (stpcpy (result, libname), " "), s); return result; } static const char * my_strusage( int level ) { static char *ver_gcry; const char *p; switch (level) { case 9: p = "GPL-3.0-or-later"; break; case 11: p = "@GPG@v (GnuPG)"; break; case 13: p = VERSION; break; case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break; case 17: p = PRINTABLE_OS_NAME; break; case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break; case 1: case 40: p = _("Usage: gpgv [options] [files] (-h for help)"); break; case 41: p = _("Syntax: gpgv [options] [files]\n" "Check signatures against known trusted keys\n"); break; case 20: if (!ver_gcry) ver_gcry = make_libversion ("libgcrypt", gcry_check_version); p = ver_gcry; break; default: p = NULL; } return p; } int main( int argc, char **argv ) { gpgrt_argparse_t pargs; int rc=0; strlist_t sl; strlist_t nrings = NULL; ctrl_t ctrl; early_system_init (); gpgrt_set_strusage (my_strusage); log_set_prefix ("gpgv", GPGRT_LOG_WITH_PREFIX); /* Make sure that our subsystems are ready. */ i18n_init(); init_common_subsystems (&argc, &argv); gcry_control (GCRYCTL_DISABLE_SECMEM, 0); gnupg_init_signals (0, NULL); opt.command_fd = -1; /* no command fd */ opt.keyserver_options.options |= KEYSERVER_AUTO_KEY_RETRIEVE; opt.trust_model = TM_ALWAYS; opt.no_sig_cache = 1; opt.flags.require_cross_cert = 1; opt.batch = 1; opt.answer_yes = 1; opt.weak_digests = NULL; tty_no_terminal(1); tty_batchmode(1); dotlock_disable (); gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); additional_weak_digest("MD5"); gnupg_initialize_compliance (GNUPG_MODULE_NAME_GPG); pargs.argc = &argc; pargs.argv = &argv; pargs.flags= ARGPARSE_FLAG_KEEP; while (gpgrt_argparser (&pargs, opts, NULL)) { switch (pargs.r_opt) { case ARGPARSE_CONFFILE: break; case oQuiet: opt.quiet = 1; break; case oVerbose: opt.verbose++; opt.list_sigs=1; gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose); break; case oDebug: if (parse_debug_flag (pargs.r.ret_str, &opt.debug, debug_flags)) { pargs.r_opt = ARGPARSE_INVALID_ARG; pargs.err = ARGPARSE_PRINT_ERROR; } break; case oKeyring: append_to_strlist( &nrings, pargs.r.ret_str); break; case oOutput: opt.outfile = pargs.r.ret_str; break; case oStatusFD: set_status_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1)); break; case oLoggerFD: log_set_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1)); break; case oLoggerFile: log_set_file (pargs.r.ret_str); log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID) ); break; case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break; case oWeakDigest: additional_weak_digest(pargs.r.ret_str); break; case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break; case oEnableSpecialFilenames: enable_special_filenames (); break; default : pargs.err = ARGPARSE_PRINT_ERROR; break; } } gpgrt_argparse (NULL, &pargs, NULL); /* Release internal state. */ if (log_get_errorcount (0)) g10_exit(2); if (opt.verbose > 1) set_packet_list_mode(1); /* Note: We open all keyrings in read-only mode. */ if (!nrings) /* No keyring given: use default one. */ keydb_add_resource ("trustedkeys" EXTSEP_S "kbx", (KEYDB_RESOURCE_FLAG_READONLY |KEYDB_RESOURCE_FLAG_GPGVDEF)); for (sl = nrings; sl; sl = sl->next) keydb_add_resource (sl->d, KEYDB_RESOURCE_FLAG_READONLY); FREE_STRLIST (nrings); ctrl = xcalloc (1, sizeof *ctrl); if ((rc = verify_signatures (ctrl, argc, argv))) log_error("verify signatures failed: %s\n", gpg_strerror (rc) ); keydb_release (ctrl->cached_getkey_kdb); xfree (ctrl); /* cleanup */ g10_exit (0); return 8; /*NOTREACHED*/ } void g10_exit( int rc ) { rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0; exit(rc ); } /* Stub: * We have to override the trustcheck from pkclist.c because * this utility assumes that all keys in the keyring are trustworthy */ gpg_error_t check_signatures_trust (ctrl_t ctrl, kbnode_t kblock, PKT_public_key *pk, PKT_signature *sig) { (void)ctrl; (void)kblock; (void)pk; (void)sig; return 0; } void read_trust_options (ctrl_t ctrl, byte *trust_model, ulong *created, ulong *nextcheck, byte *marginals, byte *completes, byte *cert_depth, byte *min_cert_level) { (void)ctrl; (void)trust_model; (void)created; (void)nextcheck; (void)marginals; (void)completes; (void)cert_depth; (void)min_cert_level; } /* Stub: * We don't have the trustdb , so we have to provide some stub functions * instead */ int cache_disabled_value (ctrl_t ctrl, PKT_public_key *pk) { (void)ctrl; (void)pk; return 0; } void check_trustdb_stale (ctrl_t ctrl) { (void)ctrl; } int get_validity_info (ctrl_t ctrl, kbnode_t kb, PKT_public_key *pk, PKT_user_id *uid) { (void)ctrl; (void)kb; (void)pk; (void)uid; return '?'; } unsigned int get_validity (ctrl_t ctrl, kbnode_t kb, PKT_public_key *pk, PKT_user_id *uid, PKT_signature *sig, int may_ask) { (void)ctrl; (void)kb; (void)pk; (void)uid; (void)sig; (void)may_ask; return 0; } const char * trust_value_to_string (unsigned int value) { (void)value; return "err"; } const char * uid_trust_string_fixed (ctrl_t ctrl, PKT_public_key *key, PKT_user_id *uid) { (void)ctrl; (void)key; (void)uid; return "err"; } int get_ownertrust_info (ctrl_t ctrl, PKT_public_key *pk, int no_create) { (void)ctrl; (void)pk; (void)no_create; return '?'; } unsigned int get_ownertrust (ctrl_t ctrl, PKT_public_key *pk) { (void)ctrl; (void)pk; return TRUST_UNKNOWN; } /* Stubs: * Because we only work with trusted keys, it does not make sense to * get them from a keyserver */ struct keyserver_spec * keyserver_match (struct keyserver_spec *spec) { (void)spec; return NULL; } int keyserver_any_configured (ctrl_t ctrl) { (void)ctrl; return 0; } int -keyserver_import_keyid (u32 *keyid, void *dummy, int quick) +keyserver_import_keyid (u32 *keyid, void *dummy, unsigned int flags) { (void)keyid; (void)dummy; - (void)quick; + (void)flags; return -1; } int keyserver_import_fprint (ctrl_t ctrl, const byte *fprint,size_t fprint_len, - struct keyserver_spec *keyserver, int quick) + struct keyserver_spec *keyserver, unsigned int flags) { (void)ctrl; (void)fprint; (void)fprint_len; (void)keyserver; - (void)quick; + (void)flags; return -1; } int keyserver_import_cert (const char *name) { (void)name; return -1; } gpg_error_t -keyserver_import_wkd (ctrl_t ctrl, const char *name, int quick, +keyserver_import_wkd (ctrl_t ctrl, const char *name, unsigned int flags, unsigned char **fpr, size_t *fpr_len) { (void)ctrl; (void)name; - (void)quick; + (void)flags; (void)fpr; (void)fpr_len; return GPG_ERR_BUG; } int keyserver_import_name (const char *name,struct keyserver_spec *spec) { (void)name; (void)spec; return -1; } int keyserver_import_ntds (ctrl_t ctrl, const char *mbox, unsigned char **fpr, size_t *fprlen) { (void)ctrl; (void)mbox; (void)fpr; (void)fprlen; return -1; } int keyserver_import_ldap (const char *name) { (void)name; return -1; } gpg_error_t read_key_from_file_or_buffer (ctrl_t ctrl, const char *fname, const void *buffer, size_t buflen, kbnode_t *r_keyblock) { (void)ctrl; (void)fname; (void)buffer; (void)buflen; (void)r_keyblock; return -1; } gpg_error_t import_included_key_block (ctrl_t ctrl, kbnode_t keyblock) { (void)ctrl; (void)keyblock; return -1; } /* Stub: * No encryption here but mainproc links to these functions. */ gpg_error_t get_session_key (ctrl_t ctrl, struct pubkey_enc_list *k, DEK *dek) { (void)ctrl; (void)k; (void)dek; return GPG_ERR_GENERAL; } /* Stub: */ gpg_error_t get_override_session_key (DEK *dek, const char *string) { (void)dek; (void)string; return GPG_ERR_GENERAL; } /* Stub: */ int decrypt_data (ctrl_t ctrl, void *procctx, PKT_encrypted *ed, DEK *dek) { (void)ctrl; (void)procctx; (void)ed; (void)dek; return GPG_ERR_GENERAL; } /* Stub: * No interactive commands, so we don't need the helptexts */ void display_online_help (const char *keyword) { (void)keyword; } /* Stub: * We don't use secret keys, but getkey.c links to this */ int check_secret_key (PKT_public_key *pk, int n) { (void)pk; (void)n; return GPG_ERR_GENERAL; } /* Stub: * No secret key, so no passphrase needed */ DEK * passphrase_to_dek (int cipher_algo, STRING2KEY *s2k, int create, int nocache, const char *tmp, int *canceled) { (void)cipher_algo; (void)s2k; (void)create; (void)nocache; (void)tmp; if (canceled) *canceled = 0; return NULL; } void passphrase_clear_cache (const char *cacheid) { (void)cacheid; } struct keyserver_spec * parse_preferred_keyserver(PKT_signature *sig) { (void)sig; return NULL; } struct keyserver_spec * parse_keyserver_uri (const char *uri, int require_scheme, const char *configname, unsigned int configlineno) { (void)uri; (void)require_scheme; (void)configname; (void)configlineno; return NULL; } void free_keyserver_spec (struct keyserver_spec *keyserver) { (void)keyserver; } /* Stubs to avoid linking to photoid.c */ void show_photos (const struct user_attribute *attrs, int count, PKT_public_key *pk) { (void)attrs; (void)count; (void)pk; } int parse_image_header (const struct user_attribute *attr, byte *type, u32 *len) { (void)attr; (void)type; (void)len; return 0; } char * image_type_to_string (byte type, int string) { (void)type; (void)string; return NULL; } #ifdef ENABLE_CARD_SUPPORT int agent_scd_getattr (const char *name, struct agent_card_info_s *info) { (void)name; (void)info; return 0; } #endif /* ENABLE_CARD_SUPPORT */ /* We do not do any locking, so use these stubs here */ void dotlock_disable (void) { } dotlock_t dotlock_create (const char *file_to_lock, unsigned int flags) { (void)file_to_lock; (void)flags; return NULL; } void dotlock_destroy (dotlock_t h) { (void)h; } int dotlock_take (dotlock_t h, long timeout) { (void)h; (void)timeout; return 0; } int dotlock_release (dotlock_t h) { (void)h; return 0; } void dotlock_remove_lockfiles (void) { } int agent_probe_secret_key (ctrl_t ctrl, PKT_public_key *pk) { (void)ctrl; (void)pk; return 0; } gpg_error_t agent_probe_any_secret_key (ctrl_t ctrl, kbnode_t keyblock) { (void)ctrl; (void)keyblock; return gpg_error (GPG_ERR_NO_SECKEY); } gpg_error_t agent_get_keyinfo (ctrl_t ctrl, const char *hexkeygrip, char **r_serialno, int *r_cleartext) { (void)ctrl; (void)hexkeygrip; (void)r_cleartext; *r_serialno = NULL; return gpg_error (GPG_ERR_NO_SECKEY); } gpg_error_t export_pubkey_buffer (ctrl_t ctrl, const char *keyspec, unsigned int options, const void *prefix, size_t prefixlen, export_stats_t stats, kbnode_t *r_keyblock, void **r_data, size_t *r_datalen) { (void)ctrl; (void)keyspec; (void)options; (void)prefix; (void)prefixlen; (void)stats; *r_keyblock = NULL; *r_data = NULL; *r_datalen = 0; return gpg_error (GPG_ERR_NOT_IMPLEMENTED); } gpg_error_t tofu_write_tfs_record (ctrl_t ctrl, estream_t fp, PKT_public_key *pk, const char *user_id) { (void)ctrl; (void)fp; (void)pk; (void)user_id; return gpg_error (GPG_ERR_GENERAL); } gpg_error_t tofu_get_policy (ctrl_t ctrl, PKT_public_key *pk, PKT_user_id *user_id, enum tofu_policy *policy) { (void)ctrl; (void)pk; (void)user_id; (void)policy; return gpg_error (GPG_ERR_GENERAL); } const char * tofu_policy_str (enum tofu_policy policy) { (void)policy; return "unknown"; } void tofu_begin_batch_update (ctrl_t ctrl) { (void)ctrl; } void tofu_end_batch_update (ctrl_t ctrl) { (void)ctrl; } gpg_error_t tofu_notice_key_changed (ctrl_t ctrl, kbnode_t kb) { (void) ctrl; (void) kb; return 0; } int get_revocation_reason (PKT_signature *sig, char **r_reason, char **r_comment, size_t *r_commentlen) { (void)sig; (void)r_commentlen; if (r_reason) *r_reason = NULL; if (r_comment) *r_comment = NULL; return 0; } diff --git a/g10/keyserver-internal.h b/g10/keyserver-internal.h index 6d0e7f4ae..ebbd6e914 100644 --- a/g10/keyserver-internal.h +++ b/g10/keyserver-internal.h @@ -1,56 +1,63 @@ /* keyserver-internal.h - Keyserver internals * Copyright (C) 2001, 2002, 2004, 2005, 2006 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #ifndef _KEYSERVER_INTERNAL_H_ #define _KEYSERVER_INTERNAL_H_ #include #include "../common/keyserver.h" #include "../common/iobuf.h" #include "../common/types.h" +/* Flags for the keyserver import functions. */ +#define KEYSERVER_IMPORT_FLAG_QUICK 1 +#define KEYSERVER_IMPORT_FLAG_LDAP 2 + int parse_keyserver_options(char *options); void free_keyserver_spec(struct keyserver_spec *keyserver); struct keyserver_spec *keyserver_match(struct keyserver_spec *spec); struct keyserver_spec *parse_keyserver_uri (const char *string, int require_scheme); struct keyserver_spec *parse_preferred_keyserver(PKT_signature *sig); int keyserver_any_configured (ctrl_t ctrl); int keyserver_export (ctrl_t ctrl, strlist_t users); int keyserver_import (ctrl_t ctrl, strlist_t users); int keyserver_import_fprint (ctrl_t ctrl, const byte *fprint,size_t fprint_len, - struct keyserver_spec *keyserver, int quick); + struct keyserver_spec *keyserver, + unsigned int flags); int keyserver_import_keyid (ctrl_t ctrl, u32 *keyid, - struct keyserver_spec *keyserver, int quick); + struct keyserver_spec *keyserver, + unsigned int flags); gpg_error_t keyserver_refresh (ctrl_t ctrl, strlist_t users); gpg_error_t keyserver_search (ctrl_t ctrl, strlist_t tokens); int keyserver_fetch (ctrl_t ctrl, strlist_t urilist, int origin); int keyserver_import_cert (ctrl_t ctrl, const char *name, int dane_mode, unsigned char **fpr,size_t *fpr_len); -gpg_error_t keyserver_import_wkd (ctrl_t ctrl, const char *name, int quick, +gpg_error_t keyserver_import_wkd (ctrl_t ctrl, const char *name, + unsigned int flags, unsigned char **fpr, size_t *fpr_len); int keyserver_import_ntds (ctrl_t ctrl, const char *name, unsigned char **fpr,size_t *fpr_len); int keyserver_import_name (ctrl_t ctrl, const char *name,unsigned char **fpr,size_t *fpr_len, struct keyserver_spec *keyserver); int keyserver_import_ldap (ctrl_t ctrl, const char *name, unsigned char **fpr,size_t *fpr_len); #endif /* !_KEYSERVER_INTERNAL_H_ */ diff --git a/g10/keyserver.c b/g10/keyserver.c index c4a1d5e19..a0620565c 100644 --- a/g10/keyserver.c +++ b/g10/keyserver.c @@ -1,2173 +1,2176 @@ /* keyserver.c - generic keyserver code * Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, * 2009, 2011, 2012 Free Software Foundation, Inc. * Copyright (C) 2014 Werner Koch * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include #include "gpg.h" #include "../common/iobuf.h" #include "filter.h" #include "keydb.h" #include "../common/status.h" #include "main.h" #include "../common/i18n.h" #include "../common/ttyio.h" #include "options.h" #include "packet.h" #include "trustdb.h" #include "keyserver-internal.h" #include "../common/util.h" #include "../common/membuf.h" #include "../common/mbox-util.h" #include "call-dirmngr.h" #ifdef HAVE_W32_SYSTEM /* It seems Vista doesn't grok X_OK and so fails access() tests. Previous versions interpreted X_OK as F_OK anyway, so we'll just use F_OK directly. */ #undef X_OK #define X_OK F_OK #endif /* HAVE_W32_SYSTEM */ struct keyrec { KEYDB_SEARCH_DESC desc; u32 createtime,expiretime; int size,flags; byte type; IOBUF uidbuf; unsigned int lines; }; /* Parameters for the search line handler. */ struct search_line_handler_parm_s { ctrl_t ctrl; /* The session control structure. */ char *searchstr_disp; /* Native encoded search string or NULL. */ KEYDB_SEARCH_DESC *desc; /* Array with search descriptions. */ int count; /* Number of keys we are currently prepared to handle. This is the size of the DESC array. If it is too small, it will grow safely. */ int validcount; /* Enable the "Key x-y of z" messages. */ int nkeys; /* Number of processed records. */ int any_lines; /* At least one line has been processed. */ unsigned int numlines; /* Counter for displayed lines. */ int eof_seen; /* EOF encountered. */ int not_found; /* Set if no keys have been found. */ }; enum ks_action {KS_UNKNOWN=0,KS_GET,KS_GETNAME,KS_SEND,KS_SEARCH}; static struct parse_options keyserver_opts[]= { /* some of these options are not real - just for the help message */ {"max-cert-size",0,NULL,NULL}, /* MUST be the first in this array! */ {"http-proxy", KEYSERVER_HTTP_PROXY, NULL, /* MUST be the second! */ N_("override proxy options set for dirmngr")}, {"include-revoked",0,NULL,N_("include revoked keys in search results")}, {"include-subkeys",0,NULL,N_("include subkeys when searching by key ID")}, {"timeout", KEYSERVER_TIMEOUT, NULL, N_("override timeout options set for dirmngr")}, {"refresh-add-fake-v3-keyids",KEYSERVER_ADD_FAKE_V3,NULL, NULL}, {"auto-key-retrieve",KEYSERVER_AUTO_KEY_RETRIEVE,NULL, N_("automatically retrieve keys when verifying signatures")}, {"honor-keyserver-url",KEYSERVER_HONOR_KEYSERVER_URL,NULL, N_("honor the preferred keyserver URL set on the key")}, {NULL,0,NULL,NULL} }; static gpg_error_t keyserver_get (ctrl_t ctrl, KEYDB_SEARCH_DESC *desc, int ndesc, struct keyserver_spec *override_keyserver, - int quick, + unsigned int flags, unsigned char **r_fpr, size_t *r_fprlen); static gpg_error_t keyserver_put (ctrl_t ctrl, strlist_t keyspecs); /* Reasonable guess. The commonly used test key simon.josefsson.org is larger than 32k, thus we need at least this value. */ #define DEFAULT_MAX_CERT_SIZE 65536 static size_t max_cert_size=DEFAULT_MAX_CERT_SIZE; static void warn_kshelper_option(char *option, int noisy) { char *p; if ((p=strchr (option, '='))) *p = 0; if (!strcmp (option, "ca-cert-file")) log_info ("keyserver option '%s' is obsolete; please use " "'%s' in dirmngr.conf\n", "ca-cert-file", "hkp-cacert"); else if (!strcmp (option, "check-cert") || !strcmp (option, "broken-http-proxy")) log_info ("keyserver option '%s' is obsolete\n", option); else if (noisy || opt.verbose) log_info ("keyserver option '%s' is unknown\n", option); } /* Called from main to parse the args for --keyserver-options. */ int parse_keyserver_options(char *options) { int ret=1; char *tok; char *max_cert=NULL; keyserver_opts[0].value=&max_cert; keyserver_opts[1].value=&opt.keyserver_options.http_proxy; while((tok=optsep(&options))) { if(tok[0]=='\0') continue; /* We accept quite a few possible options here - some options to handle specially, the keyserver_options list, and import and export options that pertain to keyserver operations. */ if (!parse_options (tok,&opt.keyserver_options.options, keyserver_opts,0) && !parse_import_options(tok,&opt.keyserver_options.import_options,0) && !parse_export_options(tok,&opt.keyserver_options.export_options,0)) { /* All of the standard options have failed, so the option was destined for a keyserver plugin as used by GnuPG < 2.1 */ warn_kshelper_option (tok, 1); } } if(max_cert) { max_cert_size=strtoul(max_cert,(char **)NULL,10); if(max_cert_size==0) max_cert_size=DEFAULT_MAX_CERT_SIZE; } return ret; } void free_keyserver_spec(struct keyserver_spec *keyserver) { xfree(keyserver->uri); xfree(keyserver->scheme); xfree(keyserver->auth); xfree(keyserver->host); xfree(keyserver->port); xfree(keyserver->path); xfree(keyserver->opaque); free_strlist(keyserver->options); xfree(keyserver); } /* Return 0 for match */ static int cmp_keyserver_spec(struct keyserver_spec *one,struct keyserver_spec *two) { if(ascii_strcasecmp(one->scheme,two->scheme)==0) { if(one->host && two->host && ascii_strcasecmp(one->host,two->host)==0) { if((one->port && two->port && ascii_strcasecmp(one->port,two->port)==0) || (!one->port && !two->port)) return 0; } else if(one->opaque && two->opaque && ascii_strcasecmp(one->opaque,two->opaque)==0) return 0; } return 1; } /* Try and match one of our keyservers. If we can, return that. If we can't, return our input. */ struct keyserver_spec * keyserver_match(struct keyserver_spec *spec) { struct keyserver_spec *ks; for(ks=opt.keyserver;ks;ks=ks->next) if(cmp_keyserver_spec(spec,ks)==0) return ks; return spec; } /* TODO: once we cut over to an all-curl world, we don't need this parser any longer so it can be removed, or at least moved to keyserver/ksutil.c for limited use in gpgkeys_ldap or the like. */ keyserver_spec_t parse_keyserver_uri (const char *string,int require_scheme) { int assume_hkp=0; struct keyserver_spec *keyserver; const char *idx; int count; char *uri, *duped_uri, *options; log_assert (string); keyserver=xmalloc_clear(sizeof(struct keyserver_spec)); duped_uri = uri = xstrdup (string); options=strchr(uri,' '); if(options) { char *tok; *options='\0'; options++; while((tok=optsep(&options))) warn_kshelper_option (tok, 0); } /* Get the scheme */ for(idx=uri,count=0;*idx && *idx!=':';idx++) { count++; /* Do we see the start of an RFC-2732 ipv6 address here? If so, there clearly isn't a scheme so get out early. */ if(*idx=='[') { /* Was the '[' the first thing in the string? If not, we have a mangled scheme with a [ in it so fail. */ if(count==1) break; else goto fail; } } if(count==0) goto fail; if(*idx=='\0' || *idx=='[') { if(require_scheme) return NULL; /* Assume HKP if there is no scheme */ assume_hkp=1; keyserver->scheme=xstrdup("hkp"); keyserver->uri=xmalloc(strlen(keyserver->scheme)+3+strlen(uri)+1); strcpy(keyserver->uri,keyserver->scheme); strcat(keyserver->uri,"://"); strcat(keyserver->uri,uri); } else { int i; keyserver->uri=xstrdup(uri); keyserver->scheme=xmalloc(count+1); /* Force to lowercase */ for(i=0;ischeme[i]=ascii_tolower(uri[i]); keyserver->scheme[i]='\0'; /* Skip past the scheme and colon */ uri+=count+1; } if(ascii_strcasecmp(keyserver->scheme,"x-broken-hkp")==0) { log_info ("keyserver option '%s' is obsolete\n", "x-broken-hkp"); } else if(ascii_strcasecmp(keyserver->scheme,"x-hkp")==0) { /* Canonicalize this to "hkp" so it works with both the internal and external keyserver interface. */ xfree(keyserver->scheme); keyserver->scheme=xstrdup("hkp"); } if (uri[0]=='/' && uri[1]=='/' && uri[2] == '/') { /* Three slashes means network path with a default host name. This is a hack because it does not crok all possible combinations. We should better replace all code by the parser from http.c. */ keyserver->path = xstrdup (uri+2); } else if(assume_hkp || (uri[0]=='/' && uri[1]=='/')) { /* Two slashes means network path. */ /* Skip over the "//", if any */ if(!assume_hkp) uri+=2; /* Do we have userinfo auth data present? */ for(idx=uri,count=0;*idx && *idx!='@' && *idx!='/';idx++) count++; /* We found a @ before the slash, so that means everything before the @ is auth data. */ if(*idx=='@') { if(count==0) goto fail; keyserver->auth=xmalloc(count+1); strncpy(keyserver->auth,uri,count); keyserver->auth[count]='\0'; uri+=count+1; } /* Is it an RFC-2732 ipv6 [literal address] ? */ if(*uri=='[') { for(idx=uri+1,count=1;*idx && ((isascii (*idx) && isxdigit(*idx)) || *idx==':' || *idx=='.');idx++) count++; /* Is the ipv6 literal address terminated? */ if(*idx==']') count++; else goto fail; } else for(idx=uri,count=0;*idx && *idx!=':' && *idx!='/';idx++) count++; if(count==0) goto fail; keyserver->host=xmalloc(count+1); strncpy(keyserver->host,uri,count); keyserver->host[count]='\0'; /* Skip past the host */ uri+=count; if(*uri==':') { /* It would seem to be reasonable to limit the range of the ports to values between 1-65535, but RFC 1738 and 1808 imply there is no limit. Of course, the real world has limits. */ for(idx=uri+1,count=0;*idx && *idx!='/';idx++) { count++; /* Ports are digits only */ if(!digitp(idx)) goto fail; } keyserver->port=xmalloc(count+1); strncpy(keyserver->port,uri+1,count); keyserver->port[count]='\0'; /* Skip past the colon and port number */ uri+=1+count; } /* Everything else is the path */ if(*uri) keyserver->path=xstrdup(uri); else keyserver->path=xstrdup("/"); if(keyserver->path[1]) keyserver->flags.direct_uri=1; } else if(uri[0]!='/') { /* No slash means opaque. Just record the opaque blob and get out. */ keyserver->opaque=xstrdup(uri); } else { /* One slash means absolute path. We don't need to support that yet. */ goto fail; } xfree (duped_uri); return keyserver; fail: free_keyserver_spec(keyserver); xfree (duped_uri); return NULL; } struct keyserver_spec * parse_preferred_keyserver(PKT_signature *sig) { struct keyserver_spec *spec=NULL; const byte *p; size_t plen; p = parse_sig_subpkt (sig, 1, SIGSUBPKT_PREF_KS, &plen); if(p && plen) { byte *dupe=xmalloc(plen+1); memcpy(dupe,p,plen); dupe[plen]='\0'; spec = parse_keyserver_uri (dupe, 1); xfree(dupe); } return spec; } static void print_keyrec (ctrl_t ctrl, int number,struct keyrec *keyrec) { iobuf_writebyte(keyrec->uidbuf,0); iobuf_flush_temp(keyrec->uidbuf); es_printf ("(%d)\t%s ", number, iobuf_get_temp_buffer (keyrec->uidbuf)); if (keyrec->size>0) es_printf ("%d bit ", keyrec->size); if(keyrec->type) { const char *str; str = openpgp_pk_algo_name (keyrec->type); if (str && strcmp (str, "?")) es_printf ("%s ",str); else es_printf ("unknown "); } switch(keyrec->desc.mode) { /* If the keyserver helper gave us a short keyid, we have no choice but to use it. Do check --keyid-format to add a 0x if needed. */ case KEYDB_SEARCH_MODE_SHORT_KID: es_printf ("key %s%08lX", (opt.keyid_format==KF_0xSHORT || opt.keyid_format==KF_0xLONG)?"0x":"", (ulong)keyrec->desc.u.kid[1]); break; /* However, if it gave us a long keyid, we can honor --keyid-format via keystr(). */ case KEYDB_SEARCH_MODE_LONG_KID: es_printf ("key %s",keystr(keyrec->desc.u.kid)); break; case KEYDB_SEARCH_MODE_FPR: { u32 kid[2]; keyid_from_fingerprint (ctrl, keyrec->desc.u.fpr, keyrec->desc.fprlen, kid); es_printf("key %s",keystr(kid)); } break; default: BUG(); break; } if(keyrec->createtime>0) { es_printf (", "); es_printf (_("created: %s"), strtimestamp(keyrec->createtime)); } if(keyrec->expiretime>0) { es_printf (", "); es_printf (_("expires: %s"), strtimestamp(keyrec->expiretime)); } if (keyrec->flags&1) es_printf (" (%s)", _("revoked")); if(keyrec->flags&2) es_printf (" (%s)", _("disabled")); if(keyrec->flags&4) es_printf (" (%s)", _("expired")); es_printf ("\n"); } /* Returns a keyrec (which must be freed) once a key is complete, and NULL otherwise. Call with a NULL keystring once key parsing is complete to return any unfinished keys. */ static struct keyrec * parse_keyrec(char *keystring) { /* FIXME: Remove the static and put the data into the parms we use for the caller anyway. */ static struct keyrec *work=NULL; struct keyrec *ret=NULL; char *record; int i; if(keystring==NULL) { if(work==NULL) return NULL; else if(work->desc.mode==KEYDB_SEARCH_MODE_NONE) { xfree(work); return NULL; } else { ret=work; work=NULL; return ret; } } if(work==NULL) { work=xmalloc_clear(sizeof(struct keyrec)); work->uidbuf=iobuf_temp(); } trim_trailing_ws (keystring, strlen (keystring)); if((record=strsep(&keystring,":"))==NULL) return ret; if(ascii_strcasecmp("pub",record)==0) { char *tok; gpg_error_t err; if(work->desc.mode) { ret=work; work=xmalloc_clear(sizeof(struct keyrec)); work->uidbuf=iobuf_temp(); } if((tok=strsep(&keystring,":"))==NULL) return ret; err = classify_user_id (tok, &work->desc, 1); if (err || (work->desc.mode != KEYDB_SEARCH_MODE_SHORT_KID && work->desc.mode != KEYDB_SEARCH_MODE_LONG_KID && work->desc.mode != KEYDB_SEARCH_MODE_FPR)) { work->desc.mode=KEYDB_SEARCH_MODE_NONE; return ret; } /* Note all items after this are optional. This allows us to have a pub line as simple as pub:keyid and nothing else. */ work->lines++; if((tok=strsep(&keystring,":"))==NULL) return ret; work->type=atoi(tok); if((tok=strsep(&keystring,":"))==NULL) return ret; work->size=atoi(tok); if((tok=strsep(&keystring,":"))==NULL) return ret; if(atoi(tok)<=0) work->createtime=0; else work->createtime=atoi(tok); if((tok=strsep(&keystring,":"))==NULL) return ret; if(atoi(tok)<=0) work->expiretime=0; else { work->expiretime=atoi(tok); /* Force the 'e' flag on if this key is expired. */ if(work->expiretime<=make_timestamp()) work->flags|=4; } if((tok=strsep(&keystring,":"))==NULL) return ret; while(*tok) switch(*tok++) { case 'r': case 'R': work->flags|=1; break; case 'd': case 'D': work->flags|=2; break; case 'e': case 'E': work->flags|=4; break; } } else if(ascii_strcasecmp("uid",record)==0 && work->desc.mode) { char *userid,*tok,*decoded; if((tok=strsep(&keystring,":"))==NULL) return ret; if(strlen(tok)==0) return ret; userid=tok; /* By definition, de-%-encoding is always smaller than the original string so we can decode in place. */ i=0; while(*tok) if(tok[0]=='%' && tok[1] && tok[2]) { int c; userid[i] = (c=hextobyte(&tok[1])) == -1 ? '?' : c; i++; tok+=3; } else userid[i++]=*tok++; /* We don't care about the other info provided in the uid: line since no keyserver supports marking userids with timestamps or revoked/expired/disabled yet. */ /* No need to check for control characters, as utf8_to_native does this for us. */ decoded=utf8_to_native(userid,i,0); if(strlen(decoded)>opt.screen_columns-10) decoded[opt.screen_columns-10]='\0'; iobuf_writestr(work->uidbuf,decoded); xfree(decoded); iobuf_writestr(work->uidbuf,"\n\t"); work->lines++; } /* Ignore any records other than "pri" and "uid" for easy future growth. */ return ret; } /* Show a prompt and allow the user to select keys for retrieval. */ static gpg_error_t show_prompt (ctrl_t ctrl, KEYDB_SEARCH_DESC *desc, int numdesc, int count, const char *search) { gpg_error_t err; char *answer = NULL; es_fflush (es_stdout); if (count && opt.command_fd == -1) { static int from = 1; tty_printf ("Keys %d-%d of %d for \"%s\". ", from, numdesc, count, search); from = numdesc + 1; } again: err = 0; xfree (answer); answer = cpr_get_no_help ("keysearch.prompt", _("Enter number(s), N)ext, or Q)uit > ")); /* control-d */ if (answer[0]=='\x04') { tty_printf ("Q\n"); answer[0] = 'q'; } if (answer[0]=='q' || answer[0]=='Q') err = gpg_error (GPG_ERR_CANCELED); else if (atoi (answer) >= 1 && atoi (answer) <= numdesc) { char *split = answer; char *num; int numarray[50]; int numidx = 0; int idx; while ((num = strsep (&split, " ,"))) if (atoi (num) >= 1 && atoi (num) <= numdesc) { if (numidx >= DIM (numarray)) { tty_printf ("Too many keys selected\n"); goto again; } numarray[numidx++] = atoi (num); } if (!numidx) goto again; { KEYDB_SEARCH_DESC *selarray; selarray = xtrymalloc (numidx * sizeof *selarray); if (!selarray) { err = gpg_error_from_syserror (); goto leave; } for (idx = 0; idx < numidx; idx++) selarray[idx] = desc[numarray[idx]-1]; err = keyserver_get (ctrl, selarray, numidx, NULL, 0, NULL, NULL); xfree (selarray); } } leave: xfree (answer); return err; } /* This is a callback used by call-dirmngr.c to process the result of KS_SEARCH command. If SPECIAL is 0, LINE is the actual data line received with all escaping removed and guaranteed to be exactly one line with stripped LF; an EOF is indicated by LINE passed as NULL. If special is 1, the line contains the source of the information (usually an URL). LINE may be modified after return. */ static gpg_error_t search_line_handler (void *opaque, int special, char *line) { struct search_line_handler_parm_s *parm = opaque; gpg_error_t err = 0; struct keyrec *keyrec; if (special == 1) { log_info ("data source: %s\n", line); return 0; } else if (special) { log_debug ("unknown value %d for special search callback", special); return 0; } if (parm->eof_seen && line) { log_debug ("ooops: unexpected data after EOF\n"); line = NULL; } /* Print the received line. */ if (opt.with_colons && line) { es_printf ("%s\n", line); } /* Look for an info: line. The only current info: values defined are the version and key count. */ if (line && !parm->any_lines && !ascii_strncasecmp ("info:", line, 5)) { char *str = line + 5; char *tok; if ((tok = strsep (&str, ":"))) { int version; if (sscanf (tok, "%d", &version) !=1 ) version = 1; if (version !=1 ) { log_error (_("invalid keyserver protocol " "(us %d!=handler %d)\n"), 1, version); return gpg_error (GPG_ERR_UNSUPPORTED_PROTOCOL); } } if ((tok = strsep (&str, ":")) && sscanf (tok, "%d", &parm->count) == 1) { if (!parm->count) parm->not_found = 1;/* Server indicated that no items follow. */ else if (parm->count < 0) parm->count = 10; /* Bad value - assume something reasonable. */ else parm->validcount = 1; /* COUNT seems to be okay. */ } parm->any_lines = 1; return 0; /* Line processing finished. */ } again: if (line) keyrec = parse_keyrec (line); else { /* Received EOF - flush data */ parm->eof_seen = 1; keyrec = parse_keyrec (NULL); if (!keyrec) { if (!parm->nkeys) parm->not_found = 1; /* No keys at all. */ else { if (parm->nkeys != parm->count) parm->validcount = 0; if (!(opt.with_colons && opt.batch)) { err = show_prompt (parm->ctrl, parm->desc, parm->nkeys, parm->validcount? parm->count : 0, parm->searchstr_disp); return err; } } } } /* Save the key in the key array. */ if (keyrec) { /* Allocate or enlarge the key array if needed. */ if (!parm->desc) { if (parm->count < 1) { parm->count = 10; parm->validcount = 0; } parm->desc = xtrymalloc (parm->count * sizeof *parm->desc); if (!parm->desc) { err = gpg_error_from_syserror (); iobuf_close (keyrec->uidbuf); xfree (keyrec); return err; } } else if (parm->nkeys == parm->count) { /* Keyserver sent more keys than claimed in the info: line. */ KEYDB_SEARCH_DESC *tmp; int newcount = parm->count + 10; tmp = xtryrealloc (parm->desc, newcount * sizeof *parm->desc); if (!tmp) { err = gpg_error_from_syserror (); iobuf_close (keyrec->uidbuf); xfree (keyrec); return err; } parm->count = newcount; parm->desc = tmp; parm->validcount = 0; } parm->desc[parm->nkeys] = keyrec->desc; if (!opt.with_colons) { /* SCREEN_LINES - 1 for the prompt. */ if (parm->numlines + keyrec->lines > opt.screen_lines - 1) { err = show_prompt (parm->ctrl, parm->desc, parm->nkeys, parm->validcount ? parm->count:0, parm->searchstr_disp); if (err) return err; parm->numlines = 0; } print_keyrec (parm->ctrl, parm->nkeys+1, keyrec); } parm->numlines += keyrec->lines; iobuf_close (keyrec->uidbuf); xfree (keyrec); parm->any_lines = 1; parm->nkeys++; /* If we are here due to a flush after the EOF, run again for the last prompt. Fixme: Make this code better readable. */ if (parm->eof_seen) goto again; } return 0; } int keyserver_export (ctrl_t ctrl, strlist_t users) { gpg_error_t err; strlist_t sl=NULL; KEYDB_SEARCH_DESC desc; int rc=0; /* Weed out descriptors that we don't support sending */ for(;users;users=users->next) { err = classify_user_id (users->d, &desc, 1); if (err || (desc.mode != KEYDB_SEARCH_MODE_SHORT_KID && desc.mode != KEYDB_SEARCH_MODE_LONG_KID && desc.mode != KEYDB_SEARCH_MODE_FPR)) { log_error(_("\"%s\" not a key ID: skipping\n"),users->d); continue; } else append_to_strlist(&sl,users->d); } if(sl) { rc = keyserver_put (ctrl, sl); free_strlist(sl); } return rc; } /* Structure to convey the arg to keyserver_retrieval_screener. */ struct ks_retrieval_screener_arg_s { KEYDB_SEARCH_DESC *desc; int ndesc; }; /* Check whether a key matches the search description. The function returns 0 if the key shall be imported. */ static gpg_error_t keyserver_retrieval_screener (kbnode_t keyblock, void *opaque) { struct ks_retrieval_screener_arg_s *arg = opaque; KEYDB_SEARCH_DESC *desc = arg->desc; int ndesc = arg->ndesc; kbnode_t node; PKT_public_key *pk; int n; u32 keyid[2]; byte fpr[MAX_FINGERPRINT_LEN]; size_t fpr_len = 0; /* Secret keys are not expected from a keyserver. We do not care about secret subkeys because the import code takes care of skipping them. Not allowing an import of a public key with a secret subkey would make it too easy to inhibit the downloading of a public key. Recall that keyservers do only limited checks. */ node = find_kbnode (keyblock, PKT_SECRET_KEY); if (node) return gpg_error (GPG_ERR_GENERAL); /* Do not import. */ if (!ndesc) return 0; /* Okay if no description given. */ /* Loop over all key packets. */ for (node = keyblock; node; node = node->next) { if (node->pkt->pkttype != PKT_PUBLIC_KEY && node->pkt->pkttype != PKT_PUBLIC_SUBKEY) continue; pk = node->pkt->pkt.public_key; fingerprint_from_pk (pk, fpr, &fpr_len); keyid_from_pk (pk, keyid); /* Compare requested and returned fingerprints if available. */ for (n = 0; n < ndesc; n++) { if (desc[n].mode == KEYDB_SEARCH_MODE_FPR) { if (fpr_len == desc[n].fprlen && !memcmp (fpr, desc[n].u.fpr, desc[n].fprlen)) return 0; } else if (desc[n].mode == KEYDB_SEARCH_MODE_LONG_KID) { if (keyid[0] == desc[n].u.kid[0] && keyid[1] == desc[n].u.kid[1]) return 0; } else if (desc[n].mode == KEYDB_SEARCH_MODE_SHORT_KID) { if (keyid[1] == desc[n].u.kid[1]) return 0; } else /* No keyid or fingerprint - can't check. */ return 0; /* allow import. */ } } return gpg_error (GPG_ERR_GENERAL); } int keyserver_import (ctrl_t ctrl, strlist_t users) { gpg_error_t err; KEYDB_SEARCH_DESC *desc; int num=100,count=0; int rc=0; /* Build a list of key ids */ desc=xmalloc(sizeof(KEYDB_SEARCH_DESC)*num); for(;users;users=users->next) { err = classify_user_id (users->d, &desc[count], 1); if (err || (desc[count].mode != KEYDB_SEARCH_MODE_SHORT_KID && desc[count].mode != KEYDB_SEARCH_MODE_LONG_KID && desc[count].mode != KEYDB_SEARCH_MODE_FPR)) { log_error (_("\"%s\" not a key ID: skipping\n"), users->d); continue; } count++; if(count==num) { num+=100; desc=xrealloc(desc,sizeof(KEYDB_SEARCH_DESC)*num); } } if(count>0) rc = keyserver_get (ctrl, desc, count, NULL, 0, NULL, NULL); xfree(desc); return rc; } /* Return true if any keyserver has been configured. */ int keyserver_any_configured (ctrl_t ctrl) { return !gpg_dirmngr_ks_list (ctrl, NULL); } /* Import all keys that exactly match NAME */ int keyserver_import_name (ctrl_t ctrl, const char *name, unsigned char **fpr, size_t *fprlen, struct keyserver_spec *keyserver) { KEYDB_SEARCH_DESC desc; memset (&desc, 0, sizeof desc); desc.mode = KEYDB_SEARCH_MODE_EXACT; desc.u.name = name; return keyserver_get (ctrl, &desc, 1, keyserver, 0, fpr, fprlen); } /* Import the keys that match exactly MBOX */ int keyserver_import_ntds (ctrl_t ctrl, const char *mbox, unsigned char **fpr, size_t *fprlen) { KEYDB_SEARCH_DESC desc = { 0 }; struct keyserver_spec keyserver = { NULL, "ldap:///" }; desc.mode = KEYDB_SEARCH_MODE_MAIL; desc.u.name = mbox; return keyserver_get (ctrl, &desc, 1, &keyserver, 0, fpr, fprlen); } int keyserver_import_fprint (ctrl_t ctrl, const byte *fprint,size_t fprint_len, - struct keyserver_spec *keyserver, int quick) + struct keyserver_spec *keyserver, + unsigned int flags) { KEYDB_SEARCH_DESC desc; memset(&desc,0,sizeof(desc)); if (fprint_len == 16 || fprint_len == 20 || fprint_len == 32) desc.mode = KEYDB_SEARCH_MODE_FPR; else return -1; memcpy(desc.u.fpr,fprint,fprint_len); desc.fprlen = fprint_len; /* TODO: Warn here if the fingerprint we got doesn't match the one we asked for? */ - return keyserver_get (ctrl, &desc, 1, keyserver, quick, NULL, NULL); + return keyserver_get (ctrl, &desc, 1, keyserver, flags, NULL, NULL); } int keyserver_import_keyid (ctrl_t ctrl, - u32 *keyid,struct keyserver_spec *keyserver, int quick) + u32 *keyid,struct keyserver_spec *keyserver, + unsigned int flags) { KEYDB_SEARCH_DESC desc; memset(&desc,0,sizeof(desc)); desc.mode=KEYDB_SEARCH_MODE_LONG_KID; desc.u.kid[0]=keyid[0]; desc.u.kid[1]=keyid[1]; - return keyserver_get (ctrl, &desc, 1, keyserver, quick, NULL, NULL); + return keyserver_get (ctrl, &desc, 1, keyserver, flags, NULL, NULL); } /* code mostly stolen from do_export_stream */ static int keyidlist (ctrl_t ctrl, strlist_t users, KEYDB_SEARCH_DESC **klist, int *count, int fakev3) { int rc = 0; int num = 100; kbnode_t keyblock = NULL; kbnode_t node; KEYDB_HANDLE kdbhd; int ndesc; KEYDB_SEARCH_DESC *desc = NULL; strlist_t sl; *count=0; *klist=xmalloc(sizeof(KEYDB_SEARCH_DESC)*num); kdbhd = keydb_new (ctrl); if (!kdbhd) { rc = gpg_error_from_syserror (); goto leave; } keydb_disable_caching (kdbhd); /* We are looping the search. */ if(!users) { ndesc = 1; desc = xmalloc_clear ( ndesc * sizeof *desc); desc[0].mode = KEYDB_SEARCH_MODE_FIRST; } else { for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++) ; desc = xmalloc ( ndesc * sizeof *desc); for (ndesc=0, sl=users; sl; sl = sl->next) { gpg_error_t err; if (!(err = classify_user_id (sl->d, desc+ndesc, 1))) ndesc++; else log_error (_("key \"%s\" not found: %s\n"), sl->d, gpg_strerror (err)); } } for (;;) { rc = keydb_search (kdbhd, desc, ndesc, NULL); if (rc) break; /* ready. */ if (!users) desc[0].mode = KEYDB_SEARCH_MODE_NEXT; /* read the keyblock */ rc = keydb_get_keyblock (kdbhd, &keyblock ); if( rc ) { log_error (_("error reading keyblock: %s\n"), gpg_strerror (rc) ); goto leave; } if((node=find_kbnode(keyblock,PKT_PUBLIC_KEY))) { /* This is to work around a bug in some keyservers (pksd and OKS) that calculate v4 RSA keyids as if they were v3 RSA. The answer is to refresh both the correct v4 keyid (e.g. 99242560) and the fake v3 keyid (e.g. 68FDDBC7). This only happens for key refresh using the HKP scheme and if the refresh-add-fake-v3-keyids keyserver option is set. */ if(fakev3 && is_RSA(node->pkt->pkt.public_key->pubkey_algo) && node->pkt->pkt.public_key->version>=4) { (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID; v3_keyid (node->pkt->pkt.public_key->pkey[0], (*klist)[*count].u.kid); (*count)++; if(*count==num) { num+=100; *klist=xrealloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num); } } /* v4 keys get full fingerprints. v3 keys get long keyids. This is because it's easy to calculate any sort of keyid from a v4 fingerprint, but not a v3 fingerprint. */ if (node->pkt->pkt.public_key->version < 4) { (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID; keyid_from_pk(node->pkt->pkt.public_key, (*klist)[*count].u.kid); } else { size_t fprlen; fingerprint_from_pk (node->pkt->pkt.public_key, (*klist)[*count].u.fpr, &fprlen); (*klist)[*count].mode = KEYDB_SEARCH_MODE_FPR; (*klist)[*count].fprlen = fprlen; } /* This is a little hackish, using the skipfncvalue as a void* pointer to the keyserver spec, but we don't need the skipfnc here, and it saves having an additional field for this (which would be wasted space most of the time). */ (*klist)[*count].skipfncvalue=NULL; /* Are we honoring preferred keyservers? */ if(opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL) { PKT_user_id *uid=NULL; PKT_signature *sig=NULL; merge_keys_and_selfsig (ctrl, keyblock); for(node=node->next;node;node=node->next) { if(node->pkt->pkttype==PKT_USER_ID && node->pkt->pkt.user_id->flags.primary) uid=node->pkt->pkt.user_id; else if(node->pkt->pkttype==PKT_SIGNATURE && node->pkt->pkt.signature-> flags.chosen_selfsig && uid) { sig=node->pkt->pkt.signature; break; } } /* Try and parse the keyserver URL. If it doesn't work, then we end up writing NULL which indicates we are the same as any other key. */ if(sig) (*klist)[*count].skipfncvalue=parse_preferred_keyserver(sig); } (*count)++; if(*count==num) { num+=100; *klist=xrealloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num); } } } if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND) rc = 0; leave: if(rc) { xfree(*klist); *klist = NULL; } xfree(desc); keydb_release(kdbhd); release_kbnode(keyblock); return rc; } /* Note this is different than the original HKP refresh. It allows usernames to refresh only part of the keyring. */ gpg_error_t keyserver_refresh (ctrl_t ctrl, strlist_t users) { gpg_error_t err; int count, numdesc; int fakev3 = 0; KEYDB_SEARCH_DESC *desc; unsigned int options=opt.keyserver_options.import_options; /* We switch merge-only on during a refresh, as 'refresh' should never import new keys, even if their keyids match. */ opt.keyserver_options.import_options|=IMPORT_MERGE_ONLY; /* Similarly, we switch on fast-import, since refresh may make multiple import sets (due to preferred keyserver URLs). We don't want each set to rebuild the trustdb. Instead we do it once at the end here. */ opt.keyserver_options.import_options|=IMPORT_FAST; /* If refresh_add_fake_v3_keyids is on and it's a HKP or MAILTO scheme, then enable fake v3 keyid generation. Note that this works only with a keyserver configured. gpg.conf (i.e. opt.keyserver); however that method of configuring a keyserver is deprecated and in any case it is questionable whether we should keep on supporting these ancient and broken keyservers. */ if((opt.keyserver_options.options&KEYSERVER_ADD_FAKE_V3) && opt.keyserver && (ascii_strcasecmp(opt.keyserver->scheme,"hkp")==0 || ascii_strcasecmp(opt.keyserver->scheme,"mailto")==0)) fakev3=1; err = keyidlist (ctrl, users, &desc, &numdesc, fakev3); if (err) return err; count=numdesc; if(count>0) { int i; /* Try to handle preferred keyserver keys first */ for(i=0;iuri); /* We use the keyserver structure we parsed out before. Note that a preferred keyserver without a scheme:// will be interpreted as hkp:// */ err = keyserver_get (ctrl, &desc[i], 1, keyserver, 0, NULL, NULL); if (err) log_info(_("WARNING: unable to refresh key %s" " via %s: %s\n"),keystr_from_desc(&desc[i]), keyserver->uri,gpg_strerror (err)); else { /* We got it, so mark it as NONE so we don't try and get it again from the regular keyserver. */ desc[i].mode=KEYDB_SEARCH_MODE_NONE; count--; } free_keyserver_spec(keyserver); } } } if(count>0) { char *tmpuri; err = gpg_dirmngr_ks_list (ctrl, &tmpuri); if (!err) { if (!opt.quiet) { log_info (ngettext("refreshing %d key from %s\n", "refreshing %d keys from %s\n", count), count, tmpuri); } xfree (tmpuri); err = keyserver_get (ctrl, desc, numdesc, NULL, 0, NULL, NULL); } } xfree(desc); opt.keyserver_options.import_options=options; /* If the original options didn't have fast import, and the trustdb is dirty, rebuild. */ if(!(opt.keyserver_options.import_options&IMPORT_FAST)) check_or_update_trustdb (ctrl); return err; } /* Search for keys on the keyservers. The patterns are given in the string list TOKENS. */ gpg_error_t keyserver_search (ctrl_t ctrl, strlist_t tokens) { gpg_error_t err; char *searchstr; struct search_line_handler_parm_s parm; memset (&parm, 0, sizeof parm); if (!tokens) return 0; /* Return success if no patterns are given. */ /* Write global options */ /* for(temp=opt.keyserver_options.other;temp;temp=temp->next) */ /* es_fprintf(spawn->tochild,"OPTION %s\n",temp->d); */ /* Write per-keyserver options */ /* for(temp=keyserver->options;temp;temp=temp->next) */ /* es_fprintf(spawn->tochild,"OPTION %s\n",temp->d); */ { membuf_t mb; strlist_t item; init_membuf (&mb, 1024); for (item = tokens; item; item = item->next) { if (item != tokens) put_membuf (&mb, " ", 1); put_membuf_str (&mb, item->d); } put_membuf (&mb, "", 1); /* Append Nul. */ searchstr = get_membuf (&mb, NULL); if (!searchstr) { err = gpg_error_from_syserror (); goto leave; } } /* FIXME: Enable the next line */ /* log_info (_("searching for \"%s\" from %s\n"), searchstr, keyserver->uri); */ parm.ctrl = ctrl; if (searchstr) parm.searchstr_disp = utf8_to_native (searchstr, strlen (searchstr), 0); err = gpg_dirmngr_ks_search (ctrl, searchstr, search_line_handler, &parm); if (parm.not_found || gpg_err_code (err) == GPG_ERR_NO_DATA) { if (parm.searchstr_disp) log_info (_("key \"%s\" not found on keyserver\n"), parm.searchstr_disp); else log_info (_("key not found on keyserver\n")); } if (gpg_err_code (err) == GPG_ERR_NO_DATA) err = gpg_error (GPG_ERR_NOT_FOUND); else if (err) log_error ("error searching keyserver: %s\n", gpg_strerror (err)); /* switch(ret) */ /* { */ /* case KEYSERVER_SCHEME_NOT_FOUND: */ /* log_error(_("no handler for keyserver scheme '%s'\n"), */ /* opt.keyserver->scheme); */ /* break; */ /* case KEYSERVER_NOT_SUPPORTED: */ /* log_error(_("action '%s' not supported with keyserver " */ /* "scheme '%s'\n"), "search", opt.keyserver->scheme); */ /* break; */ /* case KEYSERVER_TIMEOUT: */ /* log_error(_("keyserver timed out\n")); */ /* break; */ /* case KEYSERVER_INTERNAL_ERROR: */ /* default: */ /* log_error(_("keyserver internal error\n")); */ /* break; */ /* } */ /* return gpg_error (GPG_ERR_KEYSERVER); */ leave: xfree (parm.desc); xfree (parm.searchstr_disp); xfree(searchstr); return err; } /* Helper for keyserver_get. Here we only receive a chunk of the description to be processed in one batch. This is required due to the limited number of patterns the dirmngr interface (KS_GET) can grok and to limit the amount of temporary required memory. */ static gpg_error_t keyserver_get_chunk (ctrl_t ctrl, KEYDB_SEARCH_DESC *desc, int ndesc, int *r_ndesc_used, import_stats_t stats_handle, struct keyserver_spec *override_keyserver, - int quick, + unsigned int flags, unsigned char **r_fpr, size_t *r_fprlen) { gpg_error_t err = 0; char **pattern; int idx, npat, npat_fpr; estream_t datastream; char *source = NULL; size_t linelen; /* Estimated linelen for KS_GET. */ size_t n; int only_fprs; #define MAX_KS_GET_LINELEN 950 /* Somewhat lower than the real limit. */ *r_ndesc_used = 0; /* Create an array filled with a search pattern for each key. The array is delimited by a NULL entry. */ pattern = xtrycalloc (ndesc+1, sizeof *pattern); if (!pattern) return gpg_error_from_syserror (); /* Note that we break the loop as soon as our estimation of the to be used line length reaches the limit. But we do this only if we have processed at least one search requests so that an overlong single request will be rejected only later by gpg_dirmngr_ks_get but we are sure that R_NDESC_USED has been updated. This avoids a possible indefinite loop. */ - linelen = 17; /* "KS_GET --quick --" */ + linelen = 24; /* "KS_GET --quick --ldap --" */ for (npat=npat_fpr=0, idx=0; idx < ndesc; idx++) { int quiet = 0; if (desc[idx].mode == KEYDB_SEARCH_MODE_FPR) { n = 1+2+2*desc[idx].fprlen; if (idx && linelen + n > MAX_KS_GET_LINELEN) break; /* Declare end of this chunk. */ linelen += n; pattern[npat] = xtrymalloc (n); if (!pattern[npat]) err = gpg_error_from_syserror (); else { strcpy (pattern[npat], "0x"); bin2hex (desc[idx].u.fpr, desc[idx].fprlen, pattern[npat]+2); npat++; if (desc[idx].fprlen == 20 || desc[idx].fprlen == 32) npat_fpr++; } } else if(desc[idx].mode == KEYDB_SEARCH_MODE_LONG_KID) { n = 1+2+16; if (idx && linelen + n > MAX_KS_GET_LINELEN) break; /* Declare end of this chunk. */ linelen += n; pattern[npat] = xtryasprintf ("0x%08lX%08lX", (ulong)desc[idx].u.kid[0], (ulong)desc[idx].u.kid[1]); if (!pattern[npat]) err = gpg_error_from_syserror (); else npat++; } else if(desc[idx].mode == KEYDB_SEARCH_MODE_SHORT_KID) { n = 1+2+8; if (idx && linelen + n > MAX_KS_GET_LINELEN) break; /* Declare end of this chunk. */ linelen += n; pattern[npat] = xtryasprintf ("0x%08lX", (ulong)desc[idx].u.kid[1]); if (!pattern[npat]) err = gpg_error_from_syserror (); else npat++; } else if(desc[idx].mode == KEYDB_SEARCH_MODE_EXACT) { /* The Dirmngr also uses classify_user_id to detect the type of the search string. By adding the '=' prefix we force Dirmngr's KS_GET to consider this an exact search string. (In gpg 1.4 and gpg 2.0 the keyserver helpers used the KS_GETNAME command to indicate this.) */ n = 1+1+strlen (desc[idx].u.name); if (idx && linelen + n > MAX_KS_GET_LINELEN) break; /* Declare end of this chunk. */ linelen += n; pattern[npat] = strconcat ("=", desc[idx].u.name, NULL); if (!pattern[npat]) err = gpg_error_from_syserror (); else { npat++; quiet = 1; } } else if(desc[idx].mode == KEYDB_SEARCH_MODE_MAIL) { n = 1 + strlen (desc[idx].u.name) + 1 + 1; if (idx && linelen + n > MAX_KS_GET_LINELEN) break; /* Declare end of this chunk. */ linelen += n; if (desc[idx].u.name[0] == '<') pattern[npat] = xtrystrdup (desc[idx].u.name); else pattern[npat] = strconcat ("<", desc[idx].u.name, ">", NULL); if (!pattern[npat]) err = gpg_error_from_syserror (); else { npat++; quiet = 1; } } else if (desc[idx].mode == KEYDB_SEARCH_MODE_NONE) continue; else BUG(); if (err) { for (idx=0; idx < npat; idx++) xfree (pattern[idx]); xfree (pattern); return err; } if (!quiet && override_keyserver) { if (override_keyserver->host) log_info (_("requesting key %s from %s server %s\n"), keystr_from_desc (&desc[idx]), override_keyserver->scheme, override_keyserver->host); else log_info (_("requesting key %s from %s\n"), keystr_from_desc (&desc[idx]), override_keyserver->uri); } } /* Remember how many of the search items were considered. Note that this is different from NPAT. */ *r_ndesc_used = idx; only_fprs = (npat && npat == npat_fpr); - err = gpg_dirmngr_ks_get (ctrl, pattern, override_keyserver, quick, + err = gpg_dirmngr_ks_get (ctrl, pattern, override_keyserver, flags, &datastream, &source); for (idx=0; idx < npat; idx++) xfree (pattern[idx]); xfree (pattern); if (opt.verbose && source) log_info ("data source: %s\n", source); if (!err) { struct ks_retrieval_screener_arg_s screenerarg; unsigned int options; /* FIXME: Check whether this comment should be moved to dirmngr. Slurp up all the key data. In the future, it might be nice to look for KEY foo OUTOFBAND and FAILED indicators. It's harmless to ignore them, but ignoring them does make gpg complain about "no valid OpenPGP data found". One way to do this could be to continue parsing this line-by-line and make a temp iobuf for each key. Note that we don't allow the import of secret keys from a keyserver. Keyservers should never accept or send them but we better protect against rogue keyservers. */ /* For LDAP servers we reset IMPORT_SELF_SIGS_ONLY unless it has * been set explicitly. */ options = (opt.keyserver_options.import_options | IMPORT_NO_SECKEY); if (source && (!strncmp (source, "ldap:", 5) || !strncmp (source, "ldaps:", 6)) && !opt.flags.expl_import_self_sigs_only) options &= ~IMPORT_SELF_SIGS_ONLY; screenerarg.desc = desc; screenerarg.ndesc = *r_ndesc_used; import_keys_es_stream (ctrl, datastream, stats_handle, r_fpr, r_fprlen, options, keyserver_retrieval_screener, &screenerarg, only_fprs? KEYORG_KS : 0, source); } es_fclose (datastream); xfree (source); return err; } /* Retrieve a key from a keyserver. The search pattern are in (DESC,NDESC). Allowed search modes are keyid, fingerprint, and exact searches. OVERRIDE_KEYSERVER gives an optional override keyserver. If (R_FPR,R_FPRLEN) are not NULL, they may return the - fingerprint of a single imported key. If QUICK is set, dirmngr is - advised to use a shorter timeout. */ + fingerprint of a single imported key. If the FLAG bit + KEYSERVER_IMPORT_FLAG_QUICK is set, dirmngr is advised to use a + shorter timeout. */ static gpg_error_t keyserver_get (ctrl_t ctrl, KEYDB_SEARCH_DESC *desc, int ndesc, - struct keyserver_spec *override_keyserver, int quick, + struct keyserver_spec *override_keyserver, unsigned int flags, unsigned char **r_fpr, size_t *r_fprlen) { gpg_error_t err; import_stats_t stats_handle; int ndesc_used; int any_good = 0; stats_handle = import_new_stats_handle(); for (;;) { err = keyserver_get_chunk (ctrl, desc, ndesc, &ndesc_used, stats_handle, - override_keyserver, quick, r_fpr, r_fprlen); + override_keyserver, flags, r_fpr, r_fprlen); if (!err) any_good = 1; if (err || ndesc_used >= ndesc) break; /* Error or all processed. */ /* Prepare for the next chunk. */ desc += ndesc_used; ndesc -= ndesc_used; } if (any_good) import_print_stats (stats_handle); import_release_stats_handle (stats_handle); return err; } /* Send all keys specified by KEYSPECS to the configured keyserver. */ static gpg_error_t keyserver_put (ctrl_t ctrl, strlist_t keyspecs) { gpg_error_t err; strlist_t kspec; char *ksurl; if (!keyspecs) return 0; /* Return success if the list is empty. */ if (gpg_dirmngr_ks_list (ctrl, &ksurl)) { log_error (_("no keyserver known\n")); return gpg_error (GPG_ERR_NO_KEYSERVER); } for (kspec = keyspecs; kspec; kspec = kspec->next) { void *data; size_t datalen; kbnode_t keyblock; err = export_pubkey_buffer (ctrl, kspec->d, opt.keyserver_options.export_options, NULL, 0, NULL, &keyblock, &data, &datalen); if (err) log_error (_("skipped \"%s\": %s\n"), kspec->d, gpg_strerror (err)); else { if (!opt.quiet) log_info (_("sending key %s to %s\n"), keystr (keyblock->pkt->pkt.public_key->keyid), ksurl?ksurl:"[?]"); err = gpg_dirmngr_ks_put (ctrl, data, datalen, keyblock); release_kbnode (keyblock); xfree (data); if (err) { write_status_error ("keyserver_send", err); log_error (_("keyserver send failed: %s\n"), gpg_strerror (err)); } } } xfree (ksurl); return err; } /* Loop over all URLs in STRLIST and fetch the key at that URL. Note that the fetch operation ignores the configured keyservers and instead directly retrieves the keys. */ int keyserver_fetch (ctrl_t ctrl, strlist_t urilist, int origin) { gpg_error_t err; strlist_t sl; estream_t datastream; unsigned int save_options = opt.keyserver_options.import_options; /* Switch on fast-import, since fetch can handle more than one import and we don't want each set to rebuild the trustdb. Instead we do it once at the end. */ opt.keyserver_options.import_options |= IMPORT_FAST; for (sl=urilist; sl; sl=sl->next) { if (!opt.quiet) log_info (_("requesting key from '%s'\n"), sl->d); err = gpg_dirmngr_ks_fetch (ctrl, sl->d, &datastream); if (!err) { import_stats_t stats_handle; stats_handle = import_new_stats_handle(); import_keys_es_stream (ctrl, datastream, stats_handle, NULL, NULL, opt.keyserver_options.import_options, NULL, NULL, origin, sl->d); import_print_stats (stats_handle); import_release_stats_handle (stats_handle); } else log_info (_("WARNING: unable to fetch URI %s: %s\n"), sl->d, gpg_strerror (err)); es_fclose (datastream); } opt.keyserver_options.import_options = save_options; /* If the original options didn't have fast import, and the trustdb is dirty, rebuild. */ if (!(opt.keyserver_options.import_options&IMPORT_FAST)) check_or_update_trustdb (ctrl); return 0; } /* Import key in a CERT or pointed to by a CERT. In DANE_MODE fetch the certificate using the DANE method. */ int keyserver_import_cert (ctrl_t ctrl, const char *name, int dane_mode, unsigned char **fpr,size_t *fpr_len) { gpg_error_t err; char *look,*url; estream_t key; look = xstrdup(name); if (!dane_mode) { char *domain = strrchr (look,'@'); if (domain) *domain='.'; } err = gpg_dirmngr_dns_cert (ctrl, look, dane_mode? NULL : "*", &key, fpr, fpr_len, &url); if (err) ; else if (key) { int armor_status=opt.no_armor; import_filter_t save_filt; /* CERTs and DANE records are always in binary format */ opt.no_armor=1; if (dane_mode) { save_filt = save_and_clear_import_filter (); if (!save_filt) err = gpg_error_from_syserror (); else { char *filtstr = es_bsprintf ("keep-uid=mbox = %s", look); err = filtstr? 0 : gpg_error_from_syserror (); if (!err) err = parse_and_set_import_filter (filtstr); xfree (filtstr); if (!err) err = import_keys_es_stream (ctrl, key, NULL, fpr, fpr_len, IMPORT_NO_SECKEY, NULL, NULL, KEYORG_DANE, NULL); restore_import_filter (save_filt); } } else { err = import_keys_es_stream (ctrl, key, NULL, fpr, fpr_len, (opt.keyserver_options.import_options | IMPORT_NO_SECKEY), NULL, NULL, 0, NULL); } opt.no_armor=armor_status; es_fclose (key); key = NULL; } else if (*fpr) { /* We only consider the IPGP type if a fingerprint was provided. This lets us select the right key regardless of what a URL points to, or get the key from a keyserver. */ if(url) { struct keyserver_spec *spec; spec = parse_keyserver_uri (url, 1); if(spec) { err = keyserver_import_fprint (ctrl, *fpr, *fpr_len, spec, 0); free_keyserver_spec(spec); } } else if (keyserver_any_configured (ctrl)) { /* If only a fingerprint is provided, try and fetch it from the configured keyserver. */ err = keyserver_import_fprint (ctrl, *fpr, *fpr_len, opt.keyserver, 0); } else log_info(_("no keyserver known\n")); /* Give a better string here? "CERT fingerprint for \"%s\" found, but no keyserver" " known (use option --keyserver)\n" ? */ } xfree(url); xfree(look); return err; } /* Import a key using the Web Key Directory protocol. */ gpg_error_t -keyserver_import_wkd (ctrl_t ctrl, const char *name, int quick, +keyserver_import_wkd (ctrl_t ctrl, const char *name, unsigned int flags, unsigned char **fpr, size_t *fpr_len) { gpg_error_t err; char *mbox; estream_t key; char *url = NULL; /* We want to work on the mbox. That is what dirmngr will do anyway * and we need the mbox for the import filter anyway. */ mbox = mailbox_from_userid (name, 0); if (!mbox) { err = gpg_error_from_syserror (); if (gpg_err_code (err) == GPG_ERR_EINVAL) err = gpg_error (GPG_ERR_INV_USER_ID); return err; } - err = gpg_dirmngr_wkd_get (ctrl, mbox, quick, &key, &url); + err = gpg_dirmngr_wkd_get (ctrl, mbox, flags, &key, &url); if (err) ; else if (key) { int armor_status = opt.no_armor; import_filter_t save_filt; /* Keys returned via WKD are in binary format. However, we * relax that requirement and allow also for armored data. */ opt.no_armor = 0; save_filt = save_and_clear_import_filter (); if (!save_filt) err = gpg_error_from_syserror (); else { char *filtstr = es_bsprintf ("keep-uid=mbox = %s", mbox); err = filtstr? 0 : gpg_error_from_syserror (); if (!err) err = parse_and_set_import_filter (filtstr); xfree (filtstr); if (!err) err = import_keys_es_stream (ctrl, key, NULL, fpr, fpr_len, IMPORT_NO_SECKEY, NULL, NULL, KEYORG_WKD, url); } restore_import_filter (save_filt); opt.no_armor = armor_status; es_fclose (key); key = NULL; } xfree (url); xfree (mbox); return err; } /* Import a key by name using LDAP */ int keyserver_import_ldap (ctrl_t ctrl, const char *name, unsigned char **fpr, size_t *fprlen) { (void)ctrl; (void)name; (void)fpr; (void)fprlen; return gpg_error (GPG_ERR_NOT_IMPLEMENTED); /*FIXME*/ #if 0 char *domain; struct keyserver_spec *keyserver; strlist_t list=NULL; int rc,hostlen=1; struct srventry *srvlist=NULL; int srvcount,i; char srvname[MAXDNAME]; /* Parse out the domain */ domain=strrchr(name,'@'); if(!domain) return GPG_ERR_GENERAL; domain++; keyserver=xmalloc_clear(sizeof(struct keyserver_spec)); keyserver->scheme=xstrdup("ldap"); keyserver->host=xmalloc(1); keyserver->host[0]='\0'; snprintf(srvname,MAXDNAME,"_pgpkey-ldap._tcp.%s",domain); FIXME("network related - move to dirmngr or drop the code"); srvcount=getsrv(srvname,&srvlist); for(i=0;ihost=xrealloc(keyserver->host,hostlen); strcat(keyserver->host,srvlist[i].target); if(srvlist[i].port!=389) { char port[7]; hostlen+=6; /* a colon, plus 5 digits (unsigned 16-bit value) */ keyserver->host=xrealloc(keyserver->host,hostlen); snprintf(port,7,":%u",srvlist[i].port); strcat(keyserver->host,port); } strcat(keyserver->host," "); } free(srvlist); /* If all else fails, do the PGP Universal trick of ldap://keys.(domain) */ hostlen+=5+strlen(domain); keyserver->host=xrealloc(keyserver->host,hostlen); strcat(keyserver->host,"keys."); strcat(keyserver->host,domain); append_to_strlist(&list,name); rc = gpg_error (GPG_ERR_NOT_IMPLEMENTED); /*FIXME*/ /* keyserver_work (ctrl, KS_GETNAME, list, NULL, */ /* 0, fpr, fpr_len, keyserver); */ free_strlist(list); free_keyserver_spec(keyserver); return rc; #endif } diff --git a/g10/mainproc.c b/g10/mainproc.c index a75755ee3..10cc69758 100644 --- a/g10/mainproc.c +++ b/g10/mainproc.c @@ -1,2714 +1,2717 @@ /* mainproc.c - handle packets * Copyright (C) 1998-2009 Free Software Foundation, Inc. * Copyright (C) 2013-2014 Werner Koch * Copyright (C) 2020 g10 Code GmbH * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include "gpg.h" #include "../common/util.h" #include "packet.h" #include "../common/iobuf.h" #include "options.h" #include "keydb.h" #include "filter.h" #include "main.h" #include "../common/status.h" #include "../common/i18n.h" #include "trustdb.h" #include "keyserver-internal.h" #include "photoid.h" #include "../common/mbox-util.h" #include "call-dirmngr.h" #include "../common/compliance.h" /* Put an upper limit on nested packets. The 32 is an arbitrary value, a much lower should actually be sufficient. */ #define MAX_NESTING_DEPTH 32 /* * Object to hold the processing context. */ typedef struct mainproc_context *CTX; struct mainproc_context { ctrl_t ctrl; struct mainproc_context *anchor; /* May be useful in the future. */ PKT_public_key *last_pubkey; PKT_user_id *last_user_id; md_filter_context_t mfx; int sigs_only; /* Process only signatures and reject all other stuff. */ int encrypt_only; /* Process only encryption messages. */ /* Name of the file with the complete signature or the file with the detached signature. This is currently only used to deduce the file name of the data file if that has not been given. */ const char *sigfilename; /* A structure to describe the signed data in case of a detached signature. */ struct { /* A file descriptor of the signed data. Only used if not -1. */ int data_fd; /* A list of filenames with the data files or NULL. This is only used if DATA_FD is -1. */ strlist_t data_names; /* Flag to indicated that either one of the next previous fields is used. This is only needed for better readability. */ int used; } signed_data; DEK *dek; int last_was_session_key; kbnode_t list; /* The current list of packets. */ iobuf_t iobuf; /* Used to get the filename etc. */ int trustletter; /* Temporary usage in list_node. */ ulong symkeys; /* Number of symmetrically encrypted session keys. */ struct pubkey_enc_list *pkenc_list; /* List of encryption packets. */ int seen_pkt_encrypted_aead; /* PKT_ENCRYPTED_AEAD packet seen. */ struct { unsigned int sig_seen:1; /* Set to true if a signature packet has been seen. */ unsigned int data:1; /* Any data packet seen */ unsigned int uncompress_failed:1; } any; }; /* Counter with the number of literal data packets seen. Note that * this is also bumped at the end of an encryption. This counter is * used for a basic consistency check of a received PGP message. */ static int literals_seen; /*** Local prototypes. ***/ static int do_proc_packets (CTX c, iobuf_t a); static void list_node (CTX c, kbnode_t node); static void proc_tree (CTX c, kbnode_t node); /*** Functions. ***/ /* Reset the literal data counter. This is required to setup a new * decryption or verification context. */ void reset_literals_seen(void) { literals_seen = 0; } static void release_list( CTX c ) { proc_tree (c, c->list); release_kbnode (c->list); while (c->pkenc_list) { struct pubkey_enc_list *tmp = c->pkenc_list->next; mpi_release (c->pkenc_list->data[0]); mpi_release (c->pkenc_list->data[1]); xfree (c->pkenc_list); c->pkenc_list = tmp; } c->pkenc_list = NULL; c->list = NULL; c->any.data = 0; c->any.uncompress_failed = 0; c->last_was_session_key = 0; c->seen_pkt_encrypted_aead = 0; xfree (c->dek); c->dek = NULL; } static int add_onepass_sig (CTX c, PACKET *pkt) { kbnode_t node; if (c->list) /* Add another packet. */ add_kbnode (c->list, new_kbnode (pkt)); else /* Insert the first one. */ c->list = node = new_kbnode (pkt); return 1; } static int add_gpg_control (CTX c, PACKET *pkt) { if ( pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START ) { /* New clear text signature. * Process the last one and reset everything */ release_list(c); } if (c->list) /* Add another packet. */ add_kbnode (c->list, new_kbnode (pkt)); else /* Insert the first one. */ c->list = new_kbnode (pkt); return 1; } static int add_user_id (CTX c, PACKET *pkt) { if (!c->list) { log_error ("orphaned user ID\n"); return 0; } add_kbnode (c->list, new_kbnode (pkt)); return 1; } static int add_subkey (CTX c, PACKET *pkt) { if (!c->list) { log_error ("subkey w/o mainkey\n"); return 0; } add_kbnode (c->list, new_kbnode (pkt)); return 1; } static int add_ring_trust (CTX c, PACKET *pkt) { if (!c->list) { log_error ("ring trust w/o key\n"); return 0; } add_kbnode (c->list, new_kbnode (pkt)); return 1; } static int add_signature (CTX c, PACKET *pkt) { kbnode_t node; c->any.sig_seen = 1; if (pkt->pkttype == PKT_SIGNATURE && !c->list) { /* This is the first signature for the following datafile. * GPG does not write such packets; instead it always uses * onepass-sig packets. The drawback of PGP's method * of prepending the signature to the data is * that it is not possible to make a signature from data read * from stdin. (GPG is able to read PGP stuff anyway.) */ node = new_kbnode (pkt); c->list = node; return 1; } else if (!c->list) return 0; /* oops (invalid packet sequence)*/ else if (!c->list->pkt) BUG(); /* so nicht */ /* Add a new signature node item at the end. */ node = new_kbnode (pkt); add_kbnode (c->list, node); return 1; } static gpg_error_t symkey_decrypt_seskey (DEK *dek, byte *seskey, size_t slen) { gpg_error_t err; gcry_cipher_hd_t hd; unsigned int noncelen, keylen; enum gcry_cipher_modes ciphermode; if (dek->use_aead) { err = openpgp_aead_algo_info (dek->use_aead, &ciphermode, &noncelen); if (err) return err; } else { ciphermode = GCRY_CIPHER_MODE_CFB; noncelen = 0; } /* Check that the session key has a size of 16 to 32 bytes. */ if ((dek->use_aead && (slen < (noncelen + 16 + 16) || slen > (noncelen + 32 + 16))) || (!dek->use_aead && (slen < 17 || slen > 33))) { log_error ( _("weird size for an encrypted session key (%d)\n"), (int)slen); return gpg_error (GPG_ERR_BAD_KEY); } err = openpgp_cipher_open (&hd, dek->algo, ciphermode, GCRY_CIPHER_SECURE); if (!err) err = gcry_cipher_setkey (hd, dek->key, dek->keylen); if (!err) err = gcry_cipher_setiv (hd, noncelen? seskey : NULL, noncelen); if (err) goto leave; if (dek->use_aead) { byte ad[4]; ad[0] = (0xc0 | PKT_SYMKEY_ENC); ad[1] = 5; ad[2] = dek->algo; ad[3] = dek->use_aead; err = gcry_cipher_authenticate (hd, ad, 4); if (err) goto leave; gcry_cipher_final (hd); keylen = slen - noncelen - 16; err = gcry_cipher_decrypt (hd, seskey+noncelen, keylen, NULL, 0); if (err) goto leave; err = gcry_cipher_checktag (hd, seskey+noncelen+keylen, 16); if (err) goto leave; /* Now we replace the dek components with the real session key to * decrypt the contents of the sequencing packet. */ if (keylen > DIM(dek->key)) { err = gpg_error (GPG_ERR_TOO_LARGE); goto leave; } dek->keylen = keylen; memcpy (dek->key, seskey + noncelen, dek->keylen); } else { gcry_cipher_decrypt (hd, seskey, slen, NULL, 0 ); /* Here we can only test whether the algo given in decrypted * session key is a valid OpenPGP algo. With 11 defined * symmetric algorithms we will miss 4.3% of wrong passphrases * here. The actual checking is done later during bulk * decryption; we can't bring this check forward easily. We * need to use the GPG_ERR_CHECKSUM so that we won't run into * the gnupg < 2.2 bug compatible case which would terminate the * process on GPG_ERR_CIPHER_ALGO. Note that with AEAD (above) * we will have a reliable test here. */ if (openpgp_cipher_test_algo (seskey[0]) || openpgp_cipher_get_algo_keylen (seskey[0]) != slen - 1) { err = gpg_error (GPG_ERR_CHECKSUM); goto leave; } /* Now we replace the dek components with the real session key to * decrypt the contents of the sequencing packet. */ keylen = slen-1; if (keylen > DIM(dek->key)) { err = gpg_error (GPG_ERR_TOO_LARGE); goto leave; } dek->algo = seskey[0]; dek->keylen = keylen; memcpy (dek->key, seskey + 1, dek->keylen); } /*log_hexdump( "thekey", dek->key, dek->keylen );*/ leave: gcry_cipher_close (hd); return err; } static void proc_symkey_enc (CTX c, PACKET *pkt) { gpg_error_t err; PKT_symkey_enc *enc; enc = pkt->pkt.symkey_enc; if (!enc) log_error ("invalid symkey encrypted packet\n"); else if(!c->dek) { int algo = enc->cipher_algo; const char *s = openpgp_cipher_algo_name (algo); const char *a = (enc->aead_algo ? openpgp_aead_algo_name (enc->aead_algo) /**/ : "CFB"); if (!openpgp_cipher_test_algo (algo)) { if (!opt.quiet) { if (enc->seskeylen) log_info (_("%s.%s encrypted session key\n"), s, a ); else log_info (_("%s.%s encrypted data\n"), s, a ); } } else { log_error (_("encrypted with unknown algorithm %d.%s\n"), algo, a); s = NULL; /* Force a goto leave. */ } if (openpgp_md_test_algo (enc->s2k.hash_algo)) { log_error(_("passphrase generated with unknown digest" " algorithm %d\n"),enc->s2k.hash_algo); s = NULL; } c->last_was_session_key = 2; if (!s || opt.list_only) goto leave; if (opt.override_session_key) { c->dek = xmalloc_clear (sizeof *c->dek); if (get_override_session_key (c->dek, opt.override_session_key)) { xfree (c->dek); c->dek = NULL; } } else { c->dek = passphrase_to_dek (algo, &enc->s2k, 0, 0, NULL, NULL); if (c->dek) { c->dek->symmetric = 1; c->dek->use_aead = enc->aead_algo; /* FIXME: This doesn't work perfectly if a symmetric key comes before a public key in the message - if the user doesn't know the passphrase, then there is a chance that the "decrypted" algorithm will happen to be a valid one, which will make the returned dek appear valid, so we won't try any public keys that come later. */ if (enc->seskeylen) { err = symkey_decrypt_seskey (c->dek, enc->seskey, enc->seskeylen); if (err) { log_info ("decryption of the symmetrically encrypted" " session key failed: %s\n", gpg_strerror (err)); if (gpg_err_code (err) != GPG_ERR_BAD_KEY && gpg_err_code (err) != GPG_ERR_CHECKSUM) log_fatal ("process terminated to be bug compatible" " with GnuPG <= 2.2\n"); if (c->dek->s2k_cacheid[0]) { if (opt.debug) log_debug ("cleared passphrase cached with ID:" " %s\n", c->dek->s2k_cacheid); passphrase_clear_cache (c->dek->s2k_cacheid); } xfree (c->dek); c->dek = NULL; } } else c->dek->algo_info_printed = 1; } } } leave: c->symkeys++; free_packet (pkt, NULL); } static void proc_pubkey_enc (CTX c, PACKET *pkt) { PKT_pubkey_enc *enc; /* Check whether the secret key is available and store in this case. */ c->last_was_session_key = 1; enc = pkt->pkt.pubkey_enc; /*printf("enc: encrypted by a pubkey with keyid %08lX\n", enc->keyid[1] );*/ /* Hmmm: why do I have this algo check here - anyway there is * function to check it. */ if (opt.verbose) log_info (_("public key is %s\n"), keystr (enc->keyid)); if (is_status_enabled ()) { char buf[50]; snprintf (buf, sizeof buf, "%08lX%08lX %d 0", (ulong)enc->keyid[0], (ulong)enc->keyid[1], enc->pubkey_algo); write_status_text (STATUS_ENC_TO, buf); } if (!opt.list_only && !opt.override_session_key) { struct pubkey_enc_list *x = xmalloc (sizeof *x); x->keyid[0] = enc->keyid[0]; x->keyid[1] = enc->keyid[1]; x->pubkey_algo = enc->pubkey_algo; x->result = -1; x->data[0] = x->data[1] = NULL; if (enc->data[0]) { x->data[0] = mpi_copy (enc->data[0]); x->data[1] = mpi_copy (enc->data[1]); } x->next = c->pkenc_list; c->pkenc_list = x; } free_packet(pkt, NULL); } /* * Print the list of public key encrypted packets which we could * not decrypt. */ static void print_pkenc_list (ctrl_t ctrl, struct pubkey_enc_list *list) { for (; list; list = list->next) { PKT_public_key *pk; char pkstrbuf[PUBKEY_STRING_SIZE]; char *p; pk = xmalloc_clear (sizeof *pk); pk->pubkey_algo = list->pubkey_algo; if (!get_pubkey (ctrl, pk, list->keyid)) { pubkey_string (pk, pkstrbuf, sizeof pkstrbuf); log_info (_("encrypted with %s key, ID %s, created %s\n"), pkstrbuf, keystr_from_pk (pk), strtimestamp (pk->timestamp)); p = get_user_id_native (ctrl, list->keyid); log_printf (_(" \"%s\"\n"), p); xfree (p); } else log_info (_("encrypted with %s key, ID %s\n"), openpgp_pk_algo_name (list->pubkey_algo), keystr(list->keyid)); free_public_key (pk); } } static void proc_encrypted (CTX c, PACKET *pkt) { int result = 0; int early_plaintext = literals_seen; if (pkt->pkttype == PKT_ENCRYPTED_AEAD) c->seen_pkt_encrypted_aead = 1; if (early_plaintext) { log_info (_("WARNING: multiple plaintexts seen\n")); write_status_errcode ("decryption.early_plaintext", GPG_ERR_BAD_DATA); /* We fail only later so that we can print some more info first. */ } if (!opt.quiet) { if (c->symkeys>1) log_info (_("encrypted with %lu passphrases\n"), c->symkeys); else if (c->symkeys == 1) log_info (_("encrypted with 1 passphrase\n")); print_pkenc_list (c->ctrl, c->pkenc_list); } /* Figure out the session key by looking at all pkenc packets. */ if (opt.list_only || c->dek) ; else if (opt.override_session_key) { c->dek = xmalloc_clear (sizeof *c->dek); result = get_override_session_key (c->dek, opt.override_session_key); if (result) { xfree (c->dek); c->dek = NULL; log_info (_("public key decryption failed: %s\n"), gpg_strerror (result)); write_status_error ("pkdecrypt_failed", result); } } else if (c->pkenc_list) { c->dek = xmalloc_secure_clear (sizeof *c->dek); result = get_session_key (c->ctrl, c->pkenc_list, c->dek); if (is_status_enabled ()) { struct pubkey_enc_list *list; for (list = c->pkenc_list; list; list = list->next) if (list->result && list->result != -1) { char buf[20]; snprintf (buf, sizeof buf, "%08lX%08lX", (ulong)list->keyid[0], (ulong)list->keyid[1]); write_status_text (STATUS_NO_SECKEY, buf); } } if (result) { log_info (_("public key decryption failed: %s\n"), gpg_strerror (result)); write_status_error ("pkdecrypt_failed", result); /* Error: Delete the DEK. */ xfree (c->dek); c->dek = NULL; } } if (c->dek && opt.verbose > 1) log_info (_("public key encrypted data: good DEK\n")); write_status (STATUS_BEGIN_DECRYPTION); /*log_debug("dat: %sencrypted data\n", c->dek?"":"conventional ");*/ if (opt.list_only) result = -1; else if (!c->dek && !c->last_was_session_key) { int algo; STRING2KEY s2kbuf; STRING2KEY *s2k = NULL; int canceled; if (opt.override_session_key) { c->dek = xmalloc_clear (sizeof *c->dek); result = get_override_session_key (c->dek, opt.override_session_key); if (result) { xfree (c->dek); c->dek = NULL; } } else { /* Assume this is old style conventional encrypted data. */ algo = opt.def_cipher_algo; if (algo) log_info (_("assuming %s encrypted data\n"), openpgp_cipher_algo_name (algo)); else if (openpgp_cipher_test_algo (CIPHER_ALGO_IDEA)) { algo = opt.def_cipher_algo; if (!algo) algo = opt.s2k_cipher_algo; log_info (_("IDEA cipher unavailable, " "optimistically attempting to use %s instead\n"), openpgp_cipher_algo_name (algo)); } else { algo = CIPHER_ALGO_IDEA; if (!opt.s2k_digest_algo) { /* If no digest is given we assume SHA-1. */ s2kbuf.mode = 0; s2kbuf.hash_algo = DIGEST_ALGO_SHA1; s2k = &s2kbuf; } log_info (_("assuming %s encrypted data\n"), "IDEA"); } c->dek = passphrase_to_dek (algo, s2k, 0, 0, NULL, &canceled); if (c->dek) c->dek->algo_info_printed = 1; else if (canceled) result = gpg_error (GPG_ERR_CANCELED); else result = gpg_error (GPG_ERR_INV_PASSPHRASE); } } else if (!c->dek) { if (c->symkeys && !c->pkenc_list) result = gpg_error (GPG_ERR_BAD_KEY); if (!result) result = gpg_error (GPG_ERR_NO_SECKEY); } /* Compute compliance with CO_DE_VS. */ if (!result && is_status_enabled () /* Symmetric encryption and asymmetric encryption voids compliance. */ && (c->symkeys != !!c->pkenc_list ) /* Overriding session key voids compliance. */ && !opt.override_session_key /* Check symmetric cipher. */ && gnupg_gcrypt_is_compliant (CO_DE_VS) && gnupg_cipher_is_compliant (CO_DE_VS, c->dek->algo, GCRY_CIPHER_MODE_CFB)) { struct pubkey_enc_list *i; int compliant = 1; PKT_public_key *pk = xmalloc (sizeof *pk); if ( !(c->pkenc_list || c->symkeys) ) log_debug ("%s: where else did the session key come from?\n", __func__); /* Now check that every key used to encrypt the session key is * compliant. */ for (i = c->pkenc_list; i && compliant; i = i->next) { memset (pk, 0, sizeof *pk); pk->pubkey_algo = i->pubkey_algo; if (get_pubkey (c->ctrl, pk, i->keyid) != 0 || ! gnupg_pk_is_compliant (CO_DE_VS, pk->pubkey_algo, 0, pk->pkey, nbits_from_pk (pk), NULL)) compliant = 0; release_public_key_parts (pk); } xfree (pk); if (compliant) write_status_strings (STATUS_DECRYPTION_COMPLIANCE_MODE, gnupg_status_compliance_flag (CO_DE_VS), NULL); } if (!result) result = decrypt_data (c->ctrl, c, pkt->pkt.encrypted, c->dek ); /* Trigger the deferred error. */ if (!result && early_plaintext) result = gpg_error (GPG_ERR_BAD_DATA); if (result == -1) ; else if (!result && !opt.ignore_mdc_error && !pkt->pkt.encrypted->mdc_method && !pkt->pkt.encrypted->aead_algo) { /* The message has been decrypted but does not carry an MDC or * uses AEAD encryption. --ignore-mdc-error has also not been * used. To avoid attacks changing an MDC message to a non-MDC * message, we fail here. */ log_error (_("WARNING: message was not integrity protected\n")); if (!pkt->pkt.encrypted->mdc_method && (openpgp_cipher_get_algo_blklen (c->dek->algo) == 8 || c->dek->algo == CIPHER_ALGO_TWOFISH)) { /* Before 2.2.8 we did not fail hard for a missing MDC if * one of the old ciphers where used. Although these cases * are rare in practice we print a hint on how to decrypt * such messages. */ log_string (GPGRT_LOGLVL_INFO, _("Hint: If this message was created before the year 2003 it is\n" "likely that this message is legitimate. This is because back\n" "then integrity protection was not widely used.\n")); log_info (_("Use the option '%s' to decrypt anyway.\n"), "--ignore-mdc-error"); write_status_errcode ("nomdc_with_legacy_cipher", GPG_ERR_DECRYPT_FAILED); } log_info (_("decryption forced to fail!\n")); write_status (STATUS_DECRYPTION_FAILED); } else if (!result || (gpg_err_code (result) == GPG_ERR_BAD_SIGNATURE && !pkt->pkt.encrypted->aead_algo && opt.ignore_mdc_error)) { /* All is fine or for an MDC message the MDC failed but the * --ignore-mdc-error option is active. For compatibility * reasons we issue GOODMDC also for AEAD messages. */ write_status (STATUS_DECRYPTION_OKAY); if (opt.verbose > 1) log_info(_("decryption okay\n")); if (pkt->pkt.encrypted->aead_algo) write_status (STATUS_GOODMDC); else if (pkt->pkt.encrypted->mdc_method && !result) write_status (STATUS_GOODMDC); else log_info (_("WARNING: message was not integrity protected\n")); } else if (gpg_err_code (result) == GPG_ERR_BAD_SIGNATURE || gpg_err_code (result) == GPG_ERR_TRUNCATED) { glo_ctrl.lasterr = result; log_error (_("WARNING: encrypted message has been manipulated!\n")); write_status (STATUS_BADMDC); write_status (STATUS_DECRYPTION_FAILED); } else { if ((gpg_err_code (result) == GPG_ERR_BAD_KEY || gpg_err_code (result) == GPG_ERR_CHECKSUM || gpg_err_code (result) == GPG_ERR_CIPHER_ALGO) && c->dek && *c->dek->s2k_cacheid != '\0') { if (opt.debug) log_debug ("cleared passphrase cached with ID: %s\n", c->dek->s2k_cacheid); passphrase_clear_cache (c->dek->s2k_cacheid); } glo_ctrl.lasterr = result; write_status (STATUS_DECRYPTION_FAILED); log_error (_("decryption failed: %s\n"), gpg_strerror (result)); /* Hmmm: does this work when we have encrypted using multiple * ways to specify the session key (symmmetric and PK). */ } xfree (c->dek); c->dek = NULL; free_packet (pkt, NULL); c->last_was_session_key = 0; write_status (STATUS_END_DECRYPTION); /* Bump the counter even if we have not seen a literal data packet * inside an encryption container. This acts as a sentinel in case * a misplace extra literal data packets follows after this * encrypted packet. */ literals_seen++; } static int have_seen_pkt_encrypted_aead( CTX c ) { CTX cc; for (cc = c; cc; cc = cc->anchor) { if (cc->seen_pkt_encrypted_aead) return 1; } return 0; } static void proc_plaintext( CTX c, PACKET *pkt ) { PKT_plaintext *pt = pkt->pkt.plaintext; int any, clearsig, rc; kbnode_t n; unsigned char *extrahash; size_t extrahashlen; /* This is a literal data packet. Bump a counter for later checks. */ literals_seen++; if (pt->namelen == 8 && !memcmp( pt->name, "_CONSOLE", 8)) log_info (_("Note: sender requested \"for-your-eyes-only\"\n")); else if (opt.verbose) { /* We don't use print_utf8_buffer because that would require a * string change which we don't want in 2.2. It is also not * clear whether the filename is always utf-8 encoded. */ char *tmp = make_printable_string (pt->name, pt->namelen, 0); log_info (_("original file name='%.*s'\n"), (int)strlen (tmp), tmp); xfree (tmp); } free_md_filter_context (&c->mfx); if (gcry_md_open (&c->mfx.md, 0, 0)) BUG (); /* fixme: we may need to push the textfilter if we have sigclass 1 * and no armoring - Not yet tested * Hmmm, why don't we need it at all if we have sigclass 1 * Should we assume that plaintext in mode 't' has always sigclass 1?? * See: Russ Allbery's mail 1999-02-09 */ any = clearsig = 0; for (n=c->list; n; n = n->next ) { if (n->pkt->pkttype == PKT_ONEPASS_SIG) { /* The onepass signature case. */ if (n->pkt->pkt.onepass_sig->digest_algo) { if (!opt.skip_verify) gcry_md_enable (c->mfx.md, n->pkt->pkt.onepass_sig->digest_algo); any = 1; } } else if (n->pkt->pkttype == PKT_GPG_CONTROL && n->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START) { /* The clearsigned message case. */ size_t datalen = n->pkt->pkt.gpg_control->datalen; const byte *data = n->pkt->pkt.gpg_control->data; /* Check that we have at least the sigclass and one hash. */ if (datalen < 2) log_fatal ("invalid control packet CTRLPKT_CLEARSIGN_START\n"); /* Note that we don't set the clearsig flag for not-dash-escaped * documents. */ clearsig = (*data == 0x01); for (data++, datalen--; datalen; datalen--, data++) if (!opt.skip_verify) gcry_md_enable (c->mfx.md, *data); any = 1; break; /* Stop here as one-pass signature packets are not expected. */ } else if (n->pkt->pkttype == PKT_SIGNATURE) { /* The SIG+LITERAL case that PGP used to use. */ if (!opt.skip_verify) gcry_md_enable (c->mfx.md, n->pkt->pkt.signature->digest_algo); any = 1; } } if (!any && !opt.skip_verify && !have_seen_pkt_encrypted_aead(c)) { /* This is for the old GPG LITERAL+SIG case. It's not legal according to 2440, so hopefully it won't come up that often. There is no good way to specify what algorithms to use in that case, so these there are the historical answer. */ gcry_md_enable (c->mfx.md, DIGEST_ALGO_RMD160); gcry_md_enable (c->mfx.md, DIGEST_ALGO_SHA1); } if (DBG_HASHING) { gcry_md_debug (c->mfx.md, "verify"); if (c->mfx.md2) gcry_md_debug (c->mfx.md2, "verify2"); } rc=0; if (literals_seen > 1) { log_info (_("WARNING: multiple plaintexts seen\n")); write_status_text (STATUS_ERROR, "proc_pkt.plaintext 89_BAD_DATA"); log_inc_errorcount (); rc = gpg_error (GPG_ERR_UNEXPECTED); } if (!rc) { /* It we are in --verify mode, we do not want to output the * signed text. However, if --output is also used we do what * has been requested and write out the signed data. */ rc = handle_plaintext (pt, &c->mfx, (opt.outfp || opt.outfile)? 0 : c->sigs_only, clearsig); if (gpg_err_code (rc) == GPG_ERR_EACCES && !c->sigs_only) { /* Can't write output but we hash it anyway to check the signature. */ rc = handle_plaintext( pt, &c->mfx, 1, clearsig ); } } if (rc) log_error ("handle plaintext failed: %s\n", gpg_strerror (rc)); /* We add a marker control packet instead of the plaintext packet. * This is so that we can later detect invalid packet sequences. * The packet is further used to convey extra data from the * plaintext packet to the signature verification. */ extrahash = xtrymalloc (6 + pt->namelen); if (!extrahash) { /* No way to return an error. */ rc = gpg_error_from_syserror (); log_error ("malloc failed in %s: %s\n", __func__, gpg_strerror (rc)); extrahashlen = 0; } else { extrahash[0] = pt->mode; extrahash[1] = pt->namelen; if (pt->namelen) memcpy (extrahash+2, pt->name, pt->namelen); extrahashlen = 2 + pt->namelen; extrahash[extrahashlen++] = pt->timestamp >> 24; extrahash[extrahashlen++] = pt->timestamp >> 16; extrahash[extrahashlen++] = pt->timestamp >> 8; extrahash[extrahashlen++] = pt->timestamp ; } free_packet (pkt, NULL); c->last_was_session_key = 0; n = new_kbnode (create_gpg_control (CTRLPKT_PLAINTEXT_MARK, extrahash, extrahashlen)); xfree (extrahash); if (c->list) add_kbnode (c->list, n); else c->list = n; } static int proc_compressed_cb (iobuf_t a, void *info) { if ( ((CTX)info)->signed_data.used && ((CTX)info)->signed_data.data_fd != -1) return proc_signature_packets_by_fd (((CTX)info)->ctrl, info, a, ((CTX)info)->signed_data.data_fd); else return proc_signature_packets (((CTX)info)->ctrl, info, a, ((CTX)info)->signed_data.data_names, ((CTX)info)->sigfilename ); } static int proc_encrypt_cb (iobuf_t a, void *info ) { CTX c = info; return proc_encryption_packets (c->ctrl, info, a ); } static int proc_compressed (CTX c, PACKET *pkt) { PKT_compressed *zd = pkt->pkt.compressed; int rc; /*printf("zip: compressed data packet\n");*/ if (c->sigs_only) rc = handle_compressed (c->ctrl, c, zd, proc_compressed_cb, c); else if( c->encrypt_only ) rc = handle_compressed (c->ctrl, c, zd, proc_encrypt_cb, c); else rc = handle_compressed (c->ctrl, c, zd, NULL, NULL); if (gpg_err_code (rc) == GPG_ERR_BAD_DATA) { if (!c->any.uncompress_failed) { CTX cc; for (cc=c; cc; cc = cc->anchor) cc->any.uncompress_failed = 1; log_error ("uncompressing failed: %s\n", gpg_strerror (rc)); } } else if (rc) log_error ("uncompressing failed: %s\n", gpg_strerror (rc)); free_packet (pkt, NULL); c->last_was_session_key = 0; return rc; } /* * Check the signature. If R_PK is not NULL a copy of the public key * used to verify the signature will be stored there, or NULL if not * found. If FORCED_PK is not NULL, this public key is used to verify * _data signatures_ and no key lookup is done. Returns: 0 = valid * signature or an error code */ static int do_check_sig (CTX c, kbnode_t node, const void *extrahash, size_t extrahashlen, PKT_public_key *forced_pk, int *is_selfsig, int *is_expkey, int *is_revkey, PKT_public_key **r_pk) { PKT_signature *sig; gcry_md_hd_t md = NULL; gcry_md_hd_t md2 = NULL; gcry_md_hd_t md_good = NULL; int algo, rc; if (r_pk) *r_pk = NULL; log_assert (node->pkt->pkttype == PKT_SIGNATURE); if (is_selfsig) *is_selfsig = 0; sig = node->pkt->pkt.signature; algo = sig->digest_algo; rc = openpgp_md_test_algo (algo); if (rc) return rc; if (sig->sig_class == 0x00) { if (c->mfx.md) { if (gcry_md_copy (&md, c->mfx.md )) BUG (); } else /* detached signature */ { /* check_signature() will enable the md. */ if (gcry_md_open (&md, 0, 0 )) BUG (); } } else if (sig->sig_class == 0x01) { /* How do we know that we have to hash the (already hashed) text in canonical mode ??? (calculating both modes???) */ if (c->mfx.md) { if (gcry_md_copy (&md, c->mfx.md )) BUG (); if (c->mfx.md2 && gcry_md_copy (&md2, c->mfx.md2)) BUG (); } else /* detached signature */ { log_debug ("Do we really need this here?"); /* check_signature() will enable the md*/ if (gcry_md_open (&md, 0, 0 )) BUG (); if (gcry_md_open (&md2, 0, 0 )) BUG (); } } else if ((sig->sig_class&~3) == 0x10 || sig->sig_class == 0x18 || sig->sig_class == 0x1f || sig->sig_class == 0x20 || sig->sig_class == 0x28 || sig->sig_class == 0x30) { if (c->list->pkt->pkttype == PKT_PUBLIC_KEY || c->list->pkt->pkttype == PKT_PUBLIC_SUBKEY) { return check_key_signature (c->ctrl, c->list, node, is_selfsig); } else if (sig->sig_class == 0x20) { log_error (_("standalone revocation - " "use \"gpg --import\" to apply\n")); return GPG_ERR_NOT_PROCESSED; } else { log_error ("invalid root packet for sigclass %02x\n", sig->sig_class); return GPG_ERR_SIG_CLASS; } } else return GPG_ERR_SIG_CLASS; /* We only get here if we are checking the signature of a binary (0x00) or text document (0x01). */ rc = check_signature2 (c->ctrl, sig, md, extrahash, extrahashlen, forced_pk, NULL, is_expkey, is_revkey, r_pk); if (! rc) md_good = md; else if (gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE && md2) { PKT_public_key *pk2; rc = check_signature2 (c->ctrl, sig, md2, extrahash, extrahashlen, forced_pk, NULL, is_expkey, is_revkey, r_pk? &pk2 : NULL); if (!rc) { md_good = md2; if (r_pk) { free_public_key (*r_pk); *r_pk = pk2; } } } if (md_good) { unsigned char *buffer = gcry_md_read (md_good, sig->digest_algo); sig->digest_len = gcry_md_get_algo_dlen (map_md_openpgp_to_gcry (algo)); memcpy (sig->digest, buffer, sig->digest_len); } gcry_md_close (md); gcry_md_close (md2); return rc; } static void print_userid (PACKET *pkt) { if (!pkt) BUG(); if (pkt->pkttype != PKT_USER_ID) { es_printf ("ERROR: unexpected packet type %d", pkt->pkttype ); return; } if (opt.with_colons) { if (pkt->pkt.user_id->attrib_data) es_printf("%u %lu", pkt->pkt.user_id->numattribs, pkt->pkt.user_id->attrib_len); else es_write_sanitized (es_stdout, pkt->pkt.user_id->name, pkt->pkt.user_id->len, ":", NULL); } else print_utf8_buffer (es_stdout, pkt->pkt.user_id->name, pkt->pkt.user_id->len ); } /* * List the keyblock in a user friendly way */ static void list_node (CTX c, kbnode_t node) { if (!node) ; else if (node->pkt->pkttype == PKT_PUBLIC_KEY || node->pkt->pkttype == PKT_PUBLIC_SUBKEY) { PKT_public_key *pk = node->pkt->pkt.public_key; if (opt.with_colons) { u32 keyid[2]; keyid_from_pk( pk, keyid ); if (pk->flags.primary) c->trustletter = (opt.fast_list_mode ? 0 : get_validity_info (c->ctrl, node->pkt->pkttype == PKT_PUBLIC_KEY ? node : NULL, pk, NULL)); es_printf ("%s:", pk->flags.primary? "pub":"sub" ); if (c->trustletter) es_putc (c->trustletter, es_stdout); es_printf (":%u:%d:%08lX%08lX:%s:%s::", nbits_from_pk( pk ), pk->pubkey_algo, (ulong)keyid[0],(ulong)keyid[1], colon_datestr_from_pk( pk ), colon_strtime (pk->expiredate) ); if (pk->flags.primary && !opt.fast_list_mode) es_putc (get_ownertrust_info (c->ctrl, pk, 1), es_stdout); es_putc (':', es_stdout); es_putc ('\n', es_stdout); } else { print_key_line (c->ctrl, es_stdout, pk, 0); } if (opt.keyid_format == KF_NONE && !opt.with_colons) ; /* Already printed. */ else if ((pk->flags.primary && opt.fingerprint) || opt.fingerprint > 1) print_fingerprint (c->ctrl, NULL, pk, 0); if (pk->flags.primary) { int kl = opt.keyid_format == KF_NONE? 0 : keystrlen (); /* Now list all userids with their signatures. */ for (node = node->next; node; node = node->next) { if (node->pkt->pkttype == PKT_SIGNATURE) { list_node (c, node ); } else if (node->pkt->pkttype == PKT_USER_ID) { if (opt.with_colons) es_printf ("%s:::::::::", node->pkt->pkt.user_id->attrib_data?"uat":"uid"); else es_printf ("uid%*s", kl + (opt.legacy_list_mode? 9:11), "" ); print_userid (node->pkt); if (opt.with_colons) es_putc (':', es_stdout); es_putc ('\n', es_stdout); } else if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY) { list_node(c, node ); } } } } else if (node->pkt->pkttype == PKT_SECRET_KEY || node->pkt->pkttype == PKT_SECRET_SUBKEY) { log_debug ("FIXME: No way to print secret key packets here\n"); /* fixme: We may use a function to turn a secret key packet into a public key one and use that here. */ } else if (node->pkt->pkttype == PKT_SIGNATURE) { PKT_signature *sig = node->pkt->pkt.signature; int is_selfsig = 0; int rc2 = 0; size_t n; char *p; int sigrc = ' '; if (!opt.verbose) return; if (sig->sig_class == 0x20 || sig->sig_class == 0x30) es_fputs ("rev", es_stdout); else es_fputs ("sig", es_stdout); if (opt.check_sigs) { fflush (stdout); rc2 = do_check_sig (c, node, NULL, 0, NULL, &is_selfsig, NULL, NULL, NULL); switch (gpg_err_code (rc2)) { case 0: sigrc = '!'; break; case GPG_ERR_BAD_SIGNATURE: sigrc = '-'; break; case GPG_ERR_NO_PUBKEY: case GPG_ERR_UNUSABLE_PUBKEY: sigrc = '?'; break; default: sigrc = '%'; break; } } else /* Check whether this is a self signature. */ { u32 keyid[2]; if (c->list->pkt->pkttype == PKT_PUBLIC_KEY || c->list->pkt->pkttype == PKT_SECRET_KEY ) { keyid_from_pk (c->list->pkt->pkt.public_key, keyid); if (keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1]) is_selfsig = 1; } } if (opt.with_colons) { es_putc (':', es_stdout); if (sigrc != ' ') es_putc (sigrc, es_stdout); es_printf ("::%d:%08lX%08lX:%s:%s:", sig->pubkey_algo, (ulong)sig->keyid[0], (ulong)sig->keyid[1], colon_datestr_from_sig (sig), colon_expirestr_from_sig (sig)); if (sig->trust_depth || sig->trust_value) es_printf ("%d %d",sig->trust_depth,sig->trust_value); es_putc (':', es_stdout); if (sig->trust_regexp) es_write_sanitized (es_stdout, sig->trust_regexp, strlen (sig->trust_regexp), ":", NULL); es_putc (':', es_stdout); } else es_printf ("%c %s %s ", sigrc, keystr (sig->keyid), datestr_from_sig(sig)); if (sigrc == '%') es_printf ("[%s] ", gpg_strerror (rc2) ); else if (sigrc == '?') ; else if (is_selfsig) { if (opt.with_colons) es_putc (':', es_stdout); es_fputs (sig->sig_class == 0x18? "[keybind]":"[selfsig]", es_stdout); if (opt.with_colons) es_putc (':', es_stdout); } else if (!opt.fast_list_mode) { p = get_user_id (c->ctrl, sig->keyid, &n, NULL); es_write_sanitized (es_stdout, p, n, opt.with_colons?":":NULL, NULL ); xfree (p); } if (opt.with_colons) es_printf (":%02x%c:", sig->sig_class, sig->flags.exportable?'x':'l'); es_putc ('\n', es_stdout); } else log_error ("invalid node with packet of type %d\n", node->pkt->pkttype); } int proc_packets (ctrl_t ctrl, void *anchor, iobuf_t a ) { int rc; CTX c = xmalloc_clear (sizeof *c); c->ctrl = ctrl; c->anchor = anchor; rc = do_proc_packets (c, a); xfree (c); return rc; } int proc_signature_packets (ctrl_t ctrl, void *anchor, iobuf_t a, strlist_t signedfiles, const char *sigfilename ) { CTX c = xmalloc_clear (sizeof *c); int rc; c->ctrl = ctrl; c->anchor = anchor; c->sigs_only = 1; c->signed_data.data_fd = -1; c->signed_data.data_names = signedfiles; c->signed_data.used = !!signedfiles; c->sigfilename = sigfilename; rc = do_proc_packets (c, a); /* If we have not encountered any signature we print an error messages, send a NODATA status back and return an error code. Using log_error is required because verify_files does not check error codes for each file but we want to terminate the process with an error. */ if (!rc && !c->any.sig_seen) { write_status_text (STATUS_NODATA, "4"); log_error (_("no signature found\n")); rc = GPG_ERR_NO_DATA; } /* Propagate the signature seen flag upward. Do this only on success so that we won't issue the nodata status several times. */ if (!rc && c->anchor && c->any.sig_seen) c->anchor->any.sig_seen = 1; xfree (c); return rc; } int proc_signature_packets_by_fd (ctrl_t ctrl, void *anchor, iobuf_t a, int signed_data_fd ) { int rc; CTX c; c = xtrycalloc (1, sizeof *c); if (!c) return gpg_error_from_syserror (); c->ctrl = ctrl; c->anchor = anchor; c->sigs_only = 1; c->signed_data.data_fd = signed_data_fd; c->signed_data.data_names = NULL; c->signed_data.used = (signed_data_fd != -1); rc = do_proc_packets (c, a); /* If we have not encountered any signature we print an error messages, send a NODATA status back and return an error code. Using log_error is required because verify_files does not check error codes for each file but we want to terminate the process with an error. */ if (!rc && !c->any.sig_seen) { write_status_text (STATUS_NODATA, "4"); log_error (_("no signature found\n")); rc = gpg_error (GPG_ERR_NO_DATA); } /* Propagate the signature seen flag upward. Do this only on success so that we won't issue the nodata status several times. */ if (!rc && c->anchor && c->any.sig_seen) c->anchor->any.sig_seen = 1; xfree ( c ); return rc; } int proc_encryption_packets (ctrl_t ctrl, void *anchor, iobuf_t a ) { CTX c = xmalloc_clear (sizeof *c); int rc; c->ctrl = ctrl; c->anchor = anchor; c->encrypt_only = 1; rc = do_proc_packets (c, a); xfree (c); return rc; } static int check_nesting (CTX c) { int level; for (level=0; c; c = c->anchor) level++; if (level > MAX_NESTING_DEPTH) { log_error ("input data with too deeply nested packets\n"); write_status_text (STATUS_UNEXPECTED, "1"); return GPG_ERR_BAD_DATA; } return 0; } static int do_proc_packets (CTX c, iobuf_t a) { PACKET *pkt; struct parse_packet_ctx_s parsectx; int rc = 0; int any_data = 0; int newpkt; rc = check_nesting (c); if (rc) return rc; pkt = xmalloc( sizeof *pkt ); c->iobuf = a; init_packet(pkt); init_parse_packet (&parsectx, a); while ((rc=parse_packet (&parsectx, pkt)) != -1) { any_data = 1; if (rc) { free_packet (pkt, &parsectx); /* Stop processing when an invalid packet has been encountered * but don't do so when we are doing a --list-packets. */ if (gpg_err_code (rc) == GPG_ERR_INV_PACKET && opt.list_packets == 0) break; continue; } newpkt = -1; if (opt.list_packets) { switch (pkt->pkttype) { case PKT_PUBKEY_ENC: proc_pubkey_enc (c, pkt); break; case PKT_SYMKEY_ENC: proc_symkey_enc (c, pkt); break; case PKT_ENCRYPTED: case PKT_ENCRYPTED_MDC: case PKT_ENCRYPTED_AEAD:proc_encrypted (c, pkt); break; case PKT_COMPRESSED: rc = proc_compressed (c, pkt); break; default: newpkt = 0; break; } } else if (c->sigs_only) { switch (pkt->pkttype) { case PKT_PUBLIC_KEY: case PKT_SECRET_KEY: case PKT_USER_ID: case PKT_SYMKEY_ENC: case PKT_PUBKEY_ENC: case PKT_ENCRYPTED: case PKT_ENCRYPTED_MDC: case PKT_ENCRYPTED_AEAD: write_status_text( STATUS_UNEXPECTED, "0" ); rc = GPG_ERR_UNEXPECTED; goto leave; case PKT_SIGNATURE: newpkt = add_signature (c, pkt); break; case PKT_PLAINTEXT: proc_plaintext (c, pkt); break; case PKT_COMPRESSED: rc = proc_compressed (c, pkt); break; case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break; case PKT_GPG_CONTROL: newpkt = add_gpg_control (c, pkt); break; default: newpkt = 0; break; } } else if (c->encrypt_only) { switch (pkt->pkttype) { case PKT_PUBLIC_KEY: case PKT_SECRET_KEY: case PKT_USER_ID: write_status_text (STATUS_UNEXPECTED, "0"); rc = GPG_ERR_UNEXPECTED; goto leave; case PKT_SIGNATURE: newpkt = add_signature (c, pkt); break; case PKT_SYMKEY_ENC: proc_symkey_enc (c, pkt); break; case PKT_PUBKEY_ENC: proc_pubkey_enc (c, pkt); break; case PKT_ENCRYPTED: case PKT_ENCRYPTED_MDC: case PKT_ENCRYPTED_AEAD: proc_encrypted (c, pkt); break; case PKT_PLAINTEXT: proc_plaintext (c, pkt); break; case PKT_COMPRESSED: rc = proc_compressed (c, pkt); break; case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break; case PKT_GPG_CONTROL: newpkt = add_gpg_control (c, pkt); break; default: newpkt = 0; break; } } else { switch (pkt->pkttype) { case PKT_PUBLIC_KEY: case PKT_SECRET_KEY: release_list (c); c->list = new_kbnode (pkt); newpkt = 1; break; case PKT_PUBLIC_SUBKEY: case PKT_SECRET_SUBKEY: newpkt = add_subkey (c, pkt); break; case PKT_USER_ID: newpkt = add_user_id (c, pkt); break; case PKT_SIGNATURE: newpkt = add_signature (c, pkt); break; case PKT_PUBKEY_ENC: proc_pubkey_enc (c, pkt); break; case PKT_SYMKEY_ENC: proc_symkey_enc (c, pkt); break; case PKT_ENCRYPTED: case PKT_ENCRYPTED_MDC: case PKT_ENCRYPTED_AEAD: proc_encrypted (c, pkt); break; case PKT_PLAINTEXT: proc_plaintext (c, pkt); break; case PKT_COMPRESSED: rc = proc_compressed (c, pkt); break; case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break; case PKT_GPG_CONTROL: newpkt = add_gpg_control(c, pkt); break; case PKT_RING_TRUST: newpkt = add_ring_trust (c, pkt); break; default: newpkt = 0; break; } } if (rc) goto leave; /* This is a very ugly construct and frankly, I don't remember why * I used it. Adding the MDC check here is a hack. * The right solution is to initiate another context for encrypted * packet and not to reuse the current one ... It works right * when there is a compression packet between which adds just * an extra layer. * Hmmm: Rewrite this whole module here?? */ if (pkt->pkttype != PKT_SIGNATURE && pkt->pkttype != PKT_MDC) c->any.data = (pkt->pkttype == PKT_PLAINTEXT); if (newpkt == -1) ; else if (newpkt) { pkt = xmalloc (sizeof *pkt); init_packet (pkt); } else free_packet (pkt, &parsectx); } if (rc == GPG_ERR_INV_PACKET) write_status_text (STATUS_NODATA, "3"); if (any_data) rc = 0; else if (rc == -1) write_status_text (STATUS_NODATA, "2"); leave: release_list (c); xfree(c->dek); free_packet (pkt, &parsectx); deinit_parse_packet (&parsectx); xfree (pkt); free_md_filter_context (&c->mfx); return rc; } /* Return true if the AKL has the WKD method specified. */ static int akl_has_wkd_method (void) { struct akl *akl; for (akl = opt.auto_key_locate; akl; akl = akl->next) if (akl->type == AKL_WKD) return 1; return 0; } /* Return the ISSUER fingerprint buffer and its length at R_LEN. * Returns NULL if not available. The returned buffer is valid as * long as SIG is not modified. */ const byte * issuer_fpr_raw (PKT_signature *sig, size_t *r_len) { const byte *p; size_t n; p = parse_sig_subpkt (sig, 1, SIGSUBPKT_ISSUER_FPR, &n); if (p && ((n == 21 && p[0] == 4) || (n == 33 && p[0] == 5))) { *r_len = n - 1; return p+1; } *r_len = 0; return NULL; } /* Return the ISSUER fingerprint string in human readable format if * available. Caller must release the string. */ /* FIXME: Move to another file. */ char * issuer_fpr_string (PKT_signature *sig) { const byte *p; size_t n; p = issuer_fpr_raw (sig, &n); return p? bin2hex (p, n, NULL) : NULL; } static void print_good_bad_signature (int statno, const char *keyid_str, kbnode_t un, PKT_signature *sig, int rc) { char *p; write_status_text_and_buffer (statno, keyid_str, un? un->pkt->pkt.user_id->name:"[?]", un? un->pkt->pkt.user_id->len:3, -1); if (un) p = utf8_to_native (un->pkt->pkt.user_id->name, un->pkt->pkt.user_id->len, 0); else p = xstrdup ("[?]"); if (rc) log_info (_("BAD signature from \"%s\""), p); else if (sig->flags.expired) log_info (_("Expired signature from \"%s\""), p); else log_info (_("Good signature from \"%s\""), p); xfree (p); } static int check_sig_and_print (CTX c, kbnode_t node) { PKT_signature *sig = node->pkt->pkt.signature; const char *astr; gpg_error_t rc; int is_expkey = 0; int is_revkey = 0; char *issuer_fpr = NULL; PKT_public_key *pk = NULL; /* The public key for the signature or NULL. */ const void *extrahash = NULL; size_t extrahashlen = 0; kbnode_t included_keyblock = NULL; if (opt.skip_verify) { log_info(_("signature verification suppressed\n")); return 0; } /* Check that the message composition is valid. * * Per RFC-2440bis (-15) allowed: * * S{1,n} -- detached signature. * S{1,n} P -- old style PGP2 signature * O{1,n} P S{1,n} -- standard OpenPGP signature. * C P S{1,n} -- cleartext signature. * * * O = One-Pass Signature packet. * S = Signature packet. * P = OpenPGP Message packet (Encrypted | Compressed | Literal) * (Note that the current rfc2440bis draft also allows * for a signed message but that does not work as it * introduces ambiguities.) * We keep track of these packages using the marker packet * CTRLPKT_PLAINTEXT_MARK. * C = Marker packet for cleartext signatures. * * We reject all other messages. * * Actually we are calling this too often, i.e. for verification of * each message but better have some duplicate work than to silently * introduce a bug here. */ { kbnode_t n; int n_onepass, n_sig; /* log_debug ("checking signature packet composition\n"); */ /* dump_kbnode (c->list); */ n = c->list; log_assert (n); if ( n->pkt->pkttype == PKT_SIGNATURE ) { /* This is either "S{1,n}" case (detached signature) or "S{1,n} P" (old style PGP2 signature). */ for (n = n->next; n; n = n->next) if (n->pkt->pkttype != PKT_SIGNATURE) break; if (!n) ; /* Okay, this is a detached signature. */ else if (n->pkt->pkttype == PKT_GPG_CONTROL && (n->pkt->pkt.gpg_control->control == CTRLPKT_PLAINTEXT_MARK) ) { if (n->next) goto ambiguous; /* We only allow one P packet. */ extrahash = n->pkt->pkt.gpg_control->data; extrahashlen = n->pkt->pkt.gpg_control->datalen; } else goto ambiguous; } else if (n->pkt->pkttype == PKT_ONEPASS_SIG) { /* This is the "O{1,n} P S{1,n}" case (standard signature). */ for (n_onepass=1, n = n->next; n && n->pkt->pkttype == PKT_ONEPASS_SIG; n = n->next) n_onepass++; if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL && (n->pkt->pkt.gpg_control->control == CTRLPKT_PLAINTEXT_MARK))) goto ambiguous; extrahash = n->pkt->pkt.gpg_control->data; extrahashlen = n->pkt->pkt.gpg_control->datalen; for (n_sig=0, n = n->next; n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next) n_sig++; if (!n_sig) goto ambiguous; /* If we wanted to disallow multiple sig verification, we'd do * something like this: * * if (n) * goto ambiguous; * * However, this can stay allowable as we can't get here. */ if (n_onepass != n_sig) { log_info ("number of one-pass packets does not match " "number of signature packets\n"); goto ambiguous; } } else if (n->pkt->pkttype == PKT_GPG_CONTROL && n->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START ) { /* This is the "C P S{1,n}" case (clear text signature). */ n = n->next; if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL && (n->pkt->pkt.gpg_control->control == CTRLPKT_PLAINTEXT_MARK))) goto ambiguous; extrahash = n->pkt->pkt.gpg_control->data; extrahashlen = n->pkt->pkt.gpg_control->datalen; for (n_sig=0, n = n->next; n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next) n_sig++; if (n || !n_sig) goto ambiguous; } else { ambiguous: log_error(_("can't handle this ambiguous signature data\n")); return 0; } } /* End checking signature packet composition. */ if (sig->signers_uid) write_status_buffer (STATUS_NEWSIG, sig->signers_uid, strlen (sig->signers_uid), 0); else write_status_text (STATUS_NEWSIG, NULL); astr = openpgp_pk_algo_name ( sig->pubkey_algo ); issuer_fpr = issuer_fpr_string (sig); if (issuer_fpr) { log_info (_("Signature made %s\n"), asctimestamp(sig->timestamp)); log_info (_(" using %s key %s\n"), astr? astr: "?", issuer_fpr); } else if (!keystrlen () || keystrlen () > 8) { log_info (_("Signature made %s\n"), asctimestamp(sig->timestamp)); log_info (_(" using %s key %s\n"), astr? astr: "?", keystr(sig->keyid)); } else /* Legacy format. */ log_info (_("Signature made %s using %s key ID %s\n"), asctimestamp(sig->timestamp), astr? astr: "?", keystr(sig->keyid)); /* In verbose mode print the signers UID. */ if (sig->signers_uid) log_info (_(" issuer \"%s\"\n"), sig->signers_uid); rc = do_check_sig (c, node, extrahash, extrahashlen, NULL, NULL, &is_expkey, &is_revkey, &pk); /* If the key is not found but the signature includes a key block we * use that key block for verification and on success import it. */ if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && sig->flags.key_block && opt.flags.auto_key_import) { PKT_public_key *included_pk; const byte *kblock; size_t kblock_len; included_pk = xcalloc (1, sizeof *included_pk); kblock = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_BLOCK, &kblock_len); if (kblock && kblock_len > 1 && !get_pubkey_from_buffer (c->ctrl, included_pk, kblock+1, kblock_len-1, sig->keyid, &included_keyblock)) { rc = do_check_sig (c, node, extrahash, extrahashlen, included_pk, NULL, &is_expkey, &is_revkey, &pk); if (opt.verbose) log_debug ("checked signature using included key block: %s\n", gpg_strerror (rc)); if (!rc) { /* The keyblock has been verified, we now import it. */ rc = import_included_key_block (c->ctrl, included_keyblock); } } free_public_key (included_pk); } /* If the key isn't found, check for a preferred keyserver. Note * that this is only done if honor-keyserver-url has been set. We * test for this in the loop so that we can show info about the * preferred keyservers. */ if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && sig->flags.pref_ks) { const byte *p; int seq = 0; size_t n; int any_pref_ks = 0; while ((p=enum_sig_subpkt (sig, 1, SIGSUBPKT_PREF_KS, &n, &seq, NULL))) { /* According to my favorite copy editor, in English grammar, you say "at" if the key is located on a web page, but "from" if it is located on a keyserver. I'm not going to even try to make two strings here :) */ log_info(_("Key available at: ") ); print_utf8_buffer (log_get_stream(), p, n); log_printf ("\n"); any_pref_ks = 1; if ((opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE) && (opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL)) { struct keyserver_spec *spec; spec = parse_preferred_keyserver (sig); if (spec) { int res; if (DBG_LOOKUP) log_debug ("trying auto-key-retrieve method %s\n", "Pref-KS"); free_public_key (pk); pk = NULL; glo_ctrl.in_auto_key_retrieve++; - res = keyserver_import_keyid (c->ctrl, sig->keyid,spec, 1); + res = keyserver_import_keyid (c->ctrl, sig->keyid,spec, + KEYSERVER_IMPORT_FLAG_QUICK); glo_ctrl.in_auto_key_retrieve--; if (!res) rc = do_check_sig (c, node, extrahash, extrahashlen, NULL, NULL, &is_expkey, &is_revkey, &pk); else if (DBG_LOOKUP) log_debug ("lookup via %s failed: %s\n", "Pref-KS", gpg_strerror (res)); free_keyserver_spec (spec); if (!rc) break; } } } if (any_pref_ks && (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE) && !(opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL)) log_info (_("Note: Use '%s' to make use of this info\n"), "--keyserver-option honor-keyserver-url"); } /* If the above methods didn't work, our next try is to retrieve the * key from the WKD. This requires that WKD is in the AKL and the * Signer's UID is in the signature. */ if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && (opt.keyserver_options.options & KEYSERVER_AUTO_KEY_RETRIEVE) && !opt.flags.disable_signer_uid && akl_has_wkd_method () && sig->signers_uid) { int res; if (DBG_LOOKUP) log_debug ("trying auto-key-retrieve method %s\n", "WKD"); free_public_key (pk); pk = NULL; glo_ctrl.in_auto_key_retrieve++; - res = keyserver_import_wkd (c->ctrl, sig->signers_uid, 1, NULL, NULL); + res = keyserver_import_wkd (c->ctrl, sig->signers_uid, + KEYSERVER_IMPORT_FLAG_QUICK, NULL, NULL); glo_ctrl.in_auto_key_retrieve--; /* Fixme: If the fingerprint is embedded in the signature, * compare it to the fingerprint of the returned key. */ if (!res) rc = do_check_sig (c, node, extrahash, extrahashlen, NULL, NULL, &is_expkey, &is_revkey, &pk); else if (DBG_LOOKUP) log_debug ("lookup via %s failed: %s\n", "WKD", gpg_strerror (res)); } /* If the above methods didn't work, our next try is to locate * the key via its fingerprint from a keyserver. This requires * that the signers fingerprint is encoded in the signature. */ if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE) && keyserver_any_configured (c->ctrl)) { int res; const byte *p; size_t n; p = issuer_fpr_raw (sig, &n); if (p) { if (DBG_LOOKUP) log_debug ("trying auto-key-retrieve method %s\n", "KS"); /* v4 or v5 packet with a SHA-1/256 fingerprint. */ free_public_key (pk); pk = NULL; glo_ctrl.in_auto_key_retrieve++; - res = keyserver_import_fprint (c->ctrl, p, n, opt.keyserver, 1); + res = keyserver_import_fprint (c->ctrl, p, n, opt.keyserver, + KEYSERVER_IMPORT_FLAG_QUICK); glo_ctrl.in_auto_key_retrieve--; if (!res) rc = do_check_sig (c, node, extrahash, extrahashlen, NULL, NULL, &is_expkey, &is_revkey, &pk); else if (DBG_LOOKUP) log_debug ("lookup via %s failed: %s\n", "KS", gpg_strerror (res)); } } /* Do do something with the result of the signature checking. */ if (!rc || gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE) { /* We have checked the signature and the result is either a good * signature or a bad signature. Further examination follows. */ kbnode_t un, keyblock; int count = 0; int keyblock_has_pk = 0; /* For failsafe check. */ int statno; char keyid_str[50]; PKT_public_key *mainpk = NULL; if (rc) statno = STATUS_BADSIG; else if (sig->flags.expired) statno = STATUS_EXPSIG; else if (is_expkey) statno = STATUS_EXPKEYSIG; else if(is_revkey) statno = STATUS_REVKEYSIG; else statno = STATUS_GOODSIG; /* FIXME: We should have the public key in PK and thus the * keyblock has already been fetched. Thus we could use the * fingerprint or PK itself to lookup the entire keyblock. That * would best be done with a cache. */ if (included_keyblock) { keyblock = included_keyblock; included_keyblock = NULL; } else keyblock = get_pubkeyblock_for_sig (c->ctrl, sig); snprintf (keyid_str, sizeof keyid_str, "%08lX%08lX [uncertain] ", (ulong)sig->keyid[0], (ulong)sig->keyid[1]); /* Find and print the primary user ID along with the "Good|Expired|Bad signature" line. */ for (un=keyblock; un; un = un->next) { int valid; if (!keyblock_has_pk && (un->pkt->pkttype == PKT_PUBLIC_KEY || un->pkt->pkttype == PKT_PUBLIC_SUBKEY) && !cmp_public_keys (un->pkt->pkt.public_key, pk)) { keyblock_has_pk = 1; } if (un->pkt->pkttype == PKT_PUBLIC_KEY) { mainpk = un->pkt->pkt.public_key; continue; } if (un->pkt->pkttype != PKT_USER_ID) continue; if (!un->pkt->pkt.user_id->created) continue; if (un->pkt->pkt.user_id->flags.revoked) continue; if (un->pkt->pkt.user_id->flags.expired) continue; if (!un->pkt->pkt.user_id->flags.primary) continue; /* We want the textual primary user ID here */ if (un->pkt->pkt.user_id->attrib_data) continue; log_assert (mainpk); /* Since this is just informational, don't actually ask the user to update any trust information. (Note: we register the signature later.) Because print_good_bad_signature does not print a LF we need to compute the validity before calling that function. */ if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY)) valid = get_validity (c->ctrl, keyblock, mainpk, un->pkt->pkt.user_id, NULL, 0); else valid = 0; /* Not used. */ keyid_str[17] = 0; /* cut off the "[uncertain]" part */ print_good_bad_signature (statno, keyid_str, un, sig, rc); if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY)) log_printf (" [%s]\n",trust_value_to_string(valid)); else log_printf ("\n"); count++; /* At this point we could in theory stop because the primary * UID flag is never set for more than one User ID per * keyblock. However, we use this loop also for a failsafe * check that the public key used to create the signature is * contained in the keyring.*/ } log_assert (mainpk); if (!keyblock_has_pk) { log_error ("signature key lost from keyblock\n"); rc = gpg_error (GPG_ERR_INTERNAL); } /* In case we did not found a valid textual userid above we print the first user id packet or a "[?]" instead along with the "Good|Expired|Bad signature" line. */ if (!count) { /* Try for an invalid textual userid */ for (un=keyblock; un; un = un->next) { if (un->pkt->pkttype == PKT_USER_ID && !un->pkt->pkt.user_id->attrib_data) break; } /* Try for any userid at all */ if (!un) { for (un=keyblock; un; un = un->next) { if (un->pkt->pkttype == PKT_USER_ID) break; } } if (opt.trust_model==TM_ALWAYS || !un) keyid_str[17] = 0; /* cut off the "[uncertain]" part */ print_good_bad_signature (statno, keyid_str, un, sig, rc); if (opt.trust_model != TM_ALWAYS && un) log_printf (" %s",_("[uncertain]") ); log_printf ("\n"); } /* If we have a good signature and already printed * the primary user ID, print all the other user IDs */ if (count && !rc && !(opt.verify_options & VERIFY_SHOW_PRIMARY_UID_ONLY)) { char *p; for( un=keyblock; un; un = un->next) { if (un->pkt->pkttype != PKT_USER_ID) continue; if ((un->pkt->pkt.user_id->flags.revoked || un->pkt->pkt.user_id->flags.expired) && !(opt.verify_options & VERIFY_SHOW_UNUSABLE_UIDS)) continue; /* Skip textual primary user ids which we printed above. */ if (un->pkt->pkt.user_id->flags.primary && !un->pkt->pkt.user_id->attrib_data ) continue; /* If this user id has attribute data, print that. */ if (un->pkt->pkt.user_id->attrib_data) { dump_attribs (un->pkt->pkt.user_id, mainpk); if (opt.verify_options&VERIFY_SHOW_PHOTOS) show_photos (c->ctrl, un->pkt->pkt.user_id->attribs, un->pkt->pkt.user_id->numattribs, mainpk ,un->pkt->pkt.user_id); } p = utf8_to_native (un->pkt->pkt.user_id->name, un->pkt->pkt.user_id->len, 0); log_info (_(" aka \"%s\""), p); xfree (p); if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY)) { const char *valid; if (un->pkt->pkt.user_id->flags.revoked) valid = _("revoked"); else if (un->pkt->pkt.user_id->flags.expired) valid = _("expired"); else /* Since this is just informational, don't actually ask the user to update any trust information. */ valid = (trust_value_to_string (get_validity (c->ctrl, keyblock, mainpk, un->pkt->pkt.user_id, NULL, 0))); log_printf (" [%s]\n",valid); } else log_printf ("\n"); } } /* For good signatures print notation data. */ if (!rc) { if ((opt.verify_options & VERIFY_SHOW_POLICY_URLS)) show_policy_url (sig, 0, 1); else show_policy_url (sig, 0, 2); if ((opt.verify_options & VERIFY_SHOW_KEYSERVER_URLS)) show_keyserver_url (sig, 0, 1); else show_keyserver_url (sig, 0, 2); if ((opt.verify_options & VERIFY_SHOW_NOTATIONS)) show_notation (sig, 0, 1, (((opt.verify_options&VERIFY_SHOW_STD_NOTATIONS)?1:0) + ((opt.verify_options&VERIFY_SHOW_USER_NOTATIONS)?2:0))); else show_notation (sig, 0, 2, 0); } /* For good signatures print the VALIDSIG status line. */ if (!rc && is_status_enabled () && pk) { char pkhex[MAX_FINGERPRINT_LEN*2+1]; char mainpkhex[MAX_FINGERPRINT_LEN*2+1]; hexfingerprint (pk, pkhex, sizeof pkhex); hexfingerprint (mainpk, mainpkhex, sizeof mainpkhex); /* TODO: Replace the reserved '0' in the field below with bits for status flags (policy url, notation, etc.). */ write_status_printf (STATUS_VALIDSIG, "%s %s %lu %lu %d 0 %d %d %02X %s", pkhex, strtimestamp (sig->timestamp), (ulong)sig->timestamp, (ulong)sig->expiredate, sig->version, sig->pubkey_algo, sig->digest_algo, sig->sig_class, mainpkhex); } /* Print compliance warning for Good signatures. */ if (!rc && pk && !opt.quiet && !gnupg_pk_is_compliant (opt.compliance, pk->pubkey_algo, 0, pk->pkey, nbits_from_pk (pk), NULL)) { log_info (_("WARNING: This key is not suitable for signing" " in %s mode\n"), gnupg_compliance_option_string (opt.compliance)); } /* For good signatures compute and print the trust information. Note that in the Tofu trust model this may ask the user on how to resolve a conflict. */ if (!rc) { rc = check_signatures_trust (c->ctrl, keyblock, pk, sig); } /* Print extra information about the signature. */ if (sig->flags.expired) { log_info (_("Signature expired %s\n"), asctimestamp(sig->expiredate)); if (!rc) rc = gpg_error (GPG_ERR_GENERAL); /* Need a better error here? */ } else if (sig->expiredate) log_info (_("Signature expires %s\n"), asctimestamp(sig->expiredate)); if (opt.verbose) { char pkstrbuf[PUBKEY_STRING_SIZE]; if (pk) pubkey_string (pk, pkstrbuf, sizeof pkstrbuf); else *pkstrbuf = 0; log_info (_("%s signature, digest algorithm %s%s%s\n"), sig->sig_class==0x00?_("binary"): sig->sig_class==0x01?_("textmode"):_("unknown"), gcry_md_algo_name (sig->digest_algo), *pkstrbuf?_(", key algorithm "):"", pkstrbuf); } /* Print final warnings. */ if (!rc && !c->signed_data.used) { /* Signature is basically good but we test whether the deprecated command gpg --verify FILE.sig was used instead of gpg --verify FILE.sig FILE to verify a detached signature. If we figure out that a data file with a matching name exists, we print a warning. The problem is that the first form would also verify a standard signature. This behavior could be used to create a made up .sig file for a tarball by creating a standard signature from a valid detached signature packet (for example from a signed git tag). Then replace the sig file on the FTP server along with a changed tarball. Using the first form the verify command would correctly verify the signature but don't even consider the tarball. */ kbnode_t n; char *dfile; dfile = get_matching_datafile (c->sigfilename); if (dfile) { for (n = c->list; n; n = n->next) if (n->pkt->pkttype != PKT_SIGNATURE) break; if (n) { /* Not only signature packets in the tree thus this is not a detached signature. */ log_info (_("WARNING: not a detached signature; " "file '%s' was NOT verified!\n"), dfile); } xfree (dfile); } } /* Compute compliance with CO_DE_VS. */ if (pk && is_status_enabled () && gnupg_gcrypt_is_compliant (CO_DE_VS) && gnupg_pk_is_compliant (CO_DE_VS, pk->pubkey_algo, 0, pk->pkey, nbits_from_pk (pk), NULL) && gnupg_digest_is_compliant (CO_DE_VS, sig->digest_algo)) write_status_strings (STATUS_VERIFICATION_COMPLIANCE_MODE, gnupg_status_compliance_flag (CO_DE_VS), NULL); free_public_key (pk); pk = NULL; release_kbnode( keyblock ); if (rc) g10_errors_seen = 1; if (opt.batch && rc) g10_exit (1); } else /* Error checking the signature. (neither Good nor Bad). */ { write_status_printf (STATUS_ERRSIG, "%08lX%08lX %d %d %02x %lu %d %s", (ulong)sig->keyid[0], (ulong)sig->keyid[1], sig->pubkey_algo, sig->digest_algo, sig->sig_class, (ulong)sig->timestamp, gpg_err_code (rc), issuer_fpr? issuer_fpr:"-"); if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY) { write_status_printf (STATUS_NO_PUBKEY, "%08lX%08lX", (ulong)sig->keyid[0], (ulong)sig->keyid[1]); } if (gpg_err_code (rc) != GPG_ERR_NOT_PROCESSED) log_error (_("Can't check signature: %s\n"), gpg_strerror (rc)); } free_public_key (pk); release_kbnode (included_keyblock); xfree (issuer_fpr); return rc; } /* * Process the tree which starts at node */ static void proc_tree (CTX c, kbnode_t node) { kbnode_t n1; int rc; if (opt.list_packets || opt.list_only) return; /* We must skip our special plaintext marker packets here because they may be the root packet. These packets are only used in additional checks and skipping them here doesn't matter. */ while (node && node->pkt->pkttype == PKT_GPG_CONTROL && node->pkt->pkt.gpg_control->control == CTRLPKT_PLAINTEXT_MARK) { node = node->next; } if (!node) return; c->trustletter = ' '; if (node->pkt->pkttype == PKT_PUBLIC_KEY || node->pkt->pkttype == PKT_PUBLIC_SUBKEY) { merge_keys_and_selfsig (c->ctrl, node); list_node (c, node); } else if (node->pkt->pkttype == PKT_SECRET_KEY) { merge_keys_and_selfsig (c->ctrl, node); list_node (c, node); } else if (node->pkt->pkttype == PKT_ONEPASS_SIG) { /* Check all signatures. */ if (!c->any.data) { int use_textmode = 0; free_md_filter_context (&c->mfx); /* Prepare to create all requested message digests. */ rc = gcry_md_open (&c->mfx.md, 0, 0); if (rc) goto hash_err; /* Fixme: why looking for the signature packet and not the one-pass packet? */ for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));) gcry_md_enable (c->mfx.md, n1->pkt->pkt.signature->digest_algo); if (n1 && n1->pkt->pkt.onepass_sig->sig_class == 0x01) use_textmode = 1; /* Ask for file and hash it. */ if (c->sigs_only) { if (c->signed_data.used && c->signed_data.data_fd != -1) rc = hash_datafile_by_fd (c->mfx.md, NULL, c->signed_data.data_fd, use_textmode); else rc = hash_datafiles (c->mfx.md, NULL, c->signed_data.data_names, c->sigfilename, use_textmode); } else { rc = ask_for_detached_datafile (c->mfx.md, c->mfx.md2, iobuf_get_real_fname (c->iobuf), use_textmode); } hash_err: if (rc) { log_error ("can't hash datafile: %s\n", gpg_strerror (rc)); return; } } else if (c->signed_data.used) { log_error (_("not a detached signature\n")); return; } for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));) check_sig_and_print (c, n1); } else if (node->pkt->pkttype == PKT_GPG_CONTROL && node->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START) { /* Clear text signed message. */ if (!c->any.data) { log_error ("cleartext signature without data\n"); return; } else if (c->signed_data.used) { log_error (_("not a detached signature\n")); return; } for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));) check_sig_and_print (c, n1); } else if (node->pkt->pkttype == PKT_SIGNATURE) { PKT_signature *sig = node->pkt->pkt.signature; int multiple_ok = 1; n1 = find_next_kbnode (node, PKT_SIGNATURE); if (n1) { byte class = sig->sig_class; byte hash = sig->digest_algo; for (; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE))) { /* We can't currently handle multiple signatures of * different classes (we'd pretty much have to run a * different hash context for each), but if they are all * the same and it is detached signature, we make an * exception. Note that the old code also disallowed * multiple signatures if the digest algorithms are * different. We softened this restriction only for * detached signatures, to be on the safe side. */ if (n1->pkt->pkt.signature->sig_class != class || (c->any.data && n1->pkt->pkt.signature->digest_algo != hash)) { multiple_ok = 0; log_info (_("WARNING: multiple signatures detected. " "Only the first will be checked.\n")); break; } } } if (sig->sig_class != 0x00 && sig->sig_class != 0x01) { log_info(_("standalone signature of class 0x%02x\n"), sig->sig_class); } else if (!c->any.data) { /* Detached signature */ free_md_filter_context (&c->mfx); rc = gcry_md_open (&c->mfx.md, sig->digest_algo, 0); if (rc) goto detached_hash_err; if (multiple_ok) { /* If we have and want to handle multiple signatures we * need to enable all hash algorithms for the context. */ for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE)); ) if (!openpgp_md_test_algo (n1->pkt->pkt.signature->digest_algo)) gcry_md_enable (c->mfx.md, map_md_openpgp_to_gcry (n1->pkt->pkt.signature->digest_algo)); } if (RFC2440 || RFC4880) ; /* Strict RFC mode. */ else if (sig->digest_algo == DIGEST_ALGO_SHA1 && sig->pubkey_algo == PUBKEY_ALGO_DSA && sig->sig_class == 0x01) { /* Enable a workaround for a pgp5 bug when the detached * signature has been created in textmode. Note that we * do not implement this for multiple signatures with * different hash algorithms. */ rc = gcry_md_open (&c->mfx.md2, sig->digest_algo, 0); if (rc) goto detached_hash_err; } /* Here we used to have another hack to work around a pgp * 2 bug: It worked by not using the textmode for detached * signatures; this would let the first signature check * (on md) fail but the second one (on md2), which adds an * extra CR would then have produced the "correct" hash. * This is very, very ugly hack but it may haved help in * some cases (and break others). * c->mfx.md2? 0 :(sig->sig_class == 0x01) */ if (DBG_HASHING) { gcry_md_debug (c->mfx.md, "verify"); if (c->mfx.md2) gcry_md_debug (c->mfx.md2, "verify2"); } if (c->sigs_only) { if (c->signed_data.used && c->signed_data.data_fd != -1) rc = hash_datafile_by_fd (c->mfx.md, c->mfx.md2, c->signed_data.data_fd, (sig->sig_class == 0x01)); else rc = hash_datafiles (c->mfx.md, c->mfx.md2, c->signed_data.data_names, c->sigfilename, (sig->sig_class == 0x01)); } else { rc = ask_for_detached_datafile (c->mfx.md, c->mfx.md2, iobuf_get_real_fname(c->iobuf), (sig->sig_class == 0x01)); } detached_hash_err: if (rc) { log_error ("can't hash datafile: %s\n", gpg_strerror (rc)); return; } } else if (c->signed_data.used) { log_error (_("not a detached signature\n")); return; } else if (!opt.quiet) log_info (_("old style (PGP 2.x) signature\n")); if (multiple_ok) { for (n1 = node; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE))) check_sig_and_print (c, n1); } else check_sig_and_print (c, node); } else { dump_kbnode (c->list); log_error ("invalid root packet detected in proc_tree()\n"); dump_kbnode (node); } } diff --git a/g10/test-stubs.c b/g10/test-stubs.c index 913d49890..174af82f7 100644 --- a/g10/test-stubs.c +++ b/g10/test-stubs.c @@ -1,557 +1,557 @@ /* test-stubs.c - The GnuPG signature verify utility * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2005, 2006, * 2008, 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 . */ #include #include #include #include #include #include #include #define INCLUDED_BY_MAIN_MODULE 1 #include "gpg.h" #include "../common/util.h" #include "packet.h" #include "../common/iobuf.h" #include "main.h" #include "options.h" #include "keydb.h" #include "trustdb.h" #include "filter.h" #include "../common/ttyio.h" #include "../common/i18n.h" #include "../common/sysutils.h" #include "../common/status.h" #include "call-agent.h" int g10_errors_seen; void g10_exit( int rc ) { rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0; exit(rc ); } /* Stub: * We have to override the trustcheck from pkclist.c because * this utility assumes that all keys in the keyring are trustworthy */ gpg_error_t check_signatures_trust (ctrl_t ctrl, kbnode_t kblock, PKT_public_key *pk, PKT_signature *sig) { (void)ctrl; (void)kblock; (void)pk; (void)sig; return 0; } void read_trust_options (ctrl_t ctrl, byte *trust_model, ulong *created, ulong *nextcheck, byte *marginals, byte *completes, byte *cert_depth, byte *min_cert_level) { (void)ctrl; (void)trust_model; (void)created; (void)nextcheck; (void)marginals; (void)completes; (void)cert_depth; (void)min_cert_level; } /* Stub: * We don't have the trustdb , so we have to provide some stub functions * instead */ int cache_disabled_value (ctrl_t ctrl, PKT_public_key *pk) { (void)ctrl; (void)pk; return 0; } void check_trustdb_stale (ctrl_t ctrl) { (void)ctrl; } int get_validity_info (ctrl_t ctrl, kbnode_t kb, PKT_public_key *pk, PKT_user_id *uid) { (void)ctrl; (void)kb; (void)pk; (void)uid; return '?'; } unsigned int get_validity (ctrl_t ctrl, kbnode_t kb, PKT_public_key *pk, PKT_user_id *uid, PKT_signature *sig, int may_ask) { (void)ctrl; (void)kb; (void)pk; (void)uid; (void)sig; (void)may_ask; return 0; } const char * trust_value_to_string (unsigned int value) { (void)value; return "err"; } const char * uid_trust_string_fixed (ctrl_t ctrl, PKT_public_key *key, PKT_user_id *uid) { (void)ctrl; (void)key; (void)uid; return "err"; } int get_ownertrust_info (ctrl_t ctrl, PKT_public_key *pk, int no_create) { (void)ctrl; (void)pk; (void)no_create; return '?'; } unsigned int get_ownertrust (ctrl_t ctrl, PKT_public_key *pk) { (void)ctrl; (void)pk; return TRUST_UNKNOWN; } /* Stubs: * Because we only work with trusted keys, it does not make sense to * get them from a keyserver */ struct keyserver_spec * keyserver_match (struct keyserver_spec *spec) { (void)spec; return NULL; } int keyserver_any_configured (ctrl_t ctrl) { (void)ctrl; return 0; } int -keyserver_import_keyid (u32 *keyid, void *dummy, int quick) +keyserver_import_keyid (u32 *keyid, void *dummy, unsigned int flags) { (void)keyid; (void)dummy; - (void)quick; + (void)flags; return -1; } int keyserver_import_fprint (ctrl_t ctrl, const byte *fprint,size_t fprint_len, - struct keyserver_spec *keyserver, int quick) + struct keyserver_spec *keyserver, unsigned int flags) { (void)ctrl; (void)fprint; (void)fprint_len; (void)keyserver; - (void)quick; + (void)flags; return -1; } int keyserver_import_cert (const char *name) { (void)name; return -1; } gpg_error_t -keyserver_import_wkd (ctrl_t ctrl, const char *name, int quick, +keyserver_import_wkd (ctrl_t ctrl, const char *name, unsigned int flags, unsigned char **fpr, size_t *fpr_len) { (void)ctrl; (void)name; - (void)quick; + (void)flags; (void)fpr; (void)fpr_len; return GPG_ERR_BUG; } int keyserver_import_name (const char *name,struct keyserver_spec *spec) { (void)name; (void)spec; return -1; } int keyserver_import_ntds (ctrl_t ctrl, const char *mbox, unsigned char **fpr, size_t *fprlen) { (void)ctrl; (void)mbox; (void)fpr; (void)fprlen; return -1; } int keyserver_import_ldap (const char *name) { (void)name; return -1; } gpg_error_t read_key_from_file_or_buffer (ctrl_t ctrl, const char *fname, const void *buffer, size_t buflen, kbnode_t *r_keyblock) { (void)ctrl; (void)fname; (void)buffer; (void)buflen; (void)r_keyblock; return -1; } gpg_error_t import_included_key_block (ctrl_t ctrl, kbnode_t keyblock) { (void)ctrl; (void)keyblock; return -1; } /* Stub: * No encryption here but mainproc links to these functions. */ gpg_error_t get_session_key (ctrl_t ctrl, struct pubkey_enc_list *k, DEK *dek) { (void)ctrl; (void)k; (void)dek; return GPG_ERR_GENERAL; } /* Stub: */ gpg_error_t get_override_session_key (DEK *dek, const char *string) { (void)dek; (void)string; return GPG_ERR_GENERAL; } /* Stub: */ int decrypt_data (ctrl_t ctrl, void *procctx, PKT_encrypted *ed, DEK *dek) { (void)ctrl; (void)procctx; (void)ed; (void)dek; return GPG_ERR_GENERAL; } /* Stub: * No interactive commands, so we don't need the helptexts */ void display_online_help (const char *keyword) { (void)keyword; } /* Stub: * We don't use secret keys, but getkey.c links to this */ int check_secret_key (PKT_public_key *pk, int n) { (void)pk; (void)n; return GPG_ERR_GENERAL; } /* Stub: * No secret key, so no passphrase needed */ DEK * passphrase_to_dek (int cipher_algo, STRING2KEY *s2k, int create, int nocache, const char *tmp, int *canceled) { (void)cipher_algo; (void)s2k; (void)create; (void)nocache; (void)tmp; if (canceled) *canceled = 0; return NULL; } void passphrase_clear_cache (const char *cacheid) { (void)cacheid; } struct keyserver_spec * parse_preferred_keyserver(PKT_signature *sig) { (void)sig; return NULL; } struct keyserver_spec * parse_keyserver_uri (const char *uri, int require_scheme, const char *configname, unsigned int configlineno) { (void)uri; (void)require_scheme; (void)configname; (void)configlineno; return NULL; } void free_keyserver_spec (struct keyserver_spec *keyserver) { (void)keyserver; } /* Stubs to avoid linking to photoid.c */ void show_photos (const struct user_attribute *attrs, int count, PKT_public_key *pk) { (void)attrs; (void)count; (void)pk; } int parse_image_header (const struct user_attribute *attr, byte *type, u32 *len) { (void)attr; (void)type; (void)len; return 0; } char * image_type_to_string (byte type, int string) { (void)type; (void)string; return NULL; } #ifdef ENABLE_CARD_SUPPORT int agent_scd_getattr (const char *name, struct agent_card_info_s *info) { (void)name; (void)info; return 0; } #endif /* ENABLE_CARD_SUPPORT */ /* We do not do any locking, so use these stubs here */ void dotlock_disable (void) { } dotlock_t dotlock_create (const char *file_to_lock, unsigned int flags) { (void)file_to_lock; (void)flags; return NULL; } void dotlock_destroy (dotlock_t h) { (void)h; } int dotlock_take (dotlock_t h, long timeout) { (void)h; (void)timeout; return 0; } int dotlock_release (dotlock_t h) { (void)h; return 0; } void dotlock_remove_lockfiles (void) { } int agent_probe_secret_key (ctrl_t ctrl, PKT_public_key *pk) { (void)ctrl; (void)pk; return 0; } gpg_error_t agent_probe_any_secret_key (ctrl_t ctrl, kbnode_t keyblock) { (void)ctrl; (void)keyblock; return gpg_error (GPG_ERR_NO_SECKEY); } gpg_error_t agent_get_keyinfo (ctrl_t ctrl, const char *hexkeygrip, char **r_serialno, int *r_cleartext) { (void)ctrl; (void)hexkeygrip; (void)r_cleartext; *r_serialno = NULL; return gpg_error (GPG_ERR_NO_SECKEY); } gpg_error_t export_pubkey_buffer (ctrl_t ctrl, const char *keyspec, unsigned int options, const void *prefix, size_t prefixlen, export_stats_t stats, kbnode_t *r_keyblock, void **r_data, size_t *r_datalen) { (void)ctrl; (void)keyspec; (void)options; (void)prefix; (void)prefixlen; (void)stats; *r_keyblock = NULL; *r_data = NULL; *r_datalen = 0; return gpg_error (GPG_ERR_NOT_IMPLEMENTED); } gpg_error_t tofu_write_tfs_record (ctrl_t ctrl, estream_t fp, PKT_public_key *pk, const char *user_id) { (void)ctrl; (void)fp; (void)pk; (void)user_id; return gpg_error (GPG_ERR_GENERAL); } gpg_error_t tofu_get_policy (ctrl_t ctrl, PKT_public_key *pk, PKT_user_id *user_id, enum tofu_policy *policy) { (void)ctrl; (void)pk; (void)user_id; (void)policy; return gpg_error (GPG_ERR_GENERAL); } const char * tofu_policy_str (enum tofu_policy policy) { (void)policy; return "unknown"; } void tofu_begin_batch_update (ctrl_t ctrl) { (void)ctrl; } void tofu_end_batch_update (ctrl_t ctrl) { (void)ctrl; } gpg_error_t tofu_notice_key_changed (ctrl_t ctrl, kbnode_t kb) { (void) ctrl; (void) kb; return 0; } int get_revocation_reason (PKT_signature *sig, char **r_reason, char **r_comment, size_t *r_commentlen) { (void)sig; (void)r_commentlen; if (r_reason) *r_reason = NULL; if (r_comment) *r_comment = NULL; return 0; }