diff --git a/dirmngr/dirmngr.c b/dirmngr/dirmngr.c index 38ae1c6ed..ebb6ae08a 100644 --- a/dirmngr/dirmngr.c +++ b/dirmngr/dirmngr.c @@ -1,2423 +1,2458 @@ /* dirmngr.c - Keyserver and X.509 LDAP access * Copyright (C) 2002 Klarälvdalens Datakonsult AB * Copyright (C) 2003-2004, 2006-2007, 2008, 2010-2011, 2020 g10 Code GmbH * 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 . * SPDX-License-Identifier: GPL-3.0-or-later */ #include #include #include #include #include #include #include #include #include #include #ifndef HAVE_W32_SYSTEM #include #include #endif #include #include #ifdef HAVE_SIGNAL_H # include #endif #ifdef HAVE_INOTIFY_INIT # include #endif /*HAVE_INOTIFY_INIT*/ #include #include "dirmngr-err.h" #if HTTP_USE_NTBTLS # include #elif HTTP_USE_GNUTLS # include #endif /*HTTP_USE_GNUTLS*/ #define INCLUDED_BY_MAIN_MODULE 1 #define GNUPG_COMMON_NEED_AFLOCAL #include "dirmngr.h" #include #include "certcache.h" #include "crlcache.h" #include "crlfetch.h" #include "misc.h" #if USE_LDAP # include "ldapserver.h" #endif #include "../common/asshelp.h" #if USE_LDAP # include "ldap-wrapper.h" #endif #include "../common/comopt.h" #include "../common/init.h" #include "../common/gc-opt-flags.h" #include "dns-stuff.h" #include "http-common.h" #ifndef ENAMETOOLONG # define ENAMETOOLONG EINVAL #endif enum cmd_and_opt_values { aNull = 0, oCsh = 'c', oQuiet = 'q', oSh = 's', oVerbose = 'v', oNoVerbose = 500, aServer, aDaemon, aSupervised, aListCRLs, aLoadCRL, aFetchCRL, aShutdown, aFlush, aGPGConfList, aGPGConfTest, aGPGConfVersions, oOptions, oDebug, oDebugAll, oDebugWait, oDebugLevel, oGnutlsDebug, oNoGreeting, oNoOptions, oHomedir, oNoDetach, oLogFile, oBatch, oDisableHTTP, oDisableLDAP, oDisableIPv4, oDisableIPv6, oIgnoreLDAPDP, oIgnoreHTTPDP, oIgnoreOCSPSvcUrl, oHonorHTTPProxy, oHTTPProxy, oLDAPProxy, oOnlyLDAPProxy, + oLDAPServer, oLDAPFile, oLDAPTimeout, oLDAPAddServers, oOCSPResponder, oOCSPSigner, oOCSPMaxClockSkew, oOCSPMaxPeriod, oOCSPCurrentPeriod, oMaxReplies, oHkpCaCert, oFakedSystemTime, oForce, oAllowOCSP, oAllowVersionCheck, oSocketName, oLDAPWrapperProgram, oHTTPWrapperProgram, oIgnoreCertExtension, oUseTor, oNoUseTor, oKeyServer, oNameServer, oDisableCheckOwnSocket, oStandardResolver, oRecursiveResolver, oResolverTimeout, oConnectTimeout, oConnectQuickTimeout, oListenBacklog, aTest }; static gpgrt_opt_t opts[] = { ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"), ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"), ARGPARSE_c (aGPGConfVersions, "gpgconf-versions", "@"), ARGPARSE_group (300, N_("@Commands:\n ")), ARGPARSE_c (aServer, "server", N_("run in server mode (foreground)") ), ARGPARSE_c (aDaemon, "daemon", N_("run in daemon mode (background)") ), #ifndef HAVE_W32_SYSTEM ARGPARSE_c (aSupervised, "supervised", N_("run in supervised mode")), #endif ARGPARSE_c (aListCRLs, "list-crls", N_("list the contents of the CRL cache")), ARGPARSE_c (aLoadCRL, "load-crl", N_("|FILE|load CRL from FILE into cache")), ARGPARSE_c (aFetchCRL, "fetch-crl", N_("|URL|fetch a CRL from URL")), ARGPARSE_c (aShutdown, "shutdown", N_("shutdown the dirmngr")), ARGPARSE_c (aFlush, "flush", N_("flush the cache")), ARGPARSE_header (NULL, N_("Options used for startup")), ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")), ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")), ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")), ARGPARSE_s_s (oHomedir, "homedir", "@"), ARGPARSE_conffile (oOptions, "options", N_("|FILE|read options from FILE")), ARGPARSE_noconffile (oNoOptions, "no-options", "@"), ARGPARSE_header ("Monitor", N_("Options controlling the diagnostic output")), ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")), ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")), ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"), ARGPARSE_s_s (oDebugLevel, "debug-level", N_("|LEVEL|set the debugging level to LEVEL")), ARGPARSE_s_s (oDebug, "debug", "@"), ARGPARSE_s_n (oDebugAll, "debug-all", "@"), ARGPARSE_s_i (oGnutlsDebug, "gnutls-debug", "@"), ARGPARSE_s_i (oGnutlsDebug, "tls-debug", "@"), ARGPARSE_s_i (oDebugWait, "debug-wait", "@"), ARGPARSE_s_s (oLogFile, "log-file", N_("|FILE|write server mode logs to FILE")), ARGPARSE_header ("Configuration", N_("Options controlling the configuration")), ARGPARSE_s_n (oAllowVersionCheck, "allow-version-check", N_("allow online software version check")), ARGPARSE_s_i (oListenBacklog, "listen-backlog", "@"), ARGPARSE_s_i (oMaxReplies, "max-replies", N_("|N|do not return more than N items in one query")), ARGPARSE_s_u (oFakedSystemTime, "faked-system-time", "@"), /*(epoch time)*/ ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"), ARGPARSE_s_s (oIgnoreCertExtension,"ignore-cert-extension", "@"), ARGPARSE_header ("Network", N_("Network related options")), ARGPARSE_s_n (oUseTor, "use-tor", N_("route all network traffic via Tor")), ARGPARSE_s_n (oNoUseTor, "no-use-tor", "@"), ARGPARSE_s_n (oDisableIPv4, "disable-ipv4", "@"), ARGPARSE_s_n (oDisableIPv6, "disable-ipv6", "@"), ARGPARSE_s_n (oStandardResolver, "standard-resolver", "@"), ARGPARSE_s_n (oRecursiveResolver, "recursive-resolver", "@"), ARGPARSE_s_i (oResolverTimeout, "resolver-timeout", "@"), ARGPARSE_s_s (oNameServer, "nameserver", "@"), ARGPARSE_s_i (oConnectTimeout, "connect-timeout", "@"), ARGPARSE_s_i (oConnectQuickTimeout, "connect-quick-timeout", "@"), ARGPARSE_header ("Keyserver", N_("Configuration for Keyservers")), ARGPARSE_s_s (oKeyServer, "keyserver", N_("|URL|use keyserver at URL")), ARGPARSE_s_s (oHkpCaCert, "hkp-cacert", N_("|FILE|use the CA certificates in FILE for HKP over TLS")), ARGPARSE_header ("HTTP", N_("Configuration for HTTP servers")), ARGPARSE_s_n (oDisableHTTP, "disable-http", N_("inhibit the use of HTTP")), ARGPARSE_s_n (oIgnoreHTTPDP,"ignore-http-dp", N_("ignore HTTP CRL distribution points")), ARGPARSE_s_s (oHTTPProxy, "http-proxy", N_("|URL|redirect all HTTP requests to URL")), ARGPARSE_s_n (oHonorHTTPProxy, "honor-http-proxy", N_("use system's HTTP proxy setting")), ARGPARSE_s_s (oLDAPWrapperProgram, "ldap-wrapper-program", "@"), ARGPARSE_header ("LDAP", N_("Configuration of LDAP servers to use")), ARGPARSE_s_n (oDisableLDAP, "disable-ldap", N_("inhibit the use of LDAP")), ARGPARSE_s_n (oIgnoreLDAPDP,"ignore-ldap-dp", N_("ignore LDAP CRL distribution points")), ARGPARSE_s_s (oLDAPProxy, "ldap-proxy", N_("|HOST|use HOST for LDAP queries")), ARGPARSE_s_n (oOnlyLDAPProxy, "only-ldap-proxy", N_("do not use fallback hosts with --ldap-proxy")), + ARGPARSE_s_s (oLDAPServer, "ldapserver", + N_("|SPEC|use this keyserver to lookup keys")), ARGPARSE_s_s (oLDAPFile, "ldapserverlist-file", N_("|FILE|read LDAP server list from FILE")), ARGPARSE_s_n (oLDAPAddServers, "add-servers", N_("add new servers discovered in CRL distribution" " points to serverlist")), ARGPARSE_s_i (oLDAPTimeout, "ldaptimeout", N_("|N|set LDAP timeout to N seconds")), ARGPARSE_header ("OCSP", N_("Configuration for OCSP")), ARGPARSE_s_n (oAllowOCSP, "allow-ocsp", N_("allow sending OCSP requests")), ARGPARSE_s_n (oIgnoreOCSPSvcUrl, "ignore-ocsp-service-url", N_("ignore certificate contained OCSP service URLs")), ARGPARSE_s_s (oOCSPResponder, "ocsp-responder", N_("|URL|use OCSP responder at URL")), ARGPARSE_s_s (oOCSPSigner, "ocsp-signer", N_("|FPR|OCSP response signed by FPR")), ARGPARSE_s_i (oOCSPMaxClockSkew, "ocsp-max-clock-skew", "@"), ARGPARSE_s_i (oOCSPMaxPeriod, "ocsp-max-period", "@"), ARGPARSE_s_i (oOCSPCurrentPeriod, "ocsp-current-period", "@"), ARGPARSE_header (NULL, N_("Other options")), ARGPARSE_s_n (oForce, "force", N_("force loading of outdated CRLs")), ARGPARSE_s_s (oSocketName, "socket-name", "@"), /* Only for debugging. */ ARGPARSE_header (NULL, ""), /* Stop the header group. */ /* Not yet used options. */ ARGPARSE_s_n (oBatch, "batch", "@"), ARGPARSE_s_s (oHTTPWrapperProgram, "http-wrapper-program", "@"), ARGPARSE_group (302,N_("@\n(See the \"info\" manual for a complete listing " "of all commands and options)\n")), ARGPARSE_end () }; /* The list of supported debug flags. */ static struct debug_flags_s debug_flags [] = { { DBG_X509_VALUE , "x509" }, { DBG_CRYPTO_VALUE , "crypto" }, { DBG_MEMORY_VALUE , "memory" }, { DBG_CACHE_VALUE , "cache" }, { DBG_MEMSTAT_VALUE, "memstat" }, { DBG_HASHING_VALUE, "hashing" }, { DBG_IPC_VALUE , "ipc" }, { DBG_DNS_VALUE , "dns" }, { DBG_NETWORK_VALUE, "network" }, { DBG_LOOKUP_VALUE , "lookup" }, { DBG_EXTPROG_VALUE, "extprog" }, { 77, NULL } /* 77 := Do not exit on "help" or "?". */ }; #define DEFAULT_MAX_REPLIES 10 #define DEFAULT_LDAP_TIMEOUT 15 /* seconds */ #define DEFAULT_CONNECT_TIMEOUT (15*1000) /* 15 seconds */ #define DEFAULT_CONNECT_QUICK_TIMEOUT ( 2*1000) /* 2 seconds */ /* For the cleanup handler we need to keep track of the socket's name. */ static const char *socket_name; /* If the socket has been redirected, this is the name of the redirected socket.. */ static const char *redir_socket_name; /* We need to keep track of the server's nonces (these are dummies for POSIX systems). */ static assuan_sock_nonce_t socket_nonce; /* Value for the listen() backlog argument. * Change at runtime with --listen-backlog. */ static int listen_backlog = 64; /* Only if this flag has been set will we remove the socket file. */ static int cleanup_socket; /* Keep track of the current log file so that we can avoid updating the log file after a SIGHUP if it didn't changed. Malloced. */ static char *current_logfile; /* Helper to implement --debug-level. */ static const char *debug_level; /* Helper to set the NTBTLS or GNUTLS log level. */ static int opt_gnutls_debug = -1; /* Flag indicating that a shutdown has been requested. */ static volatile int shutdown_pending; /* Flags to indicate that we shall not watch our own socket. */ static int disable_check_own_socket; /* Flag to control the Tor mode. */ static enum { TOR_MODE_AUTO = 0, /* Switch to NO or YES */ TOR_MODE_NEVER, /* Never use Tor. */ TOR_MODE_NO, /* Do not use Tor */ TOR_MODE_YES, /* Use Tor */ TOR_MODE_FORCE /* Force using Tor */ } tor_mode; /* Counter for the active connections. */ static int active_connections; /* This flag is set by any network access and used by the housekeeping * thread to run background network tasks. */ static int network_activity_seen; /* A list of filenames registered with --hkp-cacert. */ static strlist_t hkp_cacert_filenames; +/* A flag used to clear the list of ldapservers iff --ldapserver is + * given on the command line or one of the conf files. In this case we + * want to clear all old specifications through the legacy + * dirmngr_ldapservers.conf. */ +static int ldapserver_list_needs_reset; /* The timer tick used for housekeeping stuff. The second constant is used when a shutdown is pending. */ #define TIMERTICK_INTERVAL (60) #define TIMERTICK_INTERVAL_SHUTDOWN (4) /* How oft to run the housekeeping. */ #define HOUSEKEEPING_INTERVAL (600) /* This union is used to avoid compiler warnings in case a pointer is 64 bit and an int 32 bit. We store an integer in a pointer and get it back later (npth_getspecific et al.). */ union int_and_ptr_u { int aint; assuan_fd_t afd; void *aptr; }; /* The key used to store the current file descriptor in the thread local storage. We use this in conjunction with the log_set_pid_suffix_cb feature. */ #ifndef HAVE_W32_SYSTEM static npth_key_t my_tlskey_current_fd; #endif /* Prototypes. */ static void cleanup (void); #if USE_LDAP static ldap_server_t parse_ldapserver_file (const char* filename, int ienoent); #endif /*USE_LDAP*/ static fingerprint_list_t parse_ocsp_signer (const char *string); static void netactivity_action (void); static void handle_connections (assuan_fd_t listen_fd); static void gpgconf_versions (void); /* NPth wrapper function definitions. */ ASSUAN_SYSTEM_NPTH_IMPL; static const char * my_strusage( int level ) { const char *p; switch ( level ) { case 9: p = "GPL-3.0-or-later"; break; case 11: p = "@DIRMNGR@ (@GNUPG@)"; break; case 13: p = VERSION; break; case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break; case 17: p = PRINTABLE_OS_NAME; break; /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug reporting address. This is so that we can change the reporting address without breaking the translations. */ case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break; case 49: p = PACKAGE_BUGREPORT; break; case 1: case 40: p = _("Usage: @DIRMNGR@ [options] (-h for help)"); break; case 41: p = _("Syntax: @DIRMNGR@ [options] [command [args]]\n" "Keyserver, CRL, and OCSP access for @GNUPG@\n"); break; default: p = NULL; } return p; } /* Callback from libksba to hash a provided buffer. Our current implementation does only allow SHA-1 for hashing. This may be extended by mapping the name, testing for algorithm availability and adjust the length checks accordingly. */ static gpg_error_t my_ksba_hash_buffer (void *arg, const char *oid, const void *buffer, size_t length, size_t resultsize, unsigned char *result, size_t *resultlen) { (void)arg; if (oid && strcmp (oid, "1.3.14.3.2.26")) return gpg_error (GPG_ERR_NOT_SUPPORTED); if (resultsize < 20) return gpg_error (GPG_ERR_BUFFER_TOO_SHORT); gcry_md_hash_buffer (2, result, buffer, length); *resultlen = 20; return 0; } /* GNUTLS log function callback. */ #ifdef HTTP_USE_GNUTLS static void my_gnutls_log (int level, const char *text) { int n; n = strlen (text); while (n && text[n-1] == '\n') n--; log_debug ("gnutls:L%d: %.*s\n", level, n, text); } #endif /*HTTP_USE_GNUTLS*/ /* Setup the debugging. With a LEVEL of NULL only the active debug flags are propagated to the subsystems. With LEVEL set, a specific set of debug flags is set; thus overriding all flags already set. */ static void set_debug (void) { int numok = (debug_level && digitp (debug_level)); int numlvl = numok? atoi (debug_level) : 0; if (!debug_level) ; else if (!strcmp (debug_level, "none") || (numok && numlvl < 1)) opt.debug = 0; else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2)) opt.debug = DBG_IPC_VALUE; else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5)) opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE|DBG_LOOKUP_VALUE); else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8)) opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE|DBG_LOOKUP_VALUE |DBG_CACHE_VALUE|DBG_CRYPTO_VALUE); else if (!strcmp (debug_level, "guru") || numok) { opt.debug = ~0; /* Unless the "guru" string has been used we don't want to allow hashing debugging. The rationale is that people tend to select the highest debug value and would then clutter their disk with debug files which may reveal confidential data. */ if (numok) opt.debug &= ~(DBG_HASHING_VALUE); } else { log_error (_("invalid debug-level '%s' given\n"), debug_level); log_info (_("valid debug levels are: %s\n"), "none, basic, advanced, expert, guru"); opt.debug = 0; /* Reset debugging, so that prior debug statements won't have an undesired effect. */ } if (opt.debug && !opt.verbose) { opt.verbose = 1; gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose); } if (opt.debug && opt.quiet) opt.quiet = 0; if (opt.debug & DBG_CRYPTO_VALUE ) gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1); #if HTTP_USE_NTBTLS if (opt_gnutls_debug >= 0) { ntbtls_set_debug (opt_gnutls_debug, NULL, NULL); } #elif HTTP_USE_GNUTLS if (opt_gnutls_debug >= 0) { gnutls_global_set_log_function (my_gnutls_log); gnutls_global_set_log_level (opt_gnutls_debug); } #endif /*HTTP_USE_GNUTLS*/ if (opt.debug) parse_debug_flag (NULL, &opt.debug, debug_flags); } static void set_tor_mode (void) { if (dirmngr_use_tor ()) { /* Enable Tor mode and when called again force a new circuit * (e.g. on SIGHUP). */ enable_dns_tormode (1); if (assuan_sock_set_flag (ASSUAN_INVALID_FD, "tor-mode", 1)) { log_error ("error enabling Tor mode: %s\n", strerror (errno)); log_info ("(is your Libassuan recent enough?)\n"); } } else disable_dns_tormode (); } /* Return true if Tor shall be used. */ int dirmngr_use_tor (void) { if (tor_mode == TOR_MODE_AUTO) { /* Figure out whether Tor is running. */ assuan_fd_t sock; sock = assuan_sock_connect_byname (NULL, 0, 0, NULL, ASSUAN_SOCK_TOR); if (sock == ASSUAN_INVALID_FD) tor_mode = TOR_MODE_NO; else { tor_mode = TOR_MODE_YES; assuan_sock_close (sock); } } if (tor_mode == TOR_MODE_FORCE) return 2; /* Use Tor (using 2 to indicate force mode) */ else if (tor_mode == TOR_MODE_YES) return 1; /* Use Tor */ else return 0; /* Do not use Tor. */ } static void wrong_args (const char *text) { es_fprintf (es_stderr, _("usage: %s [options] "), DIRMNGR_NAME); es_fputs (text, es_stderr); es_putc ('\n', es_stderr); dirmngr_exit (2); } /* Helper to stop the reaper thread for the ldap wrapper. */ static void shutdown_reaper (void) { #if USE_LDAP ldap_wrapper_wait_connections (); #endif } /* Handle options which are allowed to be reset after program start. Return true if the current option in PARGS could be handled and false if not. As a special feature, passing a value of NULL for PARGS, resets the options to the default. REREAD should be set true if it is not the initial option parsing. */ static int parse_rereadable_options (gpgrt_argparse_t *pargs, int reread) { if (!pargs) { /* Reset mode. */ opt.quiet = 0; opt.verbose = 0; opt.debug = 0; opt.ldap_wrapper_program = NULL; opt.disable_http = 0; opt.disable_ldap = 0; opt.honor_http_proxy = 0; opt.http_proxy = NULL; opt.ldap_proxy = NULL; opt.only_ldap_proxy = 0; opt.ignore_http_dp = 0; opt.ignore_ldap_dp = 0; opt.ignore_ocsp_service_url = 0; opt.allow_ocsp = 0; opt.allow_version_check = 0; opt.ocsp_responder = NULL; opt.ocsp_max_clock_skew = 10 * 60; /* 10 minutes. */ opt.ocsp_max_period = 90 * 86400; /* 90 days. */ opt.ocsp_current_period = 3 * 60 * 60; /* 3 hours. */ opt.max_replies = DEFAULT_MAX_REPLIES; while (opt.ocsp_signer) { fingerprint_list_t tmp = opt.ocsp_signer->next; xfree (opt.ocsp_signer); opt.ocsp_signer = tmp; } FREE_STRLIST (opt.ignored_cert_extensions); http_register_tls_ca (NULL); FREE_STRLIST (hkp_cacert_filenames); FREE_STRLIST (opt.keyserver); /* Note: We do not allow resetting of TOR_MODE_FORCE at runtime. */ if (tor_mode != TOR_MODE_FORCE) tor_mode = TOR_MODE_AUTO; disable_check_own_socket = 0; enable_standard_resolver (0); set_dns_timeout (0); opt.connect_timeout = 0; opt.connect_quick_timeout = 0; + ldapserver_list_needs_reset = 1; return 1; } switch (pargs->r_opt) { case oQuiet: opt.quiet = 1; break; case oVerbose: opt.verbose++; break; case oDebug: parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags); break; case oDebugAll: opt.debug = ~0; break; case oDebugLevel: debug_level = pargs->r.ret_str; break; case oGnutlsDebug: opt_gnutls_debug = pargs->r.ret_int; break; case oLogFile: if (!reread) return 0; /* Not handled. */ if (!current_logfile || !pargs->r.ret_str || strcmp (current_logfile, pargs->r.ret_str)) { log_set_file (pargs->r.ret_str); xfree (current_logfile); current_logfile = xtrystrdup (pargs->r.ret_str); } break; case oDisableCheckOwnSocket: disable_check_own_socket = 1; break; case oLDAPWrapperProgram: opt.ldap_wrapper_program = pargs->r.ret_str; break; case oHTTPWrapperProgram: opt.http_wrapper_program = pargs->r.ret_str; break; case oDisableHTTP: opt.disable_http = 1; break; case oDisableLDAP: opt.disable_ldap = 1; break; case oDisableIPv4: opt.disable_ipv4 = 1; break; case oDisableIPv6: opt.disable_ipv6 = 1; break; case oHonorHTTPProxy: opt.honor_http_proxy = 1; break; case oHTTPProxy: opt.http_proxy = pargs->r.ret_str; break; case oLDAPProxy: opt.ldap_proxy = pargs->r.ret_str; break; case oOnlyLDAPProxy: opt.only_ldap_proxy = 1; break; case oIgnoreHTTPDP: opt.ignore_http_dp = 1; break; case oIgnoreLDAPDP: opt.ignore_ldap_dp = 1; break; case oIgnoreOCSPSvcUrl: opt.ignore_ocsp_service_url = 1; break; case oAllowOCSP: opt.allow_ocsp = 1; break; case oAllowVersionCheck: opt.allow_version_check = 1; break; case oOCSPResponder: opt.ocsp_responder = pargs->r.ret_str; break; case oOCSPSigner: opt.ocsp_signer = parse_ocsp_signer (pargs->r.ret_str); break; case oOCSPMaxClockSkew: opt.ocsp_max_clock_skew = pargs->r.ret_int; break; case oOCSPMaxPeriod: opt.ocsp_max_period = pargs->r.ret_int; break; case oOCSPCurrentPeriod: opt.ocsp_current_period = pargs->r.ret_int; break; case oMaxReplies: opt.max_replies = pargs->r.ret_int; break; case oHkpCaCert: { /* We need to register the filenames with gnutls (http.c) and * also for our own cert cache. */ char *tmpname; /* Do tilde expansion and make path absolute. */ tmpname = make_absfilename (pargs->r.ret_str, NULL); http_register_tls_ca (tmpname); add_to_strlist (&hkp_cacert_filenames, pargs->r.ret_str); xfree (tmpname); } break; case oIgnoreCertExtension: add_to_strlist (&opt.ignored_cert_extensions, pargs->r.ret_str); break; case oUseTor: tor_mode = TOR_MODE_FORCE; break; case oNoUseTor: if (tor_mode != TOR_MODE_FORCE) tor_mode = TOR_MODE_NEVER; break; case oStandardResolver: enable_standard_resolver (1); break; case oRecursiveResolver: enable_recursive_resolver (1); break; + case oLDAPServer: + { + ldap_server_t server; + char *p; + + p = pargs->r.ret_str; + if (!strncmp (p, "ldap:", 5) && !(p[5] == '/' && p[6] == '/')) + p += 5; + + server = ldapserver_parse_one (p, NULL, 0); + if (server) + { + if (ldapserver_list_needs_reset) + { + ldapserver_list_needs_reset = 0; + ldapserver_list_free (opt.ldapservers); + opt.ldapservers = NULL; + } + server->next = opt.ldapservers; + opt.ldapservers = server; + } + } + break; + case oKeyServer: if (*pargs->r.ret_str) add_to_strlist (&opt.keyserver, pargs->r.ret_str); break; case oNameServer: set_dns_nameserver (pargs->r.ret_str); break; case oResolverTimeout: set_dns_timeout (pargs->r.ret_int); break; case oConnectTimeout: opt.connect_timeout = pargs->r.ret_ulong * 1000; break; case oConnectQuickTimeout: opt.connect_quick_timeout = pargs->r.ret_ulong * 1000; break; default: return 0; /* Not handled. */ } set_dns_verbose (opt.verbose, !!DBG_DNS); http_set_verbose (opt.verbose, !!DBG_NETWORK); set_dns_disable_ipv4 (opt.disable_ipv4); set_dns_disable_ipv6 (opt.disable_ipv6); return 1; /* Handled. */ } /* This function is called after option parsing to adjust some values * and call option setup functions. */ static void post_option_parsing (void) { /* It would be too surpirsing if the quick timeout is larger than * the standard value. */ if (opt.connect_quick_timeout > opt.connect_timeout) opt.connect_quick_timeout = opt.connect_timeout; set_debug (); } #ifndef HAVE_W32_SYSTEM static int pid_suffix_callback (unsigned long *r_suffix) { union int_and_ptr_u value; memset (&value, 0, sizeof value); value.aptr = npth_getspecific (my_tlskey_current_fd); *r_suffix = value.aint; return (*r_suffix != -1); /* Use decimal representation. */ } #endif /*!HAVE_W32_SYSTEM*/ #if HTTP_USE_NTBTLS static void my_ntbtls_log_handler (void *opaque, int level, const char *fmt, va_list argv) { (void)opaque; if (level == -1) log_logv_prefix (GPGRT_LOGLVL_INFO, "ntbtls: ", fmt, argv); else { char prefix[10+20]; snprintf (prefix, sizeof prefix, "ntbtls(%d): ", level); log_logv_prefix (GPGRT_LOGLVL_DEBUG, prefix, fmt, argv); } } #endif static void thread_init (void) { npth_init (); assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH); gpgrt_set_syscall_clamp (npth_unprotect, npth_protect); /* Now with NPth running we can set the logging callback. Our windows implementation does not yet feature the NPth TLS functions. */ #ifndef HAVE_W32_SYSTEM if (npth_key_create (&my_tlskey_current_fd, NULL) == 0) if (npth_setspecific (my_tlskey_current_fd, NULL) == 0) log_set_pid_suffix_cb (pid_suffix_callback); #endif /*!HAVE_W32_SYSTEM*/ } int main (int argc, char **argv) { enum cmd_and_opt_values cmd = 0; gpgrt_argparse_t pargs; int orig_argc; char **orig_argv; char *last_configname = NULL; const char *configname = NULL; const char *shell; int debug_argparser = 0; int greeting = 0; int nogreeting = 0; int nodetach = 0; int csh_style = 0; char *logfile = NULL; #if USE_LDAP char *ldapfile = NULL; #endif /*USE_LDAP*/ int debug_wait = 0; int rc; struct assuan_malloc_hooks malloc_hooks; early_system_init (); gpgrt_set_strusage (my_strusage); log_set_prefix (DIRMNGR_NAME, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_PID); /* Make sure that our subsystems are ready. */ i18n_init (); init_common_subsystems (&argc, &argv); gcry_control (GCRYCTL_DISABLE_SECMEM, 0); /* Check that the libraries are suitable. Do it here because the option parsing may need services of the libraries. */ if (!ksba_check_version (NEED_KSBA_VERSION) ) log_fatal( _("%s is too old (need %s, have %s)\n"), "libksba", NEED_KSBA_VERSION, ksba_check_version (NULL) ); ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free ); ksba_set_hash_buffer_function (my_ksba_hash_buffer, NULL); /* Init TLS library. */ #if HTTP_USE_NTBTLS if (!ntbtls_check_version (NEED_NTBTLS_VERSION) ) log_fatal( _("%s is too old (need %s, have %s)\n"), "ntbtls", NEED_NTBTLS_VERSION, ntbtls_check_version (NULL) ); #elif HTTP_USE_GNUTLS rc = gnutls_global_init (); if (rc) log_fatal ("gnutls_global_init failed: %s\n", gnutls_strerror (rc)); #endif /*HTTP_USE_GNUTLS*/ /* Init Assuan. */ malloc_hooks.malloc = gcry_malloc; malloc_hooks.realloc = gcry_realloc; malloc_hooks.free = gcry_free; assuan_set_malloc_hooks (&malloc_hooks); assuan_set_assuan_log_prefix (log_get_prefix (NULL)); assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT); assuan_sock_init (); setup_libassuan_logging (&opt.debug, dirmngr_assuan_log_monitor); setup_libgcrypt_logging (); #if HTTP_USE_NTBTLS ntbtls_set_log_handler (my_ntbtls_log_handler, NULL); #endif /* Setup defaults. */ shell = getenv ("SHELL"); if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") ) csh_style = 1; /* Reset rereadable options to default values. */ parse_rereadable_options (NULL, 0); /* Default TCP timeouts. */ opt.connect_timeout = DEFAULT_CONNECT_TIMEOUT; opt.connect_quick_timeout = DEFAULT_CONNECT_QUICK_TIMEOUT; /* LDAP defaults. */ opt.add_new_ldapservers = 0; opt.ldaptimeout = DEFAULT_LDAP_TIMEOUT; /* Other defaults. */ /* Check whether we have a config file given on the commandline */ orig_argc = argc; orig_argv = argv; pargs.argc = &argc; pargs.argv = &argv; pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION); while (gpgrt_argparse (NULL, &pargs, opts)) { switch (pargs.r_opt) { case oDebug: case oDebugAll: debug_argparser++; break; case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break; } } /* Reset the flags. */ pargs.flags &= ~(ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION); socket_name = dirmngr_socket_name (); /* The configuraton directories for use by gpgrt_argparser. */ gpgrt_set_confdir (GPGRT_CONFDIR_SYS, gnupg_sysconfdir ()); gpgrt_set_confdir (GPGRT_CONFDIR_USER, gnupg_homedir ()); /* We are re-using the struct, thus the reset flag. We OR the * flags so that the internal intialized flag won't be cleared. */ argc = orig_argc; argv = orig_argv; pargs.argc = &argc; pargs.argv = &argv; pargs.flags |= (ARGPARSE_FLAG_RESET | ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_SYS | ARGPARSE_FLAG_USER); while (gpgrt_argparser (&pargs, opts, DIRMNGR_NAME EXTSEP_S "conf")) { if (pargs.r_opt == ARGPARSE_CONFFILE) { if (debug_argparser) log_info (_("reading options from '%s'\n"), pargs.r_type? pargs.r.ret_str: "[cmdline]"); if (pargs.r_type) { xfree (last_configname); last_configname = xstrdup (pargs.r.ret_str); configname = last_configname; } else configname = NULL; continue; } if (parse_rereadable_options (&pargs, 0)) continue; /* Already handled */ switch (pargs.r_opt) { case aServer: case aDaemon: case aSupervised: case aShutdown: case aFlush: case aListCRLs: case aLoadCRL: case aFetchCRL: case aGPGConfList: case aGPGConfTest: case aGPGConfVersions: cmd = pargs.r_opt; break; case oQuiet: opt.quiet = 1; break; case oVerbose: opt.verbose++; break; case oBatch: opt.batch=1; break; case oDebugWait: debug_wait = pargs.r.ret_int; break; case oNoGreeting: nogreeting = 1; break; case oNoVerbose: opt.verbose = 0; break; case oHomedir: /* Ignore this option here. */; break; case oNoDetach: nodetach = 1; break; case oLogFile: logfile = pargs.r.ret_str; break; case oCsh: csh_style = 1; break; case oSh: csh_style = 0; break; case oLDAPFile: # if USE_LDAP ldapfile = pargs.r.ret_str; # endif /*USE_LDAP*/ break; case oLDAPAddServers: opt.add_new_ldapservers = 1; break; case oLDAPTimeout: opt.ldaptimeout = pargs.r.ret_int; break; case oFakedSystemTime: gnupg_set_time ((time_t)pargs.r.ret_ulong, 0); break; case oForce: opt.force = 1; break; case oSocketName: socket_name = pargs.r.ret_str; break; case oListenBacklog: listen_backlog = pargs.r.ret_int; break; default: if (configname) pargs.err = ARGPARSE_PRINT_WARNING; else pargs.err = ARGPARSE_PRINT_ERROR; break; } } gpgrt_argparse (NULL, &pargs, NULL); /* Release internal state. */ if (!last_configname) opt.config_filename = gpgrt_fnameconcat (gnupg_homedir (), DIRMNGR_NAME EXTSEP_S "conf", NULL); else { opt.config_filename = last_configname; last_configname = NULL; } if (log_get_errorcount(0)) exit(2); /* Get a default log file from common.conf. */ if (!logfile && !parse_comopt (GNUPG_MODULE_NAME_DIRMNGR, debug_argparser)) { logfile = comopt.logfile; comopt.logfile = NULL; } if (nogreeting ) greeting = 0; if (!opt.homedir_cache) opt.homedir_cache = xstrdup (gnupg_homedir ()); if (greeting) { es_fprintf (es_stderr, "%s %s; %s\n", gpgrt_strusage(11), gpgrt_strusage(13), gpgrt_strusage(14)); es_fprintf (es_stderr, "%s\n", gpgrt_strusage(15)); } #ifdef IS_DEVELOPMENT_VERSION log_info ("NOTE: this is a development version!\n"); #endif /* Print a warning if an argument looks like an option. */ if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN)) { int i; for (i=0; i < argc; i++) if (argv[i][0] == '-' && argv[i][1] == '-') log_info (_("Note: '%s' is not considered an option\n"), argv[i]); } if (!gnupg_access ("/etc/"DIRMNGR_NAME, F_OK) && !strncmp (gnupg_homedir (), "/etc/", 5)) log_info ("NOTE: DirMngr is now a proper part of %s. The configuration and" " other directory names changed. Please check that no other version" " of dirmngr is still installed. To disable this warning, remove the" " directory '/etc/dirmngr'.\n", GNUPG_NAME); if (gnupg_faked_time_p ()) { gnupg_isotime_t tbuf; log_info (_("WARNING: running with faked system time: ")); gnupg_get_isotime (tbuf); dump_isotime (tbuf); log_printf ("\n"); } /* Note that we do not run set_tor_mode in --gpgconf-list mode * because it will attempt to connect to the tor client and that can * be time consuming. */ post_option_parsing (); if (cmd != aGPGConfTest && cmd != aGPGConfList && cmd != aGPGConfVersions) set_tor_mode (); - /* Get LDAP server list from file. */ + /* Get LDAP server list from file unless --ldapserver has been used. */ #if USE_LDAP - if (!ldapfile) + if (opt.ldapservers) + ; + else if (!ldapfile) { ldapfile = make_filename (gnupg_homedir (), "dirmngr_ldapservers.conf", NULL); opt.ldapservers = parse_ldapserver_file (ldapfile, 1); xfree (ldapfile); } else opt.ldapservers = parse_ldapserver_file (ldapfile, 0); #endif /*USE_LDAP*/ #ifndef HAVE_W32_SYSTEM /* We need to ignore the PIPE signal because the we might log to a socket and that code handles EPIPE properly. The ldap wrapper also requires us to ignore this silly signal. Assuan would set this signal to ignore anyway.*/ signal (SIGPIPE, SIG_IGN); #endif /* Ready. Now to our duties. */ if (!cmd) cmd = aServer; rc = 0; if (cmd == aServer) { /* Note that this server mode is mainly useful for debugging. */ if (argc) wrong_args ("--server"); if (logfile) { log_set_file (logfile); log_set_prefix (NULL, GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID); } if (debug_wait) { log_debug ("waiting for debugger - my pid is %u .....\n", (unsigned int)getpid()); gnupg_sleep (debug_wait); log_debug ("... okay\n"); } thread_init (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); ks_hkp_init (); http_register_netactivity_cb (netactivity_action); start_command_handler (ASSUAN_INVALID_FD, 0); shutdown_reaper (); } #ifndef HAVE_W32_SYSTEM else if (cmd == aSupervised) { /* In supervised mode, we expect file descriptor 3 to be an already opened, listening socket. We will also not detach from the controlling process or close stderr; the supervisor should handle all of that. */ struct stat statbuf; if (fstat (3, &statbuf) == -1 && errno == EBADF) { log_error ("file descriptor 3 must be validin --supervised mode\n"); dirmngr_exit (1); } socket_name = gnupg_get_socket_name (3); /* Now start with logging to a file if this is desired. */ if (logfile) { log_set_file (logfile); log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX |GPGRT_LOG_WITH_TIME |GPGRT_LOG_WITH_PID)); current_logfile = xstrdup (logfile); } else log_set_prefix (NULL, 0); thread_init (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); ks_hkp_init (); http_register_netactivity_cb (netactivity_action); handle_connections (3); shutdown_reaper (); } #endif /*HAVE_W32_SYSTEM*/ else if (cmd == aDaemon) { assuan_fd_t fd; pid_t pid; int len; struct sockaddr_un serv_addr; if (argc) wrong_args ("--daemon"); /* Now start with logging to a file if this is desired. */ if (logfile) { log_set_file (logfile); log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX |GPGRT_LOG_WITH_TIME |GPGRT_LOG_WITH_PID)); current_logfile = xstrdup (logfile); } if (debug_wait) { log_debug ("waiting for debugger - my pid is %u .....\n", (unsigned int)getpid()); gnupg_sleep (debug_wait); log_debug ("... okay\n"); } #ifndef HAVE_W32_SYSTEM if (strchr (socket_name, ':')) { log_error (_("colons are not allowed in the socket name\n")); dirmngr_exit (1); } #endif fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0); if (fd == ASSUAN_INVALID_FD) { log_error (_("can't create socket: %s\n"), strerror (errno)); cleanup (); dirmngr_exit (1); } { int redirected; if (assuan_sock_set_sockaddr_un (socket_name, (struct sockaddr*)&serv_addr, &redirected)) { if (errno == ENAMETOOLONG) log_error (_("socket name '%s' is too long\n"), socket_name); else log_error ("error preparing socket '%s': %s\n", socket_name, gpg_strerror (gpg_error_from_syserror ())); dirmngr_exit (1); } if (redirected) { redir_socket_name = xstrdup (serv_addr.sun_path); if (opt.verbose) log_info ("redirecting socket '%s' to '%s'\n", socket_name, redir_socket_name); } } len = SUN_LEN (&serv_addr); rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len); if (rc == -1 && (errno == EADDRINUSE #ifdef HAVE_W32_SYSTEM || errno == EEXIST #endif )) { /* Fixme: We should test whether a dirmngr is already running. */ gnupg_remove (redir_socket_name? redir_socket_name : socket_name); rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len); } if (rc != -1 && (rc = assuan_sock_get_nonce ((struct sockaddr*) &serv_addr, len, &socket_nonce))) log_error (_("error getting nonce for the socket\n")); if (rc == -1) { log_error (_("error binding socket to '%s': %s\n"), serv_addr.sun_path, gpg_strerror (gpg_error_from_syserror ())); assuan_sock_close (fd); dirmngr_exit (1); } cleanup_socket = 1; if (gnupg_chmod (serv_addr.sun_path, "-rwx")) log_error (_("can't set permissions of '%s': %s\n"), serv_addr.sun_path, strerror (errno)); if (listen (FD2INT (fd), listen_backlog) == -1) { log_error ("listen(fd,%d) failed: %s\n", listen_backlog, strerror (errno)); assuan_sock_close (fd); dirmngr_exit (1); } if (opt.verbose) log_info (_("listening on socket '%s'\n"), serv_addr.sun_path); es_fflush (NULL); /* Note: We keep the dirmngr_info output only for the sake of existing scripts which might use this to detect a successful start of the dirmngr. */ #ifdef HAVE_W32_SYSTEM (void)csh_style; (void)nodetach; pid = getpid (); es_printf ("set %s=%s;%lu;1\n", DIRMNGR_INFO_NAME, socket_name, (ulong) pid); #else pid = fork(); if (pid == (pid_t)-1) { log_fatal (_("error forking process: %s\n"), strerror (errno)); dirmngr_exit (1); } if (pid) { /* We are the parent */ char *infostr; /* Don't let cleanup() remove the socket - the child is responsible for doing that. */ cleanup_socket = 0; close (fd); /* Create the info string: :: */ if (asprintf (&infostr, "%s=%s:%lu:1", DIRMNGR_INFO_NAME, serv_addr.sun_path, (ulong)pid ) < 0) { log_error (_("out of core\n")); kill (pid, SIGTERM); dirmngr_exit (1); } /* Print the environment string, so that the caller can use shell's eval to set it. But see above. */ if (csh_style) { *strchr (infostr, '=') = ' '; es_printf ( "setenv %s;\n", infostr); } else { es_printf ( "%s; export %s;\n", infostr, DIRMNGR_INFO_NAME); } free (infostr); exit (0); /*NEVER REACHED*/ } /* end parent */ /* This is the child */ /* Detach from tty and put process into a new session */ if (!nodetach ) { int i; unsigned int oldflags; /* Close stdin, stdout and stderr unless it is the log stream */ for (i=0; i <= 2; i++) { if (!log_test_fd (i) && i != fd ) { if ( !close (i) && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1) { log_error ("failed to open '%s': %s\n", "/dev/null", strerror (errno)); cleanup (); dirmngr_exit (1); } } } if (setsid() == -1) { log_error ("setsid() failed: %s\n", strerror(errno) ); dirmngr_exit (1); } log_get_prefix (&oldflags); log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED); opt.running_detached = 1; } #endif if (!nodetach ) { if (gnupg_chdir (gnupg_daemon_rootdir ())) { log_error ("chdir to '%s' failed: %s\n", gnupg_daemon_rootdir (), strerror (errno)); dirmngr_exit (1); } } thread_init (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); ks_hkp_init (); http_register_netactivity_cb (netactivity_action); handle_connections (fd); shutdown_reaper (); } else if (cmd == aListCRLs) { /* Just list the CRL cache and exit. */ if (argc) wrong_args ("--list-crls"); crl_cache_init (); crl_cache_list (es_stdout); } else if (cmd == aLoadCRL) { struct server_control_s ctrlbuf; memset (&ctrlbuf, 0, sizeof ctrlbuf); dirmngr_init_default_ctrl (&ctrlbuf); thread_init (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); ks_hkp_init (); if (!argc) rc = crl_cache_load (&ctrlbuf, NULL); else { for (; !rc && argc; argc--, argv++) rc = crl_cache_load (&ctrlbuf, *argv); } dirmngr_deinit_default_ctrl (&ctrlbuf); } else if (cmd == aFetchCRL) { ksba_reader_t reader; struct server_control_s ctrlbuf; if (argc != 1) wrong_args ("--fetch-crl URL"); memset (&ctrlbuf, 0, sizeof ctrlbuf); dirmngr_init_default_ctrl (&ctrlbuf); thread_init (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); ks_hkp_init (); rc = crl_fetch (&ctrlbuf, argv[0], &reader); if (rc) log_error (_("fetching CRL from '%s' failed: %s\n"), argv[0], gpg_strerror (rc)); else { rc = crl_cache_insert (&ctrlbuf, argv[0], reader); if (rc) log_error (_("processing CRL from '%s' failed: %s\n"), argv[0], gpg_strerror (rc)); crl_close_reader (reader); } dirmngr_deinit_default_ctrl (&ctrlbuf); } else if (cmd == aFlush) { /* Delete cache and exit. */ if (argc) wrong_args ("--flush"); rc = crl_cache_flush(); } else if (cmd == aGPGConfTest) dirmngr_exit (0); else if (cmd == aGPGConfList) { unsigned long flags = 0; char *filename_esc; es_printf ("debug-level:%lu:\"none\n", flags | GC_OPT_FLAG_DEFAULT); es_printf ("ldaptimeout:%lu:%u\n", flags | GC_OPT_FLAG_DEFAULT, DEFAULT_LDAP_TIMEOUT); es_printf ("max-replies:%lu:%u\n", flags | GC_OPT_FLAG_DEFAULT, DEFAULT_MAX_REPLIES); filename_esc = percent_escape (get_default_keyserver (0), NULL); es_printf ("keyserver:%lu:\"%s:\n", flags | GC_OPT_FLAG_DEFAULT, filename_esc); xfree (filename_esc); es_printf ("resolver-timeout:%lu:%u\n", flags | GC_OPT_FLAG_DEFAULT, 0); } else if (cmd == aGPGConfVersions) gpgconf_versions (); cleanup (); return !!rc; } static void cleanup (void) { crl_cache_deinit (); cert_cache_deinit (1); reload_dns_stuff (1); #if USE_LDAP ldapserver_list_free (opt.ldapservers); #endif /*USE_LDAP*/ opt.ldapservers = NULL; if (cleanup_socket) { cleanup_socket = 0; if (redir_socket_name) gnupg_remove (redir_socket_name); else if (socket_name && *socket_name) gnupg_remove (socket_name); } } void dirmngr_exit (int rc) { cleanup (); exit (rc); } void dirmngr_init_default_ctrl (ctrl_t ctrl) { ctrl->magic = SERVER_CONTROL_MAGIC; if (opt.http_proxy) ctrl->http_proxy = xstrdup (opt.http_proxy); ctrl->http_no_crl = 1; ctrl->timeout = opt.connect_timeout; } void dirmngr_deinit_default_ctrl (ctrl_t ctrl) { if (!ctrl) return; ctrl->magic = 0xdeadbeef; xfree (ctrl->http_proxy); ctrl->http_proxy = NULL; } /* Create a list of LDAP servers from the file FILENAME. Returns the list or NULL in case of errors. The format of such a file is line oriented where empty lines and lines starting with a hash mark are ignored. All other lines are assumed to be colon seprated with these fields: 1. field: Hostname 2. field: Portnumber 3. field: Username 4. field: Password 5. field: Base DN */ #if USE_LDAP static ldap_server_t parse_ldapserver_file (const char* filename, int ignore_enoent) { char buffer[1024]; char *p; ldap_server_t server, serverstart, *serverend; int c; unsigned int lineno = 0; estream_t fp; fp = es_fopen (filename, "r"); if (!fp) { if (ignore_enoent && gpg_err_code_from_syserror () == GPG_ERR_ENOENT) ; else log_info ("failed to open '%s': %s\n", filename, strerror (errno)); return NULL; } serverstart = NULL; serverend = &serverstart; while (es_fgets (buffer, sizeof buffer, fp)) { lineno++; if (!*buffer || buffer[strlen(buffer)-1] != '\n') { if (*buffer && es_feof (fp)) ; /* Last line not terminated - continue. */ else { log_error (_("%s:%u: line too long - skipped\n"), filename, lineno); while ( (c=es_fgetc (fp)) != EOF && c != '\n') ; /* Skip until end of line. */ continue; } } /* Skip empty and comment lines.*/ for (p=buffer; spacep (p); p++) ; if (!*p || *p == '\n' || *p == '#') continue; /* Parse the colon separated fields. */ server = ldapserver_parse_one (buffer, filename, lineno); if (server) { *serverend = server; serverend = &server->next; } } if (es_ferror (fp)) log_error (_("error reading '%s': %s\n"), filename, strerror (errno)); es_fclose (fp); return serverstart; } #endif /*USE_LDAP*/ static fingerprint_list_t parse_ocsp_signer (const char *string) { gpg_error_t err; char *fname; estream_t fp; char line[256]; char *p; fingerprint_list_t list, *list_tail, item; unsigned int lnr = 0; int c, i, j; int errflag = 0; /* Check whether this is not a filename and treat it as a direct fingerprint specification. */ if (!strpbrk (string, "/.~\\")) { item = xcalloc (1, sizeof *item); for (i=j=0; (string[i] == ':' || hexdigitp (string+i)) && j < 40; i++) if ( string[i] != ':' ) item->hexfpr[j++] = string[i] >= 'a'? (string[i] & 0xdf): string[i]; item->hexfpr[j] = 0; if (j != 40 || !(spacep (string+i) || !string[i])) { log_error (_("%s:%u: invalid fingerprint detected\n"), "--ocsp-signer", 0); xfree (item); return NULL; } return item; } /* Well, it is a filename. */ if (*string == '/' || (*string == '~' && string[1] == '/')) fname = make_filename (string, NULL); else { if (string[0] == '.' && string[1] == '/' ) string += 2; fname = make_filename (gnupg_homedir (), string, NULL); } fp = es_fopen (fname, "r"); if (!fp) { err = gpg_error_from_syserror (); log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err)); xfree (fname); return NULL; } list = NULL; list_tail = &list; for (;;) { if (!es_fgets (line, DIM(line)-1, fp) ) { if (!es_feof (fp)) { err = gpg_error_from_syserror (); log_error (_("%s:%u: read error: %s\n"), fname, lnr, gpg_strerror (err)); errflag = 1; } es_fclose (fp); if (errflag) { while (list) { fingerprint_list_t tmp = list->next; xfree (list); list = tmp; } } xfree (fname); return list; /* Ready. */ } lnr++; if (!*line || line[strlen(line)-1] != '\n') { /* Eat until end of line. */ while ( (c=es_getc (fp)) != EOF && c != '\n') ; err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG /* */: GPG_ERR_INCOMPLETE_LINE); log_error (_("%s:%u: read error: %s\n"), fname, lnr, gpg_strerror (err)); errflag = 1; continue; } /* Allow for empty lines and spaces */ for (p=line; spacep (p); p++) ; if (!*p || *p == '\n' || *p == '#') continue; item = xcalloc (1, sizeof *item); *list_tail = item; list_tail = &item->next; for (i=j=0; (p[i] == ':' || hexdigitp (p+i)) && j < 40; i++) if ( p[i] != ':' ) item->hexfpr[j++] = p[i] >= 'a'? (p[i] & 0xdf): p[i]; item->hexfpr[j] = 0; if (j != 40 || !(spacep (p+i) || p[i] == '\n')) { log_error (_("%s:%u: invalid fingerprint detected\n"), fname, lnr); errflag = 1; } i++; while (spacep (p+i)) i++; if (p[i] && p[i] != '\n') log_info (_("%s:%u: garbage at end of line ignored\n"), fname, lnr); } /*NOTREACHED*/ } /* Stuff used in daemon mode. */ /* Reread parts of the configuration. Note, that this function is obviously not thread-safe and should only be called from the NPTH signal handler. Fixme: Due to the way the argument parsing works, we create a memory leak here for all string type arguments. There is currently no clean way to tell whether the memory for the argument has been allocated or points into the process's original arguments. Unless we have a mechanism to tell this, we need to live on with this. */ static void reread_configuration (void) { gpgrt_argparse_t pargs; char *twopart; int dummy; int logfile_seen = 0; if (!opt.config_filename) goto finish; /* No config file. */ twopart = strconcat (DIRMNGR_NAME EXTSEP_S "conf" PATHSEP_S, opt.config_filename, NULL); if (!twopart) return; /* Out of core. */ parse_rereadable_options (NULL, 1); /* Start from the default values. */ memset (&pargs, 0, sizeof pargs); dummy = 0; pargs.argc = &dummy; pargs.flags = (ARGPARSE_FLAG_KEEP |ARGPARSE_FLAG_SYS |ARGPARSE_FLAG_USER); while (gpgrt_argparser (&pargs, opts, twopart)) { if (pargs.r_opt == ARGPARSE_CONFFILE) { log_info (_("reading options from '%s'\n"), pargs.r_type? pargs.r.ret_str: "[cmdline]"); } else if (pargs.r_opt < -1) pargs.err = ARGPARSE_PRINT_WARNING; else /* Try to parse this option - ignore unchangeable ones. */ { if (pargs.r_opt == oLogFile) logfile_seen = 1; parse_rereadable_options (&pargs, 1); } } gpgrt_argparse (NULL, &pargs, NULL); /* Release internal state. */ xfree (twopart); post_option_parsing (); finish: /* Get a default log file from common.conf. */ if (!logfile_seen && !parse_comopt (GNUPG_MODULE_NAME_DIRMNGR, !!opt.debug)) { if (!current_logfile || !comopt.logfile || strcmp (current_logfile, comopt.logfile)) { log_set_file (comopt.logfile); xfree (current_logfile); current_logfile = comopt.logfile? xtrystrdup (comopt.logfile) : NULL; } } } /* A global function which allows us to trigger the reload stuff from other places. */ void dirmngr_sighup_action (void) { log_info (_("SIGHUP received - " "re-reading configuration and flushing caches\n")); reread_configuration (); set_tor_mode (); cert_cache_deinit (0); crl_cache_deinit (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); reload_dns_stuff (0); ks_hkp_reload (); } /* This function is called if some network activity was done. At this * point we know the we have a network and we can decide whether to * run scheduled background tasks soon. The function should return * quickly and only trigger actions for another thread. */ static void netactivity_action (void) { network_activity_seen = 1; } /* The signal handler. */ #ifndef HAVE_W32_SYSTEM static void handle_signal (int signo) { switch (signo) { case SIGHUP: dirmngr_sighup_action (); break; case SIGUSR1: cert_cache_print_stats (); domaininfo_print_stats (); break; case SIGUSR2: log_info (_("SIGUSR2 received - no action defined\n")); break; case SIGTERM: if (!shutdown_pending) log_info (_("SIGTERM received - shutting down ...\n")); else log_info (_("SIGTERM received - still %d active connections\n"), active_connections); shutdown_pending++; if (shutdown_pending > 2) { log_info (_("shutdown forced\n")); log_info ("%s %s stopped\n", gpgrt_strusage(11), gpgrt_strusage(13)); cleanup (); dirmngr_exit (0); } break; case SIGINT: log_info (_("SIGINT received - immediate shutdown\n")); log_info( "%s %s stopped\n", gpgrt_strusage(11), gpgrt_strusage(13)); cleanup (); dirmngr_exit (0); break; default: log_info (_("signal %d received - no action defined\n"), signo); } } #endif /*!HAVE_W32_SYSTEM*/ /* Thread to do the housekeeping. */ static void * housekeeping_thread (void *arg) { static int sentinel; time_t curtime; struct server_control_s ctrlbuf; (void)arg; curtime = gnupg_get_time (); if (sentinel) { log_info ("housekeeping is already going on\n"); return NULL; } sentinel++; if (opt.verbose > 1) log_info ("starting housekeeping\n"); memset (&ctrlbuf, 0, sizeof ctrlbuf); dirmngr_init_default_ctrl (&ctrlbuf); dns_stuff_housekeeping (); ks_hkp_housekeeping (curtime); if (network_activity_seen) { network_activity_seen = 0; if (opt.allow_version_check) dirmngr_load_swdb (&ctrlbuf, 0); workqueue_run_global_tasks (&ctrlbuf, 1); } else workqueue_run_global_tasks (&ctrlbuf, 0); dirmngr_deinit_default_ctrl (&ctrlbuf); if (opt.verbose > 1) log_info ("ready with housekeeping\n"); sentinel--; return NULL; } /* We try to enable correct overflow handling for signed int (commonly * used for time_t). With gcc 4.2 -fno-strict-overflow was introduced * and used here as a pragma. Later gcc versions (gcc 6?) removed * this as a pragma and -fwrapv was then suggested as a replacement * for -fno-strict-overflow. */ #if GPGRT_HAVE_PRAGMA_GCC_PUSH # pragma GCC push_options # pragma GCC optimize ("wrapv") #endif static int time_for_housekeeping_p (time_t curtime) { static time_t last_housekeeping; if (!last_housekeeping) last_housekeeping = curtime; if (last_housekeeping + HOUSEKEEPING_INTERVAL <= curtime || last_housekeeping > curtime /*(be prepared for y2038)*/) { last_housekeeping = curtime; return 1; } return 0; } #if GPGRT_HAVE_PRAGMA_GCC_PUSH # pragma GCC pop_options #endif /* This is the worker for the ticker. It is called every few seconds and may only do fast operations. */ static void handle_tick (void) { struct stat statbuf; if (time_for_housekeeping_p (gnupg_get_time ())) { npth_t thread; npth_attr_t tattr; int err; err = npth_attr_init (&tattr); if (err) log_error ("error preparing housekeeping thread: %s\n", strerror (err)); else { npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED); err = npth_create (&thread, &tattr, housekeeping_thread, NULL); if (err) log_error ("error spawning housekeeping thread: %s\n", strerror (err)); npth_attr_destroy (&tattr); } } /* Check whether the homedir is still available. */ if (!shutdown_pending && gnupg_stat (gnupg_homedir (), &statbuf) && errno == ENOENT) { shutdown_pending = 1; log_info ("homedir has been removed - shutting down\n"); } } /* Check the nonce on a new connection. This is a NOP unless we are using our Unix domain socket emulation under Windows. */ static int check_nonce (assuan_fd_t fd, assuan_sock_nonce_t *nonce) { if (assuan_sock_check_nonce (fd, nonce)) { log_info (_("error reading nonce on fd %d: %s\n"), FD2INT (fd), strerror (errno)); assuan_sock_close (fd); return -1; } else return 0; } /* Helper to call a connection's main function. */ static void * start_connection_thread (void *arg) { static unsigned int last_session_id; unsigned int session_id; union int_and_ptr_u argval; gnupg_fd_t fd; memset (&argval, 0, sizeof argval); argval.aptr = arg; fd = argval.afd; if (check_nonce (fd, &socket_nonce)) { log_error ("handler nonce check FAILED\n"); return NULL; } #ifndef HAVE_W32_SYSTEM npth_setspecific (my_tlskey_current_fd, argval.aptr); #endif active_connections++; if (opt.verbose) log_info (_("handler for fd %d started\n"), FD2INT (fd)); session_id = ++last_session_id; if (!session_id) session_id = ++last_session_id; start_command_handler (fd, session_id); if (opt.verbose) log_info (_("handler for fd %d terminated\n"), FD2INT (fd)); active_connections--; workqueue_run_post_session_tasks (session_id); #ifndef HAVE_W32_SYSTEM argval.afd = ASSUAN_INVALID_FD; npth_setspecific (my_tlskey_current_fd, argval.aptr); #endif return NULL; } #ifdef HAVE_INOTIFY_INIT /* Read an inotify event and return true if it matches NAME. */ static int my_inotify_is_name (int fd, const char *name) { union { struct inotify_event ev; char _buf[sizeof (struct inotify_event) + 100 + 1]; } buf; int n; const char *s; s = strrchr (name, '/'); if (s && s[1]) name = s + 1; n = npth_read (fd, &buf, sizeof buf); if (n < sizeof (struct inotify_event)) return 0; if (buf.ev.len < strlen (name)+1) return 0; if (strcmp (buf.ev.name, name)) return 0; /* Not the desired file. */ return 1; /* Found. */ } #endif /*HAVE_INOTIFY_INIT*/ /* Main loop in daemon mode. Note that LISTEN_FD will be owned by * this function. */ static void handle_connections (assuan_fd_t listen_fd) { npth_attr_t tattr; #ifndef HAVE_W32_SYSTEM int signo; #endif struct sockaddr_un paddr; socklen_t plen = sizeof( paddr ); int nfd, ret; fd_set fdset, read_fdset; struct timespec abstime; struct timespec curtime; struct timespec timeout; int saved_errno; int my_inotify_fd = -1; npth_attr_init (&tattr); npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED); #ifndef HAVE_W32_SYSTEM /* FIXME */ npth_sigev_init (); npth_sigev_add (SIGHUP); npth_sigev_add (SIGUSR1); npth_sigev_add (SIGUSR2); npth_sigev_add (SIGINT); npth_sigev_add (SIGTERM); npth_sigev_fini (); #endif #ifdef HAVE_INOTIFY_INIT if (disable_check_own_socket) my_inotify_fd = -1; else if ((my_inotify_fd = inotify_init ()) == -1) log_info ("error enabling fast daemon termination: %s\n", strerror (errno)); else { /* We need to watch the directory for the file because there * won't be an IN_DELETE_SELF for a socket file. */ char *slash = strrchr (socket_name, '/'); log_assert (slash && slash[1]); *slash = 0; if (inotify_add_watch (my_inotify_fd, socket_name, IN_DELETE) == -1) { close (my_inotify_fd); my_inotify_fd = -1; } *slash = '/'; } #endif /*HAVE_INOTIFY_INIT*/ /* Setup the fdset. It has only one member. This is because we use pth_select instead of pth_accept to properly sync timeouts with to full second. */ FD_ZERO (&fdset); FD_SET (FD2INT (listen_fd), &fdset); nfd = FD2INT (listen_fd); if (my_inotify_fd != -1) { FD_SET (my_inotify_fd, &fdset); if (my_inotify_fd > nfd) nfd = my_inotify_fd; } npth_clock_gettime (&abstime); abstime.tv_sec += TIMERTICK_INTERVAL; /* Main loop. */ for (;;) { /* Shutdown test. */ if (shutdown_pending) { if (!active_connections) break; /* ready */ /* Do not accept new connections but keep on running the * loop to cope with the timer events. * * Note that we do not close the listening socket because a * client trying to connect to that socket would instead * restart a new dirmngr instance - which is unlikely the * intention of a shutdown. */ /* assuan_sock_close (listen_fd); */ /* listen_fd = -1; */ FD_ZERO (&fdset); nfd = -1; if (my_inotify_fd != -1) { FD_SET (my_inotify_fd, &fdset); nfd = my_inotify_fd; } } /* Take a copy of the fdset. */ read_fdset = fdset; npth_clock_gettime (&curtime); if (!(npth_timercmp (&curtime, &abstime, <))) { /* Timeout. When a shutdown is pending we use a shorter * interval to handle the shutdown more quickly. */ handle_tick (); npth_clock_gettime (&abstime); abstime.tv_sec += (shutdown_pending ? TIMERTICK_INTERVAL_SHUTDOWN : TIMERTICK_INTERVAL); } npth_timersub (&abstime, &curtime, &timeout); #ifndef HAVE_W32_SYSTEM ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout, npth_sigev_sigmask()); saved_errno = errno; while (npth_sigev_get_pending(&signo)) handle_signal (signo); #else ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout, NULL, NULL); saved_errno = errno; #endif if (ret == -1 && saved_errno != EINTR) { log_error (_("npth_pselect failed: %s - waiting 1s\n"), strerror (saved_errno)); npth_sleep (1); continue; } if (ret <= 0) { /* Interrupt or timeout. Will be handled when calculating the next timeout. */ continue; } if (shutdown_pending) { /* Do not anymore accept connections. */ continue; } #ifdef HAVE_INOTIFY_INIT if (my_inotify_fd != -1 && FD_ISSET (my_inotify_fd, &read_fdset) && my_inotify_is_name (my_inotify_fd, socket_name)) { shutdown_pending = 1; log_info ("socket file has been removed - shutting down\n"); } #endif /*HAVE_INOTIFY_INIT*/ if (FD_ISSET (FD2INT (listen_fd), &read_fdset)) { gnupg_fd_t fd; plen = sizeof paddr; fd = INT2FD (npth_accept (FD2INT(listen_fd), (struct sockaddr *)&paddr, &plen)); if (fd == GNUPG_INVALID_FD) { log_error ("accept failed: %s\n", strerror (errno)); } else { char threadname[50]; union int_and_ptr_u argval; npth_t thread; memset (&argval, 0, sizeof argval); argval.afd = fd; snprintf (threadname, sizeof threadname, "conn fd=%d", FD2INT(fd)); ret = npth_create (&thread, &tattr, start_connection_thread, argval.aptr); if (ret) { log_error ("error spawning connection handler: %s\n", strerror (ret) ); assuan_sock_close (fd); } npth_setname_np (thread, threadname); } } } #ifdef HAVE_INOTIFY_INIT if (my_inotify_fd != -1) close (my_inotify_fd); #endif /*HAVE_INOTIFY_INIT*/ npth_attr_destroy (&tattr); if (listen_fd != GNUPG_INVALID_FD) assuan_sock_close (listen_fd); cleanup (); log_info ("%s %s stopped\n", gpgrt_strusage(11), gpgrt_strusage(13)); } const char* dirmngr_get_current_socket_name (void) { if (socket_name) return socket_name; else return dirmngr_socket_name (); } /* Parse the revision part from the extended version blurb. */ static const char * get_revision_from_blurb (const char *blurb, int *r_len) { const char *s = blurb? blurb : ""; int n; for (; *s; s++) if (*s == '\n' && s[1] == '(') break; if (*s) { s += 2; for (n=0; s[n] && s[n] != ' '; n++) ; } else { s = "?"; n = 1; } *r_len = n; return s; } /* Print versions of dirmngr and used libraries. This is used by * "gpgconf --show-versions" so that there is no need to link gpgconf * against all these libraries. This is an internal API and should * not be relied upon. */ static void gpgconf_versions (void) { const char *s; int n; /* Unfortunately Npth has no way to get the version. */ s = get_revision_from_blurb (assuan_check_version ("\x01\x01"), &n); es_fprintf (es_stdout, "* Libassuan %s (%.*s)\n\n", assuan_check_version (NULL), n, s); s = get_revision_from_blurb (ksba_check_version ("\x01\x01"), &n); es_fprintf (es_stdout, "* KSBA %s (%.*s)\n\n", ksba_check_version (NULL), n, s); #ifdef HTTP_USE_NTBTLS s = get_revision_from_blurb (ntbtls_check_version ("\x01\x01"), &n); es_fprintf (es_stdout, "* NTBTLS %s (%.*s)\n\n", ntbtls_check_version (NULL), n, s); #elif HTTP_USE_GNUTLS es_fprintf (es_stdout, "* GNUTLS %s\n\n", gnutls_check_version (NULL)); #endif } diff --git a/dirmngr/ks-engine-ldap.c b/dirmngr/ks-engine-ldap.c index 1b5c2ca32..dcd581c28 100644 --- a/dirmngr/ks-engine-ldap.c +++ b/dirmngr/ks-engine-ldap.c @@ -1,2366 +1,2368 @@ /* ks-engine-ldap.c - talk to a LDAP keyserver * Copyright (C) 2001, 2002, 2004, 2005, 2006 * 2007 Free Software Foundation, Inc. * 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 . */ #include #include #include #include #include #ifdef HAVE_GETOPT_H # include #endif #include #include #include #ifdef _WIN32 # include # include #else # ifdef NEED_LBER_H # include # endif /* For OpenLDAP, to enable the API that we're using. */ # define LDAP_DEPRECATED 1 # include #endif #include #include "dirmngr.h" #include "misc.h" #include "../common/userids.h" #include "../common/mbox-util.h" #include "ks-engine.h" #include "ldap-parse-uri.h" #include "ldapserver.h" /* Flags with infos from the connected server. */ #define SERVERINFO_REALLDAP 1 /* This is not the PGP keyserver. */ #define SERVERINFO_PGPKEYV2 2 /* Needs "pgpeyV2" instead of "pgpKey" */ #define SERVERINFO_SCHEMAV2 4 /* Version 2 of the Schema. */ #define SERVERINFO_NTDS 8 /* Server is an Active Directory. */ #ifndef HAVE_TIMEGM time_t timegm(struct tm *tm); #endif /* Convert an LDAP error to a GPG error. */ static int ldap_err_to_gpg_err (int code) { gpg_err_code_t ec; switch (code) { #ifdef LDAP_X_CONNECTING case LDAP_X_CONNECTING: ec = GPG_ERR_LDAP_X_CONNECTING; break; #endif case LDAP_REFERRAL_LIMIT_EXCEEDED: ec = GPG_ERR_LDAP_REFERRAL_LIMIT; break; case LDAP_CLIENT_LOOP: ec = GPG_ERR_LDAP_CLIENT_LOOP; break; case LDAP_NO_RESULTS_RETURNED: ec = GPG_ERR_LDAP_NO_RESULTS; break; case LDAP_CONTROL_NOT_FOUND: ec = GPG_ERR_LDAP_CONTROL_NOT_FOUND; break; case LDAP_NOT_SUPPORTED: ec = GPG_ERR_LDAP_NOT_SUPPORTED; break; case LDAP_CONNECT_ERROR: ec = GPG_ERR_LDAP_CONNECT; break; case LDAP_NO_MEMORY: ec = GPG_ERR_LDAP_NO_MEMORY; break; case LDAP_PARAM_ERROR: ec = GPG_ERR_LDAP_PARAM; break; case LDAP_USER_CANCELLED: ec = GPG_ERR_LDAP_USER_CANCELLED; break; case LDAP_FILTER_ERROR: ec = GPG_ERR_LDAP_FILTER; break; case LDAP_AUTH_UNKNOWN: ec = GPG_ERR_LDAP_AUTH_UNKNOWN; break; case LDAP_TIMEOUT: ec = GPG_ERR_LDAP_TIMEOUT; break; case LDAP_DECODING_ERROR: ec = GPG_ERR_LDAP_DECODING; break; case LDAP_ENCODING_ERROR: ec = GPG_ERR_LDAP_ENCODING; break; case LDAP_LOCAL_ERROR: ec = GPG_ERR_LDAP_LOCAL; break; case LDAP_SERVER_DOWN: ec = GPG_ERR_LDAP_SERVER_DOWN; break; case LDAP_SUCCESS: ec = GPG_ERR_LDAP_SUCCESS; break; case LDAP_OPERATIONS_ERROR: ec = GPG_ERR_LDAP_OPERATIONS; break; case LDAP_PROTOCOL_ERROR: ec = GPG_ERR_LDAP_PROTOCOL; break; case LDAP_TIMELIMIT_EXCEEDED: ec = GPG_ERR_LDAP_TIMELIMIT; break; case LDAP_SIZELIMIT_EXCEEDED: ec = GPG_ERR_LDAP_SIZELIMIT; break; case LDAP_COMPARE_FALSE: ec = GPG_ERR_LDAP_COMPARE_FALSE; break; case LDAP_COMPARE_TRUE: ec = GPG_ERR_LDAP_COMPARE_TRUE; break; case LDAP_AUTH_METHOD_NOT_SUPPORTED: ec=GPG_ERR_LDAP_UNSUPPORTED_AUTH;break; case LDAP_STRONG_AUTH_REQUIRED: ec = GPG_ERR_LDAP_STRONG_AUTH_RQRD; break; case LDAP_PARTIAL_RESULTS: ec = GPG_ERR_LDAP_PARTIAL_RESULTS; break; case LDAP_REFERRAL: ec = GPG_ERR_LDAP_REFERRAL; break; #ifdef LDAP_ADMINLIMIT_EXCEEDED case LDAP_ADMINLIMIT_EXCEEDED: ec = GPG_ERR_LDAP_ADMINLIMIT; break; #endif #ifdef LDAP_UNAVAILABLE_CRITICAL_EXTENSION case LDAP_UNAVAILABLE_CRITICAL_EXTENSION: ec = GPG_ERR_LDAP_UNAVAIL_CRIT_EXTN; break; #endif case LDAP_CONFIDENTIALITY_REQUIRED: ec = GPG_ERR_LDAP_CONFIDENT_RQRD; break; case LDAP_SASL_BIND_IN_PROGRESS: ec = GPG_ERR_LDAP_SASL_BIND_INPROG; break; case LDAP_NO_SUCH_ATTRIBUTE: ec = GPG_ERR_LDAP_NO_SUCH_ATTRIBUTE; break; case LDAP_UNDEFINED_TYPE: ec = GPG_ERR_LDAP_UNDEFINED_TYPE; break; case LDAP_INAPPROPRIATE_MATCHING: ec = GPG_ERR_LDAP_BAD_MATCHING; break; case LDAP_CONSTRAINT_VIOLATION: ec = GPG_ERR_LDAP_CONST_VIOLATION; break; #ifdef LDAP_TYPE_OR_VALUE_EXISTS case LDAP_TYPE_OR_VALUE_EXISTS: ec = GPG_ERR_LDAP_TYPE_VALUE_EXISTS; break; #endif case LDAP_INVALID_SYNTAX: ec = GPG_ERR_LDAP_INV_SYNTAX; break; case LDAP_NO_SUCH_OBJECT: ec = GPG_ERR_LDAP_NO_SUCH_OBJ; break; case LDAP_ALIAS_PROBLEM: ec = GPG_ERR_LDAP_ALIAS_PROBLEM; break; case LDAP_INVALID_DN_SYNTAX: ec = GPG_ERR_LDAP_INV_DN_SYNTAX; break; case LDAP_IS_LEAF: ec = GPG_ERR_LDAP_IS_LEAF; break; case LDAP_ALIAS_DEREF_PROBLEM: ec = GPG_ERR_LDAP_ALIAS_DEREF; break; #ifdef LDAP_X_PROXY_AUTHZ_FAILURE case LDAP_X_PROXY_AUTHZ_FAILURE: ec = GPG_ERR_LDAP_X_PROXY_AUTH_FAIL; break; #endif case LDAP_INAPPROPRIATE_AUTH: ec = GPG_ERR_LDAP_BAD_AUTH; break; case LDAP_INVALID_CREDENTIALS: ec = GPG_ERR_LDAP_INV_CREDENTIALS; break; #ifdef LDAP_INSUFFICIENT_ACCESS case LDAP_INSUFFICIENT_ACCESS: ec = GPG_ERR_LDAP_INSUFFICIENT_ACC; break; #endif case LDAP_BUSY: ec = GPG_ERR_LDAP_BUSY; break; case LDAP_UNAVAILABLE: ec = GPG_ERR_LDAP_UNAVAILABLE; break; case LDAP_UNWILLING_TO_PERFORM: ec = GPG_ERR_LDAP_UNWILL_TO_PERFORM; break; case LDAP_LOOP_DETECT: ec = GPG_ERR_LDAP_LOOP_DETECT; break; case LDAP_NAMING_VIOLATION: ec = GPG_ERR_LDAP_NAMING_VIOLATION; break; case LDAP_OBJECT_CLASS_VIOLATION: ec = GPG_ERR_LDAP_OBJ_CLS_VIOLATION; break; case LDAP_NOT_ALLOWED_ON_NONLEAF: ec=GPG_ERR_LDAP_NOT_ALLOW_NONLEAF;break; case LDAP_NOT_ALLOWED_ON_RDN: ec = GPG_ERR_LDAP_NOT_ALLOW_ON_RDN; break; case LDAP_ALREADY_EXISTS: ec = GPG_ERR_LDAP_ALREADY_EXISTS; break; case LDAP_NO_OBJECT_CLASS_MODS: ec = GPG_ERR_LDAP_NO_OBJ_CLASS_MODS; break; case LDAP_RESULTS_TOO_LARGE: ec = GPG_ERR_LDAP_RESULTS_TOO_LARGE; break; case LDAP_AFFECTS_MULTIPLE_DSAS: ec = GPG_ERR_LDAP_AFFECTS_MULT_DSAS; break; #ifdef LDAP_VLV_ERROR case LDAP_VLV_ERROR: ec = GPG_ERR_LDAP_VLV; break; #endif case LDAP_OTHER: ec = GPG_ERR_LDAP_OTHER; break; #ifdef LDAP_CUP_RESOURCES_EXHAUSTED case LDAP_CUP_RESOURCES_EXHAUSTED: ec=GPG_ERR_LDAP_CUP_RESOURCE_LIMIT;break; case LDAP_CUP_SECURITY_VIOLATION: ec=GPG_ERR_LDAP_CUP_SEC_VIOLATION; break; case LDAP_CUP_INVALID_DATA: ec = GPG_ERR_LDAP_CUP_INV_DATA; break; case LDAP_CUP_UNSUPPORTED_SCHEME: ec = GPG_ERR_LDAP_CUP_UNSUP_SCHEME; break; case LDAP_CUP_RELOAD_REQUIRED: ec = GPG_ERR_LDAP_CUP_RELOAD; break; #endif #ifdef LDAP_CANCELLED case LDAP_CANCELLED: ec = GPG_ERR_LDAP_CANCELLED; break; #endif #ifdef LDAP_NO_SUCH_OPERATION case LDAP_NO_SUCH_OPERATION: ec = GPG_ERR_LDAP_NO_SUCH_OPERATION; break; #endif #ifdef LDAP_TOO_LATE case LDAP_TOO_LATE: ec = GPG_ERR_LDAP_TOO_LATE; break; #endif #ifdef LDAP_CANNOT_CANCEL case LDAP_CANNOT_CANCEL: ec = GPG_ERR_LDAP_CANNOT_CANCEL; break; #endif #ifdef LDAP_ASSERTION_FAILED case LDAP_ASSERTION_FAILED: ec = GPG_ERR_LDAP_ASSERTION_FAILED; break; #endif #ifdef LDAP_PROXIED_AUTHORIZATION_DENIED case LDAP_PROXIED_AUTHORIZATION_DENIED: ec = GPG_ERR_LDAP_PROX_AUTH_DENIED; break; #endif default: #if defined(LDAP_E_ERROR) && defined(LDAP_X_ERROR) if (LDAP_E_ERROR (code)) ec = GPG_ERR_LDAP_E_GENERAL; else if (LDAP_X_ERROR (code)) ec = GPG_ERR_LDAP_X_GENERAL; else #endif ec = GPG_ERR_LDAP_GENERAL; break; } return ec; } /* Retrieve an LDAP error and return it's GPG equivalent. */ static int ldap_to_gpg_err (LDAP *ld) { #if defined(HAVE_LDAP_GET_OPTION) && defined(LDAP_OPT_ERROR_NUMBER) int err; if (ldap_get_option (ld, LDAP_OPT_ERROR_NUMBER, &err) == 0) return ldap_err_to_gpg_err (err); else return GPG_ERR_GENERAL; #elif defined(HAVE_LDAP_LD_ERRNO) return ldap_err_to_gpg_err (ld->ld_errno); #else /* We should never get here since the LDAP library should always have either ldap_get_option or ld_errno, but just in case... */ return GPG_ERR_INTERNAL; #endif } static time_t ldap2epochtime (const char *timestr) { struct tm pgptime; time_t answer; memset (&pgptime, 0, sizeof(pgptime)); /* YYYYMMDDHHmmssZ */ sscanf (timestr, "%4d%2d%2d%2d%2d%2d", &pgptime.tm_year, &pgptime.tm_mon, &pgptime.tm_mday, &pgptime.tm_hour, &pgptime.tm_min, &pgptime.tm_sec); pgptime.tm_year -= 1900; pgptime.tm_isdst = -1; pgptime.tm_mon--; /* mktime() takes the timezone into account, so we use timegm() */ answer = timegm (&pgptime); return answer; } /* Caller must free the result. */ static char * tm2ldaptime (struct tm *tm) { struct tm tmp = *tm; char buf[16]; /* YYYYMMDDHHmmssZ */ tmp.tm_year += 1900; tmp.tm_mon ++; snprintf (buf, sizeof buf, "%04d%02d%02d%02d%02d%02dZ", tmp.tm_year, tmp.tm_mon, tmp.tm_mday, tmp.tm_hour, tmp.tm_min, tmp.tm_sec); return xstrdup (buf); } #if 0 /* Caller must free */ static char * epoch2ldaptime (time_t stamp) { struct tm tm; if (gmtime_r (&stamp, &tm)) return tm2ldaptime (&tm); else return xstrdup ("INVALID TIME"); } #endif static void my_ldap_value_free (char **vals) { if (vals) ldap_value_free (vals); } /* Print a help output for the schemata supported by this module. */ gpg_error_t ks_ldap_help (ctrl_t ctrl, parsed_uri_t uri) { const char data[] = "Handler for LDAP URLs:\n" " ldap://HOST:PORT/[BASEDN]???[bindname=BINDNAME,password=PASSWORD]\n" "\n" "Note: basedn, bindname and password need to be percent escaped. In\n" "particular, spaces need to be replaced with %20 and commas with %2c.\n" "Thus bindname will typically be of the form:\n" "\n" " uid=user%2cou=PGP%20Users%2cdc=EXAMPLE%2cdc=ORG\n" "\n" "The ldaps:// and ldapi:// schemes are also supported. If ldaps is used\n" "then the server's certificate will be checked. If it is not valid, any\n" "operation will be aborted. Note that ldaps means LDAP with STARTTLS\n" "\n" "As an alternative to an URL a string in this form may be used:\n" "\n" " HOST:PORT:BINDNAME:PASSWORD:BASEDN:FLAGS:\n" "\n" "The use of the percent sign or a colon in one of the string values is\n" "currently not supported.\n" "\n" "Supported methods: search, get, put\n"; gpg_error_t err; if(!uri) err = ks_print_help (ctrl, " ldap"); else if (uri->is_ldap || uri->opaque) err = ks_print_help (ctrl, data); else err = 0; return err; } /* Convert a keyspec to a filter. Return an error if the keyspec is bad or is not supported. The filter is escaped and returned in *filter. It is the caller's responsibility to free *filter. *filter is only set if this function returns success (i.e., 0). */ static gpg_error_t keyspec_to_ldap_filter (const char *keyspec, char **filter, int only_exact, unsigned int serverinfo) { /* Remove search type indicator and adjust PATTERN accordingly. Note: don't include a preceding 0x when searching by keyid. */ /* XXX: Should we include disabled / revoke options? */ KEYDB_SEARCH_DESC desc; char *f = NULL; char *freeme = NULL; char *p; gpg_error_t err = classify_user_id (keyspec, &desc, 1); if (err) return err; switch (desc.mode) { case KEYDB_SEARCH_MODE_EXACT: f = xasprintf ("(pgpUserID=%s)", (freeme = ldap_escape_filter (desc.u.name))); break; case KEYDB_SEARCH_MODE_SUBSTR: if (! only_exact) f = xasprintf ("(pgpUserID=*%s*)", (freeme = ldap_escape_filter (desc.u.name))); break; case KEYDB_SEARCH_MODE_MAIL: freeme = ldap_escape_filter (desc.u.name); if (!freeme) break; if (*freeme == '<' && freeme[1] && freeme[2]) { /* Strip angle brackets. Note that it is does not * matter whether we work on the plan or LDAP escaped * version of the mailbox. */ p = freeme + 1; if (p[strlen(p)-1] == '>') p[strlen(p)-1] = 0; } else p = freeme; if ((serverinfo & SERVERINFO_SCHEMAV2)) f = xasprintf ("(&(gpgMailbox=%s)(!(|(pgpRevoked=1)(pgpDisabled=1))))", p); else if (!only_exact) f = xasprintf ("(pgpUserID=*<%s>*)", p); break; case KEYDB_SEARCH_MODE_MAILSUB: if (! only_exact) f = xasprintf ("(pgpUserID=*<*%s*>*)", (freeme = ldap_escape_filter (desc.u.name))); break; case KEYDB_SEARCH_MODE_MAILEND: if (! only_exact) f = xasprintf ("(pgpUserID=*<*%s>*)", (freeme = ldap_escape_filter (desc.u.name))); break; case KEYDB_SEARCH_MODE_SHORT_KID: f = xasprintf ("(pgpKeyID=%08lX)", (ulong) desc.u.kid[1]); break; case KEYDB_SEARCH_MODE_LONG_KID: f = xasprintf ("(pgpCertID=%08lX%08lX)", (ulong) desc.u.kid[0], (ulong) desc.u.kid[1]); break; case KEYDB_SEARCH_MODE_FPR: if ((serverinfo & SERVERINFO_SCHEMAV2)) { freeme = bin2hex (desc.u.fpr, desc.fprlen, NULL); if (!freeme) return gpg_error_from_syserror (); f = xasprintf ("(|(gpgFingerprint=%s)(gpgSubFingerprint=%s))", freeme, freeme); /* FIXME: For an exact search and in case of a match on * gpgSubFingerprint we need to check that there is only one * matching value. */ } break; case KEYDB_SEARCH_MODE_ISSUER: case KEYDB_SEARCH_MODE_ISSUER_SN: case KEYDB_SEARCH_MODE_SN: case KEYDB_SEARCH_MODE_SUBJECT: case KEYDB_SEARCH_MODE_KEYGRIP: case KEYDB_SEARCH_MODE_WORDS: case KEYDB_SEARCH_MODE_FIRST: case KEYDB_SEARCH_MODE_NEXT: default: break; } xfree (freeme); if (! f) { log_error ("Unsupported search mode.\n"); return gpg_error (GPG_ERR_NOT_SUPPORTED); } *filter = f; return 0; } /* Connect to an LDAP server and interrogate it. - uri describes the server to connect to and various options including whether to use TLS and the username and password (see ldap_parse_uri for a description of the various fields). This function returns: - The ldap connection handle in *LDAP_CONNP. - The base DN for the PGP key space by querying the pgpBaseKeySpaceDN attribute (This is normally 'ou=PGP Keys,dc=EXAMPLE,dc=ORG'). - The attribute to lookup to find the pgp key. This is either 'pgpKey' or 'pgpKeyV2'. - Whether this is a real ldap server. (It's unclear what this exactly means.) The values are returned in the passed variables. If you pass NULL, then the value won't be returned. It is the caller's responsibility to release *LDAP_CONNP with ldap_unbind and xfree *BASEDNP. If this function successfully interrogated the server, it returns 0. If there was an LDAP error, it returns the LDAP error code. If an error occurred, *basednp, etc., are undefined (and don't need to be freed.) R_SERVERINFO receives information about the server. If no LDAP error occurred, you still need to check that *basednp is valid. If it is NULL, then the server does not appear to be an OpenPGP Keyserver. */ static gpg_error_t my_ldap_connect (parsed_uri_t uri, LDAP **ldap_connp, char **r_basedn, char **r_host, int *r_use_tls, unsigned int *r_serverinfo) { gpg_error_t err = 0; int lerr; ldap_server_t server = NULL; LDAP *ldap_conn = NULL; char *basedn = NULL; char *host = NULL; /* Host to use. */ int port; /* Port to use. */ int use_tls; /* 1 = starttls, 2 = ldap-over-tls */ int use_ntds; /* Use Active Directory authentication. */ const char *bindname; const char *password; const char *basedn_arg; +#ifndef HAVE_W32_SYSTEM char *tmpstr; +#endif if (r_basedn) *r_basedn = NULL; if (r_host) *r_host = NULL; if (r_use_tls) *r_use_tls = 0; *r_serverinfo = 0; if (uri->opaque) { server = ldapserver_parse_one (uri->path, NULL, 0); if (!server) return gpg_error (GPG_ERR_LDAP_OTHER); host = server->host; port = server->port; bindname = server->user; password = bindname? server->pass : NULL; basedn_arg = server->base; use_tls = server->starttls? 1 : server->ldap_over_tls? 2 : 0; use_ntds = server->ntds; } else { struct uri_tuple_s *password_param; password_param = uri_query_lookup (uri, "password"); password = password_param ? password_param->value : NULL; host = uri->host; port = uri->port; bindname = uri->auth; password = bindname? uri_query_value (uri, "password") : NULL; basedn_arg = uri->path; use_tls = uri->use_tls ? 1 : 0; use_ntds = uri->ad_current; } if (!port) port = use_tls == 2? 636 : 389; if (host) { host = xtrystrdup (host); if (!host) { err = gpg_error_from_syserror (); goto out; } } if (opt.debug) log_debug ("my_ldap_connect(%s:%d/%s????%s%s%s%s%s)\n", host, port, basedn_arg ? basedn_arg : "", bindname ? "bindname=" : "", bindname ? bindname : "", password ? "," : "", password ? "password=>not_shown<" : "", use_ntds ? " auth=>current_user<":""); /* If the uri specifies a secure connection and we don't support TLS, then fail; don't silently revert to an insecure connection. */ if (use_tls) { #ifndef HAVE_LDAP_START_TLS_S log_error ("ldap: can't connect to the server: no TLS support."); err = GPG_ERR_LDAP_NOT_SUPPORTED; goto out; #endif } #ifdef HAVE_W32_SYSTEM npth_unprotect (); ldap_conn = ldap_sslinit (host, port, (use_tls == 2)); npth_protect (); if (!ldap_conn) { lerr = LdapGetLastError (); err = ldap_err_to_gpg_err (lerr); log_error ("error initializing LDAP '%s:%d': %s\n", host, port, ldap_err2string (lerr)); goto out; } #else /* Unix */ tmpstr = xtryasprintf ("%s://%s:%d", use_tls == 2? "ldaps" : "ldap", host, port); if (!tmpstr) { err = gpg_error_from_syserror (); goto out; } npth_unprotect (); lerr = ldap_initialize (&ldap_conn, tmpstr); npth_protect (); if (lerr || !ldap_conn) { err = ldap_err_to_gpg_err (lerr); log_error ("error initializing LDAP '%s': %s\n", tmpstr, ldap_err2string (lerr)); xfree (tmpstr); goto out; } xfree (tmpstr); #endif /* Unix */ #ifdef HAVE_LDAP_SET_OPTION { int ver = LDAP_VERSION3; lerr = ldap_set_option (ldap_conn, LDAP_OPT_PROTOCOL_VERSION, &ver); if (lerr != LDAP_SUCCESS) { log_error ("ks-ldap: unable to go to LDAP 3: %s\n", ldap_err2string (lerr)); err = ldap_err_to_gpg_err (lerr); goto out; } } #endif #ifdef HAVE_LDAP_START_TLS_S if (use_tls == 1) { #ifndef HAVE_W32_SYSTEM int check_cert = LDAP_OPT_X_TLS_HARD; /* LDAP_OPT_X_TLS_NEVER */ lerr = ldap_set_option (ldap_conn, LDAP_OPT_X_TLS_REQUIRE_CERT, &check_cert); if (lerr) { log_error ("ldap: error setting an TLS option: %s\n", ldap_err2string (lerr)); err = ldap_err_to_gpg_err (lerr); goto out; } #else /* On Windows, the certificates are checked by default. If the option to disable checking mentioned above is ever implemented, the way to do that on Windows is to install a callback routine using ldap_set_option (.., LDAP_OPT_SERVER_CERTIFICATE, ..); */ #endif npth_unprotect (); lerr = ldap_start_tls_s (ldap_conn, #ifdef HAVE_W32_SYSTEM /* ServerReturnValue, result */ NULL, NULL, #endif /* ServerControls, ClientControls */ NULL, NULL); npth_protect (); if (lerr) { log_error ("ldap: error switching to STARTTLS mode: %s\n", ldap_err2string (lerr)); err = ldap_err_to_gpg_err (lerr); goto out; } } #endif if (use_ntds) { if (opt.debug) log_debug ("ldap: binding to current user via AD\n"); #ifdef HAVE_W32_SYSTEM npth_unprotect (); lerr = ldap_bind_s (ldap_conn, NULL, NULL, LDAP_AUTH_NEGOTIATE); npth_protect (); if (lerr != LDAP_SUCCESS) { log_error ("error binding to LDAP via AD: %s\n", ldap_err2string (lerr)); err = ldap_err_to_gpg_err (lerr); goto out; } #else err = gpg_error (GPG_ERR_NOT_SUPPORTED); goto out; #endif } else if (bindname) { if (opt.debug) log_debug ("LDAP bind to '%s', password '%s'\n", bindname, password ? ">not_shown<" : ">none<"); npth_unprotect (); lerr = ldap_simple_bind_s (ldap_conn, bindname, password); npth_protect (); if (lerr != LDAP_SUCCESS) { log_error ("error binding to LDAP: %s\n", ldap_err2string (lerr)); err = ldap_err_to_gpg_err (lerr); goto out; } } else { /* By default we don't bind as there is usually no need to. */ } if (basedn_arg && *basedn_arg) { /* User specified base DN. In this case we know the server is a * real LDAP server. */ basedn = xtrystrdup (basedn_arg); if (!basedn) { err = gpg_error_from_syserror (); goto out; } *r_serverinfo |= SERVERINFO_REALLDAP; } else { /* Look for namingContexts. */ LDAPMessage *res = NULL; char *attr[] = { "namingContexts", NULL }; npth_unprotect (); lerr = ldap_search_s (ldap_conn, "", LDAP_SCOPE_BASE, "(objectClass=*)", attr, 0, &res); npth_protect (); if (lerr == LDAP_SUCCESS) { char **context; npth_unprotect (); context = ldap_get_values (ldap_conn, res, "namingContexts"); npth_protect (); if (context) { /* We found some, so try each namingContext as the * search base and look for pgpBaseKeySpaceDN. Because * we found this, we know we're talking to a regular-ish * LDAP server and not an LDAP keyserver. */ int i; char *attr2[] = { "pgpBaseKeySpaceDN", "pgpVersion", "pgpSoftware", NULL }; *r_serverinfo |= SERVERINFO_REALLDAP; for (i = 0; context[i] && !basedn; i++) { char **vals; LDAPMessage *si_res; int is_gnupg = 0; { char *object = xasprintf ("cn=pgpServerInfo,%s", context[i]); npth_unprotect (); lerr = ldap_search_s (ldap_conn, object, LDAP_SCOPE_BASE, "(objectClass=*)", attr2, 0, &si_res); npth_protect (); xfree (object); } if (lerr == LDAP_SUCCESS) { vals = ldap_get_values (ldap_conn, si_res, "pgpBaseKeySpaceDN"); if (vals && vals[0]) { basedn = xtrystrdup (vals[0]); } my_ldap_value_free (vals); vals = ldap_get_values (ldap_conn, si_res, "pgpSoftware"); if (vals && vals[0]) { if (opt.debug) log_debug ("Server: \t%s\n", vals[0]); if (!ascii_strcasecmp (vals[0], "GnuPG")) is_gnupg = 1; } my_ldap_value_free (vals); vals = ldap_get_values (ldap_conn, si_res, "pgpVersion"); if (vals && vals[0]) { if (opt.debug) log_debug ("Version:\t%s\n", vals[0]); if (is_gnupg) { const char *fields[2]; int nfields; nfields = split_fields (vals[0], fields, DIM(fields)); if (nfields > 0 && atoi(fields[0]) > 1) *r_serverinfo |= SERVERINFO_SCHEMAV2; if (nfields > 1 && !ascii_strcasecmp (fields[1], "ntds")) *r_serverinfo |= SERVERINFO_NTDS; } } my_ldap_value_free (vals); } /* From man ldap_search_s: "res parameter of ldap_search_ext_s() and ldap_search_s() should be freed with ldap_msgfree() regardless of return value of these functions. */ ldap_msgfree (si_res); } ldap_value_free (context); } } else /* ldap_search failed. */ { /* We don't have an answer yet, which means the server might be a PGP.com keyserver. */ char **vals; LDAPMessage *si_res = NULL; char *attr2[] = { "pgpBaseKeySpaceDN", "version", "software", NULL }; npth_unprotect (); lerr = ldap_search_s (ldap_conn, "cn=pgpServerInfo", LDAP_SCOPE_BASE, "(objectClass=*)", attr2, 0, &si_res); npth_protect (); if (lerr == LDAP_SUCCESS) { /* For the PGP LDAP keyserver, this is always * "OU=ACTIVE,O=PGP KEYSPACE,C=US", but it might not be * in the future. */ vals = ldap_get_values (ldap_conn, si_res, "baseKeySpaceDN"); if (vals && vals[0]) { basedn = xtrystrdup (vals[0]); } my_ldap_value_free (vals); vals = ldap_get_values (ldap_conn, si_res, "software"); if (vals && vals[0]) { if (opt.debug) log_debug ("ks-ldap: PGP Server: \t%s\n", vals[0]); } my_ldap_value_free (vals); vals = ldap_get_values (ldap_conn, si_res, "version"); if (vals && vals[0]) { if (opt.debug) log_debug ("ks-ldap: PGP Server Version:\t%s\n", vals[0]); /* If the version is high enough, use the new pgpKeyV2 attribute. This design is iffy at best, but it matches how PGP does it. I figure the NAI folks assumed that there would never be an LDAP keyserver vendor with a different numbering scheme. */ if (atoi (vals[0]) > 1) *r_serverinfo |= SERVERINFO_PGPKEYV2; } my_ldap_value_free (vals); } ldap_msgfree (si_res); } /* From man ldap_search_s: "res parameter of ldap_search_ext_s() and ldap_search_s() should be freed with ldap_msgfree() regardless of return value of these functions. */ ldap_msgfree (res); } out: if (!err && opt.debug) { log_debug ("ldap_conn: %p\n", ldap_conn); log_debug ("server_type: %s\n", ((*r_serverinfo & SERVERINFO_REALLDAP) ? "LDAP" : "PGP.com keyserver") ); log_debug ("basedn: %s\n", basedn); log_debug ("pgpkeyattr: %s\n", (*r_serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey"); } ldapserver_list_free (server); if (err) { xfree (basedn); if (ldap_conn) ldap_unbind (ldap_conn); } else { if (r_basedn) *r_basedn = basedn; else xfree (basedn); if (r_host) *r_host = host; else xfree (host); *ldap_connp = ldap_conn; } return err; } /* Extract keys from an LDAP reply and write them out to the output stream OUTPUT in a format GnuPG can import (either the OpenPGP binary format or armored format). */ static void extract_keys (estream_t output, LDAP *ldap_conn, const char *certid, LDAPMessage *message) { char **vals; es_fprintf (output, "INFO %s BEGIN\n", certid); /* Note: ldap_get_values returns a NULL terminated array of strings. */ vals = ldap_get_values (ldap_conn, message, "gpgfingerprint"); if (vals && vals[0] && vals[0][0]) es_fprintf (output, "pub:%s:", vals[0]); else es_fprintf (output, "pub:%s:", certid); my_ldap_value_free (vals); vals = ldap_get_values (ldap_conn, message, "pgpkeytype"); if (vals && vals[0]) { if (strcmp (vals[0], "RSA") == 0) es_fprintf (output, "1"); else if (strcmp (vals[0],"DSS/DH") == 0) es_fprintf (output, "17"); } my_ldap_value_free (vals); es_fprintf (output, ":"); vals = ldap_get_values (ldap_conn, message, "pgpkeysize"); if (vals && vals[0]) { int v = atoi (vals[0]); if (v > 0) es_fprintf (output, "%d", v); } my_ldap_value_free (vals); es_fprintf (output, ":"); vals = ldap_get_values (ldap_conn, message, "pgpkeycreatetime"); if (vals && vals[0]) { if (strlen (vals[0]) == 15) es_fprintf (output, "%u", (unsigned int) ldap2epochtime (vals[0])); } my_ldap_value_free (vals); es_fprintf (output, ":"); vals = ldap_get_values (ldap_conn, message, "pgpkeyexpiretime"); if (vals && vals[0]) { if (strlen (vals[0]) == 15) es_fprintf (output, "%u", (unsigned int) ldap2epochtime (vals[0])); } my_ldap_value_free (vals); es_fprintf (output, ":"); vals = ldap_get_values (ldap_conn, message, "pgprevoked"); if (vals && vals[0]) { if (atoi (vals[0]) == 1) es_fprintf (output, "r"); } my_ldap_value_free (vals); es_fprintf (output, "\n"); vals = ldap_get_values (ldap_conn, message, "pgpuserid"); if (vals && vals[0]) { int i; for (i = 0; vals[i]; i++) es_fprintf (output, "uid:%s\n", vals[i]); } my_ldap_value_free (vals); es_fprintf (output, "INFO %s END\n", certid); } /* Get the key described key the KEYSPEC string from the keyserver identified by URI. On success R_FP has an open stream to read the data. */ gpg_error_t ks_ldap_get (ctrl_t ctrl, parsed_uri_t uri, const char *keyspec, estream_t *r_fp) { gpg_error_t err = 0; int ldap_err; unsigned int serverinfo; char *host = NULL; int use_tls; char *filter = NULL; LDAP *ldap_conn = NULL; char *basedn = NULL; estream_t fp = NULL; LDAPMessage *message = NULL; (void) ctrl; if (dirmngr_use_tor ()) { /* For now we do not support LDAP over Tor. */ log_error (_("LDAP access not possible due to Tor mode\n")); return gpg_error (GPG_ERR_NOT_SUPPORTED); } /* Make sure we are talking to an OpenPGP LDAP server. */ err = my_ldap_connect (uri, &ldap_conn, &basedn, &host, &use_tls, &serverinfo); if (err || !basedn) { if (!err) err = gpg_error (GPG_ERR_GENERAL); goto out; } /* Now that we have information about the server we can construct a * query best suited for the capabilities of the server. */ err = keyspec_to_ldap_filter (keyspec, &filter, 1, serverinfo); if (err) goto out; if (opt.debug) log_debug ("ks-ldap: using filter: %s\n", filter); { /* The ordering is significant. Specifically, "pgpcertid" needs to be the second item in the list, since everything after it may be discarded if we aren't in verbose mode. */ char *attrs[] = { "dummy", "pgpcertid", "pgpuserid", "pgpkeyid", "pgprevoked", "pgpdisabled", "pgpkeycreatetime", "modifytimestamp", "pgpkeysize", "pgpkeytype", "gpgfingerprint", NULL }; /* 1 if we want just attribute types; 0 if we want both attribute * types and values. */ int attrsonly = 0; int count; /* Replace "dummy". */ attrs[0] = (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2" : "pgpKey"; npth_unprotect (); ldap_err = ldap_search_s (ldap_conn, basedn, LDAP_SCOPE_SUBTREE, filter, attrs, attrsonly, &message); npth_protect (); if (ldap_err) { err = ldap_err_to_gpg_err (ldap_err); log_error ("ks-ldap: LDAP search error: %s\n", ldap_err2string (ldap_err)); goto out; } count = ldap_count_entries (ldap_conn, message); if (count < 1) { log_info ("ks-ldap: key %s not found on keyserver\n", keyspec); if (count == -1) err = ldap_to_gpg_err (ldap_conn); else err = gpg_error (GPG_ERR_NO_DATA); goto out; } { /* There may be more than one unique result for a given keyID, so we should fetch them all (test this by fetching short key id 0xDEADBEEF). */ /* The set of entries that we've seen. */ strlist_t seen = NULL; LDAPMessage *each; int anykey = 0; for (npth_unprotect (), each = ldap_first_entry (ldap_conn, message), npth_protect (); each; npth_unprotect (), each = ldap_next_entry (ldap_conn, each), npth_protect ()) { char **vals; char **certid; /* Use the long keyid to remove duplicates. The LDAP server returns the same keyid more than once if there are multiple user IDs on the key. Note that this does NOT mean that a keyid that exists multiple times on the keyserver will not be fetched. It means that each KEY, no matter how many user IDs share its keyid, will be fetched only once. If a keyid that belongs to more than one key is fetched, the server quite properly responds with all matching keys. -ds */ certid = ldap_get_values (ldap_conn, each, "pgpcertid"); if (certid && certid[0]) { if (! strlist_find (seen, certid[0])) { /* It's not a duplicate, add it */ add_to_strlist (&seen, certid[0]); if (! fp) fp = es_fopenmem(0, "rw"); extract_keys (fp, ldap_conn, certid[0], each); vals = ldap_get_values (ldap_conn, each, attrs[0]); if (! vals) { err = ldap_to_gpg_err (ldap_conn); log_error("ks-ldap: unable to retrieve key %s " "from keyserver\n", certid[0]); goto out; } else { /* We should strip the new lines. */ es_fprintf (fp, "KEY 0x%s BEGIN\n", certid[0]); es_fputs (vals[0], fp); es_fprintf (fp, "\nKEY 0x%s END\n", certid[0]); ldap_value_free (vals); anykey = 1; } } } my_ldap_value_free (certid); } free_strlist (seen); if (! fp) err = gpg_error (GPG_ERR_NO_DATA); if (!err && anykey) err = dirmngr_status_printf (ctrl, "SOURCE", "%s://%s", use_tls? "ldaps" : "ldap", host? host:""); } } out: if (message) ldap_msgfree (message); if (err) { if (fp) es_fclose (fp); } else { if (fp) es_fseek (fp, 0, SEEK_SET); *r_fp = fp; } xfree (basedn); xfree (host); if (ldap_conn) ldap_unbind (ldap_conn); xfree (filter); return err; } /* Search the keyserver identified by URI for keys matching PATTERN. On success R_FP has an open stream to read the data. */ gpg_error_t ks_ldap_search (ctrl_t ctrl, parsed_uri_t uri, const char *pattern, estream_t *r_fp) { gpg_error_t err; int ldap_err; unsigned int serverinfo; char *filter = NULL; LDAP *ldap_conn = NULL; char *basedn = NULL; estream_t fp = NULL; (void) ctrl; if (dirmngr_use_tor ()) { /* For now we do not support LDAP over Tor. */ log_error (_("LDAP access not possible due to Tor mode\n")); return gpg_error (GPG_ERR_NOT_SUPPORTED); } /* Make sure we are talking to an OpenPGP LDAP server. */ err = my_ldap_connect (uri, &ldap_conn, &basedn, NULL, NULL, &serverinfo); if (err || !basedn) { if (!err) err = GPG_ERR_GENERAL; goto out; } /* Now that we have information about the server we can construct a * query best suited for the capabilities of the server. */ err = keyspec_to_ldap_filter (pattern, &filter, 0, serverinfo); if (err) { log_error ("Bad search pattern: '%s'\n", pattern); goto out; } /* Even if we have no results, we want to return a stream. */ fp = es_fopenmem(0, "rw"); if (!fp) { err = gpg_error_from_syserror (); goto out; } { char **vals; LDAPMessage *res, *each; int count = 0; strlist_t dupelist = NULL; /* The maximum size of the search, including the optional stuff and the trailing \0 */ char *attrs[] = { "pgpcertid", "pgpuserid", "pgprevoked", "pgpdisabled", "pgpkeycreatetime", "pgpkeyexpiretime", "modifytimestamp", "pgpkeysize", "pgpkeytype", "gpgfingerprint", NULL }; if (opt.debug) log_debug ("SEARCH '%s' => '%s' BEGIN\n", pattern, filter); npth_unprotect (); ldap_err = ldap_search_s (ldap_conn, basedn, LDAP_SCOPE_SUBTREE, filter, attrs, 0, &res); npth_protect (); xfree (filter); filter = NULL; if (ldap_err != LDAP_SUCCESS && ldap_err != LDAP_SIZELIMIT_EXCEEDED) { err = ldap_err_to_gpg_err (ldap_err); log_error ("SEARCH %s FAILED %d\n", pattern, err); log_error ("ks-ldap: LDAP search error: %s\n", ldap_err2string (err)); goto out; } /* The LDAP server doesn't return a real count of unique keys, so we can't use ldap_count_entries here. */ for (npth_unprotect (), each = ldap_first_entry (ldap_conn, res), npth_protect (); each; npth_unprotect (), each = ldap_next_entry (ldap_conn, each), npth_protect ()) { char **certid = ldap_get_values (ldap_conn, each, "pgpcertid"); if (certid && certid[0] && ! strlist_find (dupelist, certid[0])) { add_to_strlist (&dupelist, certid[0]); count++; } my_ldap_value_free (certid); } if (ldap_err == LDAP_SIZELIMIT_EXCEEDED) { if (count == 1) log_error ("ks-ldap: search results exceeded server limit." " First 1 result shown.\n"); else log_error ("ks-ldap: search results exceeded server limit." " First %d results shown.\n", count); } free_strlist (dupelist); dupelist = NULL; if (count < 1) es_fputs ("info:1:0\n", fp); else { es_fprintf (fp, "info:1:%d\n", count); for (each = ldap_first_entry (ldap_conn, res); each; each = ldap_next_entry (ldap_conn, each)) { char **certid; LDAPMessage *uids; certid = ldap_get_values (ldap_conn, each, "pgpcertid"); if (!certid || !certid[0]) { my_ldap_value_free (certid); continue; } /* Have we seen this certid before? */ if (! strlist_find (dupelist, certid[0])) { add_to_strlist (&dupelist, certid[0]); vals = ldap_get_values (ldap_conn, each, "gpgfingerprint"); if (vals && vals[0] && vals[0][0]) es_fprintf (fp, "pub:%s:", vals[0]); else es_fprintf (fp, "pub:%s:", certid[0]); my_ldap_value_free (vals); vals = ldap_get_values (ldap_conn, each, "pgpkeytype"); if (vals && vals[0]) { /* The LDAP server doesn't exactly handle this well. */ if (strcasecmp (vals[0], "RSA") == 0) es_fputs ("1", fp); else if (strcasecmp (vals[0], "DSS/DH") == 0) es_fputs ("17", fp); } my_ldap_value_free (vals); es_fputc (':', fp); vals = ldap_get_values (ldap_conn, each, "pgpkeysize"); if (vals && vals[0]) { /* Not sure why, but some keys are listed with a key size of 0. Treat that like an unknown. */ if (atoi (vals[0]) > 0) es_fprintf (fp, "%d", atoi (vals[0])); } my_ldap_value_free (vals); es_fputc (':', fp); /* YYYYMMDDHHmmssZ */ vals = ldap_get_values (ldap_conn, each, "pgpkeycreatetime"); if(vals && vals[0] && strlen (vals[0]) == 15) { es_fprintf (fp, "%u", (unsigned int) ldap2epochtime(vals[0])); } my_ldap_value_free (vals); es_fputc (':', fp); vals = ldap_get_values (ldap_conn, each, "pgpkeyexpiretime"); if (vals && vals[0] && strlen (vals[0]) == 15) { es_fprintf (fp, "%u", (unsigned int) ldap2epochtime (vals[0])); } my_ldap_value_free (vals); es_fputc (':', fp); vals = ldap_get_values (ldap_conn, each, "pgprevoked"); if (vals && vals[0]) { if (atoi (vals[0]) == 1) es_fprintf (fp, "r"); } my_ldap_value_free (vals); vals = ldap_get_values (ldap_conn, each, "pgpdisabled"); if (vals && vals[0]) { if (atoi (vals[0]) ==1) es_fprintf (fp, "d"); } my_ldap_value_free (vals); #if 0 /* This is not yet specified in the keyserver protocol, but may be someday. */ es_fputc (':', fp); vals = ldap_get_values (ldap_conn, each, "modifytimestamp"); if(vals && vals[0] strlen (vals[0]) == 15) { es_fprintf (fp, "%u", (unsigned int) ldap2epochtime (vals[0])); } my_ldap_value_free (vals); #endif es_fprintf (fp, "\n"); /* Now print all the uids that have this certid */ for (uids = ldap_first_entry (ldap_conn, res); uids; uids = ldap_next_entry (ldap_conn, uids)) { vals = ldap_get_values (ldap_conn, uids, "pgpcertid"); if (!vals || !vals[0]) { my_ldap_value_free (vals); continue; } if (!ascii_strcasecmp (certid[0], vals[0])) { char **uidvals; es_fprintf (fp, "uid:"); uidvals = ldap_get_values (ldap_conn, uids, "pgpuserid"); if (uidvals) { /* Need to percent escape any colons */ char *quoted = try_percent_escape (uidvals[0], NULL); if (quoted) es_fputs (quoted, fp); xfree (quoted); } my_ldap_value_free (uidvals); es_fprintf (fp, "\n"); } ldap_value_free(vals); } } my_ldap_value_free (certid); } } ldap_msgfree (res); free_strlist (dupelist); } if (opt.debug) log_debug ("SEARCH %s END\n", pattern); out: if (err) { es_fclose (fp); } else { /* Return the read stream. */ if (fp) es_fseek (fp, 0, SEEK_SET); *r_fp = fp; } xfree (basedn); if (ldap_conn) ldap_unbind (ldap_conn); xfree (filter); return err; } /* A modlist describes a set of changes to an LDAP entry. (An entry consists of 1 or more attributes. Attributes are pairs. Note: an attribute may be multi-valued in which case multiple values are associated with a single name.) A modlist is a NULL terminated array of struct LDAPMod's. Thus, if we have: LDAPMod **modlist; Then: modlist[i] Is the ith modification. Each LDAPMod describes a change to a single attribute. Further, there is one modification for each attribute that we want to change. The attribute's new value is stored in LDAPMod.mod_values. If the attribute is multi-valued, we still only use a single LDAPMod structure: mod_values is a NULL-terminated array of strings. To delete an attribute from an entry, we set mod_values to NULL. Thus, if: modlist[i]->mod_values == NULL then we remove the attribute. (Using LDAP_MOD_DELETE doesn't work here as we don't know if the attribute in question exists or not.) Note: this function does NOT copy or free ATTR. It does copy VALUE. */ static void modlist_add (LDAPMod ***modlistp, char *attr, const char *value) { LDAPMod **modlist = *modlistp; LDAPMod **m; int nummods = 0; /* Search modlist for the attribute we're playing with. If modlist is NULL, then the list is empty. Recall: modlist is a NULL terminated array. */ for (m = modlist; m && *m; m++, nummods ++) { /* The attribute is already on the list. */ char **ptr; int numvalues = 0; if (strcasecmp ((*m)->mod_type, attr) != 0) continue; /* We have this attribute already, so when the REPLACE happens, the server attributes will be replaced anyway. */ if (! value) return; /* Attributes can be multi-valued. See if the value is already present. mod_values is a NULL terminated array of pointers. Note: mod_values can be NULL. */ for (ptr = (*m)->mod_values; ptr && *ptr; ptr++) { if (strcmp (*ptr, value) == 0) /* Duplicate value, we're done. */ return; numvalues ++; } /* Append the value. */ ptr = xrealloc ((*m)->mod_values, sizeof (char *) * (numvalues + 2)); (*m)->mod_values = ptr; ptr[numvalues] = xstrdup (value); ptr[numvalues + 1] = NULL; return; } /* We didn't find the attr, so make one and add it to the end */ /* Like attribute values, the list of attributes is NULL terminated array of pointers. */ modlist = xrealloc (modlist, sizeof (LDAPMod *) * (nummods + 2)); *modlistp = modlist; modlist[nummods] = xmalloc (sizeof (LDAPMod)); modlist[nummods]->mod_op = LDAP_MOD_REPLACE; modlist[nummods]->mod_type = attr; if (value) { modlist[nummods]->mod_values = xmalloc (sizeof(char *) * 2); modlist[nummods]->mod_values[0] = xstrdup (value); modlist[nummods]->mod_values[1] = NULL; } else modlist[nummods]->mod_values = NULL; modlist[nummods + 1] = NULL; return; } /* Look up the value of an attribute in the specified modlist. If the attribute is not on the mod list, returns NULL. The result is a NULL-terminated array of strings. Don't change it. */ static char ** modlist_lookup (LDAPMod **modlist, const char *attr) { LDAPMod **m; for (m = modlist; m && *m; m++) { if (strcasecmp ((*m)->mod_type, attr) != 0) continue; return (*m)->mod_values; } return NULL; } /* Dump a modlist to a file. This is useful for debugging. */ static estream_t modlist_dump (LDAPMod **modlist, estream_t output) GPGRT_ATTR_USED; static estream_t modlist_dump (LDAPMod **modlist, estream_t output) { LDAPMod **m; int opened = 0; if (! output) { output = es_fopenmem (0, "rw"); if (!output) return NULL; opened = 1; } for (m = modlist; m && *m; m++) { es_fprintf (output, " %s:", (*m)->mod_type); if (! (*m)->mod_values) es_fprintf(output, " delete.\n"); else { char **ptr; int i; int multi = 0; if ((*m)->mod_values[0] && (*m)->mod_values[1]) /* Have at least 2. */ multi = 1; if (multi) es_fprintf (output, "\n"); for ((ptr = (*m)->mod_values), (i = 1); ptr && *ptr; ptr++, i ++) { /* Assuming terminals are about 80 characters wide, display at most about 10 lines of debugging output. If we do trim the buffer, append '...' to the end. */ const int max_len = 10 * 70; size_t value_len = strlen (*ptr); int elide = value_len > max_len; if (multi) es_fprintf (output, " %d. ", i); es_fprintf (output, "`%.*s", max_len, *ptr); if (elide) es_fprintf (output, "...' (%zd bytes elided)", value_len - max_len); else es_fprintf (output, "'"); es_fprintf (output, "\n"); } } } if (opened) es_fseek (output, 0, SEEK_SET); return output; } /* Free all of the memory allocated by the mod list. This assumes that the attribute names don't have to be freed, but the attributes values do. (Which is what modlist_add does.) */ static void modlist_free (LDAPMod **modlist) { LDAPMod **ml; if (! modlist) return; /* Unwind and free the whole modlist structure */ /* The modlist is a NULL terminated array of pointers. */ for (ml = modlist; *ml; ml++) { LDAPMod *mod = *ml; char **ptr; /* The list of values is a NULL termianted array of pointers. If the list is NULL, there are no values. */ if (mod->mod_values) { for (ptr = mod->mod_values; *ptr; ptr++) xfree (*ptr); xfree (mod->mod_values); } xfree (mod); } xfree (modlist); } /* Append two onto the end of one. Two is not freed, but its pointers are now part of one. Make sure you don't free them both! As long as you don't add anything to ONE, TWO is still valid. After that all bets are off. */ static void modlists_join (LDAPMod ***one, LDAPMod **two) { int i, one_count = 0, two_count = 0; LDAPMod **grow; if (!*two) /* two is empty. Nothing to do. */ return; if (!*one) /* one is empty. Just set it equal to *two. */ { *one = two; return; } for (grow = *one; *grow; grow++) one_count ++; for (grow = two; *grow; grow++) two_count ++; grow = xrealloc (*one, sizeof(LDAPMod *) * (one_count + two_count + 1)); for (i = 0; i < two_count; i++) grow[one_count + i] = two[i]; grow[one_count + i] = NULL; *one = grow; } /* Given a string, unescape C escapes. In particular, \xXX. This modifies the string in place. */ static void uncescape (char *str) { size_t r = 0; size_t w = 0; char *first = strchr (str, '\\'); if (! first) /* No backslashes => no escaping. We're done. */ return; /* Start at the first '\\'. */ r = w = (uintptr_t) first - (uintptr_t) str; while (str[r]) { /* XXX: What to do about bad escapes? XXX: hextobyte already checks the string thus the hexdigitp could be removed. */ if (str[r] == '\\' && str[r + 1] == 'x' && str[r+2] && str[r+3] && hexdigitp (str + r + 2) && hexdigitp (str + r + 3)) { int x = hextobyte (&str[r + 2]); assert (0 <= x && x <= 0xff); str[w] = x; /* We consumed 4 characters and wrote 1. */ r += 4; w ++; } else str[w ++] = str[r ++]; } str[w] = '\0'; } /* Given one line from an info block (`gpg --list-{keys,sigs} --with-colons KEYID'), pull it apart and fill in the modlist with the relevant (for the LDAP schema) attributes. EXTRACT_STATE should initally be set to 0 by the caller. SCHEMAV2 is set if the server supports the version 2 schema. */ static void extract_attributes (LDAPMod ***modlist, int *extract_state, char *line, int schemav2) { int field_count; char **fields; char *keyid; int is_pub, is_sub, is_uid, is_sig; /* Remove trailing whitespace */ trim_trailing_spaces (line); fields = strsplit (line, ':', '\0', &field_count); if (field_count == 1) /* We only have a single field. There is definitely nothing to do. */ goto out; if (field_count < 7) goto out; is_pub = !ascii_strcasecmp ("pub", fields[0]); is_sub = !ascii_strcasecmp ("sub", fields[0]); is_uid = !ascii_strcasecmp ("uid", fields[0]); is_sig = !ascii_strcasecmp ("sig", fields[0]); if (!ascii_strcasecmp ("fpr", fields[0])) { /* Special treatment for a fingerprint. */ if (!(*extract_state & 1)) goto out; /* Stray fingerprint line - ignore. */ *extract_state &= ~1; if (field_count >= 10 && schemav2) { if ((*extract_state & 2)) modlist_add (modlist, "gpgFingerprint", fields[9]); else modlist_add (modlist, "gpgSubFingerprint", fields[9]); } goto out; } *extract_state &= ~(1|2); if (is_pub) *extract_state |= (1|2); else if (is_sub) *extract_state |= 1; if (!is_pub && !is_sub && !is_uid && !is_sig) goto out; /* Not a relevant line. */ keyid = fields[4]; if (is_uid && strlen (keyid) == 0) ; /* The uid record type can have an empty keyid. */ else if (strlen (keyid) == 16 && strspn (keyid, "0123456789aAbBcCdDeEfF") == 16) ; /* Otherwise, we expect exactly 16 hex characters. */ else { log_error ("malformed record!\n"); goto out; } if (is_pub) { int disabled = 0; int revoked = 0; char *flags; for (flags = fields[1]; *flags; flags ++) switch (*flags) { case 'r': case 'R': revoked = 1; break; case 'd': case 'D': disabled = 1; break; } /* Note: we always create the pgpDisabled and pgpRevoked attributes, regardless of whether the key is disabled/revoked or not. This is because a very common search is like "(&(pgpUserID=*isabella*)(pgpDisabled=0))" */ if (is_pub) { modlist_add (modlist,"pgpDisabled", disabled ? "1" : "0"); modlist_add (modlist,"pgpRevoked", revoked ? "1" : "0"); } } if (is_pub || is_sub) { char padded[6]; int val; val = atoi (fields[2]); if (val < 99999 && val > 0) { /* We zero pad this on the left to make PGP happy. */ snprintf (padded, sizeof padded, "%05u", val); modlist_add (modlist, "pgpKeySize", padded); } } if (is_pub) { char *algo = fields[3]; int val = atoi (algo); switch (val) { case 1: algo = "RSA"; break; case 17: algo = "DSS/DH"; break; default: algo = NULL; break; } if (algo) modlist_add (modlist, "pgpKeyType", algo); } if (is_pub || is_sub || is_sig) { if (is_pub) { modlist_add (modlist, "pgpCertID", keyid); /* Long keyid(!) */ modlist_add (modlist, "pgpKeyID", &keyid[8]); /* Short keyid */ } if (is_sub) modlist_add (modlist, "pgpSubKeyID", keyid); /* Long keyid(!) */ } if (is_pub) { char *create_time = fields[5]; if (strlen (create_time) == 0) create_time = NULL; else { char *create_time_orig = create_time; struct tm tm; time_t t; char *end; memset (&tm, 0, sizeof (tm)); /* parse_timestamp handles both seconds fromt he epoch and ISO 8601 format. We also need to handle YYYY-MM-DD format (as generated by gpg1 --with-colons --list-key). Check that first and then if it fails, then try parse_timestamp. */ if (!isodate_human_to_tm (create_time, &tm)) create_time = tm2ldaptime (&tm); else if ((t = parse_timestamp (create_time, &end)) != (time_t) -1 && *end == '\0') { if (!gnupg_gmtime (&t, &tm)) create_time = NULL; else create_time = tm2ldaptime (&tm); } else create_time = NULL; if (! create_time) /* Failed to parse string. */ log_error ("Failed to parse creation time ('%s')", create_time_orig); } if (create_time) { modlist_add (modlist, "pgpKeyCreateTime", create_time); xfree (create_time); } } if (is_pub) { char *expire_time = fields[6]; if (strlen (expire_time) == 0) expire_time = NULL; else { char *expire_time_orig = expire_time; struct tm tm; time_t t; char *end; memset (&tm, 0, sizeof (tm)); /* parse_timestamp handles both seconds fromt he epoch and ISO 8601 format. We also need to handle YYYY-MM-DD format (as generated by gpg1 --with-colons --list-key). Check that first and then if it fails, then try parse_timestamp. */ if (!isodate_human_to_tm (expire_time, &tm)) expire_time = tm2ldaptime (&tm); else if ((t = parse_timestamp (expire_time, &end)) != (time_t) -1 && *end == '\0') { if (!gnupg_gmtime (&t, &tm)) expire_time = NULL; else expire_time = tm2ldaptime (&tm); } else expire_time = NULL; if (! expire_time) /* Failed to parse string. */ log_error ("Failed to parse creation time ('%s')", expire_time_orig); } if (expire_time) { modlist_add (modlist, "pgpKeyExpireTime", expire_time); xfree (expire_time); } } if (is_uid && field_count >= 10) { char *uid = fields[9]; char *mbox; uncescape (uid); modlist_add (modlist, "pgpUserID", uid); if (schemav2 && (mbox = mailbox_from_userid (uid, 0))) { modlist_add (modlist, "gpgMailbox", mbox); xfree (mbox); } } out: xfree (fields); } /* Send the key in {KEY,KEYLEN} with the metadata {INFO,INFOLEN} to the keyserver identified by URI. See server.c:cmd_ks_put for the format of the data and metadata. */ gpg_error_t ks_ldap_put (ctrl_t ctrl, parsed_uri_t uri, void *data, size_t datalen, void *info, size_t infolen) { gpg_error_t err = 0; int ldap_err; unsigned int serverinfo; LDAP *ldap_conn = NULL; char *basedn = NULL; LDAPMod **modlist = NULL; LDAPMod **addlist = NULL; char *data_armored = NULL; int extract_state; /* The last byte of the info block. */ const char *infoend = (const char *) info + infolen - 1; /* Enable this code to dump the modlist to /tmp/modlist.txt. */ #if 0 # warning Disable debug code before checking in. const int dump_modlist = 1; #else const int dump_modlist = 0; #endif estream_t dump = NULL; /* Elide a warning. */ (void) ctrl; if (dirmngr_use_tor ()) { /* For now we do not support LDAP over Tor. */ log_error (_("LDAP access not possible due to Tor mode\n")); return gpg_error (GPG_ERR_NOT_SUPPORTED); } err = my_ldap_connect (uri, &ldap_conn, &basedn, NULL, NULL, &serverinfo); if (err || !basedn) { if (!err) err = GPG_ERR_GENERAL; goto out; } if (!(serverinfo & SERVERINFO_REALLDAP)) { /* We appear to have a PGP.com Keyserver, which can unpack the * key on its own (not just a dump LDAP server). This will * rarely be the case these days. */ LDAPMod mod; LDAPMod *attrs[2]; char *key[2]; char *dn; key[0] = data; key[1] = NULL; memset (&mod, 0, sizeof (mod)); mod.mod_op = LDAP_MOD_ADD; mod.mod_type = (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey"; mod.mod_values = key; attrs[0] = &mod; attrs[1] = NULL; dn = xtryasprintf ("pgpCertid=virtual,%s", basedn); if (!dn) { err = gpg_error_from_syserror (); goto out; } ldap_err = ldap_add_s (ldap_conn, dn, attrs); xfree (dn); if (ldap_err != LDAP_SUCCESS) { err = ldap_err_to_gpg_err (err); goto out; } goto out; } modlist = xtrymalloc (sizeof (LDAPMod *)); if (!modlist) { err = gpg_error_from_syserror (); goto out; } *modlist = NULL; if (dump_modlist) { dump = es_fopen("/tmp/modlist.txt", "w"); if (! dump) log_error ("Failed to open /tmp/modlist.txt: %s\n", strerror (errno)); if (dump) { es_fprintf(dump, "data (%zd bytes)\n", datalen); es_fprintf(dump, "info (%zd bytes): '\n", infolen); es_fwrite(info, infolen, 1, dump); es_fprintf(dump, "'\n"); } } /* Start by nulling out all attributes. We try and do a modify operation first, so this ensures that we don't leave old attributes lying around. */ modlist_add (&modlist, "pgpDisabled", NULL); modlist_add (&modlist, "pgpKeyID", NULL); modlist_add (&modlist, "pgpKeyType", NULL); modlist_add (&modlist, "pgpUserID", NULL); modlist_add (&modlist, "pgpKeyCreateTime", NULL); modlist_add (&modlist, "pgpRevoked", NULL); modlist_add (&modlist, "pgpSubKeyID", NULL); modlist_add (&modlist, "pgpKeySize", NULL); modlist_add (&modlist, "pgpKeyExpireTime", NULL); modlist_add (&modlist, "pgpCertID", NULL); if ((serverinfo & SERVERINFO_SCHEMAV2)) { modlist_add (&modlist, "gpgFingerprint", NULL); modlist_add (&modlist, "gpgSubFingerprint", NULL); modlist_add (&modlist, "gpgMailbox", NULL); } /* Assemble the INFO stuff into LDAP attributes */ extract_state = 0; while (infolen > 0) { char *temp = NULL; char *newline = memchr (info, '\n', infolen); if (! newline) /* The last line is not \n terminated! Make a copy so we can add a NUL terminator. */ { temp = xmalloc (infolen + 1); memcpy (temp, info, infolen); info = temp; newline = (char *) info + infolen; } *newline = '\0'; extract_attributes (&addlist, &extract_state, info, (serverinfo & SERVERINFO_SCHEMAV2)); infolen = infolen - ((uintptr_t) newline - (uintptr_t) info + 1); info = newline + 1; /* Sanity check. */ if (! temp) log_assert ((char *) info + infolen - 1 == infoend); else { log_assert (infolen == -1); xfree (temp); } } modlist_add (&addlist, "objectClass", "pgpKeyInfo"); err = armor_data (&data_armored, data, datalen); if (err) goto out; modlist_add (&addlist, (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey", data_armored); /* Now append addlist onto modlist. */ modlists_join (&modlist, addlist); if (dump) { estream_t input = modlist_dump (modlist, NULL); if (input) { copy_stream (input, dump); es_fclose (input); } } /* Going on the assumption that modify operations are more frequent than adds, we try a modify first. If it's not there, we just turn around and send an add command for the same key. Otherwise, the modify brings the server copy into compliance with our copy. Note that unlike the LDAP keyserver (and really, any other keyserver) this does NOT merge signatures, but replaces the whole key. This should make some people very happy. */ { char **attrval; char *dn; if ((serverinfo & SERVERINFO_NTDS)) { /* The modern way using a CN RDN with the fingerprint. This * has the advantage that we won't have duplicate 64 bit * keyids in the store. In particular NTDS requires the * DN to be unique. */ attrval = modlist_lookup (addlist, "gpgFingerprint"); /* We should have exactly one value. */ if (!attrval || !(attrval[0] && !attrval[1])) { log_error ("ks-ldap: bad gpgFingerprint provided\n"); err = GPG_ERR_GENERAL; goto out; } dn = xtryasprintf ("CN=%s,%s", attrval[0], basedn); } else /* The old style way. */ { attrval = modlist_lookup (addlist, "pgpCertID"); /* We should have exactly one value. */ if (!attrval || !(attrval[0] && !attrval[1])) { log_error ("ks-ldap: bad pgpCertID provided\n"); err = GPG_ERR_GENERAL; goto out; } dn = xtryasprintf ("pgpCertID=%s,%s", attrval[0], basedn); } if (!dn) { err = gpg_error_from_syserror (); goto out; } if (opt.debug) log_debug ("ks-ldap: using DN: %s\n", dn); npth_unprotect (); err = ldap_modify_s (ldap_conn, dn, modlist); if (err == LDAP_NO_SUCH_OBJECT) err = ldap_add_s (ldap_conn, dn, addlist); npth_protect (); xfree (dn); if (err != LDAP_SUCCESS) { log_error ("ks-ldap: error adding key to keyserver: %s\n", ldap_err2string (err)); err = ldap_err_to_gpg_err (err); } } out: if (dump) es_fclose (dump); if (ldap_conn) ldap_unbind (ldap_conn); xfree (basedn); modlist_free (modlist); xfree (addlist); xfree (data_armored); return err; } diff --git a/dirmngr/server.c b/dirmngr/server.c index 105275845..c5542fe6c 100644 --- a/dirmngr/server.c +++ b/dirmngr/server.c @@ -1,3148 +1,3196 @@ /* 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" + "LDAPSERVER [--clear] \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.\n" - "An optional prefix \"ldap:\" is allowed."; + "An optional prefix \"ldap:\" is allowed. With no args all\n" + "configured ldapservers are listed. Option --clear removes all\n" + "servers configured in this session."; 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; + int clear_flag; + clear_flag = has_option (line, "--clear"); + line = skip_options (line); while (spacep (line)) line++; - if (*line == '\0') - return leave_cmd (ctx, PARM_ERROR (_("ldapserver missing"))); + + if (clear_flag) + { +#if USE_LDAP + ldapserver_list_free (ctrl->server_local->ldapservers); +#endif /*USE_LDAP*/ + ctrl->server_local->ldapservers = NULL; + } + + if (!*line && clear_flag) + return leave_cmd (ctx, 0); + + if (!*line) + { + /* List all ldapservers. */ + struct ldapserver_iter ldapserver_iter; + char *tmpstr; + char portstr[20]; + + for (ldapserver_iter_begin (&ldapserver_iter, ctrl); + !ldapserver_iter_end_p (&ldapserver_iter); + ldapserver_iter_next (&ldapserver_iter)) + { + server = ldapserver_iter.server; + if (server->port) + snprintf (portstr, sizeof portstr, "%d", server->port); + else + *portstr = 0; + + tmpstr = xtryasprintf ("ldap:%s:%s:%s:%s:%s:%s%s:", + server->host? server->host : "", + portstr, + server->user? server->user : "", + server->pass? "[not_shown]": "", + server->base? server->base : "", + server->starttls ? "starttls" : + server->ldap_over_tls ? "ldaptls" : "none", + server->ntds ? ",ntds" : ""); + if (!tmpstr) + return leave_cmd (ctx, gpg_error_from_syserror ()); + dirmngr_status (ctrl, "LDAPSERVER", tmpstr, NULL); + xfree (tmpstr); + } + return leave_cmd (ctx, 0); + } /* Skip an "ldap:" prefix unless it is a valid ldap url. */ if (!strncmp (line, "ldap:", 5) && !(line[5] == '/' && line[6] == '/')) line += 5; server = ldapserver_parse_one (line, NULL, 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; const char *s; *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 (!strncmp (uri, "ldap:", 5) && !(uri[5] == '/' && uri[6] == '/')) { char *tmpstr; /* Special ldap scheme given. This differs from a valid ldap * scheme in that no double slash follows.. Use http_parse_uri * to put it as opaque value into parsed_uri. */ tmpstr = strconcat ("opaque:", uri+5, NULL); if (!tmpstr) err = gpg_error_from_syserror (); else { log_debug ("tmpstr='%s'\n", tmpstr); err = http_parse_uri (&item->parsed_uri, tmpstr, 0); xfree (tmpstr); } } else if ((s=strchr (uri, ':')) && !(s[1] == '/' && s[2] == '/')) { char *tmpstr; /* No valid scheme given. Use http_parse_uri to put the string * as opaque value into parsed_uri. */ tmpstr = strconcat ("opaque:", uri, NULL); if (!tmpstr) err = gpg_error_from_syserror (); else { log_debug ("tmpstr2='%s'\n", tmpstr); err = http_parse_uri (&item->parsed_uri, tmpstr, 0); xfree (tmpstr); } } else if (ldap_uri_p (uri)) { /* Fixme: We should get rid of that parser and replace it with * our generic (http) URI parser. */ err = ldap_parse_uri (&item->parsed_uri, uri); } else #endif { err = http_parse_uri (&item->parsed_uri, uri, HTTP_PARSE_NO_SCHEME_CHECK); } 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 [--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. 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, 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/doc/dirmngr.texi b/doc/dirmngr.texi index 981b48b4e..516433e11 100644 --- a/doc/dirmngr.texi +++ b/doc/dirmngr.texi @@ -1,1276 +1,1303 @@ @c Copyright (C) 2002 Klar"alvdalens Datakonsult AB @c Copyright (C) 2004, 2005, 2006, 2007 g10 Code GmbH @c This is part of the GnuPG manual. @c For copying conditions, see the file gnupg.texi. @include defs.inc @node Invoking DIRMNGR @chapter Invoking DIRMNGR @cindex DIRMNGR command options @cindex command options @cindex options, DIRMNGR command @manpage dirmngr.8 @ifset manverb .B dirmngr -\- CRL and OCSP daemon +\- GnuPG's network access daemon @end ifset @mansect synopsis @ifset manverb .B dirmngr .RI [ options ] .I command .RI [ args ] @end ifset @mansect description Since version 2.1 of GnuPG, @command{dirmngr} takes care of accessing the OpenPGP keyservers. As with previous versions it is also used as a server for managing and downloading certificate revocation lists (CRLs) for X.509 certificates, downloading X.509 certificates, and providing access to OCSP providers. Dirmngr is invoked internally by @command{gpg}, @command{gpgsm}, or via the @command{gpg-connect-agent} tool. @manpause @noindent @xref{Option Index},for an index to @command{DIRMNGR}'s commands and options. @mancont @menu * Dirmngr Commands:: List of all commands. * Dirmngr Options:: List of all options. * Dirmngr Configuration:: Configuration files. * Dirmngr Signals:: Use of signals. * Dirmngr Examples:: Some usage examples. * Dirmngr Protocol:: The protocol dirmngr uses. @end menu @node Dirmngr Commands @section Commands @mansect commands Commands are not distinguished from options except for the fact that only one command is allowed. @table @gnupgtabopt @item --version @opindex version Print the program version and licensing information. Note that you cannot abbreviate this command. @item --help, -h @opindex help Print a usage message summarizing the most useful command-line options. Note that you cannot abbreviate this command. @item --dump-options @opindex dump-options Print a list of all available options and commands. Note that you cannot abbreviate this command. @item --server @opindex server Run in server mode and wait for commands on the @code{stdin}. The default mode is to create a socket and listen for commands there. This is only used for testing. @item --daemon @opindex daemon Run in background daemon mode and listen for commands on a socket. This is the way @command{dirmngr} is started on demand by the other GnuPG components. To force starting @command{dirmngr} it is in general best to use @code{gpgconf --launch dirmngr}. @item --supervised @opindex supervised Run in the foreground, sending logs to stderr, and listening on file descriptor 3, which must already be bound to a listening socket. This is useful when running under systemd or other similar process supervision schemes. This option is not supported on Windows. @item --list-crls @opindex list-crls List the contents of the CRL cache on @code{stdout}. This is probably only useful for debugging purposes. @item --load-crl @var{file} @opindex load-crl This command requires a filename as additional argument, and it will make Dirmngr try to import the CRL in @var{file} into it's cache. Note, that this is only possible if Dirmngr is able to retrieve the CA's certificate directly by its own means. In general it is better to use @code{gpgsm}'s @code{--call-dirmngr loadcrl filename} command so that @code{gpgsm} can help dirmngr. @item --fetch-crl @var{url} @opindex fetch-crl This command requires an URL as additional argument, and it will make dirmngr try to retrieve and import the CRL from that @var{url} into it's cache. This is mainly useful for debugging purposes. The @command{dirmngr-client} provides the same feature for a running dirmngr. @item --shutdown @opindex shutdown This commands shuts down an running instance of Dirmngr. This command has currently no effect. @item --flush @opindex flush This command removes all CRLs from Dirmngr's cache. Client requests will thus trigger reading of fresh CRLs. @end table @mansect options @node Dirmngr Options @section Option Summary Note that all long options with the exception of @option{--options} and @option{--homedir} may also be given in the configuration file after stripping off the two leading dashes. @table @gnupgtabopt @item --options @var{file} @opindex options Reads configuration from @var{file} instead of from the default per-user configuration file. The default configuration file is named @file{dirmngr.conf} and expected in the home directory. @item --homedir @var{dir} @opindex options Set the name of the home directory to @var{dir}. This option is only effective when used on the command line. The default is the directory named @file{.gnupg} directly below the home directory of the user unless the environment variable @code{GNUPGHOME} has been set in which case its value will be used. Many kinds of data are stored within this directory. @item -v @item --verbose @opindex v @opindex verbose Outputs additional information while running. You can increase the verbosity by giving several verbose commands to @sc{dirmngr}, such as @option{-vv}. @item --log-file @var{file} @opindex log-file Append all logging output to @var{file}. This is very helpful in seeing what the agent actually does. Use @file{socket://} to log to socket. @item --debug-level @var{level} @opindex debug-level Select the debug level for investigating problems. @var{level} may be a numeric value or by a keyword: @table @code @item none No debugging at all. A value of less than 1 may be used instead of the keyword. @item basic Some basic debug messages. A value between 1 and 2 may be used instead of the keyword. @item advanced More verbose debug messages. A value between 3 and 5 may be used instead of the keyword. @item expert Even more detailed messages. A value between 6 and 8 may be used instead of the keyword. @item guru All of the debug messages you can get. A value greater than 8 may be used instead of the keyword. The creation of hash tracing files is only enabled if the keyword is used. @end table How these messages are mapped to the actual debugging flags is not specified and may change with newer releases of this program. They are however carefully selected to best aid in debugging. @item --debug @var{flags} @opindex debug Set debug flags. All flags are or-ed and @var{flags} may be given in C syntax (e.g. 0x0042) or as a comma separated list of flag names. To get a list of all supported flags the single word "help" can be used. This option is only useful for debugging and the behavior may change at any time without notice. @item --debug-all @opindex debug-all Same as @code{--debug=0xffffffff} @item --tls-debug @var{level} @opindex tls-debug Enable debugging of the TLS layer at @var{level}. The details of the debug level depend on the used TLS library and are not set in stone. @item --debug-wait @var{n} @opindex debug-wait When running in server mode, wait @var{n} seconds before entering the actual processing loop and print the pid. This gives time to attach a debugger. @item --disable-check-own-socket @opindex disable-check-own-socket On some platforms @command{dirmngr} is able to detect the removal of its socket file and shutdown itself. This option disable this self-test for debugging purposes. @item -s @itemx --sh @itemx -c @itemx --csh @opindex s @opindex sh @opindex c @opindex csh Format the info output in daemon mode for use with the standard Bourne shell respective the C-shell. The default is to guess it based on the environment variable @code{SHELL} which is in almost all cases sufficient. @item --force @opindex force Enabling this option forces loading of expired CRLs; this is only useful for debugging. @item --use-tor @itemx --no-use-tor @opindex use-tor @opindex no-use-tor The option @option{--use-tor} switches Dirmngr and thus GnuPG into ``Tor mode'' to route all network access via Tor (an anonymity network). Certain other features are disabled in this mode. The effect of @option{--use-tor} cannot be overridden by any other command or even by reloading dirmngr. The use of @option{--no-use-tor} disables the use of Tor. The default is to use Tor if it is available on startup or after reloading dirmngr. The test on the availability of Tor is done by trying to connect to a SOCKS proxy at either port 9050 or 9150; if another type of proxy is listening on one of these ports, you should use @option{--no-use-tor}. @item --standard-resolver @opindex standard-resolver This option forces the use of the system's standard DNS resolver code. This is mainly used for debugging. Note that on Windows a standard resolver is not used and all DNS access will return the error ``Not Implemented'' if this option is used. Using this together with enabled Tor mode returns the error ``Not Enabled''. @item --recursive-resolver @opindex recursive-resolver When possible use a recursive resolver instead of a stub resolver. @item --resolver-timeout @var{n} @opindex resolver-timeout Set the timeout for the DNS resolver to N seconds. The default are 30 seconds. @item --connect-timeout @var{n} @item --connect-quick-timeout @var{n} @opindex connect-timeout @opindex connect-quick-timeout Set the timeout for HTTP and generic TCP connection attempts to N seconds. The value set with the quick variant is used when the --quick option has been given to certain Assuan commands. The quick value is capped at the value of the regular connect timeout. The default values are 15 and 2 seconds. Note that the timeout values are for each connection attempt; the connection code will attempt to connect all addresses listed for a server. @item --listen-backlog @var{n} @opindex listen-backlog Set the size of the queue for pending connections. The default is 64. @item --allow-version-check @opindex allow-version-check Allow Dirmngr to connect to @code{https://versions.gnupg.org} to get the list of current software versions. If this option is enabled the list is retrieved in case the local copy does not exist or is older than 5 to 7 days. See the option @option{--query-swdb} of the command @command{gpgconf} for more details. Note, that regardless of this option a version check can always be triggered using this command: @example gpg-connect-agent --dirmngr 'loadswdb --force' /bye @end example @item --keyserver @var{name} @opindex keyserver Use @var{name} as your keyserver. This is the server that @command{gpg} communicates with to receive keys, send keys, and search for keys. The format of the @var{name} is a URI: `scheme:[//]keyservername[:port]' The scheme is the type of keyserver: "hkp" for the HTTP (or compatible) keyservers, "ldap" for the LDAP keyservers, or "mailto" for the Graff email keyserver. Note that your particular installation of GnuPG may have other keyserver types available as well. Keyserver schemes are case-insensitive. After the keyserver name, optional keyserver configuration options may be provided. These are the same as the @option{--keyserver-options} of @command{gpg}, but apply only to this particular keyserver. Most keyservers synchronize with each other, so there is generally no need to send keys to more than one server. The keyserver @code{hkp://keys.gnupg.net} uses round robin DNS to give a different keyserver each time you use it. If exactly two keyservers are configured and only one is a Tor hidden service (.onion), Dirmngr selects the keyserver to use depending on whether Tor is locally running or not. The check for a running Tor is done for each new connection. If no keyserver is explicitly configured, dirmngr will use the built-in default of @code{hkps://hkps.pool.sks-keyservers.net}. Windows users with a keyserver running on their Active Directory should use @code{ldap:///} for @var{name} to access this directory. As an alternative it is also possible to add @code{gpgNtds=1} as extension (i.e. after the fourth question mark). For accessing anonymous LDAP keyservers @var{name} is in general just a @code{ldaps://ldap.example.com}. A BaseDN parameter should never be specified. If authentication is required the value of @var{name} is for example: @example keyserver ldaps://ldap.example.com/????bindname=uid=USERNAME %2Cou=GnuPG%20Users%2Cdc=example%2Cdc=com,password=PASSWORD @end example Put this all on one line without any spaces and keep the '%2C' as given. Replace USERNAME, PASSWORD, and the 'dc' parts according to the instructions received from the LDAP administrator. Note that only simple authentication (i.e. cleartext passwords) is supported and thus using ldaps is strongly suggested. @item --nameserver @var{ipaddr} @opindex nameserver In ``Tor mode'' Dirmngr uses a public resolver via Tor to resolve DNS names. If the default public resolver, which is @code{8.8.8.8}, shall not be used a different one can be given using this option. Note that a numerical IP address must be given (IPv6 or IPv4) and that no error checking is done for @var{ipaddr}. @item --disable-ipv4 @item --disable-ipv6 @opindex disable-ipv4 @opindex disable-ipv6 Disable the use of all IPv4 or IPv6 addresses. @item --disable-ldap @opindex disable-ldap Entirely disables the use of LDAP. @item --disable-http @opindex disable-http Entirely disables the use of HTTP. @item --ignore-http-dp @opindex ignore-http-dp When looking for the location of a CRL, the to be tested certificate usually contains so called @dfn{CRL Distribution Point} (DP) entries which are URLs describing the way to access the CRL. The first found DP entry is used. With this option all entries using the @acronym{HTTP} scheme are ignored when looking for a suitable DP. @item --ignore-ldap-dp @opindex ignore-ldap-dp This is similar to @option{--ignore-http-dp} but ignores entries using the @acronym{LDAP} scheme. Both options may be combined resulting in ignoring DPs entirely. @item --ignore-ocsp-service-url @opindex ignore-ocsp-service-url Ignore all OCSP URLs contained in the certificate. The effect is to force the use of the default responder. @item --honor-http-proxy @opindex honor-http-proxy If the environment variable @env{http_proxy} has been set, use its value to access HTTP servers. @item --http-proxy @var{host}[:@var{port}] @opindex http-proxy @efindex http_proxy Use @var{host} and @var{port} to access HTTP servers. The use of this option overrides the environment variable @env{http_proxy} regardless whether @option{--honor-http-proxy} has been set. @item --ldap-proxy @var{host}[:@var{port}] @opindex ldap-proxy Use @var{host} and @var{port} to connect to LDAP servers. If @var{port} is omitted, port 389 (standard LDAP port) is used. This overrides any specified host and port part in a LDAP URL and will also be used if host and port have been omitted from the URL. @item --only-ldap-proxy @opindex only-ldap-proxy Never use anything else but the LDAP "proxy" as configured with @option{--ldap-proxy}. Usually @command{dirmngr} tries to use other configured LDAP server if the connection using the "proxy" failed. @item --ldapserverlist-file @var{file} @opindex ldapserverlist-file -Read a list of LDAP servers to consult for CRLs and certificates from -file. This servers from this list are used after any servers set by a -client for its session. The default value for @var{file} is -@file{dirmngr_ldapservers.conf}. +Read the list of LDAP servers to consult for CRLs and X.509 certificates from +file instead of the default per-user ldap server list file. The default +value for @var{file} is @file{dirmngr_ldapservers.conf}. This server list file contains one LDAP server per line in the format @sc{hostname:port:username:password:base_dn:flags} Lines starting with a @samp{#} are comments. -The only defined flag is @code{ldaps} to specify that a TLS -connections shall be used. Flags are comma delimited; unknown flags -are ignored. - Note that as usual all strings entered are expected to be UTF-8 encoded. Obviously this will lead to problems if the password has originally been encoded as Latin-1. There is no other solution here than to put such a password in the binary encoding into the file (i.e. non-ascii characters won't show up readable).@footnote{The @command{gpgconf} tool might be helpful for frontends as it enables editing this configuration file using -percent-escaped strings.} +percent-escaped strings.}jj + + +@item --ldapserver @var{spec} +@opindex ldapserver +This is an alternative way to specify LDAP servers for CRL and X.509 +certificate retrieval. If this option is used the servers configured +in @file{dirmngr_ldapservers.conf} (or the file given by +@option{--ldapserverlist-file}) are cleared. Reloading dirmngr will +consider these again will in no case use those from +@file{dirmngr_ldapservers.conf} again. The @var{spec} is either a +proper LDAP URL or a colon delimited list of the form + +@sc{hostname:port:username:password:base_dn:flags:} + +with an optional prefix of @code{ldap:} (but without the two slashes +which would turn this into a proper LDAP URL). @sc{flags} is a list +of one or more comma delimited keywords: +@table @code +@item plain +The default: Do not use a TLS secured connection at all; the default +port is 389. +@item starttls +Use STARTTLS to secure the connection; the default port is 389. +@item ldaptls +Tunnel LDAP through a TLS connection; the default port is 636. +@item ntds +On Windows authenticate the LDAP connection using the Active Directory +with the current user. +@end table + +Note that in an URL style specification the scheme @code{ldaps://} +refers to STARTTLS and _not_ to LDAP-over-TLS. @item --ldaptimeout @var{secs} @opindex ldaptimeout Specify the number of seconds to wait for an LDAP query before timing out. The default are 15 seconds. 0 will never timeout. @item --add-servers @opindex add-servers This option makes dirmngr add any servers it discovers when validating certificates against CRLs to the internal list of servers to consult for certificates and CRLs. This option should in general not be used. This option might be useful when trying to validate a certificate that has a CRL distribution point that points to a server that is not already listed in the ldapserverlist. Dirmngr will always go to this server and try to download the CRL, but chances are high that the certificate used to sign the CRL is located on the same server. So if dirmngr doesn't add that new server to list, it will often not be able to verify the signature of the CRL unless the @code{--add-servers} option is used. Caveat emptor: Using this option may enable denial-of-service attacks and leak search requests to unknown third parties. This is because arbitrary servers are added to the internal list of LDAP servers which in turn is used for all unspecific LDAP queries as well as a fallback for queries which did not return a result. @item --allow-ocsp @opindex allow-ocsp This option enables OCSP support if requested by the client. OCSP requests are rejected by default because they may violate the privacy of the user; for example it is possible to track the time when a user is reading a mail. @item --ocsp-responder @var{url} @opindex ocsp-responder Use @var{url} as the default OCSP Responder if the certificate does not contain information about an assigned responder. Note, that @code{--ocsp-signer} must also be set to a valid certificate. @item --ocsp-signer @var{fpr}|@var{file} @opindex ocsp-signer Use the certificate with the fingerprint @var{fpr} to check the responses of the default OCSP Responder. Alternatively a filename can be given in which case the response is expected to be signed by one of the certificates described in that file. Any argument which contains a slash, dot or tilde is considered a filename. Usual filename expansion takes place: A tilde at the start followed by a slash is replaced by the content of @env{HOME}, no slash at start describes a relative filename which will be searched at the home directory. To make sure that the @var{file} is searched in the home directory, either prepend the name with "./" or use a name which contains a dot. If a response has been signed by a certificate described by these fingerprints no further check upon the validity of this certificate is done. The format of the @var{FILE} is a list of SHA-1 fingerprint, one per line with optional colons between the bytes. Empty lines and lines prefix with a hash mark are ignored. @item --ocsp-max-clock-skew @var{n} @opindex ocsp-max-clock-skew The number of seconds a skew between the OCSP responder and them local clock is accepted. Default is 600 (10 minutes). @item --ocsp-max-period @var{n} @opindex ocsp-max-period Seconds a response is at maximum considered valid after the time given in the thisUpdate field. Default is 7776000 (90 days). @item --ocsp-current-period @var{n} @opindex ocsp-current-period The number of seconds an OCSP response is considered valid after the time given in the NEXT_UPDATE datum. Default is 10800 (3 hours). @item --max-replies @var{n} @opindex max-replies Do not return more that @var{n} items in one query. The default is 10. @item --ignore-cert-extension @var{oid} @opindex ignore-cert-extension Add @var{oid} to the list of ignored certificate extensions. The @var{oid} is expected to be in dotted decimal form, like @code{2.5.29.3}. This option may be used more than once. Critical flagged certificate extensions matching one of the OIDs in the list are treated as if they are actually handled and thus the certificate won't be rejected due to an unknown critical extension. Use this option with care because extensions are usually flagged as critical for a reason. @item --hkp-cacert @var{file} Use the root certificates in @var{file} for verification of the TLS certificates used with @code{hkps} (keyserver access over TLS). If the file is in PEM format a suffix of @code{.pem} is expected for @var{file}. This option may be given multiple times to add more root certificates. Tilde expansion is supported. If no @code{hkp-cacert} directive is present, dirmngr will make a reasonable choice: if the keyserver in question is the special pool @code{hkps.pool.sks-keyservers.net}, it will use the bundled root certificate for that pool. Otherwise, it will use the system CAs. @end table @c @c Dirmngr Configuration @c @mansect files @node Dirmngr Configuration @section Configuration Dirmngr makes use of several directories when running in daemon mode: There are a few configuration files to control the operation of dirmngr. By default they may all be found in the current home directory (@pxref{option --homedir}). @table @file @item dirmngr.conf @efindex dirmngr.conf This is the standard configuration file read by @command{dirmngr} on startup. It may contain any valid long option; the leading two dashes may not be entered and the option may not be abbreviated. This file is also read after a @code{SIGHUP} however not all options will actually have an effect. This default name may be changed on the command line (@pxref{option --options}). You should backup this file. @item /etc/gnupg/trusted-certs This directory should be filled with certificates of Root CAs you are trusting in checking the CRLs and signing OCSP Responses. Usually these are the same certificates you use with the applications making use of dirmngr. It is expected that each of these certificate files contain exactly one @acronym{DER} encoded certificate in a file with the suffix @file{.crt} or @file{.der}. @command{dirmngr} reads those certificates on startup and when given a SIGHUP. Certificates which are not readable or do not make up a proper X.509 certificate are ignored; see the log file for details. Applications using dirmngr (e.g. gpgsm) can request these certificates to complete a trust chain in the same way as with the extra-certs directory (see below). Note that for OCSP responses the certificate specified using the option @option{--ocsp-signer} is always considered valid to sign OCSP requests. @item /etc/gnupg/extra-certs This directory may contain extra certificates which are preloaded into the internal cache on startup. Applications using dirmngr (e.g. gpgsm) can request cached certificates to complete a trust chain. This is convenient in cases you have a couple intermediate CA certificates or certificates usually used to sign OCSP responses. These certificates are first tried before going out to the net to look for them. These certificates must also be @acronym{DER} encoded and suffixed with @file{.crt} or @file{.der}. @item ~/.gnupg/crls.d This directory is used to store cached CRLs. The @file{crls.d} part will be created by dirmngr if it does not exists but you need to make sure that the upper directory exists. @end table Several options control the use of trusted certificates for TLS and CRLs. Here is an Overview on the use and origin of those Root CA certificates: @table @asis @item System These System root certificates are used by: FIXME The origin of the system provided certificates depends on the platform. On Windows all certificates from the Windows System Stores @code{ROOT} and @code{CA} are used. On other platforms the certificates are read from the first file found form this list: @file{/etc/ssl/ca-bundle.pem}, @file{/etc/ssl/certs/ca-certificates.crt}, @file{/etc/pki/tls/cert.pem}, @file{/usr/local/share/certs/ca-root-nss.crt}, @file{/etc/ssl/cert.pem}. @item GnuPG The GnuPG specific certificates stored in the directory @file{/etc/gnupg/trusted-certs} are only used to validate CRLs. @c Note that dirmngr's VALIDATE command also uses them but that @c command is anyway only intended for debugging. @item OpenPGP keyserver For accessing the OpenPGP keyservers the only certificates used are those set with the configuration option @option{hkp-cacert}. @item OpenPGP keyserver pool This is usually only one certificate read from the file @file{@value{DATADIR}/gnupg/sks-keyservers.netCA.pem}. If this certificate exists it is used to access the special keyservers @code{hkps.pool.sks-keyservers.net} (or @file{hkps://keys.gnupg.net}). @end table Please note that @command{gpgsm} accepts Root CA certificates for its own purposes only if they are listed in its file @file{trustlist.txt}. @command{dirmngr} does not make use of this list - except FIXME. @mansect notes To be able to see diagnostics it is often useful to put at least the following lines into the configuration file @file{~/gnupg/dirmngr.conf}: @example log-file ~/dirmngr.log verbose @end example You may want to check the log file to see whether all desired root CA certificates are correctly loaded. To be able to perform OCSP requests you probably want to add the line: @example allow-ocsp @end example To make sure that new options are read or that after the installation of a new GnuPG versions the right dirmngr version is running, you should kill an existing dirmngr so that a new instance is started as needed by the otehr components: @example gpgconf --kill dirmngr @end example Direct interfaction with the dirmngr is possible by using the command @example gpg-connect-agent --dirmngr @end example Enter @code{HELP} at the prompt to see a list of commands and enter @code{HELP} followed by a command name to get help on that command. @c @c Dirmngr Signals @c @mansect signals @node Dirmngr Signals @section Use of signals A running @command{dirmngr} may be controlled by signals, i.e. using the @command{kill} command to send a signal to the process. Here is a list of supported signals: @table @gnupgtabopt @item SIGHUP @cpindex SIGHUP This signal flushes all internally cached CRLs as well as any cached certificates. Then the certificate cache is reinitialized as on startup. Options are re-read from the configuration file. Instead of sending this signal it is better to use @example gpgconf --reload dirmngr @end example @item SIGTERM @cpindex SIGTERM Shuts down the process but waits until all current requests are fulfilled. If the process has received 3 of these signals and requests are still pending, a shutdown is forced. You may also use @example gpgconf --kill dirmngr @end example instead of this signal @item SIGINT @cpindex SIGINT Shuts down the process immediately. @item SIGUSR1 @cpindex SIGUSR1 This prints some caching statistics to the log file. @end table @c @c Examples @c @mansect examples @node Dirmngr Examples @section Examples Here is an example on how to show dirmngr's internal table of OpenPGP keyserver addresses. The output is intended for debugging purposes and not part of a defined API. @example gpg-connect-agent --dirmngr 'keyserver --hosttable' /bye @end example To inhibit the use of a particular host you have noticed in one of the keyserver pools, you may use @example gpg-connect-agent --dirmngr 'keyserver --dead pgpkeys.bnd.de' /bye @end example The description of the @code{keyserver} command can be printed using @example gpg-connect-agent --dirmngr 'help keyserver' /bye @end example @c @c Assuan Protocol @c @manpause @node Dirmngr Protocol @section Dirmngr's Assuan Protocol Assuan is the IPC protocol used to access dirmngr. This is a description of the commands implemented by dirmngr. @menu * Dirmngr LOOKUP:: Look up a certificate via LDAP * Dirmngr ISVALID:: Validate a certificate using a CRL or OCSP. * Dirmngr CHECKCRL:: Validate a certificate using a CRL. * Dirmngr CHECKOCSP:: Validate a certificate using OCSP. * Dirmngr CACHECERT:: Put a certificate into the internal cache. * Dirmngr VALIDATE:: Validate a certificate for debugging. @end menu @node Dirmngr LOOKUP @subsection Return the certificate(s) found Lookup certificate. To allow multiple patterns (which are ORed) quoting is required: Spaces are to be translated into "+" or into "%20"; obviously this requires that the usual escape quoting rules are applied. The server responds with: @example S: D S: END S: D S: END S: OK @end example In this example 2 certificates are returned. The server may return any number of certificates; OK will also be returned when no certificates were found. The dirmngr might return a status line @example S: S TRUNCATED @end example To indicate that the output was truncated to N items due to a limitation of the server or by an arbitrary set limit. The option @option{--url} may be used if instead of a search pattern a complete URL to the certificate is known: @example C: LOOKUP --url CN%3DWerner%20Koch,o%3DIntevation%20GmbH,c%3DDE?userCertificate @end example If the option @option{--cache-only} is given, no external lookup is done so that only certificates from the cache are returned. With the option @option{--single}, the first and only the first match will be returned. Unless option @option{--cache-only} is also used, no local lookup will be done in this case. @node Dirmngr ISVALID @subsection Validate a certificate using a CRL or OCSP @example ISVALID [--only-ocsp] [--force-default-responder] @var{certid}|@var{certfpr} @end example Check whether the certificate described by the @var{certid} has been revoked. Due to caching, the Dirmngr is able to answer immediately in most cases. The @var{certid} is a hex encoded string consisting of two parts, delimited by a single dot. The first part is the SHA-1 hash of the issuer name and the second part the serial number. Alternatively the certificate's SHA-1 fingerprint @var{certfpr} may be given in which case an OCSP request is done before consulting the CRL. If the option @option{--only-ocsp} is given, no fallback to a CRL check will be used. If the option @option{--force-default-responder} is given, only the default OCSP responder will be used and any other methods of obtaining an OCSP responder URL won't be used. @noindent Common return values are: @table @code @item GPG_ERR_NO_ERROR (0) This is the positive answer: The certificate is not revoked and we have an up-to-date revocation list for that certificate. If OCSP was used the responder confirmed that the certificate has not been revoked. @item GPG_ERR_CERT_REVOKED This is the negative answer: The certificate has been revoked. Either it is in a CRL and that list is up to date or an OCSP responder informed us that it has been revoked. @item GPG_ERR_NO_CRL_KNOWN No CRL is known for this certificate or the CRL is not valid or out of date. @item GPG_ERR_NO_DATA The OCSP responder returned an ``unknown'' status. This means that it is not aware of the certificate's status. @item GPG_ERR_NOT_SUPPORTED This is commonly seen if OCSP support has not been enabled in the configuration. @end table If DirMngr has not enough information about the given certificate (which is the case for not yet cached certificates), it will inquire the missing data: @example S: INQUIRE SENDCERT C: D C: END @end example A client should be aware that DirMngr may ask for more than one certificate. If Dirmngr has a certificate but the signature of the certificate could not been validated because the root certificate is not known to dirmngr as trusted, it may ask back to see whether the client trusts this the root certificate: @example S: INQUIRE ISTRUSTED C: D 1 C: END @end example Only this answer will let Dirmngr consider the certificate as valid. @node Dirmngr CHECKCRL @subsection Validate a certificate using a CRL Check whether the certificate with FINGERPRINT (SHA-1 hash of the entire X.509 certificate blob) is valid or not by consulting the CRL responsible for this certificate. If the fingerprint has not been given or the certificate is not known, the function inquires the certificate using: @example S: INQUIRE TARGETCERT C: D C: END @end example Thus the caller is expected to return the certificate for the request (which should match FINGERPRINT) as a binary blob. Processing then takes place without further interaction; in particular dirmngr tries to locate other required certificate by its own mechanism which includes a local certificate store as well as a list of trusted root certificates. @noindent The return code is 0 for success; i.e. the certificate has not been revoked or one of the usual error codes from libgpg-error. @node Dirmngr CHECKOCSP @subsection Validate a certificate using OCSP @example CHECKOCSP [--force-default-responder] [@var{fingerprint}] @end example Check whether the certificate with @var{fingerprint} (the SHA-1 hash of the entire X.509 certificate blob) is valid by consulting the appropriate OCSP responder. If the fingerprint has not been given or the certificate is not known by Dirmngr, the function inquires the certificate using: @example S: INQUIRE TARGETCERT C: D C: END @end example Thus the caller is expected to return the certificate for the request (which should match @var{fingerprint}) as a binary blob. Processing then takes place without further interaction; in particular dirmngr tries to locate other required certificates by its own mechanism which includes a local certificate store as well as a list of trusted root certificates. If the option @option{--force-default-responder} is given, only the default OCSP responder is used. This option is the per-command variant of the global option @option{--ignore-ocsp-service-url}. @noindent The return code is 0 for success; i.e. the certificate has not been revoked or one of the usual error codes from libgpg-error. @node Dirmngr CACHECERT @subsection Put a certificate into the internal cache Put a certificate into the internal cache. This command might be useful if a client knows in advance certificates required for a test and wants to make sure they get added to the internal cache. It is also helpful for debugging. To get the actual certificate, this command immediately inquires it using @example S: INQUIRE TARGETCERT C: D C: END @end example Thus the caller is expected to return the certificate for the request as a binary blob. @noindent The return code is 0 for success; i.e. the certificate has not been successfully cached or one of the usual error codes from libgpg-error. @node Dirmngr VALIDATE @subsection Validate a certificate for debugging Validate a certificate using the certificate validation function used internally by dirmngr. This command is only useful for debugging. To get the actual certificate, this command immediately inquires it using @example S: INQUIRE TARGETCERT C: D C: END @end example Thus the caller is expected to return the certificate for the request as a binary blob. @mansect see also @ifset isman @command{gpgsm}(1), @command{dirmngr-client}(1) @end ifset @include see-also-note.texi @c @c !!! UNDER CONSTRUCTION !!! @c @c @c @section Verifying a Certificate @c @c There are several ways to request services from Dirmngr. Almost all of @c them are done using the Assuan protocol. What we describe here is the @c Assuan command CHECKCRL as used for example by the dirmnr-client tool if @c invoked as @c @c @example @c dirmngr-client foo.crt @c @end example @c @c This command will send an Assuan request to an already running Dirmngr @c instance. foo.crt is expected to be a standard X.509 certificate and @c dirmngr will receive the Assuan command @c @c @example @c CHECKCRL @var [{fingerprint}] @c @end example @c @c @var{fingerprint} is optional and expected to be the SHA-1 has of the @c DER encoding of the certificate under question. It is to be HEX @c encoded. The rationale for sending the fingerprint is that it allows @c dirmngr to reply immediately if it has already cached such a request. If @c this is not the case and no certificate has been found in dirmngr's @c internal certificate storage, dirmngr will request the certificate using @c the Assuan inquiry @c @c @example @c INQUIRE TARGETCERT @c @end example @c @c The caller (in our example dirmngr-client) is then expected to return @c the certificate for the request (which should match @var{fingerprint}) @c as a binary blob. @c @c Dirmngr now passes control to @code{crl_cache_cert_isvalid}. This @c function checks whether a CRL item exists for target certificate. These @c CRL items are kept in a database of already loaded and verified CRLs. @c This mechanism is called the CRL cache. Obviously timestamps are kept @c there with each item to cope with the expiration date of the CRL. The @c possible return values are: @code{0} to indicate that a valid CRL is @c available for the certificate and the certificate itself is not listed @c in this CRL, @code{GPG_ERR_CERT_REVOKED} to indicate that the certificate is @c listed in the CRL or @code{GPG_ERR_NO_CRL_KNOWN} in cases where no CRL or no @c information is available. The first two codes are immediately returned to @c the caller and the processing of this request has been done. @c @c Only the @code{GPG_ERR_NO_CRL_KNOWN} needs more attention: Dirmngr now @c calls @code{clr_cache_reload_crl} and if this succeeds calls @c @code{crl_cache_cert_isvald) once more. All further errors are @c immediately returned to the caller. @c @c @code{crl_cache_reload_crl} is the actual heart of the CRL management. @c It locates the corresponding CRL for the target certificate, reads and @c verifies this CRL and stores it in the CRL cache. It works like this: @c @c * Loop over all crlDPs in the target certificate. @c * If the crlDP is invalid immediately terminate the loop. @c * Loop over all names in the current crlDP. @c * If the URL scheme is unknown or not enabled @c (--ignore-http-dp, --ignore-ldap-dp) continues with @c the next name. @c * @code{crl_fetch} is called to actually retrieve the CRL. @c In case of problems this name is ignore and we continue with @c the next name. Note that @code{crl_fetch} does only return @c a descriptor for the CRL for further reading so does the CRL @c does not yet end up in memory. @c * @code{crl_cache_insert} is called with that descriptor to @c actually read the CRL into the cache. See below for a @c description of this function. If there is any error (e.g. read @c problem, CRL not correctly signed or verification of signature @c not possible), this descriptor is rejected and we continue @c with the next name. If the CRL has been successfully loaded, @c the loop is terminated. @c * If no crlDP has been found in the previous loop use a default CRL. @c Note, that if any crlDP has been found but loading of the CRL failed, @c this condition is not true. @c * Try to load a CRL from all configured servers (ldapservers.conf) @c in turn. The first server returning a CRL is used. @c * @code(crl_cache_insert) is then used to actually insert the CRL @c into the cache. If this failed we give up immediately without @c checking the rest of the servers from the first step. @c * Ready. @c @c @c The @code{crl_cache_insert} function takes care of reading the bulk of @c the CRL, parsing it and checking the signature. It works like this: A @c new database file is created using a temporary file name. The CRL @c parsing machinery is started and all items of the CRL are put into @c this database file. At the end the issuer certificate of the CRL @c needs to be retrieved. Three cases are to be distinguished: @c @c a) An authorityKeyIdentifier with an issuer and serialno exits: The @c certificate is retrieved using @code{find_cert_bysn}. If @c the certificate is in the certificate cache, it is directly @c returned. Then the requester (i.e. the client who requested the @c CRL check) is asked via the Assuan inquiry ``SENDCERT'' whether @c he can provide this certificate. If this succeed the returned @c certificate gets cached and returned. Note, that dirmngr does not @c verify in any way whether the expected certificate is returned. @c It is in the interest of the client to return a useful certificate @c as otherwise the service request will fail due to a bad signature. @c The last way to get the certificate is by looking it up at @c external resources. This is done using the @code{ca_cert_fetch} @c and @code{fetch_next_ksba_cert} and comparing the returned @c certificate to match the requested issuer and seriano (This is @c needed because the LDAP layer may return several certificates as @c LDAP as no standard way to retrieve by serial number). @c @c b) An authorityKeyIdentifier with a key ID exists: The certificate is @c retrieved using @code{find_cert_bysubject}. If the certificate is @c in the certificate cache, it is directly returned. Then the @c requester is asked via the Assuan inquiry ``SENDCERT_SKI'' whether @c he can provide this certificate. If this succeed the returned @c certificate gets cached and returned. Note, that dirmngr does not @c verify in any way whether the expected certificate is returned. @c It is in the interest of the client to return a useful certificate @c as otherwise the service request will fail due to a bad signature. @c The last way to get the certificate is by looking it up at @c external resources. This is done using the @code{ca_cert_fetch} @c and @code{fetch_next_ksba_cert} and comparing the returned @c certificate to match the requested subject and key ID. @c @c c) No authorityKeyIdentifier exits: The certificate is retrieved @c using @code{find_cert_bysubject} without the key ID argument. If @c the certificate is in the certificate cache the first one with a @c matching subject is directly returned. Then the requester is @c asked via the Assuan inquiry ``SENDCERT'' and an exact @c specification of the subject whether he can @c provide this certificate. If this succeed the returned @c certificate gets cached and returned. Note, that dirmngr does not @c verify in any way whether the expected certificate is returned. @c It is in the interest of the client to return a useful certificate @c as otherwise the service request will fail due to a bad signature. @c The last way to get the certificate is by looking it up at @c external resources. This is done using the @code{ca_cert_fetch} @c and @code{fetch_next_ksba_cert} and comparing the returned @c certificate to match the requested subject; the first certificate @c with a matching subject is then returned. @c @c If no certificate was found, the function returns with the error @c GPG_ERR_MISSING_CERT. Now the signature is verified. If this fails, @c the error is returned. On success the @code{validate_cert_chain} is @c used to verify that the certificate is actually valid. @c @c Here we may encounter a recursive situation: @c @code{validate_cert_chain} needs to look at other certificates and @c also at CRLs to check whether these other certificates and well, the @c CRL issuer certificate itself are not revoked. FIXME: We need to make @c sure that @code{validate_cert_chain} does not try to lookup the CRL we @c are currently processing. This would be a catch-22 and may indicate a @c broken PKI. However, due to overlapping expiring times and imprecise @c clocks this may actually happen. @c @c For historical reasons the Assuan command ISVALID is a bit different @c to CHECKCRL but this is mainly due to different calling conventions. @c In the end the same fucntionality is used, albeit hidden by a couple @c of indirection and argument and result code mangling. It furthere @c ingetrages OCSP checking depending on options are the way it is @c called. GPGSM still uses this command but might eventually switch over @c to CHECKCRL and CHECKOCSP so that ISVALID can be retired. @c @c @c @section Validating a certificate @c @c We describe here how the internal function @code{validate_cert_chain} @c works. Note that mainly testing purposes this functionality may be @c called directly using @cmd{dirmngr-client --validate @file{foo.crt}}. @c @c The function takes the target certificate and a mode argument as @c parameters and returns an error code and optionally the closes @c expiration time of all certificates in the chain. @c @c We first check that the certificate may be used for the requested @c purpose (i.e. OCSP or CRL signing). If this is not the case @c GPG_ERR_WRONG_KEY_USAGE is returned. @c @c The next step is to find the trust anchor (root certificate) and to @c assemble the chain in memory: Starting with the target certificate, @c the expiration time is checked against the current date, unknown @c critical extensions are detected and certificate policies are matched @c (We only allow 2.289.9.9 but I have no clue about that OID and from @c where I got it - it does not even seem to be assigned - debug cruft?). @c @c Now if this certificate is a self-signed one, we have reached the @c trust anchor. In this case we check that the signature is good, the @c certificate is allowed to act as a CA, that it is a trusted one (by @c checking whether it is has been put into the trusted-certs @c configuration directory) and finally prepend into to our list @c representing the certificate chain. This steps ends then. @c @c If it is not a self-signed certificate, we check that the chain won't @c get too long (current limit is 100), if this is the case we terminate @c with the error GPG_ERR_BAD_CERT_CHAIN. @c @c Now the issuer's certificate is looked up: If an @c authorityKeyIdentifier is available, this one is used to locate the @c certificate either using issuer and serialnumber or subject DN @c (i.e. the issuer's DN) and the keyID. The functions @c @code{find_cert_bysn) and @code{find_cert_bysubject} are used @c respectively. The have already been described above under the @c description of @code{crl_cache_insert}. If no certificate was found @c or with no authorityKeyIdentifier, only the cache is consulted using @c @code{get_cert_bysubject}. The latter is done under the assumption @c that a matching certificate has explicitly been put into the @c certificate cache. If the issuer's certificate could not be found, @c the validation terminates with the error code @code{GPG_ERR_MISSING_CERT}. @c @c If the issuer's certificate has been found, the signature of the @c actual certificate is checked and in case this fails the error @c #code{GPG_ERR_BAD_CERT_CHAIN} is returned. If the signature checks out, the @c maximum chain length of the issuing certificate is checked as well as @c the capability of the certificate (i.e. whether he may be used for @c certificate signing). Then the certificate is prepended to our list @c representing the certificate chain. Finally the loop is continued now @c with the issuer's certificate as the current certificate. @c @c After the end of the loop and if no error as been encountered @c (i.e. the certificate chain has been assempled correctly), a check is @c done whether any certificate expired or a critical policy has not been @c met. In any of these cases the validation terminates with an @c appropriate error. @c @c Finally the function @code{check_revocations} is called to verify no @c certificate in the assempled chain has been revoked: This is an @c recursive process because a CRL has to be checked for each certificate @c in the chain except for the root certificate, of which we already know @c that it is trusted and we avoid checking a CRL here due to common @c setup problems and the assumption that a revoked root certificate has @c been removed from the list of trusted certificates. @c @c @c @c @c @section Looking up certificates through LDAP. @c @c This describes the LDAP layer to retrieve certificates. @c the functions @code{ca_cert_fetch} and @code{fetch_next_ksba_cert} are @c used for this. The first one starts a search and the second one is @c used to retrieve certificate after certificate. @c