diff --git a/dirmngr/dirmngr.h b/dirmngr/dirmngr.h index 92d9d4b6a..498a3d7b1 100644 --- a/dirmngr/dirmngr.h +++ b/dirmngr/dirmngr.h @@ -1,270 +1,272 @@ /* dirmngr.h - Common definitions for the dirmngr * Copyright (C) 2002 Klarälvdalens Datakonsult AB * Copyright (C) 2004, 2015 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+ */ #ifndef DIRMNGR_H #define DIRMNGR_H #include "./dirmngr-err.h" #define map_assuan_err(a) \ map_assuan_err_with_source (GPG_ERR_SOURCE_DEFAULT, (a)) #include #include #include #include "../common/util.h" #include "../common/membuf.h" #include "../common/sysutils.h" /* (gnupg_fd_t) */ #include "../common/asshelp.h" /* (assuan_context_t) */ #include "../common/i18n.h" #include "dirmngr-status.h" #include "http.h" /* (parsed_uri_t) */ /* This objects keeps information about a particular LDAP server and is used as item of a single linked list of servers. */ struct ldap_server_s { struct ldap_server_s* next; char *host; int port; char *user; char *pass; char *base; - unsigned int use_ldaps:1; + unsigned int starttls:1; /* Use STARTTLS. */ + unsigned int ldap_over_tls:1; /* Use LDAP over an TLS tunnel */ + unsigned int ntds:1; /* Use Active Directory authentication. */ }; typedef struct ldap_server_s *ldap_server_t; /* This objects is used to build a list of URI consisting of the original and the parsed URI. */ struct uri_item_s { struct uri_item_s *next; parsed_uri_t parsed_uri; /* The broken down URI. */ char uri[1]; /* The original URI. */ }; typedef struct uri_item_s *uri_item_t; /* A list of fingerprints. */ struct fingerprint_list_s; typedef struct fingerprint_list_s *fingerprint_list_t; struct fingerprint_list_s { fingerprint_list_t next; char hexfpr[20+20+1]; }; /* A large struct named "opt" to keep global flags. */ EXTERN_UNLESS_MAIN_MODULE struct { unsigned int debug; /* debug flags (DBG_foo_VALUE) */ int verbose; /* verbosity level */ int quiet; /* be as quiet as possible */ int dry_run; /* don't change any persistent data */ int batch; /* batch mode */ const char *homedir_cache; /* Dir for cache files (/var/cache/dirmngr). */ char *config_filename; /* Name of a config file, which will be reread on a HUP if it is not NULL. */ char *ldap_wrapper_program; /* Override value for the LDAP wrapper program. */ char *http_wrapper_program; /* Override value for the HTTP wrapper program. */ int running_detached; /* We are running in detached mode. */ int allow_version_check; /* --allow-version-check is active. */ int force; /* Force loading outdated CRLs. */ unsigned int connect_timeout; /* Timeout for connect. */ unsigned int connect_quick_timeout; /* Shorter timeout for connect. */ int disable_http; /* Do not use HTTP at all. */ int disable_ldap; /* Do not use LDAP at all. */ int disable_ipv4; /* Do not use legacy IP addresses. */ int disable_ipv6; /* Do not use standard IP addresses. */ int honor_http_proxy; /* Honor the http_proxy env variable. */ const char *http_proxy; /* The default HTTP proxy. */ const char *ldap_proxy; /* Use given LDAP proxy. */ int only_ldap_proxy; /* Only use the LDAP proxy; no fallback. */ int ignore_http_dp; /* Ignore HTTP CRL distribution points. */ int ignore_ldap_dp; /* Ignore LDAP CRL distribution points. */ int ignore_ocsp_service_url; /* Ignore OCSP service URLs as given in the certificate. */ /* A list of certificate extension OIDs which are ignored so that one can claim that a critical extension has been handled. One OID per string. */ strlist_t ignored_cert_extensions; int allow_ocsp; /* Allow using OCSP. */ int max_replies; unsigned int ldaptimeout; ldap_server_t ldapservers; int add_new_ldapservers; const char *ocsp_responder; /* Standard OCSP responder's URL. */ fingerprint_list_t ocsp_signer; /* The list of fingerprints with allowed standard OCSP signer certificates. */ unsigned int ocsp_max_clock_skew; /* Allowed seconds of clocks skew. */ unsigned int ocsp_max_period; /* Seconds a response is at maximum considered valid after thisUpdate. */ unsigned int ocsp_current_period; /* Seconds a response is considered current after nextUpdate. */ strlist_t keyserver; /* List of default keyservers. */ } opt; #define DBG_X509_VALUE 1 /* debug x.509 parsing */ #define DBG_CRYPTO_VALUE 4 /* debug low level crypto */ #define DBG_DNS_VALUE 16 /* debug DNS calls. */ #define DBG_MEMORY_VALUE 32 /* debug memory allocation stuff */ #define DBG_CACHE_VALUE 64 /* debug the caching */ #define DBG_MEMSTAT_VALUE 128 /* show memory statistics */ #define DBG_HASHING_VALUE 512 /* debug hashing operations */ #define DBG_IPC_VALUE 1024 /* debug assuan communication */ #define DBG_NETWORK_VALUE 2048 /* debug network I/O. */ #define DBG_LOOKUP_VALUE 8192 /* debug lookup details */ #define DBG_EXTPROG_VALUE 16384 /* debug external program calls */ #define DBG_X509 (opt.debug & DBG_X509_VALUE) #define DBG_CRYPTO (opt.debug & DBG_CRYPTO_VALUE) #define DBG_DNS (opt.debug & DBG_DNS_VALUE) #define DBG_MEMORY (opt.debug & DBG_MEMORY_VALUE) #define DBG_CACHE (opt.debug & DBG_CACHE_VALUE) #define DBG_HASHING (opt.debug & DBG_HASHING_VALUE) #define DBG_IPC (opt.debug & DBG_IPC_VALUE) #define DBG_NETWORK (opt.debug & DBG_NETWORK_VALUE) #define DBG_LOOKUP (opt.debug & DBG_LOOKUP_VALUE) #define DBG_EXTPROG (opt.debug & DBG_EXTPROG_VALUE) /* A simple list of certificate references. FIXME: Better use certlist_t also for references (Store NULL at .cert) */ struct cert_ref_s { struct cert_ref_s *next; unsigned char fpr[20]; }; typedef struct cert_ref_s *cert_ref_t; /* Forward references; access only through server.c. */ struct server_local_s; #if SIZEOF_UNSIGNED_LONG == 8 # define SERVER_CONTROL_MAGIC 0x6469726d6e677220 #else # define SERVER_CONTROL_MAGIC 0x6469726d #endif /* Connection control structure. */ struct server_control_s { unsigned long magic;/* Always has SERVER_CONTROL_MAGIC. */ int refcount; /* Count additional references to this object. */ int no_server; /* We are not running under server control. */ int status_fd; /* Only for non-server mode. */ struct server_local_s *server_local; int force_crl_refresh; /* Always load a fresh CRL. */ int check_revocations_nest_level; /* Internal to check_revovations. */ cert_ref_t ocsp_certs; /* Certificates from the current OCSP response. */ int audit_events; /* Send audit events to client. */ char *http_proxy; /* The used http_proxy or NULL. */ unsigned int timeout; /* Timeout for connect calls in ms. */ unsigned int http_no_crl:1; /* Do not check CRLs for https. */ }; /*-- dirmngr.c --*/ void dirmngr_exit( int ); /* Wrapper for exit() */ void dirmngr_init_default_ctrl (ctrl_t ctrl); void dirmngr_deinit_default_ctrl (ctrl_t ctrl); void dirmngr_sighup_action (void); const char* dirmngr_get_current_socket_name (void); int dirmngr_use_tor (void); /*-- Various housekeeping functions. --*/ void ks_hkp_housekeeping (time_t curtime); void ks_hkp_reload (void); void ks_hkp_init (void); /*-- server.c --*/ ldap_server_t get_ldapservers_from_ctrl (ctrl_t ctrl); ksba_cert_t get_cert_local (ctrl_t ctrl, const char *issuer); ksba_cert_t get_issuing_cert_local (ctrl_t ctrl, const char *issuer); ksba_cert_t get_cert_local_ski (ctrl_t ctrl, const char *name, ksba_sexp_t keyid); gpg_error_t get_istrusted_from_client (ctrl_t ctrl, const char *hexfpr); int dirmngr_assuan_log_monitor (assuan_context_t ctx, unsigned int cat, const char *msg); void start_command_handler (gnupg_fd_t fd, unsigned int session_id); gpg_error_t dirmngr_tick (ctrl_t ctrl); /*-- http-ntbtls.c --*/ /* Note that we don't use a callback for gnutls. */ gpg_error_t gnupg_http_tls_verify_cb (void *opaque, http_t http, http_session_t session, unsigned int flags, void *tls_context); /*-- loadswdb.c --*/ gpg_error_t dirmngr_load_swdb (ctrl_t ctrl, int force); /*-- domaininfo.c --*/ void domaininfo_print_stats (void); int domaininfo_is_wkd_not_supported (const char *domain); void domaininfo_set_no_name (const char *domain); void domaininfo_set_wkd_supported (const char *domain); void domaininfo_set_wkd_not_supported (const char *domain); void domaininfo_set_wkd_not_found (const char *domain); /*-- workqueue.c --*/ typedef const char *(*wqtask_t)(ctrl_t ctrl, const char *args); void workqueue_dump_queue (ctrl_t ctrl); gpg_error_t workqueue_add_task (wqtask_t func, const char *args, unsigned int session_id, int need_network); void workqueue_run_global_tasks (ctrl_t ctrl, int with_network); void workqueue_run_post_session_tasks (unsigned int session_id); #endif /*DIRMNGR_H*/ diff --git a/dirmngr/ks-action.c b/dirmngr/ks-action.c index 5c097754e..57cf04a7e 100644 --- a/dirmngr/ks-action.c +++ b/dirmngr/ks-action.c @@ -1,415 +1,447 @@ /* ks-action.c - OpenPGP keyserver actions * Copyright (C) 2011 Free Software Foundation, Inc. * Copyright (C) 2011, 2014 Werner Koch * Copyright (C) 2015 g10 Code GmbH * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #include "dirmngr.h" #include "misc.h" #include "ks-engine.h" #include "ks-action.h" #if USE_LDAP # include "ldap-parse-uri.h" #endif /* Called by the engine's help functions to print the actual help. */ gpg_error_t ks_print_help (ctrl_t ctrl, const char *text) { return dirmngr_status_help (ctrl, text); } /* Called by the engine's help functions to print the actual help. */ gpg_error_t ks_printf_help (ctrl_t ctrl, const char *format, ...) { va_list arg_ptr; gpg_error_t err; char *buf; va_start (arg_ptr, format); buf = es_vbsprintf (format, arg_ptr); err = buf? 0 : gpg_error_from_syserror (); va_end (arg_ptr); if (!err) err = dirmngr_status_help (ctrl, buf); es_free (buf); return err; } /* Run the help command for the engine responsible for URI. */ gpg_error_t ks_action_help (ctrl_t ctrl, const char *url) { gpg_error_t err; parsed_uri_t parsed_uri; /* The broken down URI. */ + char *tmpstr; + const char *s; if (!url || !*url) { ks_print_help (ctrl, "Known schemata:\n"); parsed_uri = NULL; } else { #if USE_LDAP - if (ldap_uri_p (url)) + if (!strncmp (url, "ldap:", 5) && !(url[5] == '/' && url[6] == '/')) + { + /* 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:", url+5, NULL); + if (!tmpstr) + err = gpg_error_from_syserror (); + else + { + err = http_parse_uri (&parsed_uri, tmpstr, 0); + xfree (tmpstr); + } + } + else if ((s=strchr (url, ':')) && !(s[1] == '/' && s[2] == '/')) + { + /* No scheme given. Use http_parse_uri to put the string as + * opaque value into parsed_uri. */ + tmpstr = strconcat ("opaque:", url, NULL); + if (!tmpstr) + err = gpg_error_from_syserror (); + else + { + err = http_parse_uri (&parsed_uri, tmpstr, 0); + xfree (tmpstr); + } + } + else if (ldap_uri_p (url)) err = ldap_parse_uri (&parsed_uri, url); else #endif { err = http_parse_uri (&parsed_uri, url, HTTP_PARSE_NO_SCHEME_CHECK); } if (err) return err; } /* Call all engines to give them a chance to print a help string. */ err = ks_hkp_help (ctrl, parsed_uri); if (!err) err = ks_http_help (ctrl, parsed_uri); if (!err) err = ks_finger_help (ctrl, parsed_uri); if (!err) err = ks_kdns_help (ctrl, parsed_uri); #if USE_LDAP if (!err) err = ks_ldap_help (ctrl, parsed_uri); #endif if (!parsed_uri) ks_print_help (ctrl, "(Use an URL for engine specific help.)"); else http_release_parsed_uri (parsed_uri); return err; } /* Resolve all host names. This is useful for looking at the status of configured keyservers. */ gpg_error_t ks_action_resolve (ctrl_t ctrl, uri_item_t keyservers) { gpg_error_t err = 0; int any_server = 0; uri_item_t uri; for (uri = keyservers; !err && uri; uri = uri->next) { if (uri->parsed_uri->is_http) { any_server = 1; err = ks_hkp_resolve (ctrl, uri->parsed_uri); if (err) break; } } if (!any_server) err = gpg_error (GPG_ERR_NO_KEYSERVER); return err; } /* Search all configured keyservers for keys matching PATTERNS and write the result to the provided output stream. */ gpg_error_t ks_action_search (ctrl_t ctrl, uri_item_t keyservers, strlist_t patterns, estream_t outfp) { gpg_error_t err = 0; int any_server = 0; int any_results = 0; uri_item_t uri; estream_t infp; if (!patterns) return gpg_error (GPG_ERR_NO_USER_ID); /* FIXME: We only take care of the first pattern. To fully support multiple patterns we might either want to run several queries in parallel and merge them. We also need to decide what to do with errors - it might not be the best idea to ignore an error from one server and silently continue with another server. For now we stop at the first error, unless the server responds with '404 Not Found', in which case we try the next server. */ for (uri = keyservers; !err && uri; uri = uri->next) { int is_http = uri->parsed_uri->is_http; int is_ldap = 0; unsigned int http_status = 0; #if USE_LDAP - is_ldap = (strcmp (uri->parsed_uri->scheme, "ldap") == 0 - || strcmp (uri->parsed_uri->scheme, "ldaps") == 0 - || strcmp (uri->parsed_uri->scheme, "ldapi") == 0); + is_ldap = (!strcmp (uri->parsed_uri->scheme, "ldap") + || !strcmp (uri->parsed_uri->scheme, "ldaps") + || !strcmp (uri->parsed_uri->scheme, "ldapi") + || uri->parsed_uri->opaque); #endif if (is_http || is_ldap) { any_server = 1; #if USE_LDAP if (is_ldap) err = ks_ldap_search (ctrl, uri->parsed_uri, patterns->d, &infp); else #endif { err = ks_hkp_search (ctrl, uri->parsed_uri, patterns->d, &infp, &http_status); } if (err == gpg_error (GPG_ERR_NO_DATA) && http_status == 404 /* not found */) { /* No record found. Clear error and try next server. */ err = 0; continue; } if (!err) { err = copy_stream (infp, outfp); es_fclose (infp); any_results = 1; break; } } } if (!any_server) err = gpg_error (GPG_ERR_NO_KEYSERVER); else if (err == 0 && !any_results) err = gpg_error (GPG_ERR_NO_DATA); return err; } /* Get the requested keys (matching PATTERNS) using all configured keyservers and write the result to the provided output stream. */ gpg_error_t ks_action_get (ctrl_t ctrl, uri_item_t keyservers, strlist_t patterns, int ldap_only, estream_t outfp) { gpg_error_t err = 0; gpg_error_t first_err = 0; int any_server = 0; int any_data = 0; strlist_t sl; uri_item_t uri; estream_t infp; if (!patterns) return gpg_error (GPG_ERR_NO_USER_ID); /* FIXME: We only take care of the first keyserver. To fully support multiple keyservers we need to track the result for each pattern and use the next keyserver if one key was not found. The keyservers might not all be fully synced thus it is not clear whether the first keyserver has the freshest copy of the key. Need to think about a better strategy. */ for (uri = keyservers; !err && uri; uri = uri->next) { int is_hkp_s = (strcmp (uri->parsed_uri->scheme, "hkp") == 0 || strcmp (uri->parsed_uri->scheme, "hkps") == 0); int is_http_s = (strcmp (uri->parsed_uri->scheme, "http") == 0 || strcmp (uri->parsed_uri->scheme, "https") == 0); int is_ldap = 0; if (ldap_only) is_hkp_s = is_http_s = 0; #if USE_LDAP - is_ldap = (strcmp (uri->parsed_uri->scheme, "ldap") == 0 - || strcmp (uri->parsed_uri->scheme, "ldaps") == 0 - || strcmp (uri->parsed_uri->scheme, "ldapi") == 0); + is_ldap = (!strcmp (uri->parsed_uri->scheme, "ldap") + || !strcmp (uri->parsed_uri->scheme, "ldaps") + || !strcmp (uri->parsed_uri->scheme, "ldapi") + || uri->parsed_uri->opaque); #endif if (is_hkp_s || is_http_s || is_ldap) { any_server = 1; for (sl = patterns; !err && sl; sl = sl->next) { #if USE_LDAP if (is_ldap) err = ks_ldap_get (ctrl, uri->parsed_uri, sl->d, &infp); else #endif if (is_hkp_s) err = ks_hkp_get (ctrl, uri->parsed_uri, sl->d, &infp); else if (is_http_s) err = ks_http_fetch (ctrl, uri->parsed_uri->original, KS_HTTP_FETCH_NOCACHE, &infp); else BUG (); if (err) { /* It is possible that a server does not carry a key, thus we only save the error and continue with the next pattern. FIXME: It is an open question how to return such an error condition to the caller. */ first_err = err; err = 0; } else { err = copy_stream (infp, outfp); /* Reading from the keyserver should never fail, thus return this error. */ if (!err) any_data = 1; es_fclose (infp); infp = NULL; } } } if (any_data) break; /* Stop loop after a keyserver returned something. */ } if (!any_server) err = gpg_error (GPG_ERR_NO_KEYSERVER); else if (!err && first_err && !any_data) err = first_err; return err; } /* Retrieve keys from URL and write the result to the provided output * stream OUTFP. If OUTFP is NULL the data is written to the bit * bucket. */ gpg_error_t ks_action_fetch (ctrl_t ctrl, const char *url, estream_t outfp) { gpg_error_t err = 0; estream_t infp; parsed_uri_t parsed_uri; /* The broken down URI. */ if (!url) return gpg_error (GPG_ERR_INV_URI); err = http_parse_uri (&parsed_uri, url, HTTP_PARSE_NO_SCHEME_CHECK); if (err) return err; if (parsed_uri->is_http) { err = ks_http_fetch (ctrl, url, KS_HTTP_FETCH_NOCACHE, &infp); if (!err) { err = copy_stream (infp, outfp); es_fclose (infp); } } else if (!parsed_uri->opaque) { err = gpg_error (GPG_ERR_INV_URI); } else if (!strcmp (parsed_uri->scheme, "finger")) { err = ks_finger_fetch (ctrl, parsed_uri, &infp); if (!err) { err = copy_stream (infp, outfp); es_fclose (infp); } } else if (!strcmp (parsed_uri->scheme, "kdns")) { err = ks_kdns_fetch (ctrl, parsed_uri, &infp); if (!err) { err = copy_stream (infp, outfp); es_fclose (infp); } } else err = gpg_error (GPG_ERR_INV_URI); http_release_parsed_uri (parsed_uri); return err; } /* Send an OpenPGP key to all keyservers. The key in {DATA,DATALEN} is expected to be in OpenPGP binary transport format. The metadata in {INFO,INFOLEN} is in colon-separated format (concretely, it is the output of 'gpg --list-keys --with-colons KEYID'). This function may modify DATA and INFO. If this is a problem, then the caller should create a copy. */ gpg_error_t ks_action_put (ctrl_t ctrl, uri_item_t keyservers, void *data, size_t datalen, void *info, size_t infolen) { gpg_error_t err = 0; gpg_error_t first_err = 0; int any_server = 0; uri_item_t uri; (void) info; (void) infolen; for (uri = keyservers; !err && uri; uri = uri->next) { int is_http = uri->parsed_uri->is_http; int is_ldap = 0; #if USE_LDAP - is_ldap = (strcmp (uri->parsed_uri->scheme, "ldap") == 0 - || strcmp (uri->parsed_uri->scheme, "ldaps") == 0 - || strcmp (uri->parsed_uri->scheme, "ldapi") == 0); + is_ldap = (!strcmp (uri->parsed_uri->scheme, "ldap") + || !strcmp (uri->parsed_uri->scheme, "ldaps") + || !strcmp (uri->parsed_uri->scheme, "ldapi") + || uri->parsed_uri->opaque); #endif if (is_http || is_ldap) { any_server = 1; #if USE_LDAP if (is_ldap) err = ks_ldap_put (ctrl, uri->parsed_uri, data, datalen, info, infolen); else #endif { err = ks_hkp_put (ctrl, uri->parsed_uri, data, datalen); } if (err) { first_err = err; err = 0; } } } if (!any_server) err = gpg_error (GPG_ERR_NO_KEYSERVER); else if (!err && first_err) err = first_err; return err; } diff --git a/dirmngr/ks-engine-ldap.c b/dirmngr/ks-engine-ldap.c index b7ff0633c..1b5c2ca32 100644 --- a/dirmngr/ks-engine-ldap.c +++ b/dirmngr/ks-engine-ldap.c @@ -1,2280 +1,2366 @@ /* 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" + " 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" - "bindname will typically be of the form:\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) + 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 int +static gpg_error_t my_ldap_connect (parsed_uri_t uri, LDAP **ldap_connp, - char **basednp, unsigned int *r_serverinfo) + char **r_basedn, char **r_host, int *r_use_tls, + unsigned int *r_serverinfo) { - int err = 0; + gpg_error_t err = 0; + int lerr; + ldap_server_t server = NULL; LDAP *ldap_conn = NULL; - char *user = uri->auth; - struct uri_tuple_s *password_param; - char *password; 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; + char *tmpstr; + + if (r_basedn) + *r_basedn = NULL; + if (r_host) + *r_host = NULL; + if (r_use_tls) + *r_use_tls = 0; *r_serverinfo = 0; - password_param = uri_query_lookup (uri, "password"); - password = password_param ? password_param->value : NULL; + 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%s)\n", - uri->host, uri->port, - uri->path ? uri->path : "", - uri->auth ? "bindname=" : "", - uri->auth ? uri->auth : "", - uri->auth && password ? "," : "", - password ? "password=" : "", - password ? ">not shown<": "", - uri->ad_current? " auth=>current_user<":""); + 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 (uri->use_tls) + if (use_tls) { #ifndef HAVE_LDAP_START_TLS_S - log_error ("Can't use LDAP to connect to the server: no TLS support."); + log_error ("ldap: can't connect to the server: no TLS support."); err = GPG_ERR_LDAP_NOT_SUPPORTED; goto out; #endif } - ldap_conn = ldap_init (uri->host, uri->port); + +#ifdef HAVE_W32_SYSTEM + npth_unprotect (); + ldap_conn = ldap_sslinit (host, port, (use_tls == 2)); + npth_protect (); if (!ldap_conn) { - err = gpg_err_code_from_syserror (); - log_error ("error initializing LDAP for (%s://%s:%d)\n", - uri->scheme, uri->host, uri->port); + 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; - err = ldap_set_option (ldap_conn, LDAP_OPT_PROTOCOL_VERSION, &ver); - if (err != LDAP_SUCCESS) + 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 (err)); + ldap_err2string (lerr)); + err = ldap_err_to_gpg_err (lerr); goto out; } } #endif - /* XXX: It would be nice to have an option to provide the server's - certificate. */ -#if 0 -#if defined(LDAP_OPT_X_TLS_CACERTFILE) && defined(HAVE_LDAP_SET_OPTION) - err = ldap_set_option (NULL, LDAP_OPT_X_TLS_CACERTFILE, ca_cert_file); - if (err) - { - log_error ("unable to set ca-cert-file to '%s': %s\n", - ca_cert_file, ldap_err2string (err)); - goto out; - } -#endif /* LDAP_OPT_X_TLS_CACERTFILE && HAVE_LDAP_SET_OPTION */ -#endif #ifdef HAVE_LDAP_START_TLS_S - if (uri->use_tls) + if (use_tls == 1) { - /* XXX: We need an option to determine whether to abort if the - certificate is bad or not. Right now we conservatively - default to checking the certificate and aborting. */ #ifndef HAVE_W32_SYSTEM int check_cert = LDAP_OPT_X_TLS_HARD; /* LDAP_OPT_X_TLS_NEVER */ - err = ldap_set_option (ldap_conn, - LDAP_OPT_X_TLS_REQUIRE_CERT, &check_cert); - if (err) + lerr = ldap_set_option (ldap_conn, + LDAP_OPT_X_TLS_REQUIRE_CERT, &check_cert); + if (lerr) { - log_error ("error setting TLS option on LDAP connection\n"); + 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 (); - err = ldap_start_tls_s (ldap_conn, + lerr = ldap_start_tls_s (ldap_conn, #ifdef HAVE_W32_SYSTEM /* ServerReturnValue, result */ NULL, NULL, #endif /* ServerControls, ClientControls */ NULL, NULL); npth_protect (); - if (err) + if (lerr) { - log_error ("error connecting to LDAP server with TLS\n"); + log_error ("ldap: error switching to STARTTLS mode: %s\n", + ldap_err2string (lerr)); + err = ldap_err_to_gpg_err (lerr); goto out; } } #endif - if (uri->ad_current) + if (use_ntds) { if (opt.debug) - log_debug ("LDAP bind to current user via AD\n"); + log_debug ("ldap: binding to current user via AD\n"); #ifdef HAVE_W32_SYSTEM npth_unprotect (); - err = ldap_bind_s (ldap_conn, NULL, NULL, LDAP_AUTH_NEGOTIATE); + lerr = ldap_bind_s (ldap_conn, NULL, NULL, LDAP_AUTH_NEGOTIATE); npth_protect (); - if (err != LDAP_SUCCESS) + if (lerr != LDAP_SUCCESS) { log_error ("error binding to LDAP via AD: %s\n", - ldap_err2string (err)); + 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 (uri->auth) + else if (bindname) { if (opt.debug) - log_debug ("LDAP bind to %s, password %s\n", - user, password ? ">not shown<" : ">none<"); + log_debug ("LDAP bind to '%s', password '%s'\n", + bindname, password ? ">not_shown<" : ">none<"); npth_unprotect (); - err = ldap_simple_bind_s (ldap_conn, user, password); + lerr = ldap_simple_bind_s (ldap_conn, bindname, password); npth_protect (); - if (err != LDAP_SUCCESS) + if (lerr != LDAP_SUCCESS) { - log_error ("error binding to LDAP: %s\n", ldap_err2string (err)); + 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 (uri->path && *uri->path) + if (basedn_arg && *basedn_arg) { - /* User specified base DN. */ - basedn = xstrdup (uri->path); - - /* If the user specifies a base DN, then we know the server is a + /* 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 (); - err = ldap_search_s (ldap_conn, "", LDAP_SCOPE_BASE, + lerr = ldap_search_s (ldap_conn, "", LDAP_SCOPE_BASE, "(objectClass=*)", attr, 0, &res); npth_protect (); - if (err == LDAP_SUCCESS) + 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++) + 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 (); - err = ldap_search_s (ldap_conn, object, LDAP_SCOPE_BASE, + lerr = ldap_search_s (ldap_conn, object, LDAP_SCOPE_BASE, "(objectClass=*)", attr2, 0, &si_res); npth_protect (); xfree (object); } - if (err == LDAP_SUCCESS) + 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 + 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 (); - err = ldap_search_s (ldap_conn, "cn=pgpServerInfo", LDAP_SCOPE_BASE, + lerr = ldap_search_s (ldap_conn, "cn=pgpServerInfo", LDAP_SCOPE_BASE, "(objectClass=*)", attr2, 0, &si_res); npth_protect (); - if (err == LDAP_SUCCESS) + 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"); } - if (err) - xfree (basedn); - else - { - if (basednp) - *basednp = basedn; - else - xfree (basedn); - } + ldapserver_list_free (server); if (err) { + xfree (basedn); if (ldap_conn) ldap_unbind (ldap_conn); } else - *ldap_connp = ldap_conn; + { + 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. */ - ldap_err = my_ldap_connect (uri, &ldap_conn, &basedn, &serverinfo); - if (ldap_err || !basedn) + err = my_ldap_connect (uri, &ldap_conn, + &basedn, &host, &use_tls, &serverinfo); + if (err || !basedn) { - if (ldap_err) - err = ldap_err_to_gpg_err (ldap_err); - else + 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", - uri->scheme, uri->host? uri->host:""); + 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. */ - ldap_err = my_ldap_connect (uri, &ldap_conn, &basedn, &serverinfo); - if (ldap_err || !basedn) + err = my_ldap_connect (uri, &ldap_conn, &basedn, NULL, NULL, &serverinfo); + if (err || !basedn) { - if (ldap_err) - err = ldap_err_to_gpg_err (ldap_err); - else + 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); } - ldap_err = my_ldap_connect (uri, &ldap_conn, &basedn, &serverinfo); - if (ldap_err || !basedn) + err = my_ldap_connect (uri, &ldap_conn, &basedn, NULL, NULL, &serverinfo); + if (err || !basedn) { - if (ldap_err) - err = ldap_err_to_gpg_err (ldap_err); - else + 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/ldap.c b/dirmngr/ldap.c index 96abc89d0..42efcfd49 100644 --- a/dirmngr/ldap.c +++ b/dirmngr/ldap.c @@ -1,883 +1,883 @@ /* ldap.c - LDAP access * Copyright (C) 2002 Klarälvdalens Datakonsult AB * Copyright (C) 2003, 2004, 2005, 2007, 2008, 2010 g10 Code GmbH * * This file is part of DirMngr. * * DirMngr 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 2 of the License, or * (at your option) any later version. * * DirMngr 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, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #include #include #include #include #include #include #include #include #include #include "dirmngr.h" #include "../common/exechelp.h" #include "crlfetch.h" #include "ldapserver.h" #include "misc.h" #include "ldap-wrapper.h" #include "../common/host2net.h" #define UNENCODED_URL_CHARS "abcdefghijklmnopqrstuvwxyz" \ "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \ "01234567890" \ "$-_.+!*'()," #define USERCERTIFICATE "userCertificate" #define CACERTIFICATE "caCertificate" #define X509CACERT "x509caCert" #define USERSMIMECERTIFICATE "userSMIMECertificate" /* Definition for the context of the cert fetch functions. */ struct cert_fetch_context_s { ksba_reader_t reader; /* The reader used (shallow copy). */ unsigned char *tmpbuf; /* Helper buffer. */ size_t tmpbufsize; /* Allocated size of tmpbuf. */ int truncated; /* Flag to indicate a truncated output. */ }; /* Add HOST and PORT to our list of LDAP servers. Fixme: We should better use an extra list of servers. */ static void add_server_to_servers (const char *host, int port) { ldap_server_t server; ldap_server_t last = NULL; const char *s; if (!port) port = 389; for (server=opt.ldapservers; server; server = server->next) { if (!strcmp (server->host, host) && server->port == port) return; /* already in list... */ last = server; } /* We assume that the host names are all supplied by our configuration files and thus are sane. To keep this assumption we must reject all invalid host names. */ for (s=host; *s; s++) if (!strchr ("abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "01234567890.-", *s)) { log_error (_("invalid char 0x%02x in host name - not added\n"), *s); return; } log_info (_("adding '%s:%d' to the ldap server list\n"), host, port); server = xtrycalloc (1, sizeof *s); if (!server) log_error (_("malloc failed: %s\n"), strerror (errno)); else { server->host = xstrdup (host); server->port = port; if (last) last->next = server; else opt.ldapservers = server; } } /* Perform an LDAP query. Returns an gpg error code or 0 on success. The function returns a new reader object at READER. */ static gpg_error_t run_ldap_wrapper (ctrl_t ctrl, int ignore_timeout, int multi_mode, const char *proxy, const char *host, int port, const char *user, const char *pass, const char *dn, const char *filter, const char *attr, const char *url, ksba_reader_t *reader) { const char *argv[40]; int argc; char portbuf[30], timeoutbuf[30]; *reader = NULL; argc = 0; if (pass) /* Note, that the password must be the first item. */ { argv[argc++] = "--pass"; argv[argc++] = pass; } if (DBG_LOOKUP) argv[argc++] = "-vv"; else if (DBG_EXTPROG) argv[argc++] = "-v"; argv[argc++] = "--log-with-pid"; if (multi_mode) argv[argc++] = "--multi"; if (opt.ldaptimeout) { sprintf (timeoutbuf, "%u", opt.ldaptimeout); argv[argc++] = "--timeout"; argv[argc++] = timeoutbuf; if (ignore_timeout) argv[argc++] = "--only-search-timeout"; } if (proxy) { argv[argc++] = "--proxy"; argv[argc++] = proxy; } if (host) { argv[argc++] = "--host"; argv[argc++] = host; } if (port) { sprintf (portbuf, "%d", port); argv[argc++] = "--port"; argv[argc++] = portbuf; } if (user) { argv[argc++] = "--user"; argv[argc++] = user; } if (dn) { argv[argc++] = "--dn"; argv[argc++] = dn; } if (filter) { argv[argc++] = "--filter"; argv[argc++] = filter; } if (attr) { argv[argc++] = "--attr"; argv[argc++] = attr; } argv[argc++] = url? url : "ldap://"; argv[argc] = NULL; return ldap_wrapper (ctrl, reader, argv); } /* Perform a LDAP query using a given URL. On success a new ksba reader is returned. If HOST or PORT are not 0, they are used to override the values from the URL. */ gpg_error_t url_fetch_ldap (ctrl_t ctrl, const char *url, const char *host, int port, ksba_reader_t *reader) { gpg_error_t err; err = run_ldap_wrapper (ctrl, 1, /* Ignore explicit timeout because CRLs might be very large. */ 0, opt.ldap_proxy, host, port, NULL, NULL, NULL, NULL, NULL, url, reader); /* FIXME: This option might be used for DoS attacks. Because it will enlarge the list of servers to consult without a limit and all LDAP queries w/o a host are will then try each host in turn. */ if (!err && opt.add_new_ldapservers && !opt.ldap_proxy) { if (host) add_server_to_servers (host, port); else if (url) { char *tmp = host_and_port_from_url (url, &port); if (tmp) { add_server_to_servers (tmp, port); xfree (tmp); } } } /* If the lookup failed and we are not only using the proxy, we try again using our default list of servers. */ if (err && !(opt.ldap_proxy && opt.only_ldap_proxy)) { struct ldapserver_iter iter; if (DBG_LOOKUP) log_debug ("no hostname in URL or query failed; " "trying all default hostnames\n"); for (ldapserver_iter_begin (&iter, ctrl); err && ! ldapserver_iter_end_p (&iter); ldapserver_iter_next (&iter)) { ldap_server_t server = iter.server; err = run_ldap_wrapper (ctrl, 0, 0, NULL, server->host, server->port, NULL, NULL, NULL, NULL, NULL, url, reader); if (!err) break; } } return err; } /* Perform an LDAP query on all configured servers. On error the error code of the last try is returned. */ gpg_error_t attr_fetch_ldap (ctrl_t ctrl, const char *dn, const char *attr, ksba_reader_t *reader) { gpg_error_t err = gpg_error (GPG_ERR_CONFIGURATION); struct ldapserver_iter iter; *reader = NULL; /* FIXME; we might want to look at the Base SN to try matching servers first. */ for (ldapserver_iter_begin (&iter, ctrl); ! ldapserver_iter_end_p (&iter); ldapserver_iter_next (&iter)) { ldap_server_t server = iter.server; err = run_ldap_wrapper (ctrl, 0, 0, opt.ldap_proxy, server->host, server->port, server->user, server->pass, dn, "objectClass=*", attr, NULL, reader); if (!err) break; /* Probably found a result. Ready. */ } return err; } /* Parse PATTERN and return a new strlist to be used for the actual LDAP query. Bit 0 of the flags field is set if that pattern is actually a base specification. Caller must release the returned strlist. NULL is returned on error. * Possible patterns: * * KeyID * Fingerprint * OpenPGP userid * x Email address Indicated by a left angle bracket. * Exact word match in user id or subj. name * x Subj. DN indicated bu a leading slash * Issuer DN * Serial number + subj. DN * x Substring match indicated by a leading '*; is also the default. */ strlist_t parse_one_pattern (const char *pattern) { strlist_t result = NULL; char *p; switch (*pattern) { case '<': /* Email. */ { pattern++; result = xmalloc (sizeof *result + 5 + strlen (pattern)); result->next = NULL; result->flags = 0; p = stpcpy (stpcpy (result->d, "mail="), pattern); if (p[-1] == '>') *--p = 0; if (!*result->d) /* Error. */ { xfree (result); result = NULL; } break; } case '/': /* Subject DN. */ pattern++; if (*pattern) { result = xmalloc (sizeof *result + strlen (pattern)); result->next = NULL; result->flags = 1; /* Base spec. */ strcpy (result->d, pattern); } break; case '#': /* Issuer DN. */ pattern++; if (*pattern == '/') /* Just issuer DN. */ { pattern++; } else /* Serial number + issuer DN */ { } break; case '*': pattern++; /* fall through */ default: /* Take as substring match. */ { const char format[] = "(|(sn=*%s*)(|(cn=*%s*)(mail=*%s*)))"; if (*pattern) { result = xmalloc (sizeof *result + strlen (format) + 3 * strlen (pattern)); result->next = NULL; result->flags = 0; sprintf (result->d, format, pattern, pattern, pattern); } } break; } return result; } /* Take the string STRING and escape it according to the URL rules. Return a newly allocated string. */ static char * escape4url (const char *string) { const char *s; char *buf, *p; size_t n; if (!string) string = ""; for (s=string,n=0; *s; s++) if (strchr (UNENCODED_URL_CHARS, *s)) n++; else n += 3; buf = malloc (n+1); if (!buf) return NULL; for (s=string,p=buf; *s; s++) if (strchr (UNENCODED_URL_CHARS, *s)) *p++ = *s; else { sprintf (p, "%%%02X", *(const unsigned char *)s); p += 3; } *p = 0; return buf; } /* Create a LDAP URL from DN and FILTER and return it in URL. We don't need the host and port because this will be specified using the override options. */ static gpg_error_t make_url (char **url, const char *dn, const char *filter) { gpg_error_t err; char *u_dn, *u_filter; char const attrs[] = (USERCERTIFICATE "," /* In 2005 wk mentioned in the changelog that * work on the userSMIMECertificate has * started but it seems that no further * progress was made or the whole thing was * simply forgotten. */ /* USERSMIMECERTIFICATE "," */ CACERTIFICATE "," X509CACERT ); *url = NULL; u_dn = escape4url (dn); if (!u_dn) return gpg_error_from_errno (errno); u_filter = escape4url (filter); if (!u_filter) { err = gpg_error_from_errno (errno); xfree (u_dn); return err; } *url = strconcat ("ldap:///", u_dn, "?", attrs, "?sub?", u_filter, NULL); if (!*url) err = gpg_error_from_syserror (); else err = 0; xfree (u_dn); xfree (u_filter); return err; } /* Prepare an LDAP query to return the cACertificate attribute for DN. * All configured default servers are queried until one responds. * This function returns an error code or 0 and stored a newly * allocated contect object at CONTEXT on success. */ gpg_error_t start_cacert_fetch_ldap (ctrl_t ctrl, cert_fetch_context_t *r_context, const char *dn) { gpg_error_t err; struct ldapserver_iter iter; *r_context = xtrycalloc (1, sizeof **r_context); if (!*r_context) return gpg_error_from_errno (errno); /* FIXME; we might want to look at the Base SN to try matching servers first. */ err = gpg_error (GPG_ERR_CONFIGURATION); for (ldapserver_iter_begin (&iter, ctrl); ! ldapserver_iter_end_p (&iter); ldapserver_iter_next (&iter)) { ldap_server_t server = iter.server; err = run_ldap_wrapper (ctrl, 0, 1, /* --multi (record format) */ opt.ldap_proxy, server->host, server->port, server->user, server->pass, dn, "objectClass=*", "cACertificate", NULL, &(*r_context)->reader); if (!err) break; /* Probably found a result. */ } if (err) { xfree (*r_context); *r_context = NULL; } return err; } /* Prepare an LDAP query to return certificates matching PATTERNS * using the SERVER. This function returns an error code or 0 and * stores a newly allocated object at R_CONTEXT on success. */ gpg_error_t start_cert_fetch_ldap (ctrl_t ctrl, cert_fetch_context_t *r_context, strlist_t patterns, const ldap_server_t server) { gpg_error_t err; char *proxy = NULL; char *host = NULL; int port; char *user = NULL; char *pass = NULL; const char *base; char *argv[50]; int argc = 0; int argc_malloced = 0; char portbuf[30], timeoutbuf[30]; int use_ldaps = 0; *r_context = NULL; if (opt.ldap_proxy && !(proxy = xtrystrdup (opt.ldap_proxy))) { err = gpg_error_from_syserror (); goto leave; } if (server) { if (server->host && !(host = xtrystrdup (server->host))) { err = gpg_error_from_syserror (); goto leave; } port = server->port; if (server->user && !(user = xtrystrdup (server->user))) { err = gpg_error_from_syserror (); goto leave; } if (server->pass && !(pass = xtrystrdup (server->pass))) { err = gpg_error_from_syserror (); goto leave; } base = server->base; - use_ldaps = server->use_ldaps; + use_ldaps = server->ldap_over_tls; } else /* Use a default server. */ { xfree (proxy); return gpg_error (GPG_ERR_NOT_IMPLEMENTED); } if (!base) base = ""; if (pass) /* Note: Must be the first item. */ { argv[argc++] = "--pass"; argv[argc++] = pass; } if (DBG_LOOKUP) argv[argc++] = "-vv"; else if (DBG_EXTPROG) argv[argc++] = "-v"; argv[argc++] = "--log-with-pid"; argv[argc++] = "--multi"; if (opt.ldaptimeout) { snprintf (timeoutbuf, sizeof timeoutbuf, "%u", opt.ldaptimeout); argv[argc++] = "--timeout"; argv[argc++] = timeoutbuf; } if (opt.ldap_proxy) { argv[argc++] = "--proxy"; argv[argc++] = proxy; } if (use_ldaps) argv[argc++] = "--tls"; if (host) { argv[argc++] = "--host"; argv[argc++] = host; } if (port) { snprintf (portbuf, sizeof portbuf, "%d", port); argv[argc++] = "--port"; argv[argc++] = portbuf; } if (user) { argv[argc++] = "--user"; argv[argc++] = user; } /* All entries in argv from this index on are malloc'ed. */ argc_malloced = argc; for (; patterns; patterns = patterns->next) { strlist_t sl; char *url; if (argc >= DIM (argv) - 1) { /* Too many patterns. It does not make sense to allow an arbitrary number of patters because the length of the command line is limited anyway. */ /* fixme: cleanup. */ return gpg_error (GPG_ERR_RESOURCE_LIMIT); } sl = parse_one_pattern (patterns->d); if (!sl) { log_error (_("start_cert_fetch: invalid pattern '%s'\n"), patterns->d); err = gpg_error (GPG_ERR_INV_USER_ID); goto leave; } if ((sl->flags & 1)) err = make_url (&url, sl->d, "objectClass=*"); else err = make_url (&url, base, sl->d); free_strlist (sl); if (err) goto leave; argv[argc++] = url; } argv[argc] = NULL; *r_context = xtrycalloc (1, sizeof **r_context); if (!*r_context) { err = gpg_error_from_errno (errno); goto leave; } err = ldap_wrapper (ctrl, &(*r_context)->reader, (const char**)argv); if (err) { xfree (*r_context); *r_context = NULL; } leave: for (; argc_malloced < argc; argc_malloced++) xfree (argv[argc_malloced]); xfree (proxy); xfree (host); xfree (user); xfree (pass); return err; } /* Read a fixed amount of data from READER into BUFFER. */ static gpg_error_t read_buffer (ksba_reader_t reader, unsigned char *buffer, size_t count) { gpg_error_t err; size_t nread; while (count) { err = ksba_reader_read (reader, buffer, count, &nread); if (err) return err; buffer += nread; count -= nread; } return 0; } /* Fetch the next certificate. Return 0 on success, GPG_ERR_EOF if no (more) certificates are available or any other error code. GPG_ERR_TRUNCATED may be returned to indicate that the result has been truncated. */ gpg_error_t fetch_next_cert_ldap (cert_fetch_context_t context, unsigned char **value, size_t *valuelen) { gpg_error_t err; unsigned char hdr[5]; char *p, *pend; unsigned long n; int okay = 0; /* int is_cms = 0; */ *value = NULL; *valuelen = 0; err = 0; while (!err) { err = read_buffer (context->reader, hdr, 5); if (err) break; n = buf32_to_ulong (hdr+1); if (*hdr == 'V' && okay) { #if 0 /* That code to extra a cert from a CMS object is not yet ready. */ if (is_cms) { /* The certificate needs to be parsed from CMS data. */ ksba_cms_t cms; ksba_stop_reason_t stopreason; int i; err = ksba_cms_new (&cms); if (err) goto leave; err = ksba_cms_set_reader_writer (cms, context->reader, NULL); if (err) { log_error ("ksba_cms_set_reader_writer failed: %s\n", gpg_strerror (err)); goto leave; } do { err = ksba_cms_parse (cms, &stopreason); if (err) { log_error ("ksba_cms_parse failed: %s\n", gpg_strerror (err)); goto leave; } if (stopreason == KSBA_SR_BEGIN_DATA) log_error ("userSMIMECertificate is not " "a certs-only message\n"); } while (stopreason != KSBA_SR_READY); for (i=0; (cert=ksba_cms_get_cert (cms, i)); i++) { check_and_store (ctrl, stats, cert, 0); ksba_cert_release (cert); cert = NULL; } if (!i) log_error ("no certificate found\n"); else any = 1; } else #endif /* End unfinished code to extract from a CMS object. */ { *value = xtrymalloc (n); if (!*value) return gpg_error_from_errno (errno); *valuelen = n; err = read_buffer (context->reader, *value, n); break; /* Ready or error. */ } } else if (!n && *hdr == 'A') okay = 0; else if (n) { if (n > context->tmpbufsize) { xfree (context->tmpbuf); context->tmpbufsize = 0; context->tmpbuf = xtrymalloc (n+1); if (!context->tmpbuf) return gpg_error_from_errno (errno); context->tmpbufsize = n; } err = read_buffer (context->reader, context->tmpbuf, n); if (err) break; if (*hdr == 'A') { p = context->tmpbuf; p[n] = 0; /*(we allocated one extra byte for this.)*/ /* fixme: is_cms = 0; */ if ( (pend = strchr (p, ';')) ) *pend = 0; /* Strip off the extension. */ if (!ascii_strcasecmp (p, USERCERTIFICATE)) { if (DBG_LOOKUP) log_debug ("fetch_next_cert_ldap: got attribute '%s'\n", USERCERTIFICATE); okay = 1; } else if (!ascii_strcasecmp (p, CACERTIFICATE)) { if (DBG_LOOKUP) log_debug ("fetch_next_cert_ldap: got attribute '%s'\n", CACERTIFICATE); okay = 1; } else if (!ascii_strcasecmp (p, X509CACERT)) { if (DBG_LOOKUP) log_debug ("fetch_next_cert_ldap: got attribute '%s'\n", CACERTIFICATE); okay = 1; } /* else if (!ascii_strcasecmp (p, USERSMIMECERTIFICATE)) */ /* { */ /* if (DBG_LOOKUP) */ /* log_debug ("fetch_next_cert_ldap: got attribute '%s'\n", */ /* USERSMIMECERTIFICATE); */ /* okay = 1; */ /* is_cms = 1; */ /* } */ else { if (DBG_LOOKUP) log_debug ("fetch_next_cert_ldap: got attribute '%s'" " - ignored\n", p); okay = 0; } } else if (*hdr == 'E') { p = context->tmpbuf; p[n] = 0; /*(we allocated one extra byte for this.)*/ if (!strcmp (p, "truncated")) { context->truncated = 1; log_info (_("ldap_search hit the size limit of" " the server\n")); } } } } if (err) { xfree (*value); *value = NULL; *valuelen = 0; if (gpg_err_code (err) == GPG_ERR_EOF && context->truncated) { context->truncated = 0; /* So that the next call would return EOF. */ err = gpg_error (GPG_ERR_TRUNCATED); } } return err; } void end_cert_fetch_ldap (cert_fetch_context_t context) { if (context) { ksba_reader_t reader = context->reader; xfree (context->tmpbuf); xfree (context); ldap_wrapper_release_context (reader); ksba_reader_release (reader); } } diff --git a/dirmngr/ldapserver.c b/dirmngr/ldapserver.c index 20a2bb18f..4ef28431c 100644 --- a/dirmngr/ldapserver.c +++ b/dirmngr/ldapserver.c @@ -1,161 +1,211 @@ /* dirmngr.c - LDAP access Copyright (C) 2008 g10 Code GmbH This file is part of DirMngr. DirMngr 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 2 of the License, or (at your option) any later version. DirMngr 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H # include #endif #include "dirmngr.h" #include "ldapserver.h" /* Release the list of SERVERS. As usual it is okay to call this function with SERVERS passed as NULL. */ void ldapserver_list_free (ldap_server_t servers) { while (servers) { ldap_server_t tmp = servers->next; xfree (servers->host); xfree (servers->user); if (servers->pass) memset (servers->pass, 0, strlen (servers->pass)); xfree (servers->pass); xfree (servers->base); xfree (servers); servers = tmp; } } /* Parse a single LDAP server configuration line. Returns the server - or NULL in case of errors. The configuration line is assumed to be - colon separated with these fields: - - 1. field: Hostname - 2. field: Portnumber - 3. field: Username - 4. field: Password - 5. field: Base DN - 6. field: Flags - - FILENAME and LINENO are used for diagnostic purposes only. -*/ + * or NULL in case of errors. The configuration line is assumed to be + * colon separated with these fields: + * + * 1. field: Hostname + * 2. field: Portnumber + * 3. field: Username + * 4. field: Password + * 5. field: Base DN + * 6. field: Flags + * + * Flags are: + * + * starttls := Use STARTTLS with a default port of 389 + * ldaptls := Tunnel LDAP trough a TLS tunnel with default port 636 + * plain := Switch to plain unsecured LDAP. + * (The last of these 3 flags is the effective one) + * ntds := Use Active Directory authentication + * + * FILENAME and LINENO are used for diagnostic purposes only. + */ ldap_server_t ldapserver_parse_one (char *line, const char *filename, unsigned int lineno) { char *p; char *endp; const char *s; ldap_server_t server; int fieldno; int fail = 0; int i; /* Parse the colon separated fields. */ - server = xcalloc (1, sizeof *server); + server = xtrycalloc (1, sizeof *server); + if (!server) + { + fail = 1; + goto leave; + } + for (fieldno = 1, p = line; p; p = endp, fieldno++ ) { endp = strchr (p, ':'); if (endp) *endp++ = '\0'; trim_spaces (p); switch (fieldno) { case 1: - if (*p) - server->host = xstrdup (p); - else - { - log_error (_("%s:%u: no hostname given\n"), - filename, lineno); - fail = 1; - } + server->host = xtrystrdup (p); + if (!server->host) + fail = 1; break; case 2: if (*p) server->port = atoi (p); break; case 3: - if (*p) - server->user = xstrdup (p); + server->user = xtrystrdup (p); + if (!server->user) + fail = 1; break; case 4: if (*p && !server->user) { - log_error (_("%s:%u: password given without user\n"), - filename, lineno); + if (filename) + log_error (_("%s:%u: password given without user\n"), + filename, lineno); + else + log_error ("ldap: password given without user ('%s')\n", line); fail = 1; } else if (*p) - server->pass = xstrdup (p); + { + server->pass = xtrystrdup (p); + if (!server->pass) + fail = 1; + } break; case 5: if (*p) - server->base = xstrdup (p); + { + server->base = xtrystrdup (p); + if (!server->base) + fail = 1;; + } break; case 6: { char **flags = NULL; flags = strtokenize (p, ","); if (!flags) - log_fatal ("strtokenize failed: %s\n", - gpg_strerror (gpg_error_from_syserror ())); + { + log_error ("strtokenize failed: %s\n", + gpg_strerror (gpg_error_from_syserror ())); + fail = 1; + break; + } for (i=0; (s = flags[i]); i++) { if (!*s) ; - else if (!ascii_strcasecmp (s, "ldaps")) - server->use_ldaps = 1; - else if (!ascii_strcasecmp (s, "ldap")) - server->use_ldaps = 0; + else if (!ascii_strcasecmp (s, "starttls")) + { + server->starttls = 1; + server->ldap_over_tls = 0; + } + else if (!ascii_strcasecmp (s, "ldaptls")) + { + server->starttls = 0; + server->ldap_over_tls = 1; + } + else if (!ascii_strcasecmp (s, "plain")) + { + server->starttls = 0; + server->ldap_over_tls = 0; + } + else if (!ascii_strcasecmp (s, "ntds")) + { + server->ntds = 1; + } else - log_info (_("%s:%u: ignoring unknown flag '%s'\n"), - filename, lineno, s); + { + if (filename) + log_info (_("%s:%u: ignoring unknown flag '%s'\n"), + filename, lineno, s); + else + log_info ("ldap: unknown flag '%s' ignored in (%s)\n", + s, line); + } } xfree (flags); } break; default: /* (We silently ignore extra fields.) */ break; } } + leave: if (fail) { - log_info (_("%s:%u: skipping this line\n"), filename, lineno); + if (filename) + log_info (_("%s:%u: skipping this line\n"), filename, lineno); + else + log_info ("ldap: error in server spec ('%s')\n", line); ldapserver_list_free (server); server = NULL; } return server; } diff --git a/dirmngr/ldapserver.h b/dirmngr/ldapserver.h index 1b20508db..c62f5a939 100644 --- a/dirmngr/ldapserver.h +++ b/dirmngr/ldapserver.h @@ -1,90 +1,78 @@ /* ldapserver.h Copyright (C) 2008 g10 Code GmbH This file is part of DirMngr. DirMngr 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 2 of the License, or (at your option) any later version. DirMngr is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see . */ #ifndef LDAPSERVER_H #define LDAPSERVER_H #include "dirmngr.h" /* Release the list of SERVERS. As usual it is okay to call this function with SERVERS passed as NULL. */ void ldapserver_list_free (ldap_server_t servers); -/* Parse a single LDAP server configuration line. Returns the server - or NULL in case of errors. The configuration line is assumed to be - colon separated with these fields: - - 1. field: Hostname - 2. field: Portnumber - 3. field: Username - 4. field: Password - 5. field: Base DN - - FILENAME and LINENO are used for diagnostic purposes only. -*/ ldap_server_t ldapserver_parse_one (char *line, const char *filename, unsigned int lineno); /* Iterate over all servers. */ struct ldapserver_iter { ctrl_t ctrl; enum { LDAPSERVER_SESSION, LDAPSERVER_GLOBAL } group; ldap_server_t server; }; static inline void ldapserver_iter_next (struct ldapserver_iter *iter) { if (iter->server) iter->server = iter->server->next; if (! iter->server) { if (iter->group == LDAPSERVER_SESSION) { iter->group = LDAPSERVER_GLOBAL; iter->server = opt.ldapservers; } } } static inline int ldapserver_iter_end_p (struct ldapserver_iter *iter) { return (iter->group == LDAPSERVER_GLOBAL && iter->server == NULL); } static inline void ldapserver_iter_begin (struct ldapserver_iter *iter, ctrl_t ctrl) { iter->ctrl = ctrl; iter->group = LDAPSERVER_SESSION; iter->server = get_ldapservers_from_ctrl (ctrl); while (iter->server == NULL && ! ldapserver_iter_end_p (iter)) ldapserver_iter_next (iter); } #endif /* LDAPSERVER_H */ diff --git a/dirmngr/server.c b/dirmngr/server.c index a35402271..105275845 100644 --- a/dirmngr/server.c +++ b/dirmngr/server.c @@ -1,3107 +1,3148 @@ /* server.c - LDAP and Keyserver access server * Copyright (C) 2002 Klarälvdalens Datakonsult AB * Copyright (C) 2003, 2004, 2005, 2007, 2008, 2009, 2011, 2015 g10 Code GmbH * Copyright (C) 2014, 2015, 2016 Werner Koch * Copyright (C) 2016 Bundesamt für Sicherheit in der Informationstechnik * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . * * SPDX-License-Identifier: GPL-3.0+ */ #include #include #include #include #include #include #include #include #include #include #include "dirmngr.h" #include #include "crlcache.h" #include "crlfetch.h" #if USE_LDAP # include "ldapserver.h" #endif #include "ocsp.h" #include "certcache.h" #include "validate.h" #include "misc.h" #if USE_LDAP # include "ldap-wrapper.h" #endif #include "ks-action.h" #include "ks-engine.h" /* (ks_hkp_print_hosttable) */ #if USE_LDAP # include "ldap-parse-uri.h" #endif #include "dns-stuff.h" #include "../common/mbox-util.h" #include "../common/zb32.h" #include "../common/server-help.h" /* To avoid DoS attacks we limit the size of a certificate to something reasonable. The DoS was actually only an issue back when Dirmngr was a system service and not a user service. */ #define MAX_CERT_LENGTH (16*1024) /* The limit for the CERTLIST inquiry. We allow for up to 20 * certificates but also take PEM encoding into account. */ #define MAX_CERTLIST_LENGTH ((MAX_CERT_LENGTH * 20 * 4)/3) /* The same goes for OpenPGP keyblocks, but here we need to allow for much longer blocks; a 200k keyblock is not too unusual for keys with a lot of signatures (e.g. 0x5b0358a2). 9C31503C6D866396 even has 770 KiB as of 2015-08-23. To avoid adding a runtime option we now use 20MiB which should really be enough. Well, a key with several pictures could be larger (the parser as a 18MiB limit for attribute packets) but it won't be nice to the keyservers to send them such large blobs. */ #define MAX_KEYBLOCK_LENGTH (20*1024*1024) #define PARM_ERROR(t) assuan_set_error (ctx, \ gpg_error (GPG_ERR_ASS_PARAMETER), (t)) #define set_error(e,t) (ctx ? assuan_set_error (ctx, gpg_error (e), (t)) \ /**/: gpg_error (e)) /* Control structure per connection. */ struct server_local_s { /* Data used to associate an Assuan context with local server data */ assuan_context_t assuan_ctx; /* The session id (a counter). */ unsigned int session_id; /* Per-session LDAP servers. */ ldap_server_t ldapservers; /* Per-session list of keyservers. */ uri_item_t keyservers; /* If this flag is set to true this dirmngr process will be terminated after the end of this session. */ int stopme; /* State variable private to is_tor_running. */ int tor_state; /* If the first both flags are set the assuan logging of data lines * is suppressed. The count variable is used to show the number of * non-logged bytes. */ size_t inhibit_data_logging_count; unsigned int inhibit_data_logging : 1; unsigned int inhibit_data_logging_now : 1; }; /* Cookie definition for assuan data line output. */ static gpgrt_ssize_t data_line_cookie_write (void *cookie, const void *buffer, size_t size); static int data_line_cookie_close (void *cookie); static es_cookie_io_functions_t data_line_cookie_functions = { NULL, data_line_cookie_write, NULL, data_line_cookie_close }; /* Local prototypes */ static const char *task_check_wkd_support (ctrl_t ctrl, const char *domain); /* Accessor for the local ldapservers variable. */ ldap_server_t get_ldapservers_from_ctrl (ctrl_t ctrl) { if (ctrl && ctrl->server_local) return ctrl->server_local->ldapservers; else return NULL; } /* Release an uri_item_t list. */ static void release_uri_item_list (uri_item_t list) { while (list) { uri_item_t tmp = list->next; http_release_parsed_uri (list->parsed_uri); xfree (list); list = tmp; } } /* Release all configured keyserver info from CTRL. */ void release_ctrl_keyservers (ctrl_t ctrl) { if (! ctrl->server_local) return; release_uri_item_list (ctrl->server_local->keyservers); ctrl->server_local->keyservers = NULL; } /* Helper to print a message while leaving a command. */ static gpg_error_t leave_cmd (assuan_context_t ctx, gpg_error_t err) { if (err) { const char *name = assuan_get_command_name (ctx); if (!name) name = "?"; if (gpg_err_source (err) == GPG_ERR_SOURCE_DEFAULT) log_error ("command '%s' failed: %s\n", name, gpg_strerror (err)); else log_error ("command '%s' failed: %s <%s>\n", name, gpg_strerror (err), gpg_strsource (err)); } return err; } /* This is a wrapper around assuan_send_data which makes debugging the output in verbose mode easier. */ static gpg_error_t data_line_write (assuan_context_t ctx, const void *buffer_arg, size_t size) { ctrl_t ctrl = assuan_get_pointer (ctx); const char *buffer = buffer_arg; gpg_error_t err; /* If we do not want logging, enable it here. */ if (ctrl && ctrl->server_local && ctrl->server_local->inhibit_data_logging) ctrl->server_local->inhibit_data_logging_now = 1; if (opt.verbose && buffer && size) { /* Ease reading of output by sending a physical line at each LF. */ const char *p; size_t n, nbytes; nbytes = size; do { p = memchr (buffer, '\n', nbytes); n = p ? (p - buffer) + 1 : nbytes; err = assuan_send_data (ctx, buffer, n); if (err) { gpg_err_set_errno (EIO); goto leave; } buffer += n; nbytes -= n; if (nbytes && (err=assuan_send_data (ctx, NULL, 0))) /* Flush line. */ { gpg_err_set_errno (EIO); goto leave; } } while (nbytes); } else { err = assuan_send_data (ctx, buffer, size); if (err) { gpg_err_set_errno (EIO); /* For use by data_line_cookie_write. */ goto leave; } } leave: if (ctrl && ctrl->server_local && ctrl->server_local->inhibit_data_logging) { ctrl->server_local->inhibit_data_logging_now = 0; ctrl->server_local->inhibit_data_logging_count += size; } return err; } /* A write handler used by es_fopencookie to write assuan data lines. */ static gpgrt_ssize_t data_line_cookie_write (void *cookie, const void *buffer, size_t size) { assuan_context_t ctx = cookie; if (data_line_write (ctx, buffer, size)) return -1; return (gpgrt_ssize_t)size; } static int data_line_cookie_close (void *cookie) { assuan_context_t ctx = cookie; if (DBG_IPC) { ctrl_t ctrl = assuan_get_pointer (ctx); if (ctrl && ctrl->server_local && ctrl->server_local->inhibit_data_logging && ctrl->server_local->inhibit_data_logging_count) log_debug ("(%zu bytes sent via D lines not shown)\n", ctrl->server_local->inhibit_data_logging_count); } if (assuan_send_data (ctx, NULL, 0)) { gpg_err_set_errno (EIO); return -1; } return 0; } /* Copy the % and + escaped string S into the buffer D and replace the escape sequences. Note, that it is sufficient to allocate the target string D as long as the source string S, i.e.: strlen(s)+1. Note further that if S contains an escaped binary Nul the resulting string D will contain the 0 as well as all other characters but it will be impossible to know whether this is the original EOS or a copied Nul. */ static void strcpy_escaped_plus (char *d, const unsigned char *s) { while (*s) { if (*s == '%' && s[1] && s[2]) { s++; *d++ = xtoi_2 ( s); s += 2; } else if (*s == '+') *d++ = ' ', s++; else *d++ = *s++; } *d = 0; } /* This function returns true if a Tor server is running. The status * is cached for the current connection. */ static int is_tor_running (ctrl_t ctrl) { /* Check whether we can connect to the proxy. */ if (!ctrl || !ctrl->server_local) return 0; /* Ooops. */ if (!ctrl->server_local->tor_state) { assuan_fd_t sock; sock = assuan_sock_connect_byname (NULL, 0, 0, NULL, ASSUAN_SOCK_TOR); if (sock == ASSUAN_INVALID_FD) ctrl->server_local->tor_state = -1; /* Not running. */ else { assuan_sock_close (sock); ctrl->server_local->tor_state = 1; /* Running. */ } } return (ctrl->server_local->tor_state > 0); } /* Return an error if the assuan context does not belong to the owner of the process or to root. On error FAILTEXT is set as Assuan error string. */ static gpg_error_t check_owner_permission (assuan_context_t ctx, const char *failtext) { #ifdef HAVE_W32_SYSTEM /* Under Windows the dirmngr is always run under the control of the user. */ (void)ctx; (void)failtext; #else gpg_err_code_t ec; assuan_peercred_t cred; ec = gpg_err_code (assuan_get_peercred (ctx, &cred)); if (!ec && cred->uid && cred->uid != getuid ()) ec = GPG_ERR_EPERM; if (ec) return set_error (ec, failtext); #endif return 0; } /* Common code for get_cert_local and get_issuer_cert_local. */ static ksba_cert_t do_get_cert_local (ctrl_t ctrl, const char *name, const char *command) { unsigned char *value; size_t valuelen; int rc; char *buf; ksba_cert_t cert; buf = name? strconcat (command, " ", name, NULL) : xtrystrdup (command); if (!buf) rc = gpg_error_from_syserror (); else { rc = assuan_inquire (ctrl->server_local->assuan_ctx, buf, &value, &valuelen, MAX_CERT_LENGTH); xfree (buf); } if (rc) { log_error (_("assuan_inquire(%s) failed: %s\n"), command, gpg_strerror (rc)); return NULL; } if (!valuelen) { xfree (value); return NULL; } rc = ksba_cert_new (&cert); if (!rc) { rc = ksba_cert_init_from_mem (cert, value, valuelen); if (rc) { ksba_cert_release (cert); cert = NULL; } } xfree (value); return cert; } /* Ask back to return a certificate for NAME, given as a regular gpgsm * certificate identifier (e.g. fingerprint or one of the other * methods). Alternatively, NULL may be used for NAME to return the * current target certificate. Either return the certificate in a * KSBA object or NULL if it is not available. */ ksba_cert_t get_cert_local (ctrl_t ctrl, const char *name) { if (!ctrl || !ctrl->server_local || !ctrl->server_local->assuan_ctx) { if (opt.debug) log_debug ("get_cert_local called w/o context\n"); return NULL; } return do_get_cert_local (ctrl, name, "SENDCERT"); } /* Ask back to return the issuing certificate for NAME, given as a * regular gpgsm certificate identifier (e.g. fingerprint or one * of the other methods). Alternatively, NULL may be used for NAME to * return the current target certificate. Either return the certificate * in a KSBA object or NULL if it is not available. */ ksba_cert_t get_issuing_cert_local (ctrl_t ctrl, const char *name) { if (!ctrl || !ctrl->server_local || !ctrl->server_local->assuan_ctx) { if (opt.debug) log_debug ("get_issuing_cert_local called w/o context\n"); return NULL; } return do_get_cert_local (ctrl, name, "SENDISSUERCERT"); } /* Ask back to return a certificate with subject NAME and a * subjectKeyIdentifier of KEYID. */ ksba_cert_t get_cert_local_ski (ctrl_t ctrl, const char *name, ksba_sexp_t keyid) { unsigned char *value; size_t valuelen; int rc; char *buf; ksba_cert_t cert; char *hexkeyid; if (!ctrl || !ctrl->server_local || !ctrl->server_local->assuan_ctx) { if (opt.debug) log_debug ("get_cert_local_ski called w/o context\n"); return NULL; } if (!name || !keyid) { log_debug ("get_cert_local_ski called with insufficient arguments\n"); return NULL; } hexkeyid = serial_hex (keyid); if (!hexkeyid) { log_debug ("serial_hex() failed\n"); return NULL; } buf = strconcat ("SENDCERT_SKI ", hexkeyid, " /", name, NULL); if (!buf) { log_error ("can't allocate enough memory: %s\n", strerror (errno)); xfree (hexkeyid); return NULL; } xfree (hexkeyid); rc = assuan_inquire (ctrl->server_local->assuan_ctx, buf, &value, &valuelen, MAX_CERT_LENGTH); xfree (buf); if (rc) { log_error (_("assuan_inquire(%s) failed: %s\n"), "SENDCERT_SKI", gpg_strerror (rc)); return NULL; } if (!valuelen) { xfree (value); return NULL; } rc = ksba_cert_new (&cert); if (!rc) { rc = ksba_cert_init_from_mem (cert, value, valuelen); if (rc) { ksba_cert_release (cert); cert = NULL; } } xfree (value); return cert; } /* Ask the client via an inquiry to check the istrusted status of the certificate specified by the hexified fingerprint HEXFPR. Returns 0 if the certificate is trusted by the client or an error code. */ gpg_error_t get_istrusted_from_client (ctrl_t ctrl, const char *hexfpr) { unsigned char *value; size_t valuelen; int rc; char request[100]; if (!ctrl || !ctrl->server_local || !ctrl->server_local->assuan_ctx || !hexfpr) return gpg_error (GPG_ERR_INV_ARG); snprintf (request, sizeof request, "ISTRUSTED %s", hexfpr); rc = assuan_inquire (ctrl->server_local->assuan_ctx, request, &value, &valuelen, 100); if (rc) { log_error (_("assuan_inquire(%s) failed: %s\n"), request, gpg_strerror (rc)); return rc; } /* The expected data is: "1" or "1 cruft" (not a C-string). */ if (valuelen && *value == '1' && (valuelen == 1 || spacep (value+1))) rc = 0; else rc = gpg_error (GPG_ERR_NOT_TRUSTED); xfree (value); return rc; } /* Ask the client to return the certificate associated with the current command. This is sometimes needed because the client usually sends us just the cert ID, assuming that the request can be satisfied from the cache, where the cert ID is used as key. */ static int inquire_cert_and_load_crl (assuan_context_t ctx) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; unsigned char *value = NULL; size_t valuelen; ksba_cert_t cert = NULL; err = assuan_inquire( ctx, "SENDCERT", &value, &valuelen, 0); if (err) return err; /* { */ /* FILE *fp = fopen ("foo.der", "r"); */ /* value = xmalloc (2000); */ /* valuelen = fread (value, 1, 2000, fp); */ /* fclose (fp); */ /* } */ if (!valuelen) /* No data returned; return a comprehensible error. */ return gpg_error (GPG_ERR_MISSING_CERT); err = ksba_cert_new (&cert); if (err) goto leave; err = ksba_cert_init_from_mem (cert, value, valuelen); if(err) goto leave; xfree (value); value = NULL; err = crl_cache_reload_crl (ctrl, cert); leave: ksba_cert_release (cert); xfree (value); return err; } /* Handle OPTION commands. */ static gpg_error_t option_handler (assuan_context_t ctx, const char *key, const char *value) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err = 0; if (!strcmp (key, "force-crl-refresh")) { int i = *value? atoi (value) : 0; ctrl->force_crl_refresh = i; } else if (!strcmp (key, "audit-events")) { int i = *value? atoi (value) : 0; ctrl->audit_events = i; } else if (!strcmp (key, "http-proxy")) { xfree (ctrl->http_proxy); if (!*value || !strcmp (value, "none")) ctrl->http_proxy = NULL; else if (!(ctrl->http_proxy = xtrystrdup (value))) err = gpg_error_from_syserror (); } else if (!strcmp (key, "honor-keyserver-url-used")) { /* Return an error if we are running in Tor mode. */ if (dirmngr_use_tor ()) err = gpg_error (GPG_ERR_FORBIDDEN); } else if (!strcmp (key, "http-crl")) { int i = *value? atoi (value) : 0; ctrl->http_no_crl = !i; } else err = gpg_error (GPG_ERR_UNKNOWN_OPTION); return err; } static const char hlp_dns_cert[] = "DNS_CERT \n" "DNS_CERT --pka \n" "DNS_CERT --dane \n" "\n" "Return the CERT record for . is one of\n" " * Return the first record of any supported subtype\n" " PGP Return the first record of subtype PGP (3)\n" " IPGP Return the first record of subtype IPGP (6)\n" "If the content of a certificate is available (PGP) it is returned\n" "by data lines. Fingerprints and URLs are returned via status lines.\n" "In --pka mode the fingerprint and if available an URL is returned.\n" "In --dane mode the key is returned from RR type 61"; static gpg_error_t cmd_dns_cert (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err = 0; int pka_mode, dane_mode; char *mbox = NULL; char *namebuf = NULL; char *encodedhash = NULL; const char *name; int certtype; char *p; void *key = NULL; size_t keylen; unsigned char *fpr = NULL; size_t fprlen; char *url = NULL; pka_mode = has_option (line, "--pka"); dane_mode = has_option (line, "--dane"); line = skip_options (line); if (pka_mode && dane_mode) { err = PARM_ERROR ("either --pka or --dane may be given"); goto leave; } if (pka_mode || dane_mode) ; /* No need to parse here - we do this later. */ else { p = strchr (line, ' '); if (!p) { err = PARM_ERROR ("missing arguments"); goto leave; } *p++ = 0; if (!strcmp (line, "*")) certtype = DNS_CERTTYPE_ANY; else if (!strcmp (line, "IPGP")) certtype = DNS_CERTTYPE_IPGP; else if (!strcmp (line, "PGP")) certtype = DNS_CERTTYPE_PGP; else { err = PARM_ERROR ("unknown subtype"); goto leave; } while (spacep (p)) p++; line = p; if (!*line) { err = PARM_ERROR ("name missing"); goto leave; } } if (pka_mode || dane_mode) { char *domain; /* Points to mbox. */ char hashbuf[32]; /* For SHA-1 and SHA-256. */ /* We lowercase ascii characters but the DANE I-D does not allow this. FIXME: Check after the release of the RFC whether to change this. */ mbox = mailbox_from_userid (line, 0); if (!mbox || !(domain = strchr (mbox, '@'))) { err = set_error (GPG_ERR_INV_USER_ID, "no mailbox in user id"); goto leave; } *domain++ = 0; if (pka_mode) { gcry_md_hash_buffer (GCRY_MD_SHA1, hashbuf, mbox, strlen (mbox)); encodedhash = zb32_encode (hashbuf, 8*20); if (!encodedhash) { err = gpg_error_from_syserror (); goto leave; } namebuf = strconcat (encodedhash, "._pka.", domain, NULL); if (!namebuf) { err = gpg_error_from_syserror (); goto leave; } name = namebuf; certtype = DNS_CERTTYPE_IPGP; } else { /* Note: The hash is truncated to 28 bytes and we lowercase the result only for aesthetic reasons. */ gcry_md_hash_buffer (GCRY_MD_SHA256, hashbuf, mbox, strlen (mbox)); encodedhash = bin2hex (hashbuf, 28, NULL); if (!encodedhash) { err = gpg_error_from_syserror (); goto leave; } ascii_strlwr (encodedhash); namebuf = strconcat (encodedhash, "._openpgpkey.", domain, NULL); if (!namebuf) { err = gpg_error_from_syserror (); goto leave; } name = namebuf; certtype = DNS_CERTTYPE_RR61; } } else name = line; err = get_dns_cert (ctrl, name, certtype, &key, &keylen, &fpr, &fprlen, &url); if (err) goto leave; if (key) { err = data_line_write (ctx, key, keylen); if (err) goto leave; } if (fpr) { char *tmpstr; tmpstr = bin2hex (fpr, fprlen, NULL); if (!tmpstr) err = gpg_error_from_syserror (); else { err = assuan_write_status (ctx, "FPR", tmpstr); xfree (tmpstr); } if (err) goto leave; } if (url) { err = assuan_write_status (ctx, "URL", url); if (err) goto leave; } leave: xfree (key); xfree (fpr); xfree (url); xfree (mbox); xfree (namebuf); xfree (encodedhash); return leave_cmd (ctx, err); } /* Core of cmd_wkd_get and task_check_wkd_support. If CTX is NULL * this function will not write anything to the assuan output. */ static gpg_error_t proc_wkd_get (ctrl_t ctrl, assuan_context_t ctx, char *line) { gpg_error_t err = 0; char *mbox = NULL; char *domainbuf = NULL; char *domain; /* Points to mbox or domainbuf. This is used to * connect to the host. */ char *domain_orig;/* Points to mbox. This is the used for the * query; i.e. the domain part of the * addrspec. */ char sha1buf[20]; char *uri = NULL; char *encodedhash = NULL; int opt_submission_addr; int opt_policy_flags; int is_wkd_query; /* True if this is a real WKD query. */ int no_log = 0; char portstr[20] = { 0 }; int subdomain_mode = 0; opt_submission_addr = has_option (line, "--submission-address"); opt_policy_flags = has_option (line, "--policy-flags"); if (has_option (line, "--quick")) ctrl->timeout = opt.connect_quick_timeout; line = skip_options (line); is_wkd_query = !(opt_policy_flags || opt_submission_addr); mbox = mailbox_from_userid (line, 0); if (!mbox || !(domain = strchr (mbox, '@'))) { err = set_error (GPG_ERR_INV_USER_ID, "no mailbox in user id"); goto leave; } *domain++ = 0; domain_orig = domain; /* Let's check whether we already know that the domain does not * support WKD. */ if (is_wkd_query) { if (domaininfo_is_wkd_not_supported (domain_orig)) { err = gpg_error (GPG_ERR_NO_DATA); dirmngr_status_printf (ctrl, "NOTE", "wkd_cached_result %u", err); goto leave; } } /* First try the new "openpgp" subdomain. We check that the domain * is valid because it is later used as an unescaped filename part * of the URI. */ if (is_valid_domain_name (domain_orig)) { dns_addrinfo_t aibuf; domainbuf = strconcat ( "openpgpkey.", domain_orig, NULL); if (!domainbuf) { err = gpg_error_from_syserror (); goto leave; } /* FIXME: We should put a cache into dns-stuff because the same * query (with a different port and socket type, though) will be * done later by http function. */ err = resolve_dns_name (ctrl, domainbuf, 0, 0, 0, &aibuf, NULL); if (err) { err = 0; xfree (domainbuf); domainbuf = NULL; } else /* Got a subdomain. */ { free_dns_addrinfo (aibuf); subdomain_mode = 1; domain = domainbuf; } } /* Check for SRV records unless we have a subdomain. */ if (!subdomain_mode) { struct srventry *srvs; unsigned int srvscount; size_t domainlen, targetlen; int i; err = get_dns_srv (ctrl, domain, "openpgpkey", NULL, &srvs, &srvscount); if (err) goto leave; /* Check for rogue DNS names. */ for (i = 0; i < srvscount; i++) { if (!is_valid_domain_name (srvs[i].target)) { err = gpg_error (GPG_ERR_DNS_ADDRESS); log_error ("rogue openpgpkey SRV record for '%s'\n", domain); xfree (srvs); goto leave; } } /* Find the first target which also ends in DOMAIN or is equal * to DOMAIN. */ domainlen = strlen (domain); for (i = 0; i < srvscount; i++) { if (DBG_DNS) log_debug ("srv: trying '%s:%hu'\n", srvs[i].target, srvs[i].port); targetlen = strlen (srvs[i].target); if ((targetlen > domainlen + 1 && srvs[i].target[targetlen - domainlen - 1] == '.' && !ascii_strcasecmp (srvs[i].target + targetlen - domainlen, domain)) || (targetlen == domainlen && !ascii_strcasecmp (srvs[i].target, domain))) { /* found. */ domainbuf = xtrystrdup (srvs[i].target); if (!domainbuf) { err = gpg_error_from_syserror (); xfree (srvs); goto leave; } domain = domainbuf; if (srvs[i].port) snprintf (portstr, sizeof portstr, ":%hu", srvs[i].port); break; } } xfree (srvs); } /* Prepare the hash of the local part. */ gcry_md_hash_buffer (GCRY_MD_SHA1, sha1buf, mbox, strlen (mbox)); encodedhash = zb32_encode (sha1buf, 8*20); if (!encodedhash) { err = gpg_error_from_syserror (); goto leave; } if (opt_submission_addr) { uri = strconcat ("https://", domain, portstr, "/.well-known/openpgpkey/", subdomain_mode? domain_orig : "", subdomain_mode? "/" : "", "submission-address", NULL); } else if (opt_policy_flags) { uri = strconcat ("https://", domain, portstr, "/.well-known/openpgpkey/", subdomain_mode? domain_orig : "", subdomain_mode? "/" : "", "policy", NULL); } else { char *escapedmbox; escapedmbox = http_escape_string (mbox, "%;?&="); if (escapedmbox) { uri = strconcat ("https://", domain, portstr, "/.well-known/openpgpkey/", subdomain_mode? domain_orig : "", subdomain_mode? "/" : "", "hu/", encodedhash, "?l=", escapedmbox, NULL); xfree (escapedmbox); no_log = 1; if (uri) { err = dirmngr_status_printf (ctrl, "SOURCE", "https://%s%s", domain, portstr); if (err) goto leave; } } } if (!uri) { err = gpg_error_from_syserror (); goto leave; } /* Setup an output stream and perform the get. */ { estream_t outfp; outfp = ctx? es_fopencookie (ctx, "w", data_line_cookie_functions) : NULL; if (!outfp && ctx) err = set_error (GPG_ERR_ASS_GENERAL, "error setting up a data stream"); else { if (ctrl->server_local) { if (no_log) ctrl->server_local->inhibit_data_logging = 1; ctrl->server_local->inhibit_data_logging_now = 0; ctrl->server_local->inhibit_data_logging_count = 0; } err = ks_action_fetch (ctrl, uri, outfp); es_fclose (outfp); if (ctrl->server_local) ctrl->server_local->inhibit_data_logging = 0; /* Register the result under the domain name of MBOX. */ switch (gpg_err_code (err)) { case 0: domaininfo_set_wkd_supported (domain_orig); break; case GPG_ERR_NO_NAME: /* There is no such domain. */ domaininfo_set_no_name (domain_orig); break; case GPG_ERR_NO_DATA: if (is_wkd_query && ctrl->server_local) { /* Mark that and schedule a check. */ domaininfo_set_wkd_not_found (domain_orig); workqueue_add_task (task_check_wkd_support, domain_orig, ctrl->server_local->session_id, 1); } else if (opt_policy_flags) /* No policy file - no support. */ domaininfo_set_wkd_not_supported (domain_orig); break; default: /* Don't register other errors. */ break; } } } leave: xfree (uri); xfree (encodedhash); xfree (mbox); xfree (domainbuf); return err; } static const char hlp_wkd_get[] = "WKD_GET [--submission-address|--policy-flags] \n" "\n" "Return the key or other info for \n" "from the Web Key Directory."; static gpg_error_t cmd_wkd_get (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; err = proc_wkd_get (ctrl, ctx, line); return leave_cmd (ctx, err); } /* A task to check whether DOMAIN supports WKD. This is done by * checking whether the policy flags file can be read. */ static const char * task_check_wkd_support (ctrl_t ctrl, const char *domain) { char *string; if (!ctrl || !domain) return "check_wkd_support"; string = strconcat ("--policy-flags foo@", domain, NULL); if (!string) log_error ("%s: %s\n", __func__, gpg_strerror (gpg_error_from_syserror ())); else { proc_wkd_get (ctrl, NULL, string); xfree (string); } return NULL; } static const char hlp_ldapserver[] = "LDAPSERVER \n" "\n" "Add a new LDAP server to the list of configured LDAP servers.\n" - "DATA is in the same format as expected in the configure file."; + "DATA is in the same format as expected in the configure file.\n" + "An optional prefix \"ldap:\" is allowed."; static gpg_error_t cmd_ldapserver (assuan_context_t ctx, char *line) { #if USE_LDAP ctrl_t ctrl = assuan_get_pointer (ctx); ldap_server_t server; ldap_server_t *last_next_p; while (spacep (line)) line++; if (*line == '\0') return leave_cmd (ctx, PARM_ERROR (_("ldapserver missing"))); - server = ldapserver_parse_one (line, "", 0); + /* 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 (ldap_uri_p (item->uri)) - err = ldap_parse_uri (&item->parsed_uri, uri); + 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; }