diff --git a/dirmngr/Makefile.am b/dirmngr/Makefile.am index 00d3c4217..619115322 100644 --- a/dirmngr/Makefile.am +++ b/dirmngr/Makefile.am @@ -1,193 +1,201 @@ # Makefile.am - dirmngr # Copyright (C) 2002 Klarälvdalens Datakonsult AB # Copyright (C) 2004, 2007, 2010 g10 Code GmbH # # This file is part of GnuPG. # # GnuPG is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # GnuPG is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see . # # SPDX-License-Identifier: GPL-3.0+ ## Process this file with automake to produce Makefile.in EXTRA_DIST = OAUTHORS ONEWS ChangeLog-2011 tls-ca.pem \ dirmngr-w32info.rc dirmngr.w32-manifest.in dist_pkgdata_DATA = sks-keyservers.netCA.pem bin_PROGRAMS = dirmngr dirmngr-client if USE_LDAPWRAPPER libexec_PROGRAMS = dirmngr_ldap endif noinst_PROGRAMS = $(module_tests) $(module_net_tests) $(module_maint_tests) if DISABLE_TESTS TESTS = else TESTS = $(module_tests) $(module_net_tests) endif AM_CPPFLAGS = include $(top_srcdir)/am/cmacros.am AM_CFLAGS = $(USE_C99_CFLAGS) \ $(LIBGCRYPT_CFLAGS) $(KSBA_CFLAGS) $(LIBASSUAN_CFLAGS) \ $(GPG_ERROR_CFLAGS) $(NPTH_CFLAGS) $(NTBTLS_CFLAGS) \ $(LIBGNUTLS_CFLAGS) if HAVE_W32_SYSTEM ldap_url = ldap-url.h ldap-url.c else ldap_url = endif if USE_LDAPWRAPPER extraldap_src = ldap-wrapper.c else extraldap_src = ldap-wrapper-ce.c dirmngr_ldap.c endif noinst_HEADERS = dirmngr.h crlcache.h crlfetch.h misc.h dirmngr_SOURCES = dirmngr.c dirmngr.h server.c crlcache.c crlfetch.c \ certcache.c certcache.h \ domaininfo.c \ workqueue.c \ loadswdb.c \ cdb.h cdblib.c misc.c dirmngr-err.h dirmngr-status.h \ ocsp.c ocsp.h validate.c validate.h \ dns-stuff.c dns-stuff.h \ http.c http.h http-common.c http-common.h http-ntbtls.c \ ks-action.c ks-action.h ks-engine.h \ ks-engine-hkp.c ks-engine-http.c ks-engine-finger.c ks-engine-kdns.c if USE_LIBDNS dirmngr_SOURCES += dns.c dns.h endif if USE_LDAP dirmngr_SOURCES += ldapserver.h ldapserver.c ldap.c w32-ldap-help.h \ ldap-wrapper.h ldap-parse-uri.c ldap-parse-uri.h \ + ldap-misc.c ldap-misc.h \ ks-engine-ldap.c $(ldap_url) $(extraldap_src) ldaplibs = $(LDAPLIBS) else ldaplibs = endif if HAVE_W32_SYSTEM dirmngr_robjs = $(resource_objs) dirmngr-w32info.o dirmngr-w32info.o : dirmngr.w32-manifest else dirmngr_robjs = endif dirmngr_LDADD = $(libcommonpth) \ $(DNSLIBS) $(LIBASSUAN_LIBS) \ $(LIBGCRYPT_LIBS) $(KSBA_LIBS) $(NPTH_LIBS) \ $(NTBTLS_LIBS) $(LIBGNUTLS_LIBS) $(LIBINTL) $(LIBICONV) $(NETLIBS) \ $(dirmngr_robj) if USE_LDAP dirmngr_LDADD += $(ldaplibs) endif if !USE_LDAPWRAPPER dirmngr_LDADD += $(ldaplibs) endif dirmngr_LDFLAGS = $(extra_bin_ldflags) if USE_LDAPWRAPPER -dirmngr_ldap_SOURCES = dirmngr_ldap.c $(ldap_url) +dirmngr_ldap_SOURCES = dirmngr_ldap.c ldap-misc.c ldap-misc.h $(ldap_url) dirmngr_ldap_CFLAGS = $(GPG_ERROR_CFLAGS) $(LIBGCRYPT_CFLAGS) dirmngr_ldap_LDFLAGS = dirmngr_ldap_LDADD = $(libcommon) \ $(GPG_ERROR_LIBS) $(LIBGCRYPT_LIBS) $(LDAPLIBS) \ $(LBER_LIBS) $(LIBINTL) $(LIBICONV) $(NETLIBS) endif dirmngr_client_SOURCES = dirmngr-client.c dirmngr_client_LDADD = $(libcommon) \ $(LIBASSUAN_LIBS) $(GPG_ERROR_LIBS) \ $(LIBGCRYPT_LIBS) $(NETLIBS) $(LIBINTL) $(LIBICONV) dirmngr_client_LDFLAGS = $(extra_bin_ldflags) t_common_src = t-support.h t-support.c if USE_LIBDNS t_common_src += dns.c dns.h endif t_common_ldadd = $(libcommon) $(LIBASSUAN_LIBS) $(LIBGCRYPT_LIBS) \ $(GPG_ERROR_LIBS) $(NETLIBS) \ $(NTBTLS_LIBS) $(LIBGNUTLS_LIBS) \ $(DNSLIBS) $(LIBINTL) $(LIBICONV) module_tests = t-http-basic if USE_LDAP -module_tests += t-ldap-parse-uri +module_tests += t-ldap-parse-uri t-ldap-misc endif # Test which need a network connections are only used in maintainer mode. if MAINTAINER_MODE module_net_tests = t-dns-stuff else module_net_tests = endif # Tests which are only for manually testing are only build in maintainer-mode. if MAINTAINER_MODE module_maint_tests = t-http else module_maint_tests = endif # http tests # We need to add the KSBA flags in case we are building against GNUTLS. # In that case NTBTLS flags are empty, but we need ksba anyway. t_http_SOURCES = $(t_common_src) t-http.c http.c dns-stuff.c http-common.c t_http_CFLAGS = -DWITHOUT_NPTH=1 $(USE_C99_CFLAGS) \ $(LIBGCRYPT_CFLAGS) $(NTBTLS_CFLAGS) $(LIBGNUTLS_CFLAGS) \ $(LIBASSUAN_CFLAGS) $(GPG_ERROR_CFLAGS) $(KSBA_CFLAGS) t_http_LDADD = $(t_common_ldadd) \ $(NTBTLS_LIBS) $(KSBA_LIBS) $(LIBGNUTLS_LIBS) $(DNSLIBS) t_http_basic_SOURCES = $(t_common_src) t-http-basic.c http.c \ dns-stuff.c http-common.c t_http_basic_CFLAGS = -DWITHOUT_NPTH=1 $(USE_C99_CFLAGS) \ $(LIBGCRYPT_CFLAGS) $(NTBTLS_CFLAGS) $(LIBGNUTLS_CFLAGS) \ $(LIBASSUAN_CFLAGS) $(GPG_ERROR_CFLAGS) $(KSBA_CFLAGS) t_http_basic_LDADD = $(t_common_ldadd) \ $(NTBTLS_LIBS) $(KSBA_LIBS) $(LIBGNUTLS_LIBS) $(DNSLIBS) - t_ldap_parse_uri_SOURCES = \ t-ldap-parse-uri.c ldap-parse-uri.c ldap-parse-uri.h \ - http.c http-common.c dns-stuff.c \ + http.c http-common.c dns-stuff.c ldap-misc.c \ $(ldap_url) $(t_common_src) t_ldap_parse_uri_CFLAGS = -DWITHOUT_NPTH=1 $(USE_C99_CFLAGS) \ $(LIBGCRYPT_CFLAGS) \ $(LIBASSUAN_CFLAGS) $(GPG_ERROR_CFLAGS) t_ldap_parse_uri_LDADD = $(ldaplibs) $(t_common_ldadd) $(DNSLIBS) +t_ldap_misc_SOURCES = t-ldap-misc.c ldap-misc.c ldap-misc.h $(ldap_url) +t_ldap_misc_CFLAGS = -DWITHOUT_NPTH=1 $(GPG_ERROR_CFLAGS) $(LIBGCRYPT_CFLAGS) +t_ldap_misc_LDFLAGS = +t_ldap_misc_LDADD = $(libcommon) \ + $(GPG_ERROR_LIBS) $(LIBGCRYPT_LIBS) $(LDAPLIBS) \ + $(LBER_LIBS) $(LIBINTL) $(LIBICONV) $(NETLIBS) + + t_dns_stuff_CFLAGS = -DWITHOUT_NPTH=1 $(USE_C99_CFLAGS) \ $(LIBGCRYPT_CFLAGS) \ $(LIBASSUAN_CFLAGS) $(GPG_ERROR_CFLAGS) t_dns_stuff_SOURCES = $(t_common_src) t-dns-stuff.c dns-stuff.c t_dns_stuff_LDADD = $(t_common_ldadd) $(DNSLIBS) $(PROGRAMS) : $(libcommon) $(libcommonpth) diff --git a/dirmngr/crlfetch.c b/dirmngr/crlfetch.c index c8091f6f6..e355aab16 100644 --- a/dirmngr/crlfetch.c +++ b/dirmngr/crlfetch.c @@ -1,589 +1,589 @@ /* crlfetch.c - LDAP access * Copyright (C) 2002 Klarälvdalens Datakonsult AB * Copyright (C) 2003, 2004, 2005, 2006, 2007 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 . */ #include #include #include #include #include "crlfetch.h" #include "dirmngr.h" #include "misc.h" #include "http.h" #include "ks-engine.h" /* For ks_http_fetch. */ #if USE_LDAP # include "ldap-wrapper.h" #endif /* For detecting armored CRLs received via HTTP (yes, such CRLS really exits, e.g. http://grid.fzk.de/ca/gridka-crl.pem at least in June 2008) we need a context in the reader callback. */ struct reader_cb_context_s { estream_t fp; /* The stream used with the ksba reader. */ int checked:1; /* PEM/binary detection ahs been done. */ int is_pem:1; /* The file stream is PEM encoded. */ struct b64state b64state; /* The state used for Base64 decoding. */ }; /* We need to associate a reader object with the reader callback context. This table is used for it. */ struct file_reader_map_s { ksba_reader_t reader; struct reader_cb_context_s *cb_ctx; }; #define MAX_FILE_READER 50 static struct file_reader_map_s file_reader_map[MAX_FILE_READER]; /* Associate FP with READER. If the table is full wait until another thread has removed an entry. */ static void register_file_reader (ksba_reader_t reader, struct reader_cb_context_s *cb_ctx) { int i; for (;;) { for (i=0; i < MAX_FILE_READER; i++) if (!file_reader_map[i].reader) { file_reader_map[i].reader = reader; file_reader_map[i].cb_ctx = cb_ctx; return; } log_info (_("reader to file mapping table full - waiting\n")); npth_sleep (2); } } /* Scan the table for an entry matching READER, remove that entry and return the associated file pointer. */ static struct reader_cb_context_s * get_file_reader (ksba_reader_t reader) { struct reader_cb_context_s *cb_ctx = NULL; int i; for (i=0; i < MAX_FILE_READER; i++) if (file_reader_map[i].reader == reader) { cb_ctx = file_reader_map[i].cb_ctx; file_reader_map[i].reader = NULL; file_reader_map[i].cb_ctx = NULL; break; } return cb_ctx; } static int my_es_read (void *opaque, char *buffer, size_t nbytes, size_t *nread) { struct reader_cb_context_s *cb_ctx = opaque; int result; result = es_read (cb_ctx->fp, buffer, nbytes, nread); if (result) return result; /* Fixme we should check whether the semantics of es_read are okay and well defined. I have some doubts. */ if (nbytes && !*nread && es_feof (cb_ctx->fp)) return gpg_error (GPG_ERR_EOF); if (!nread && es_ferror (cb_ctx->fp)) return gpg_error (GPG_ERR_EIO); if (!cb_ctx->checked && *nread) { int c = *(unsigned char *)buffer; cb_ctx->checked = 1; if ( ((c & 0xc0) >> 6) == 0 /* class: universal */ && (c & 0x1f) == 16 /* sequence */ && (c & 0x20) /* is constructed */ ) ; /* Binary data. */ else { cb_ctx->is_pem = 1; b64dec_start (&cb_ctx->b64state, ""); } } if (cb_ctx->is_pem && *nread) { size_t nread2; if (b64dec_proc (&cb_ctx->b64state, buffer, *nread, &nread2)) { /* EOF from decoder. */ *nread = 0; result = gpg_error (GPG_ERR_EOF); } else *nread = nread2; } return result; } /* Fetch CRL from URL and return the entire CRL using new ksba reader object in READER. Note that this reader object should be closed only using ldap_close_reader. */ gpg_error_t crl_fetch (ctrl_t ctrl, const char *url, ksba_reader_t *reader) { gpg_error_t err; parsed_uri_t uri; estream_t httpfp = NULL; *reader = NULL; if (!url) return gpg_error (GPG_ERR_INV_ARG); err = http_parse_uri (&uri, url, 0); http_release_parsed_uri (uri); if (!err) /* Yes, our HTTP code groks that. */ { if (opt.disable_http) { log_error (_("CRL access not possible due to disabled %s\n"), "HTTP"); err = gpg_error (GPG_ERR_NOT_SUPPORTED); } else { /* Note that we also allow root certificates loaded from * "/etc/gnupg/trusted-certs/". We also do not consult the * CRL for the TLS connection - that may lead to a loop. * Due to cacert.org redirecting their https URL to http we * also allow such a downgrade. */ err = ks_http_fetch (ctrl, url, (KS_HTTP_FETCH_TRUST_CFG | KS_HTTP_FETCH_NO_CRL | KS_HTTP_FETCH_ALLOW_DOWNGRADE ), &httpfp); } if (err) log_error (_("error retrieving '%s': %s\n"), url, gpg_strerror (err)); else { struct reader_cb_context_s *cb_ctx; cb_ctx = xtrycalloc (1, sizeof *cb_ctx); if (!cb_ctx) err = gpg_error_from_syserror (); else if (!(err = ksba_reader_new (reader))) { cb_ctx->fp = httpfp; err = ksba_reader_set_cb (*reader, &my_es_read, cb_ctx); if (!err) { /* The ksba reader misses a user pointer thus we * need to come up with our own way of associating a * file pointer (or well the callback context) with * the reader. It is only required when closing the * reader thus there is no performance issue doing * it this way. FIXME: We now have a close * notification which might be used here. */ register_file_reader (*reader, cb_ctx); httpfp = NULL; } } if (err) { log_error (_("error initializing reader object: %s\n"), gpg_strerror (err)); ksba_reader_release (*reader); *reader = NULL; xfree (cb_ctx); } } } else /* Let the LDAP code parse other schemes. */ { if (opt.disable_ldap) { log_error (_("CRL access not possible due to disabled %s\n"), "LDAP"); err = gpg_error (GPG_ERR_NOT_SUPPORTED); } else if (dirmngr_use_tor ()) { /* For now we do not support LDAP over Tor. */ log_error (_("CRL access not possible due to Tor mode\n")); err = gpg_error (GPG_ERR_NOT_SUPPORTED); } else { # if USE_LDAP - err = url_fetch_ldap (ctrl, url, NULL, 0, reader); + err = url_fetch_ldap (ctrl, url, reader); # else /*!USE_LDAP*/ err = gpg_error (GPG_ERR_NOT_IMPLEMENTED); # endif /*!USE_LDAP*/ } } es_fclose (httpfp); return err; } /* Fetch CRL for ISSUER using a default server. Return the entire CRL as a newly opened stream returned in R_FP. */ gpg_error_t crl_fetch_default (ctrl_t ctrl, const char *issuer, ksba_reader_t *reader) { if (dirmngr_use_tor ()) { /* For now we do not support LDAP over Tor. */ log_error (_("CRL access not possible due to Tor mode\n")); return gpg_error (GPG_ERR_NOT_SUPPORTED); } if (opt.disable_ldap) { log_error (_("CRL access not possible due to disabled %s\n"), "LDAP"); return gpg_error (GPG_ERR_NOT_SUPPORTED); } #if USE_LDAP return attr_fetch_ldap (ctrl, issuer, "certificateRevocationList", reader); #else (void)ctrl; (void)issuer; (void)reader; return gpg_error (GPG_ERR_NOT_IMPLEMENTED); #endif } /* Fetch a CA certificate for DN using the default server. This * function only initiates the fetch; fetch_next_cert must be used to * actually read the certificate; end_cert_fetch to end the * operation. */ gpg_error_t ca_cert_fetch (ctrl_t ctrl, cert_fetch_context_t *context, const char *dn) { if (dirmngr_use_tor ()) { /* For now we do not support LDAP over Tor. */ log_error (_("CRL access not possible due to Tor mode\n")); return gpg_error (GPG_ERR_NOT_SUPPORTED); } if (opt.disable_ldap) { log_error (_("CRL access not possible due to disabled %s\n"), "LDAP"); return gpg_error (GPG_ERR_NOT_SUPPORTED); } #if USE_LDAP return start_cacert_fetch_ldap (ctrl, context, dn); #else (void)ctrl; (void)context; (void)dn; return gpg_error (GPG_ERR_NOT_IMPLEMENTED); #endif } gpg_error_t start_cert_fetch (ctrl_t ctrl, cert_fetch_context_t *context, strlist_t patterns, const ldap_server_t server) { if (dirmngr_use_tor ()) { /* For now we do not support LDAP over Tor. */ log_error (_("CRL access not possible due to Tor mode\n")); return gpg_error (GPG_ERR_NOT_SUPPORTED); } if (opt.disable_ldap) { log_error (_("certificate search not possible due to disabled %s\n"), "LDAP"); return gpg_error (GPG_ERR_NOT_SUPPORTED); } #if USE_LDAP return start_cert_fetch_ldap (ctrl, context, patterns, server); #else (void)ctrl; (void)context; (void)patterns; (void)server; return gpg_error (GPG_ERR_NOT_IMPLEMENTED); #endif } gpg_error_t fetch_next_cert (cert_fetch_context_t context, unsigned char **value, size_t * valuelen) { #if USE_LDAP return fetch_next_cert_ldap (context, value, valuelen); #else (void)context; (void)value; (void)valuelen; return gpg_error (GPG_ERR_NOT_IMPLEMENTED); #endif } /* Fetch the next data from CONTEXT, assuming it is a certificate and return * it as a cert object in R_CERT. */ gpg_error_t fetch_next_ksba_cert (cert_fetch_context_t context, ksba_cert_t *r_cert) { gpg_error_t err; unsigned char *value; size_t valuelen; ksba_cert_t cert; *r_cert = NULL; #if USE_LDAP err = fetch_next_cert_ldap (context, &value, &valuelen); if (!err && !value) err = gpg_error (GPG_ERR_BUG); #else (void)context; err = gpg_error (GPG_ERR_NOT_IMPLEMENTED); #endif if (err) return err; err = ksba_cert_new (&cert); if (err) { xfree (value); return err; } err = ksba_cert_init_from_mem (cert, value, valuelen); xfree (value); if (err) { ksba_cert_release (cert); return err; } *r_cert = cert; return 0; } void end_cert_fetch (cert_fetch_context_t context) { #if USE_LDAP end_cert_fetch_ldap (context); #else (void)context; #endif } /* Read a certificate from an HTTP URL and return it as an estream * memory buffer at R_FP. */ static gpg_error_t read_cert_via_http (ctrl_t ctrl, const char *url, estream_t *r_fp) { gpg_error_t err; estream_t fp = NULL; estream_t httpfp = NULL; size_t nread, nwritten; char buffer[1024]; if ((err = ks_http_fetch (ctrl, url, KS_HTTP_FETCH_TRUST_CFG, &httpfp))) goto leave; /* We now read the data from the web server into a memory buffer. * To DOS we limit the certificate length to 32k. */ fp = es_fopenmem (32*1024, "rw"); if (!fp) { err = gpg_error_from_syserror (); log_error ("error allocating memory buffer: %s\n", gpg_strerror (err)); goto leave; } for (;;) { if (es_read (httpfp, buffer, sizeof buffer, &nread)) { err = gpg_error_from_syserror (); log_error ("error reading '%s': %s\n", es_fname_get (httpfp), gpg_strerror (err)); goto leave; } if (!nread) break; /* Ready. */ if (es_write (fp, buffer, nread, &nwritten)) { err = gpg_error_from_syserror (); log_error ("error writing '%s': %s\n", es_fname_get (fp), gpg_strerror (err)); goto leave; } else if (nread != nwritten) { err = gpg_error (GPG_ERR_EIO); log_error ("error writing '%s': %s\n", es_fname_get (fp), "short write"); goto leave; } } es_rewind (fp); *r_fp = fp; fp = NULL; leave: es_fclose (httpfp); es_fclose (fp); return err; } /* Lookup a cert by it's URL. */ gpg_error_t fetch_cert_by_url (ctrl_t ctrl, const char *url, unsigned char **value, size_t *valuelen) { const unsigned char *cert_image = NULL; size_t cert_image_n; ksba_reader_t reader = NULL; ksba_cert_t cert = NULL; gpg_error_t err; *value = NULL; *valuelen = 0; err = ksba_cert_new (&cert); if (err) goto leave; if (url && (!strncmp (url, "http:", 5) || !strncmp (url, "https:", 6))) { estream_t stream; void *der; size_t derlen; err = read_cert_via_http (ctrl, url, &stream); if (err) goto leave; if (es_fclose_snatch (stream, &der, &derlen)) { err = gpg_error_from_syserror (); goto leave; } err = ksba_cert_init_from_mem (cert, der, derlen); xfree (der); if (err) goto leave; } else /* Assume LDAP. */ { #if USE_LDAP - err = url_fetch_ldap (ctrl, url, NULL, 0, &reader); + err = url_fetch_ldap (ctrl, url, &reader); #else (void)ctrl; (void)url; err = gpg_error (GPG_ERR_NOT_IMPLEMENTED); #endif /*USE_LDAP*/ if (err) goto leave; err = ksba_cert_read_der (cert, reader); if (err) goto leave; } cert_image = ksba_cert_get_image (cert, &cert_image_n); if (!cert_image || !cert_image_n) { err = gpg_error (GPG_ERR_INV_CERT_OBJ); goto leave; } *value = xtrymalloc (cert_image_n); if (!*value) { err = gpg_error_from_syserror (); goto leave; } memcpy (*value, cert_image, cert_image_n); *valuelen = cert_image_n; leave: ksba_cert_release (cert); #if USE_LDAP ldap_wrapper_release_context (reader); #endif /*USE_LDAP*/ return err; } /* This function is to be used to close the reader object. In addition to running ksba_reader_release it also releases the LDAP or HTTP contexts associated with that reader. */ void crl_close_reader (ksba_reader_t reader) { struct reader_cb_context_s *cb_ctx; if (!reader) return; /* Check whether this is a HTTP one. */ cb_ctx = get_file_reader (reader); if (cb_ctx) { /* This is an HTTP context. */ if (cb_ctx->fp) es_fclose (cb_ctx->fp); /* Release the base64 decoder state. */ if (cb_ctx->is_pem) b64dec_finish (&cb_ctx->b64state); /* Release the callback context. */ xfree (cb_ctx); } else /* This is an ldap wrapper context (Currently not used). */ { #if USE_LDAP ldap_wrapper_release_context (reader); #endif /*USE_LDAP*/ } /* Now get rid of the reader object. */ ksba_reader_release (reader); } diff --git a/dirmngr/crlfetch.h b/dirmngr/crlfetch.h index 3822adb54..f30965301 100644 --- a/dirmngr/crlfetch.h +++ b/dirmngr/crlfetch.h @@ -1,88 +1,87 @@ /* crlfetch.h - LDAP access * Copyright (C) 2002 Klarälvdalens Datakonsult AB * * 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 CRLFETCH_H #define CRLFETCH_H #include "dirmngr.h" struct cert_fetch_context_s; typedef struct cert_fetch_context_s *cert_fetch_context_t; /* Fetch CRL from URL. */ gpg_error_t crl_fetch (ctrl_t ctrl, const char* url, ksba_reader_t *reader); /* Fetch CRL for ISSUER using default server. */ gpg_error_t crl_fetch_default (ctrl_t ctrl, const char* issuer, ksba_reader_t *reader); /* Fetch cert for DN. */ gpg_error_t ca_cert_fetch (ctrl_t ctrl, cert_fetch_context_t *context, const char *dn); /* Query the server for certs matching patterns. */ gpg_error_t start_cert_fetch (ctrl_t ctrl, cert_fetch_context_t *context, strlist_t patterns, const ldap_server_t server); gpg_error_t fetch_next_cert(cert_fetch_context_t context, unsigned char **value, size_t *valuelen); gpg_error_t fetch_next_ksba_cert (cert_fetch_context_t context, ksba_cert_t *r_cert); void end_cert_fetch (cert_fetch_context_t context); /* Lookup a cert by it's URL. */ gpg_error_t fetch_cert_by_url (ctrl_t ctrl, const char *url, unsigned char **value, size_t *valuelen); /* Close a reader object. */ void crl_close_reader (ksba_reader_t reader); /*-- ldap.c --*/ gpg_error_t url_fetch_ldap (ctrl_t ctrl, - const char *url, const char *host, int port, - ksba_reader_t *reader); + const char *url, ksba_reader_t *reader); gpg_error_t attr_fetch_ldap (ctrl_t ctrl, const char *dn, const char *attr, ksba_reader_t *reader); gpg_error_t start_cacert_fetch_ldap (ctrl_t ctrl, cert_fetch_context_t *context, const char *dn); gpg_error_t start_cert_fetch_ldap( ctrl_t ctrl, cert_fetch_context_t *context, strlist_t patterns, const ldap_server_t server ); gpg_error_t fetch_next_cert_ldap (cert_fetch_context_t context, unsigned char **value, size_t *valuelen ); void end_cert_fetch_ldap (cert_fetch_context_t context); #endif /* CRLFETCH_H */ diff --git a/dirmngr/dirmngr_ldap.c b/dirmngr/dirmngr_ldap.c index 804959008..43265c8c1 100644 --- a/dirmngr/dirmngr_ldap.c +++ b/dirmngr/dirmngr_ldap.c @@ -1,775 +1,833 @@ /* dirmngr-ldap.c - The LDAP helper for dirmngr. - * Copyright (C) 2004 g10 Code GmbH + * Copyright (C) 2004, 2021 g10 Code GmbH * Copyright (C) 2010 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . * SPDX-License-Identifier: GPL-3.0-or-later */ #include #include #include #include #include #include #ifdef HAVE_SIGNAL_H # include #endif #include #include #include -#ifndef USE_LDAPWRAPPER -# include -#endif #ifdef HAVE_W32_SYSTEM # include # include # include # include # include "ldap-url.h" #else /* For OpenLDAP, to enable the API that we're using. */ # define LDAP_DEPRECATED 1 # include #endif #include #include "../common/logging.h" #include "../common/argparse.h" #include "../common/stringhelp.h" #include "../common/mischelp.h" #include "../common/strlist.h" - -#include "../common/i18n.h" #include "../common/util.h" #include "../common/init.h" +#include "ldap-misc.h" + -/* With the ldap wrapper, there is no need for the npth_unprotect and leave - functions; thus we redefine them to nops. If we are not using the - ldap wrapper process we need to include the prototype for our - module's main function. */ -#ifdef USE_LDAPWRAPPER +/* There is no need for the npth_unprotect and leave functions here; + * thus we redefine them to nops. We keep them in the code just for + * the case we ever want to reuse parts of the code in npth programs. */ static void npth_unprotect (void) { } static void npth_protect (void) { } -#else -# include "./ldap-wrapper.h" -#endif -#ifdef HAVE_W32CE_SYSTEM -# include "w32-ldap-help.h" -# define my_ldap_init(a,b) \ - _dirmngr_ldap_init ((a), (b)) -# define my_ldap_simple_bind_s(a,b,c) \ - _dirmngr_ldap_simple_bind_s ((a),(b),(c)) -# define my_ldap_search_st(a,b,c,d,e,f,g,h) \ - _dirmngr_ldap_search_st ((a), (b), (c), (d), (e), (f), (g), (h)) -# define my_ldap_first_attribute(a,b,c) \ - _dirmngr_ldap_first_attribute ((a),(b),(c)) -# define my_ldap_next_attribute(a,b,c) \ - _dirmngr_ldap_next_attribute ((a),(b),(c)) -# define my_ldap_get_values_len(a,b,c) \ - _dirmngr_ldap_get_values_len ((a),(b),(c)) -# define my_ldap_free_attr(a) \ - xfree ((a)) -#else -# define my_ldap_init(a,b) ldap_init ((a), (b)) -# define my_ldap_simple_bind_s(a,b,c) ldap_simple_bind_s ((a), (b), (c)) -# define my_ldap_search_st(a,b,c,d,e,f,g,h) \ - ldap_search_st ((a), (b), (c), (d), (e), (f), (g), (h)) -# define my_ldap_first_attribute(a,b,c) ldap_first_attribute ((a),(b),(c)) -# define my_ldap_next_attribute(a,b,c) ldap_next_attribute ((a),(b),(c)) -# define my_ldap_get_values_len(a,b,c) ldap_get_values_len ((a),(b),(c)) -# define my_ldap_free_attr(a) ldap_memfree ((a)) -#endif #ifdef HAVE_W32_SYSTEM typedef LDAP_TIMEVAL my_ldap_timeval_t; #else typedef struct timeval my_ldap_timeval_t; #endif #define DEFAULT_LDAP_TIMEOUT 15 /* Arbitrary long timeout. */ /* Constants for the options. */ enum { oQuiet = 'q', oVerbose = 'v', oTimeout = 500, oMulti, oProxy, oHost, oPort, oUser, oPass, oEnvPass, - oDN, - oFilter, + oBase, oAttr, + oStartTLS, + oLdapTLS, + oNtds, oOnlySearchTimeout, oLogWithPID }; /* The list of options as used by the argparse.c code. */ static ARGPARSE_OPTS opts[] = { - { oVerbose, "verbose", 0, N_("verbose") }, - { oQuiet, "quiet", 0, N_("be somewhat more quiet") }, - { oTimeout, "timeout", 1, N_("|N|set LDAP timeout to N seconds")}, - { oMulti, "multi", 0, N_("return all values in" - " a record oriented format")}, + { oVerbose, "verbose", 0, "verbose" }, + { oQuiet, "quiet", 0, "be somewhat more quiet" }, + { oTimeout, "timeout", 1, "|N|set LDAP timeout to N seconds"}, + { oMulti, "multi", 0, "return all values in" + " a record oriented format"}, { oProxy, "proxy", 2, - N_("|NAME|ignore host part and connect through NAME")}, - { oHost, "host", 2, N_("|NAME|connect to host NAME")}, - { oPort, "port", 1, N_("|N|connect to port N")}, - { oUser, "user", 2, N_("|NAME|use user NAME for authentication")}, - { oPass, "pass", 2, N_("|PASS|use password PASS" - " for authentication")}, - { oEnvPass, "env-pass", 0, N_("take password from $DIRMNGR_LDAP_PASS")}, - { oDN, "dn", 2, N_("|STRING|query DN STRING")}, - { oFilter, "filter", 2, N_("|STRING|use STRING as filter expression")}, - { oAttr, "attr", 2, N_("|STRING|return the attribute STRING")}, + "|NAME|ignore host part and connect through NAME"}, + { oStartTLS, "starttls", 0, "use STARTLS for the conenction"}, + { oLdapTLS, "ldaptls", 0, "use a TLS for the connection"}, + { oNtds, "ntds", 0, "authenticate using AD"}, + { oHost, "host", 2, "|NAME|connect to host NAME"}, + { oPort, "port", 1, "|N|connect to port N"}, + { oUser, "user", 2, "|NAME|use NAME for authentication"}, + { oPass, "pass", 2, "|PASS|use password PASS" + " for authentication"}, + { oEnvPass, "env-pass", 0, "take password from $DIRMNGR_LDAP_PASS"}, + { oBase, "base", 2, "|DN|Start query at DN"}, + { oAttr, "attr", 2, "|STRING|return the attribute STRING"}, { oOnlySearchTimeout, "only-search-timeout", 0, "@"}, { oLogWithPID,"log-with-pid", 0, "@"}, ARGPARSE_end () }; -/* A structure with module options. This is not a static variable - because if we are not build as a standalone binary, each thread - using this module needs to handle its own values. */ -struct my_opt_s +/* A structure with module options. */ +static struct { int quiet; int verbose; my_ldap_timeval_t timeout;/* Timeout for the LDAP search functions. */ unsigned int alarm_timeout; /* And for the alarm based timeout. */ int multi; + int starttls; + int ldaptls; + int ntds; estream_t outstream; /* Send output to this stream. */ /* Note that we can't use const for the strings because ldap_* are not defined that way. */ char *proxy; /* Host and Port override. */ char *user; /* Authentication user. */ char *pass; /* Authentication password. */ char *host; /* Override host. */ - int port; /* Override port. */ - char *dn; /* Override DN. */ - char *filter;/* Override filter. */ + int port; /* Override port. */ + char *base; /* Override DN. */ char *attr; /* Override attribute. */ -}; -typedef struct my_opt_s *my_opt_t; +} opt; /* Prototypes. */ #ifndef HAVE_W32_SYSTEM static void catch_alarm (int dummy); #endif -static int process_url (my_opt_t myopt, const char *url); +static gpg_error_t connect_ldap (LDAP **r_ld); +static gpg_error_t process_filter (LDAP *ld, const char *string); /* Function called by argparse.c to display information. */ -#ifdef USE_LDAPWRAPPER static const char * my_strusage (int level) { const char *p; switch(level) { case 9: p = "GPL-3.0-or-later"; break; case 11: p = "dirmngr_ldap (@GNUPG@)"; break; case 13: p = VERSION; break; case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break; case 17: p = PRINTABLE_OS_NAME; break; - case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break; + case 19: p = "Please report bugs to <@EMAIL@>.\n"; break; case 49: p = PACKAGE_BUGREPORT; break; case 1: case 40: p = - _("Usage: dirmngr_ldap [options] [URL] (-h for help)\n"); + "Usage: dirmngr_ldap [options] filters (-h for help)\n"; break; case 41: p = - _("Syntax: dirmngr_ldap [options] [URL]\n" + ("Syntax: dirmngr_ldap [options] filters\n" "Internal LDAP helper for Dirmngr\n" "Interface and options may change without notice\n"); break; default: p = NULL; } return p; } -#endif /*!USE_LDAPWRAPPER*/ int -#ifdef USE_LDAPWRAPPER main (int argc, char **argv) -#else -ldap_wrapper_main (char **argv, estream_t outstream) -#endif { -#ifndef USE_LDAPWRAPPER - int argc; -#endif ARGPARSE_ARGS pargs; int any_err = 0; char *p; int only_search_timeout = 0; - struct my_opt_s my_opt_buffer; - my_opt_t myopt = &my_opt_buffer; char *malloced_buffer1 = NULL; - - memset (&my_opt_buffer, 0, sizeof my_opt_buffer); + LDAP *ld; early_system_init (); -#ifdef USE_LDAPWRAPPER set_strusage (my_strusage); log_set_prefix ("dirmngr_ldap", GPGRT_LOG_WITH_PREFIX); - /* Setup I18N and common subsystems. */ - i18n_init(); - init_common_subsystems (&argc, &argv); es_set_binary (es_stdout); - myopt->outstream = es_stdout; -#else /*!USE_LDAPWRAPPER*/ - myopt->outstream = outstream; - for (argc=0; argv[argc]; argc++) - ; -#endif /*!USE_LDAPWRAPPER*/ + opt.outstream = es_stdout; /* LDAP defaults */ - myopt->timeout.tv_sec = DEFAULT_LDAP_TIMEOUT; - myopt->timeout.tv_usec = 0; - myopt->alarm_timeout = 0; + opt.timeout.tv_sec = DEFAULT_LDAP_TIMEOUT; + opt.timeout.tv_usec = 0; + opt.alarm_timeout = 0; /* Parse the command line. */ pargs.argc = &argc; pargs.argv = &argv; pargs.flags= ARGPARSE_FLAG_KEEP; while (gnupg_argparse (NULL, &pargs, opts)) { switch (pargs.r_opt) { - case oVerbose: myopt->verbose++; break; - case oQuiet: myopt->quiet++; break; + case oVerbose: opt.verbose++; break; + case oQuiet: opt.quiet++; break; case oTimeout: - myopt->timeout.tv_sec = pargs.r.ret_int; - myopt->timeout.tv_usec = 0; - myopt->alarm_timeout = pargs.r.ret_int; + opt.timeout.tv_sec = pargs.r.ret_int; + opt.timeout.tv_usec = 0; + opt.alarm_timeout = pargs.r.ret_int; break; case oOnlySearchTimeout: only_search_timeout = 1; break; - case oMulti: myopt->multi = 1; break; - case oUser: myopt->user = pargs.r.ret_str; break; - case oPass: myopt->pass = pargs.r.ret_str; break; + case oStartTLS: opt.starttls = 1; opt.ldaptls = 0; break; + case oLdapTLS: opt.starttls = 0; opt.ldaptls = 1; break; + case oNtds: opt.ntds = 1; break; + case oMulti: opt.multi = 1; break; + case oUser: opt.user = pargs.r.ret_str; break; + case oPass: opt.pass = pargs.r.ret_str; break; case oEnvPass: - myopt->pass = getenv ("DIRMNGR_LDAP_PASS"); + opt.pass = getenv ("DIRMNGR_LDAP_PASS"); break; - case oProxy: myopt->proxy = pargs.r.ret_str; break; - case oHost: myopt->host = pargs.r.ret_str; break; - case oPort: myopt->port = pargs.r.ret_int; break; - case oDN: myopt->dn = pargs.r.ret_str; break; - case oFilter: myopt->filter = pargs.r.ret_str; break; - case oAttr: myopt->attr = pargs.r.ret_str; break; + case oProxy: opt.proxy = pargs.r.ret_str; break; + case oHost: opt.host = pargs.r.ret_str; break; + case oPort: opt.port = pargs.r.ret_int; break; + case oBase: opt.base = pargs.r.ret_str; break; + case oAttr: opt.attr = pargs.r.ret_str; break; case oLogWithPID: { unsigned int oldflags; log_get_prefix (&oldflags); log_set_prefix (NULL, oldflags | GPGRT_LOG_WITH_PID); } break; default : -#ifdef USE_LDAPWRAPPER pargs.err = ARGPARSE_PRINT_ERROR; -#else - pargs.err = ARGPARSE_PRINT_WARNING; /* No exit() please. */ -#endif break; } } gnupg_argparse (NULL, &pargs, NULL); /* Release internal state. */ if (only_search_timeout) - myopt->alarm_timeout = 0; + opt.alarm_timeout = 0; - if (myopt->proxy) + if (opt.proxy) { - malloced_buffer1 = xtrystrdup (myopt->proxy); + malloced_buffer1 = xtrystrdup (opt.proxy); if (!malloced_buffer1) { log_error ("error copying string: %s\n", strerror (errno)); return 1; } - myopt->host = malloced_buffer1; - p = strchr (myopt->host, ':'); + opt.host = malloced_buffer1; + p = strchr (opt.host, ':'); if (p) { *p++ = 0; - myopt->port = atoi (p); + opt.port = atoi (p); } - if (!myopt->port) - myopt->port = 389; /* make sure ports gets overridden. */ + if (!opt.port) + opt.port = 389; /* make sure ports gets overridden. */ } - if (myopt->port < 0 || myopt->port > 65535) - log_error (_("invalid port number %d\n"), myopt->port); + if (opt.port < 0 || opt.port > 65535) + log_error ("invalid port number %d\n", opt.port); + + if (!opt.port) + opt.port = opt.ldaptls? 636 : 389; + +#ifndef HAVE_W32_SYSTEM + if (!opt.host) + opt.host = "localhost"; +#endif + -#ifdef USE_LDAPWRAPPER if (log_get_errorcount (0)) exit (2); if (argc < 1) usage (1); -#else - /* All passed arguments should be fine in this case. */ - log_assert (argc); -#endif -#ifdef USE_LDAPWRAPPER - if (myopt->alarm_timeout) + if (opt.alarm_timeout) { #ifndef HAVE_W32_SYSTEM # if defined(HAVE_SIGACTION) && defined(HAVE_STRUCT_SIGACTION) struct sigaction act; act.sa_handler = catch_alarm; sigemptyset (&act.sa_mask); act.sa_flags = 0; if (sigaction (SIGALRM,&act,NULL)) # else if (signal (SIGALRM, catch_alarm) == SIG_ERR) # endif log_fatal ("unable to register timeout handler\n"); #endif } -#endif /*USE_LDAPWRAPPER*/ - for (; argc; argc--, argv++) - if (process_url (myopt, *argv)) - any_err = 1; + if (connect_ldap (&ld)) + any_err = 1; + else + { + for (; argc; argc--, argv++) + if (process_filter (ld, *argv)) + any_err = 1; + ldap_unbind (ld); + } xfree (malloced_buffer1); return any_err; } #ifndef HAVE_W32_SYSTEM static void catch_alarm (int dummy) { (void)dummy; _exit (10); } #endif #ifdef HAVE_W32_SYSTEM static DWORD CALLBACK alarm_thread (void *arg) { HANDLE timer = arg; WaitForSingleObject (timer, INFINITE); _exit (10); return 0; } #endif static void -set_timeout (my_opt_t myopt) +set_timeout (void) { - if (myopt->alarm_timeout) + if (opt.alarm_timeout) { #ifdef HAVE_W32_SYSTEM static HANDLE timer; LARGE_INTEGER due_time; /* A negative value is a relative time. */ - due_time.QuadPart = (unsigned long long)-10000000 * myopt->alarm_timeout; + due_time.QuadPart = (unsigned long long)-10000000 * opt.alarm_timeout; if (!timer) { SECURITY_ATTRIBUTES sec_attr; DWORD tid; memset (&sec_attr, 0, sizeof sec_attr); sec_attr.nLength = sizeof sec_attr; sec_attr.bInheritHandle = FALSE; /* Create a manual resetable timer. */ timer = CreateWaitableTimer (NULL, TRUE, NULL); - /* Intially set the timer. */ + /* Initially set the timer. */ SetWaitableTimer (timer, &due_time, 0, NULL, NULL, 0); if (CreateThread (&sec_attr, 0, alarm_thread, timer, 0, &tid)) log_error ("failed to create alarm thread\n"); } else /* Retrigger the timer. */ SetWaitableTimer (timer, &due_time, 0, NULL, NULL, 0); #else - alarm (myopt->alarm_timeout); + alarm (opt.alarm_timeout); #endif } } + +/* Connect to the ldap server. On success the connection handle is + * stored at R_LD. */ +static gpg_error_t +connect_ldap (LDAP **r_ld) +{ + gpg_error_t err = 0; + int lerr; + LDAP *ld = NULL; +#ifndef HAVE_W32_SYSTEM + char *tmpstr; +#endif + + *r_ld = NULL; + + if (opt.starttls || opt.ldaptls) + { +#ifndef HAVE_LDAP_START_TLS_S + log_error ("ldap: can't connect to the server: no TLS support."); + err = GPG_ERR_LDAP_NOT_SUPPORTED; + goto leave; +#endif + } + + + set_timeout (); +#ifdef HAVE_W32_SYSTEM + npth_unprotect (); + ld = ldap_sslinit (opt.host, opt.port, opt.ldaptls); + npth_protect (); + if (!ld) + { + lerr = LdapGetLastError (); + err = ldap_err_to_gpg_err (lerr); + log_error ("error initializing LDAP '%s:%d': %s\n", + opt.host, opt.port, ldap_err2string (lerr)); + goto leave; + } +#else /* Unix */ + tmpstr = xtryasprintf ("%s://%s:%d", + opt.ldaptls? "ldaps" : "ldap", + opt.host, opt.port); + if (!tmpstr) + { + err = gpg_error_from_syserror (); + goto leave; + } + npth_unprotect (); + lerr = ldap_initialize (&ld, tmpstr); + npth_protect (); + if (lerr || !ld) + { + err = ldap_err_to_gpg_err (lerr); + log_error ("error initializing LDAP '%s': %s\n", + tmpstr, ldap_err2string (lerr)); + xfree (tmpstr); + goto leave; + } + xfree (tmpstr); +#endif /* Unix */ + + if (opt.verbose) + log_info ("LDAP connected to '%s:%d'%s\n", + opt.host, opt.port, + opt.starttls? " using STARTTLS" : + opt.ldaptls? " using LDAP-over-TLS" : ""); + + +#ifdef HAVE_LDAP_SET_OPTION + { + int ver = LDAP_VERSION3; + + lerr = ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &ver); + if (lerr != LDAP_SUCCESS) + { + log_error ("unable to go to LDAP 3: %s\n", ldap_err2string (lerr)); + err = ldap_err_to_gpg_err (lerr); + goto leave; + } + } +#endif + + +#ifdef HAVE_LDAP_START_TLS_S + if (opt.starttls) + { +#ifndef HAVE_W32_SYSTEM + int check_cert = LDAP_OPT_X_TLS_HARD; /* LDAP_OPT_X_TLS_NEVER */ + + lerr = ldap_set_option (ld, LDAP_OPT_X_TLS_REQUIRE_CERT, &check_cert); + if (lerr) + { + log_error ("ldap: error setting an TLS option: %s\n", + ldap_err2string (lerr)); + err = ldap_err_to_gpg_err (lerr); + goto leave; + } +#else + /* On Windows, the certificates are checked by default. If the + option to disable checking mentioned above is ever + implemented, the way to do that on Windows is to install a + callback routine using ldap_set_option (.., + LDAP_OPT_SERVER_CERTIFICATE, ..); */ +#endif + + npth_unprotect (); + lerr = ldap_start_tls_s (ld, +#ifdef HAVE_W32_SYSTEM + /* ServerReturnValue, result */ + NULL, NULL, +#endif + /* ServerControls, ClientControls */ + NULL, NULL); + npth_protect (); + if (lerr) + { + log_error ("ldap: error switching to STARTTLS mode: %s\n", + ldap_err2string (lerr)); + err = ldap_err_to_gpg_err (lerr); + goto leave; + } + } +#endif + + if (opt.ntds) + { + if (opt.verbose) + log_info ("binding to current user via AD\n"); +#ifdef HAVE_W32_SYSTEM + npth_unprotect (); + lerr = ldap_bind_s (ld, NULL, NULL, LDAP_AUTH_NEGOTIATE); + npth_protect (); + if (lerr != LDAP_SUCCESS) + { + log_error ("error binding to LDAP via AD: %s\n", + ldap_err2string (lerr)); + err = ldap_err_to_gpg_err (lerr); + goto leave; + } +#else /* Unix */ + err = gpg_error (GPG_ERR_NOT_SUPPORTED); + goto leave; +#endif /* Unix */ + } + else if (opt.user) + { + if (opt.verbose) + log_info ("LDAP bind to '%s', password '%s'\n", + opt.user, opt.pass ? ">not_shown<" : ">none<"); + + npth_unprotect (); + lerr = ldap_simple_bind_s (ld, opt.user, opt.pass); + npth_protect (); + if (lerr != LDAP_SUCCESS) + { + log_error ("error binding to LDAP: %s\n", ldap_err2string (lerr)); + err = ldap_err_to_gpg_err (lerr); + goto leave; + } + } + else + { + /* By default we don't bind as there is usually no need to. */ + } + + leave: + if (err) + { + if (ld) + ldap_unbind (ld); + } + else + *r_ld = ld; + return err; +} + + /* Helper for fetch_ldap(). */ static int -print_ldap_entries (my_opt_t myopt, LDAP *ld, LDAPMessage *msg, char *want_attr) +print_ldap_entries (LDAP *ld, LDAPMessage *msg, char *want_attr) { LDAPMessage *item; int any = 0; for (npth_unprotect (), item = ldap_first_entry (ld, msg), npth_protect (); item; npth_unprotect (), item = ldap_next_entry (ld, item), npth_protect ()) { BerElement *berctx; char *attr; - if (myopt->verbose > 1) - log_info (_("scanning result for attribute '%s'\n"), + if (opt.verbose > 1) + log_info ("scanning result for attribute '%s'\n", want_attr? want_attr : "[all]"); - if (myopt->multi) + if (opt.multi) { /* Write item marker. */ - if (es_fwrite ("I\0\0\0\0", 5, 1, myopt->outstream) != 1) + if (es_fwrite ("I\0\0\0\0", 5, 1, opt.outstream) != 1) { - log_error (_("error writing to stdout: %s\n"), + log_error ("error writing to stdout: %s\n", strerror (errno)); return -1; } } - for (npth_unprotect (), attr = my_ldap_first_attribute (ld, item, &berctx), + for (npth_unprotect (), attr = ldap_first_attribute (ld, item, &berctx), npth_protect (); attr; - npth_unprotect (), attr = my_ldap_next_attribute (ld, item, berctx), + npth_unprotect (), attr = ldap_next_attribute (ld, item, berctx), npth_protect ()) { struct berval **values; int idx; - if (myopt->verbose > 1) - log_info (_(" available attribute '%s'\n"), attr); + if (opt.verbose > 1) + log_info (" available attribute '%s'\n", attr); - set_timeout (myopt); + set_timeout (); /* I case we want only one attribute we do a case insensitive compare without the optional extension (i.e. ";binary"). Case insensitive is not really correct but the best we can do. */ if (want_attr) { char *cp1, *cp2; int cmpres; cp1 = strchr (want_attr, ';'); if (cp1) *cp1 = 0; cp2 = strchr (attr, ';'); if (cp2) *cp2 = 0; cmpres = ascii_strcasecmp (want_attr, attr); if (cp1) *cp1 = ';'; if (cp2) *cp2 = ';'; if (cmpres) { - my_ldap_free_attr (attr); + ldap_memfree (attr); continue; /* Not found: Try next attribute. */ } } npth_unprotect (); - values = my_ldap_get_values_len (ld, item, attr); + values = ldap_get_values_len (ld, item, attr); npth_protect (); if (!values) { - if (myopt->verbose) - log_info (_("attribute '%s' not found\n"), attr); - my_ldap_free_attr (attr); + if (opt.verbose) + log_info ("attribute '%s' not found\n", attr); + ldap_memfree (attr); continue; } - if (myopt->verbose) + if (opt.verbose) { - log_info (_("found attribute '%s'\n"), attr); - if (myopt->verbose > 1) + log_info ("found attribute '%s'\n", attr); + if (opt.verbose > 1) for (idx=0; values[idx]; idx++) log_info (" length[%d]=%d\n", idx, (int)values[0]->bv_len); } - if (myopt->multi) + if (opt.multi) { /* Write attribute marker. */ unsigned char tmp[5]; size_t n = strlen (attr); tmp[0] = 'A'; tmp[1] = (n >> 24); tmp[2] = (n >> 16); tmp[3] = (n >> 8); tmp[4] = (n); - if (es_fwrite (tmp, 5, 1, myopt->outstream) != 1 - || es_fwrite (attr, n, 1, myopt->outstream) != 1) + if (es_fwrite (tmp, 5, 1, opt.outstream) != 1 + || es_fwrite (attr, n, 1, opt.outstream) != 1) { - log_error (_("error writing to stdout: %s\n"), + log_error ("error writing to stdout: %s\n", strerror (errno)); ldap_value_free_len (values); - my_ldap_free_attr (attr); + ldap_memfree (attr); ber_free (berctx, 0); return -1; } } for (idx=0; values[idx]; idx++) { - if (myopt->multi) + if (opt.multi) { /* Write value marker. */ unsigned char tmp[5]; size_t n = values[0]->bv_len; tmp[0] = 'V'; tmp[1] = (n >> 24); tmp[2] = (n >> 16); tmp[3] = (n >> 8); tmp[4] = (n); - if (es_fwrite (tmp, 5, 1, myopt->outstream) != 1) + if (es_fwrite (tmp, 5, 1, opt.outstream) != 1) { - log_error (_("error writing to stdout: %s\n"), + log_error ("error writing to stdout: %s\n", strerror (errno)); ldap_value_free_len (values); - my_ldap_free_attr (attr); + ldap_memfree (attr); ber_free (berctx, 0); return -1; } } if (es_fwrite (values[0]->bv_val, values[0]->bv_len, - 1, myopt->outstream) != 1) + 1, opt.outstream) != 1) { - log_error (_("error writing to stdout: %s\n"), + log_error ("error writing to stdout: %s\n", strerror (errno)); ldap_value_free_len (values); - my_ldap_free_attr (attr); + ldap_memfree (attr); ber_free (berctx, 0); return -1; } any = 1; - if (!myopt->multi) + if (!opt.multi) break; /* Print only the first value. */ } ldap_value_free_len (values); - my_ldap_free_attr (attr); - if (want_attr || !myopt->multi) + ldap_memfree (attr); + if (want_attr || !opt.multi) break; /* We only want to return the first attribute. */ } ber_free (berctx, 0); } - if (myopt->verbose > 1 && any) + if (opt.verbose > 1 && any) log_info ("result has been printed\n"); return any?0:-1; } -/* Helper for the URL based LDAP query. */ +/* Fetch data from the server at LD using FILTER. */ static int -fetch_ldap (my_opt_t myopt, const char *url, const LDAPURLDesc *ludp) +fetch_ldap (LDAP *ld, const char *base, int scope, const char *filter) { - LDAP *ld; + gpg_error_t err; + int lerr; LDAPMessage *msg; - int rc = 0; - char *host, *dn, *filter, *attrs[2], *attr; - int port; - int ret; - - host = myopt->host? myopt->host : ludp->lud_host; - port = myopt->port? myopt->port : ludp->lud_port; - dn = myopt->dn? myopt->dn : ludp->lud_dn; - filter = myopt->filter? myopt->filter : ludp->lud_filter; - attrs[0] = myopt->attr? myopt->attr : ludp->lud_attrs? ludp->lud_attrs[0]:NULL; - attrs[1] = NULL; - attr = attrs[0]; + char *attrs[2]; - if (!port) - port = (ludp->lud_scheme && !strcmp (ludp->lud_scheme, "ldaps"))? 636:389; + if (filter && !*filter) + filter = NULL; - if (myopt->verbose) + if (opt.verbose) { - log_info (_("processing url '%s'\n"), url); - if (myopt->user) - log_info (_(" user '%s'\n"), myopt->user); - if (myopt->pass) - log_info (_(" pass '%s'\n"), *myopt->pass?"*****":""); - if (host) - log_info (_(" host '%s'\n"), host); - log_info (_(" port %d\n"), port); - if (dn) - log_info (_(" DN '%s'\n"), dn); + log_info ("fetching using"); + if (base) + log_printf (" base '%s'", base); if (filter) - log_info (_(" filter '%s'\n"), filter); - if (myopt->multi && !myopt->attr && ludp->lud_attrs) - { - int i; - for (i=0; ludp->lud_attrs[i]; i++) - log_info (_(" attr '%s'\n"), ludp->lud_attrs[i]); - } - else if (attr) - log_info (_(" attr '%s'\n"), attr); - } - - - if (!host || !*host) - { - log_error (_("no host name in '%s'\n"), url); - return -1; - } - if (!myopt->multi && !attr) - { - log_error (_("no attribute given for query '%s'\n"), url); - return -1; + log_printf (" filter '%s'", filter); + log_printf ("\n"); } - if (!myopt->multi && !myopt->attr - && ludp->lud_attrs && ludp->lud_attrs[0] && ludp->lud_attrs[1]) - log_info (_("WARNING: using first attribute only\n")); - - - set_timeout (myopt); - npth_unprotect (); - ld = my_ldap_init (host, port); - npth_protect (); - if (!ld) - { - log_error (_("LDAP init to '%s:%d' failed: %s\n"), - host, port, strerror (errno)); - return -1; - } - npth_unprotect (); - /* Fixme: Can we use MYOPT->user or is it shared with other theeads?. */ - ret = my_ldap_simple_bind_s (ld, myopt->user, myopt->pass); - npth_protect (); -#ifdef LDAP_VERSION3 - if (ret == LDAP_PROTOCOL_ERROR) - { - /* Protocol error could mean that the server only supports v3. */ - int version = LDAP_VERSION3; - if (myopt->verbose) - log_info ("protocol error; retrying bind with v3 protocol\n"); - npth_unprotect (); - ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &version); - ret = my_ldap_simple_bind_s (ld, myopt->user, myopt->pass); - npth_protect (); - } -#endif - if (ret) - { - log_error (_("binding to '%s:%d' failed: %s\n"), - host, port, ldap_err2string (ret)); - ldap_unbind (ld); - return -1; - } + attrs[0] = opt.attr; + attrs[1] = NULL; - set_timeout (myopt); + set_timeout (); npth_unprotect (); - rc = my_ldap_search_st (ld, dn, ludp->lud_scope, filter, - myopt->multi && !myopt->attr && ludp->lud_attrs? - ludp->lud_attrs:attrs, - 0, - &myopt->timeout, &msg); + lerr = ldap_search_st (ld, base, scope, filter, + attrs, + 0, + &opt.timeout, &msg); npth_protect (); - if (rc == LDAP_SIZELIMIT_EXCEEDED && myopt->multi) + if (lerr == LDAP_SIZELIMIT_EXCEEDED && opt.multi) { - if (es_fwrite ("E\0\0\0\x09truncated", 14, 1, myopt->outstream) != 1) + if (es_fwrite ("E\0\0\0\x09truncated", 14, 1, opt.outstream) != 1) { - log_error (_("error writing to stdout: %s\n"), strerror (errno)); + log_error ("error writing to stdout: %s\n", strerror (errno)); return -1; } } - else if (rc) + else if (lerr) { -#ifdef HAVE_W32CE_SYSTEM - log_error ("searching '%s' failed: %d\n", url, rc); -#else - log_error (_("searching '%s' failed: %s\n"), - url, ldap_err2string (rc)); -#endif - if (rc != LDAP_NO_SUCH_OBJECT) + log_error ("searching '%s' failed: %s\n", + filter, ldap_err2string (lerr)); + if (lerr != LDAP_NO_SUCH_OBJECT) { /* FIXME: Need deinit (ld)? */ /* Hmmm: Do we need to released MSG in case of an error? */ return -1; } } - rc = print_ldap_entries (myopt, ld, msg, myopt->multi? NULL:attr); + err = print_ldap_entries (ld, msg, opt.multi? NULL:opt.attr); ldap_msgfree (msg); - ldap_unbind (ld); - return rc; + return err; } -/* Main processing. Take the URL and run the LDAP query. The result - is printed to stdout, errors are logged to the log stream. */ -static int -process_url (my_opt_t myopt, const char *url) +/* Main processing. Take the filter and run the LDAP query. The + * result is printed to stdout, errors are logged to the log stream. + * To allow searching with a different base it is possible to extend + * the filer. For example: + * + * ^CN=foo, OU=My Users&(objectClasses=*) + * + * Uses "CN=foo, OU=My Users" as base DN and "(objectClasses=*)" as + * filter. If the base prefix includes an ampersand, it needs to be + * doubled. The usual escaping rules for DNs (for the base) and + * filters apply. If no scope is given (see ldap_parse_extfilter for + * the syntax) subtree scope is used. + */ +static gpg_error_t +process_filter (LDAP *ld, const char *string) { - int rc; - LDAPURLDesc *ludp = NULL; - - - if (!ldap_is_ldap_url (url)) - { - log_error (_("'%s' is not an LDAP URL\n"), url); - return -1; - } - - if (ldap_url_parse (url, &ludp)) - { - log_error (_("'%s' is an invalid LDAP URL\n"), url); - return -1; - } - - rc = fetch_ldap (myopt, url, ludp); - - ldap_free_urldesc (ludp); - return rc; + gpg_error_t err; + char *base, *filter; + int scope = -1; + + err = ldap_parse_extfilter (string, 0, &base, &scope, &filter); + if (!err) + err = fetch_ldap (ld, + base? base : opt.base, + scope == -1? LDAP_SCOPE_SUBTREE : scope, + filter); + + xfree (base); + xfree (filter); + return err; } diff --git a/dirmngr/ks-engine-ldap.c b/dirmngr/ks-engine-ldap.c index af67a5de9..afc7f56ed 100644 --- a/dirmngr/ks-engine-ldap.c +++ b/dirmngr/ks-engine-ldap.c @@ -1,2376 +1,2198 @@ /* 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-misc.h" #include "ldap-parse-uri.h" #include "ldapserver.h" /* Flags with infos from the connected server. */ #define SERVERINFO_REALLDAP 1 /* This is not the PGP keyserver. */ #define SERVERINFO_PGPKEYV2 2 /* Needs "pgpeyV2" instead of "pgpKey" */ #define SERVERINFO_SCHEMAV2 4 /* Version 2 of the Schema. */ #define SERVERINFO_NTDS 8 /* Server is an Active Directory. */ - #ifndef HAVE_TIMEGM time_t timegm(struct tm *tm); -#endif - -/* Convert an LDAP error to a GPG error. */ -static int -ldap_err_to_gpg_err (int code) -{ - gpg_err_code_t ec; - - switch (code) - { -#ifdef LDAP_X_CONNECTING - case LDAP_X_CONNECTING: ec = GPG_ERR_LDAP_X_CONNECTING; break; -#endif - - case LDAP_REFERRAL_LIMIT_EXCEEDED: ec = GPG_ERR_LDAP_REFERRAL_LIMIT; break; - case LDAP_CLIENT_LOOP: ec = GPG_ERR_LDAP_CLIENT_LOOP; break; - case LDAP_NO_RESULTS_RETURNED: ec = GPG_ERR_LDAP_NO_RESULTS; break; - case LDAP_CONTROL_NOT_FOUND: ec = GPG_ERR_LDAP_CONTROL_NOT_FOUND; break; - case LDAP_NOT_SUPPORTED: ec = GPG_ERR_LDAP_NOT_SUPPORTED; break; - case LDAP_CONNECT_ERROR: ec = GPG_ERR_LDAP_CONNECT; break; - case LDAP_NO_MEMORY: ec = GPG_ERR_LDAP_NO_MEMORY; break; - case LDAP_PARAM_ERROR: ec = GPG_ERR_LDAP_PARAM; break; - case LDAP_USER_CANCELLED: ec = GPG_ERR_LDAP_USER_CANCELLED; break; - case LDAP_FILTER_ERROR: ec = GPG_ERR_LDAP_FILTER; break; - case LDAP_AUTH_UNKNOWN: ec = GPG_ERR_LDAP_AUTH_UNKNOWN; break; - case LDAP_TIMEOUT: ec = GPG_ERR_LDAP_TIMEOUT; break; - case LDAP_DECODING_ERROR: ec = GPG_ERR_LDAP_DECODING; break; - case LDAP_ENCODING_ERROR: ec = GPG_ERR_LDAP_ENCODING; break; - case LDAP_LOCAL_ERROR: ec = GPG_ERR_LDAP_LOCAL; break; - case LDAP_SERVER_DOWN: ec = GPG_ERR_LDAP_SERVER_DOWN; break; - - case LDAP_SUCCESS: ec = GPG_ERR_LDAP_SUCCESS; break; - - case LDAP_OPERATIONS_ERROR: ec = GPG_ERR_LDAP_OPERATIONS; break; - case LDAP_PROTOCOL_ERROR: ec = GPG_ERR_LDAP_PROTOCOL; break; - case LDAP_TIMELIMIT_EXCEEDED: ec = GPG_ERR_LDAP_TIMELIMIT; break; - case LDAP_SIZELIMIT_EXCEEDED: ec = GPG_ERR_LDAP_SIZELIMIT; break; - case LDAP_COMPARE_FALSE: ec = GPG_ERR_LDAP_COMPARE_FALSE; break; - case LDAP_COMPARE_TRUE: ec = GPG_ERR_LDAP_COMPARE_TRUE; break; - case LDAP_AUTH_METHOD_NOT_SUPPORTED: ec=GPG_ERR_LDAP_UNSUPPORTED_AUTH;break; - case LDAP_STRONG_AUTH_REQUIRED: ec = GPG_ERR_LDAP_STRONG_AUTH_RQRD; break; - case LDAP_PARTIAL_RESULTS: ec = GPG_ERR_LDAP_PARTIAL_RESULTS; break; - case LDAP_REFERRAL: ec = GPG_ERR_LDAP_REFERRAL; break; - -#ifdef LDAP_ADMINLIMIT_EXCEEDED - case LDAP_ADMINLIMIT_EXCEEDED: ec = GPG_ERR_LDAP_ADMINLIMIT; break; -#endif - -#ifdef LDAP_UNAVAILABLE_CRITICAL_EXTENSION - case LDAP_UNAVAILABLE_CRITICAL_EXTENSION: - ec = GPG_ERR_LDAP_UNAVAIL_CRIT_EXTN; break; #endif - case LDAP_CONFIDENTIALITY_REQUIRED: ec = GPG_ERR_LDAP_CONFIDENT_RQRD; break; - case LDAP_SASL_BIND_IN_PROGRESS: ec = GPG_ERR_LDAP_SASL_BIND_INPROG; break; - case LDAP_NO_SUCH_ATTRIBUTE: ec = GPG_ERR_LDAP_NO_SUCH_ATTRIBUTE; break; - case LDAP_UNDEFINED_TYPE: ec = GPG_ERR_LDAP_UNDEFINED_TYPE; break; - case LDAP_INAPPROPRIATE_MATCHING: ec = GPG_ERR_LDAP_BAD_MATCHING; break; - case LDAP_CONSTRAINT_VIOLATION: ec = GPG_ERR_LDAP_CONST_VIOLATION; break; - -#ifdef LDAP_TYPE_OR_VALUE_EXISTS - case LDAP_TYPE_OR_VALUE_EXISTS: ec = GPG_ERR_LDAP_TYPE_VALUE_EXISTS; break; -#endif - - case LDAP_INVALID_SYNTAX: ec = GPG_ERR_LDAP_INV_SYNTAX; break; - case LDAP_NO_SUCH_OBJECT: ec = GPG_ERR_LDAP_NO_SUCH_OBJ; break; - case LDAP_ALIAS_PROBLEM: ec = GPG_ERR_LDAP_ALIAS_PROBLEM; break; - case LDAP_INVALID_DN_SYNTAX: ec = GPG_ERR_LDAP_INV_DN_SYNTAX; break; - case LDAP_IS_LEAF: ec = GPG_ERR_LDAP_IS_LEAF; break; - case LDAP_ALIAS_DEREF_PROBLEM: ec = GPG_ERR_LDAP_ALIAS_DEREF; break; - -#ifdef LDAP_X_PROXY_AUTHZ_FAILURE - case LDAP_X_PROXY_AUTHZ_FAILURE: ec = GPG_ERR_LDAP_X_PROXY_AUTH_FAIL; break; -#endif - - case LDAP_INAPPROPRIATE_AUTH: ec = GPG_ERR_LDAP_BAD_AUTH; break; - case LDAP_INVALID_CREDENTIALS: ec = GPG_ERR_LDAP_INV_CREDENTIALS; break; - -#ifdef LDAP_INSUFFICIENT_ACCESS - case LDAP_INSUFFICIENT_ACCESS: ec = GPG_ERR_LDAP_INSUFFICIENT_ACC; break; -#endif - - case LDAP_BUSY: ec = GPG_ERR_LDAP_BUSY; break; - case LDAP_UNAVAILABLE: ec = GPG_ERR_LDAP_UNAVAILABLE; break; - case LDAP_UNWILLING_TO_PERFORM: ec = GPG_ERR_LDAP_UNWILL_TO_PERFORM; break; - case LDAP_LOOP_DETECT: ec = GPG_ERR_LDAP_LOOP_DETECT; break; - case LDAP_NAMING_VIOLATION: ec = GPG_ERR_LDAP_NAMING_VIOLATION; break; - case LDAP_OBJECT_CLASS_VIOLATION: ec = GPG_ERR_LDAP_OBJ_CLS_VIOLATION; break; - case LDAP_NOT_ALLOWED_ON_NONLEAF: ec=GPG_ERR_LDAP_NOT_ALLOW_NONLEAF;break; - case LDAP_NOT_ALLOWED_ON_RDN: ec = GPG_ERR_LDAP_NOT_ALLOW_ON_RDN; break; - case LDAP_ALREADY_EXISTS: ec = GPG_ERR_LDAP_ALREADY_EXISTS; break; - case LDAP_NO_OBJECT_CLASS_MODS: ec = GPG_ERR_LDAP_NO_OBJ_CLASS_MODS; break; - case LDAP_RESULTS_TOO_LARGE: ec = GPG_ERR_LDAP_RESULTS_TOO_LARGE; break; - case LDAP_AFFECTS_MULTIPLE_DSAS: ec = GPG_ERR_LDAP_AFFECTS_MULT_DSAS; break; - -#ifdef LDAP_VLV_ERROR - case LDAP_VLV_ERROR: ec = GPG_ERR_LDAP_VLV; break; -#endif - - case LDAP_OTHER: ec = GPG_ERR_LDAP_OTHER; break; - -#ifdef LDAP_CUP_RESOURCES_EXHAUSTED - case LDAP_CUP_RESOURCES_EXHAUSTED: ec=GPG_ERR_LDAP_CUP_RESOURCE_LIMIT;break; - case LDAP_CUP_SECURITY_VIOLATION: ec=GPG_ERR_LDAP_CUP_SEC_VIOLATION; break; - case LDAP_CUP_INVALID_DATA: ec = GPG_ERR_LDAP_CUP_INV_DATA; break; - case LDAP_CUP_UNSUPPORTED_SCHEME: ec = GPG_ERR_LDAP_CUP_UNSUP_SCHEME; break; - case LDAP_CUP_RELOAD_REQUIRED: ec = GPG_ERR_LDAP_CUP_RELOAD; break; -#endif -#ifdef LDAP_CANCELLED - case LDAP_CANCELLED: ec = GPG_ERR_LDAP_CANCELLED; break; -#endif - -#ifdef LDAP_NO_SUCH_OPERATION - case LDAP_NO_SUCH_OPERATION: ec = GPG_ERR_LDAP_NO_SUCH_OPERATION; break; -#endif - -#ifdef LDAP_TOO_LATE - case LDAP_TOO_LATE: ec = GPG_ERR_LDAP_TOO_LATE; break; -#endif - -#ifdef LDAP_CANNOT_CANCEL - case LDAP_CANNOT_CANCEL: ec = GPG_ERR_LDAP_CANNOT_CANCEL; break; -#endif - -#ifdef LDAP_ASSERTION_FAILED - case LDAP_ASSERTION_FAILED: ec = GPG_ERR_LDAP_ASSERTION_FAILED; break; -#endif - -#ifdef LDAP_PROXIED_AUTHORIZATION_DENIED - case LDAP_PROXIED_AUTHORIZATION_DENIED: - ec = GPG_ERR_LDAP_PROX_AUTH_DENIED; break; -#endif - - default: -#if defined(LDAP_E_ERROR) && defined(LDAP_X_ERROR) - if (LDAP_E_ERROR (code)) - ec = GPG_ERR_LDAP_E_GENERAL; - else if (LDAP_X_ERROR (code)) - ec = GPG_ERR_LDAP_X_GENERAL; - else -#endif - ec = GPG_ERR_LDAP_GENERAL; - break; - } - - return ec; -} - -/* Retrieve an LDAP error and return it's GPG equivalent. */ -static int -ldap_to_gpg_err (LDAP *ld) -{ -#if defined(HAVE_LDAP_GET_OPTION) && defined(LDAP_OPT_ERROR_NUMBER) - int err; - - if (ldap_get_option (ld, LDAP_OPT_ERROR_NUMBER, &err) == 0) - return ldap_err_to_gpg_err (err); - else - return GPG_ERR_GENERAL; -#elif defined(HAVE_LDAP_LD_ERRNO) - return ldap_err_to_gpg_err (ld->ld_errno); -#else - /* We should never get here since the LDAP library should always - have either ldap_get_option or ld_errno, but just in case... */ - return GPG_ERR_INTERNAL; -#endif -} static time_t ldap2epochtime (const char *timestr) { struct tm pgptime; time_t answer; memset (&pgptime, 0, sizeof(pgptime)); /* YYYYMMDDHHmmssZ */ sscanf (timestr, "%4d%2d%2d%2d%2d%2d", &pgptime.tm_year, &pgptime.tm_mon, &pgptime.tm_mday, &pgptime.tm_hour, &pgptime.tm_min, &pgptime.tm_sec); pgptime.tm_year -= 1900; pgptime.tm_isdst = -1; pgptime.tm_mon--; /* mktime() takes the timezone into account, so we use timegm() */ answer = timegm (&pgptime); return answer; } /* Caller must free the result. */ static char * tm2ldaptime (struct tm *tm) { struct tm tmp = *tm; char buf[16]; /* YYYYMMDDHHmmssZ */ tmp.tm_year += 1900; tmp.tm_mon ++; snprintf (buf, sizeof buf, "%04d%02d%02d%02d%02d%02dZ", tmp.tm_year, tmp.tm_mon, tmp.tm_mday, tmp.tm_hour, tmp.tm_min, tmp.tm_sec); return xstrdup (buf); } #if 0 /* Caller must free */ static char * epoch2ldaptime (time_t stamp) { struct tm tm; if (gmtime_r (&stamp, &tm)) return tm2ldaptime (&tm); else return xstrdup ("INVALID TIME"); } #endif static void my_ldap_value_free (char **vals) { if (vals) ldap_value_free (vals); } /* Print a help output for the schemata supported by this module. */ gpg_error_t ks_ldap_help (ctrl_t ctrl, parsed_uri_t uri) { const char data[] = "Handler for LDAP URLs:\n" " ldap://HOST:PORT/[BASEDN]????[bindname=BINDNAME,password=PASSWORD]\n" "\n" "Note: basedn, bindname and password need to be percent escaped. In\n" "particular, spaces need to be replaced with %20 and commas with %2c.\n" "Thus bindname will typically be of the form:\n" "\n" " uid=user%2cou=PGP%20Users%2cdc=EXAMPLE%2cdc=ORG\n" "\n" "The ldaps:// and ldapi:// schemes are also supported. If ldaps is used\n" "then the server's certificate will be checked. If it is not valid, any\n" "operation will be aborted. Note that ldaps means LDAP with STARTTLS\n" "\n" "As an alternative to an URL a string in this form may be used:\n" "\n" " HOST:PORT:BINDNAME:PASSWORD:BASEDN:FLAGS:\n" "\n" "The use of the percent sign or a colon in one of the string values is\n" "currently not supported.\n" "\n" "Supported methods: search, get, put\n"; gpg_error_t err; if(!uri) err = ks_print_help (ctrl, " ldap"); else if (!strcmp (uri->scheme, "ldap") || !strcmp (uri->scheme, "ldaps") || !strcmp (uri->scheme, "ldapi") || 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_FPR16: case KEYDB_SEARCH_MODE_FPR20: case KEYDB_SEARCH_MODE_FPR: if ((serverinfo & SERVERINFO_SCHEMAV2)) { freeme = bin2hex (desc.u.fpr, 20, NULL); if (!freeme) return gpg_error_from_syserror (); f = xasprintf ("(|(gpgFingerprint=%s)(gpgSubFingerprint=%s))", freeme, freeme); /* FIXME: For an exact search and in case of a match on * gpgSubFingerprint we need to check that there is only one * matching value. */ } break; case KEYDB_SEARCH_MODE_ISSUER: case KEYDB_SEARCH_MODE_ISSUER_SN: case KEYDB_SEARCH_MODE_SN: case KEYDB_SEARCH_MODE_SUBJECT: case KEYDB_SEARCH_MODE_KEYGRIP: case KEYDB_SEARCH_MODE_WORDS: case KEYDB_SEARCH_MODE_FIRST: case KEYDB_SEARCH_MODE_NEXT: default: break; } xfree (freeme); if (! f) { log_error ("Unsupported search mode.\n"); return gpg_error (GPG_ERR_NOT_SUPPORTED); } *filter = f; return 0; } /* Connect to an LDAP server and interrogate it. - uri describes the server to connect to and various options including whether to use TLS and the username and password (see ldap_parse_uri for a description of the various fields). This function returns: - The ldap connection handle in *LDAP_CONNP. - The base DN for the PGP key space by querying the pgpBaseKeySpaceDN attribute (This is normally 'ou=PGP Keys,dc=EXAMPLE,dc=ORG'). - The attribute to lookup to find the pgp key. This is either 'pgpKey' or 'pgpKeyV2'. - Whether this is a real ldap server. (It's unclear what this exactly means.) The values are returned in the passed variables. If you pass NULL, then the value won't be returned. It is the caller's responsibility to release *LDAP_CONNP with ldap_unbind and xfree *BASEDNP. If this function successfully interrogated the server, it returns 0. If there was an LDAP error, it returns the LDAP error code. If an error occurred, *basednp, etc., are undefined (and don't need to be freed.) R_SERVERINFO receives information about the server. If no LDAP error occurred, you still need to check that *basednp is valid. If it is NULL, then the server does not appear to be an OpenPGP Keyserver. */ static gpg_error_t my_ldap_connect (parsed_uri_t uri, LDAP **ldap_connp, char **r_basedn, char **r_host, int *r_use_tls, unsigned int *r_serverinfo) { gpg_error_t err = 0; int lerr; ldap_server_t server = NULL; LDAP *ldap_conn = NULL; char *basedn = NULL; char *host = NULL; /* Host to use. */ int port; /* Port to use. */ int use_tls; /* 1 = starttls, 2 = ldap-over-tls */ int use_ntds; /* Use Active Directory authentication. */ const char *bindname; const char *password; const char *basedn_arg; #ifndef HAVE_W32_SYSTEM char *tmpstr; #endif if (r_basedn) *r_basedn = NULL; if (r_host) *r_host = NULL; if (r_use_tls) *r_use_tls = 0; *r_serverinfo = 0; if (uri->opaque) { server = ldapserver_parse_one (uri->path, NULL, 0); if (!server) return gpg_error (GPG_ERR_LDAP_OTHER); host = server->host; port = server->port; bindname = server->user; password = bindname? server->pass : NULL; basedn_arg = server->base; use_tls = server->starttls? 1 : server->ldap_over_tls? 2 : 0; use_ntds = server->ntds; } else { 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.verbose) log_info ("ldap connect to '%s:%d:%s:%s:%s:%s%s'\n", host, port, basedn_arg ? basedn_arg : "", bindname ? bindname : "", password ? "*****" : "", use_tls == 1? "starttls" : use_tls == 2? "ldaptls" : "plain", use_ntds ? ",ntds":""); /* If the uri specifies a secure connection and we don't support TLS, then fail; don't silently revert to an insecure connection. */ if (use_tls) { #ifndef HAVE_LDAP_START_TLS_S log_error ("ldap: can't connect to the server: no TLS support."); err = GPG_ERR_LDAP_NOT_SUPPORTED; goto out; #endif } #ifdef HAVE_W32_SYSTEM /* Note that host==NULL uses the default domain controller. */ npth_unprotect (); ldap_conn = ldap_sslinit (host, port, (use_tls == 2)); npth_protect (); if (!ldap_conn) { lerr = LdapGetLastError (); err = ldap_err_to_gpg_err (lerr); log_error ("error initializing LDAP '%s:%d': %s\n", host, port, ldap_err2string (lerr)); goto out; } #else /* Unix */ tmpstr = xtryasprintf ("%s://%s:%d", use_tls == 2? "ldaps" : "ldap", host, port); if (!tmpstr) { err = gpg_error_from_syserror (); goto out; } npth_unprotect (); lerr = ldap_initialize (&ldap_conn, tmpstr); npth_protect (); if (lerr != LDAP_SUCCESS || !ldap_conn) { err = ldap_err_to_gpg_err (lerr); log_error ("error initializing LDAP '%s': %s\n", tmpstr, ldap_err2string (lerr)); xfree (tmpstr); goto out; } xfree (tmpstr); #endif /* Unix */ #ifdef HAVE_LDAP_SET_OPTION { int ver = LDAP_VERSION3; lerr = ldap_set_option (ldap_conn, LDAP_OPT_PROTOCOL_VERSION, &ver); if (lerr != LDAP_SUCCESS) { log_error ("ks-ldap: unable to go to LDAP 3: %s\n", ldap_err2string (lerr)); err = ldap_err_to_gpg_err (lerr); goto out; } } if (opt.ldaptimeout) { int ver = opt.ldaptimeout; lerr = ldap_set_option (ldap_conn, LDAP_OPT_TIMELIMIT, &ver); if (lerr != LDAP_SUCCESS) { log_error ("ks-ldap: unable to set LDAP timelimit to %us: %s\n", opt.ldaptimeout, ldap_err2string (lerr)); err = ldap_err_to_gpg_err (lerr); goto out; } if (opt.verbose) log_info ("ldap timeout set to %us\n", opt.ldaptimeout); } #endif #ifdef HAVE_LDAP_START_TLS_S if (use_tls == 1) { #ifndef HAVE_W32_SYSTEM int check_cert = LDAP_OPT_X_TLS_HARD; /* LDAP_OPT_X_TLS_NEVER */ lerr = ldap_set_option (ldap_conn, LDAP_OPT_X_TLS_REQUIRE_CERT, &check_cert); if (lerr) { log_error ("ldap: error setting an TLS option: %s\n", ldap_err2string (lerr)); err = ldap_err_to_gpg_err (lerr); goto out; } #else /* On Windows, the certificates are checked by default. If the option to disable checking mentioned above is ever implemented, the way to do that on Windows is to install a callback routine using ldap_set_option (.., LDAP_OPT_SERVER_CERTIFICATE, ..); */ #endif npth_unprotect (); lerr = ldap_start_tls_s (ldap_conn, #ifdef HAVE_W32_SYSTEM /* ServerReturnValue, result */ NULL, NULL, #endif /* ServerControls, ClientControls */ NULL, NULL); npth_protect (); if (lerr) { log_error ("ldap: error switching to STARTTLS mode: %s\n", ldap_err2string (lerr)); err = ldap_err_to_gpg_err (lerr); goto out; } } #endif if (use_ntds) { #ifdef HAVE_W32_SYSTEM npth_unprotect (); lerr = ldap_bind_s (ldap_conn, NULL, NULL, LDAP_AUTH_NEGOTIATE); npth_protect (); if (lerr != LDAP_SUCCESS) { log_error ("error binding to LDAP via AD: %s\n", ldap_err2string (lerr)); err = ldap_err_to_gpg_err (lerr); goto out; } #else log_error ("ldap: no Active Directory support but 'ntds' requested\n"); err = gpg_error (GPG_ERR_NOT_SUPPORTED); goto out; #endif } else if (bindname) { npth_unprotect (); lerr = ldap_simple_bind_s (ldap_conn, bindname, password); npth_protect (); if (lerr != LDAP_SUCCESS) { log_error ("error binding to LDAP: %s\n", ldap_err2string (lerr)); err = ldap_err_to_gpg_err (lerr); goto out; } } else { /* By default we don't bind as there is usually no need to. */ } if (basedn_arg && *basedn_arg) { /* User specified base DN. In this case we know the server is a * real LDAP server. */ basedn = xtrystrdup (basedn_arg); if (!basedn) { err = gpg_error_from_syserror (); goto out; } *r_serverinfo |= SERVERINFO_REALLDAP; } else { /* Look for namingContexts. */ LDAPMessage *res = NULL; char *attr[] = { "namingContexts", NULL }; npth_unprotect (); lerr = ldap_search_s (ldap_conn, "", LDAP_SCOPE_BASE, "(objectClass=*)", attr, 0, &res); npth_protect (); if (lerr == LDAP_SUCCESS) { char **context; npth_unprotect (); context = ldap_get_values (ldap_conn, res, "namingContexts"); npth_protect (); if (context) { /* We found some, so try each namingContext as the * search base and look for pgpBaseKeySpaceDN. Because * we found this, we know we're talking to a regular-ish * LDAP server and not an LDAP keyserver. */ int i; char *attr2[] = { "pgpBaseKeySpaceDN", "pgpVersion", "pgpSoftware", NULL }; *r_serverinfo |= SERVERINFO_REALLDAP; for (i = 0; context[i] && !basedn; i++) { char **vals; LDAPMessage *si_res; int is_gnupg = 0; { char *object = xasprintf ("cn=pgpServerInfo,%s", context[i]); npth_unprotect (); lerr = ldap_search_s (ldap_conn, object, LDAP_SCOPE_BASE, "(objectClass=*)", attr2, 0, &si_res); npth_protect (); xfree (object); } if (lerr == LDAP_SUCCESS) { vals = ldap_get_values (ldap_conn, si_res, "pgpBaseKeySpaceDN"); if (vals && vals[0]) { basedn = xtrystrdup (vals[0]); } my_ldap_value_free (vals); vals = ldap_get_values (ldap_conn, si_res, "pgpSoftware"); if (vals && vals[0]) { if (opt.debug) log_debug ("Server: \t%s\n", vals[0]); if (!ascii_strcasecmp (vals[0], "GnuPG")) is_gnupg = 1; } my_ldap_value_free (vals); vals = ldap_get_values (ldap_conn, si_res, "pgpVersion"); if (vals && vals[0]) { if (opt.debug) log_debug ("Version:\t%s\n", vals[0]); if (is_gnupg) { char *fields[2]; int nfields; nfields = split_fields (vals[0], fields, DIM(fields)); if (nfields > 0 && atoi(fields[0]) > 1) *r_serverinfo |= SERVERINFO_SCHEMAV2; if (nfields > 1 && !ascii_strcasecmp (fields[1], "ntds")) *r_serverinfo |= SERVERINFO_NTDS; } } my_ldap_value_free (vals); } /* From man ldap_search_s: "res parameter of ldap_search_ext_s() and ldap_search_s() should be freed with ldap_msgfree() regardless of return value of these functions. */ ldap_msgfree (si_res); } ldap_value_free (context); } } else /* ldap_search failed. */ { /* We don't have an answer yet, which means the server might be a PGP.com keyserver. */ char **vals; LDAPMessage *si_res = NULL; char *attr2[] = { "pgpBaseKeySpaceDN", "version", "software", NULL }; npth_unprotect (); lerr = ldap_search_s (ldap_conn, "cn=pgpServerInfo", LDAP_SCOPE_BASE, "(objectClass=*)", attr2, 0, &si_res); npth_protect (); if (lerr == LDAP_SUCCESS) { /* For the PGP LDAP keyserver, this is always * "OU=ACTIVE,O=PGP KEYSPACE,C=US", but it might not be * in the future. */ vals = ldap_get_values (ldap_conn, si_res, "baseKeySpaceDN"); if (vals && vals[0]) { basedn = xtrystrdup (vals[0]); } my_ldap_value_free (vals); vals = ldap_get_values (ldap_conn, si_res, "software"); if (vals && vals[0]) { if (opt.debug) log_debug ("ks-ldap: PGP Server: \t%s\n", vals[0]); } my_ldap_value_free (vals); vals = ldap_get_values (ldap_conn, si_res, "version"); if (vals && vals[0]) { if (opt.debug) log_debug ("ks-ldap: PGP Server Version:\t%s\n", vals[0]); /* If the version is high enough, use the new pgpKeyV2 attribute. This design is iffy at best, but it matches how PGP does it. I figure the NAI folks assumed that there would never be an LDAP keyserver vendor with a different numbering scheme. */ if (atoi (vals[0]) > 1) *r_serverinfo |= SERVERINFO_PGPKEYV2; } my_ldap_value_free (vals); } ldap_msgfree (si_res); } /* From man ldap_search_s: "res parameter of ldap_search_ext_s() and ldap_search_s() should be freed with ldap_msgfree() regardless of return value of these functions. */ ldap_msgfree (res); } out: if (!err && opt.debug) { log_debug ("ldap_conn: %p\n", ldap_conn); log_debug ("server_type: %s\n", ((*r_serverinfo & SERVERINFO_REALLDAP) ? "LDAP" : "PGP.com keyserver") ); log_debug ("basedn: %s\n", basedn); log_debug ("pgpkeyattr: %s\n", (*r_serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey"); } ldapserver_list_free (server); if (err) { xfree (basedn); if (ldap_conn) ldap_unbind (ldap_conn); } else { if (r_basedn) *r_basedn = basedn; else xfree (basedn); if (r_host) *r_host = host; else xfree (host); *ldap_connp = ldap_conn; } return err; } /* Extract keys from an LDAP reply and write them out to the output stream OUTPUT in a format GnuPG can import (either the OpenPGP binary format or armored format). */ static void extract_keys (estream_t output, LDAP *ldap_conn, const char *certid, LDAPMessage *message) { char **vals; es_fprintf (output, "INFO %s BEGIN\n", certid); /* Note: ldap_get_values returns a NULL terminated array of strings. */ vals = ldap_get_values (ldap_conn, message, "gpgfingerprint"); if (vals && vals[0] && vals[0][0]) es_fprintf (output, "pub:%s:", vals[0]); else es_fprintf (output, "pub:%s:", certid); my_ldap_value_free (vals); vals = ldap_get_values (ldap_conn, message, "pgpkeytype"); if (vals && vals[0]) { if (strcmp (vals[0], "RSA") == 0) es_fprintf (output, "1"); else if (strcmp (vals[0],"DSS/DH") == 0) es_fprintf (output, "17"); } my_ldap_value_free (vals); es_fprintf (output, ":"); vals = ldap_get_values (ldap_conn, message, "pgpkeysize"); if (vals && vals[0]) { int v = atoi (vals[0]); if (v > 0) es_fprintf (output, "%d", v); } my_ldap_value_free (vals); es_fprintf (output, ":"); vals = ldap_get_values (ldap_conn, message, "pgpkeycreatetime"); if (vals && vals[0]) { if (strlen (vals[0]) == 15) es_fprintf (output, "%u", (unsigned int) ldap2epochtime (vals[0])); } my_ldap_value_free (vals); es_fprintf (output, ":"); vals = ldap_get_values (ldap_conn, message, "pgpkeyexpiretime"); if (vals && vals[0]) { if (strlen (vals[0]) == 15) es_fprintf (output, "%u", (unsigned int) ldap2epochtime (vals[0])); } my_ldap_value_free (vals); es_fprintf (output, ":"); vals = ldap_get_values (ldap_conn, message, "pgprevoked"); if (vals && vals[0]) { if (atoi (vals[0]) == 1) es_fprintf (output, "r"); } my_ldap_value_free (vals); es_fprintf (output, "\n"); vals = ldap_get_values (ldap_conn, message, "pgpuserid"); if (vals && vals[0]) { int i; for (i = 0; vals[i]; i++) es_fprintf (output, "uid:%s\n", vals[i]); } my_ldap_value_free (vals); es_fprintf (output, "INFO %s END\n", certid); } /* Get the key described key the KEYSPEC string from the keyserver identified by URI. On success R_FP has an open stream to read the data. */ gpg_error_t ks_ldap_get (ctrl_t ctrl, parsed_uri_t uri, const char *keyspec, estream_t *r_fp) { gpg_error_t err = 0; int ldap_err; unsigned int serverinfo; char *host = NULL; int use_tls; char *filter = NULL; LDAP *ldap_conn = NULL; char *basedn = NULL; estream_t fp = NULL; LDAPMessage *message = NULL; (void) ctrl; if (dirmngr_use_tor ()) { /* For now we do not support LDAP over Tor. */ log_error (_("LDAP access not possible due to Tor mode\n")); return gpg_error (GPG_ERR_NOT_SUPPORTED); } /* Make sure we are talking to an OpenPGP LDAP server. */ err = my_ldap_connect (uri, &ldap_conn, &basedn, &host, &use_tls, &serverinfo); if (err || !basedn) { if (!err) err = gpg_error (GPG_ERR_GENERAL); goto out; } /* Now that we have information about the server we can construct a * query best suited for the capabilities of the server. */ err = keyspec_to_ldap_filter (keyspec, &filter, 1, serverinfo); if (err) goto out; if (opt.debug) log_debug ("ks-ldap: using filter: %s\n", filter); { /* The ordering is significant. Specifically, "pgpcertid" needs to be the second item in the list, since everything after it may be discarded if we aren't in verbose mode. */ char *attrs[] = { "dummy", "pgpcertid", "pgpuserid", "pgpkeyid", "pgprevoked", "pgpdisabled", "pgpkeycreatetime", "modifytimestamp", "pgpkeysize", "pgpkeytype", "gpgfingerprint", NULL }; /* 1 if we want just attribute types; 0 if we want both attribute * types and values. */ int attrsonly = 0; int count; /* Replace "dummy". */ attrs[0] = (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2" : "pgpKey"; npth_unprotect (); ldap_err = ldap_search_s (ldap_conn, basedn, LDAP_SCOPE_SUBTREE, filter, attrs, attrsonly, &message); npth_protect (); if (ldap_err) { err = ldap_err_to_gpg_err (ldap_err); log_error ("ks-ldap: LDAP search error: %s\n", ldap_err2string (ldap_err)); goto out; } count = ldap_count_entries (ldap_conn, message); if (count < 1) { log_info ("ks-ldap: key %s not found on keyserver\n", keyspec); if (count == -1) err = ldap_to_gpg_err (ldap_conn); else err = gpg_error (GPG_ERR_NO_DATA); goto out; } { /* There may be more than one unique result for a given keyID, so we should fetch them all (test this by fetching short key id 0xDEADBEEF). */ /* The set of entries that we've seen. */ strlist_t seen = NULL; LDAPMessage *each; int anykey = 0; for (npth_unprotect (), each = ldap_first_entry (ldap_conn, message), npth_protect (); each; npth_unprotect (), each = ldap_next_entry (ldap_conn, each), npth_protect ()) { char **vals; char **certid; /* Use the long keyid to remove duplicates. The LDAP server returns the same keyid more than once if there are multiple user IDs on the key. Note that this does NOT mean that a keyid that exists multiple times on the keyserver will not be fetched. It means that each KEY, no matter how many user IDs share its keyid, will be fetched only once. If a keyid that belongs to more than one key is fetched, the server quite properly responds with all matching keys. -ds */ certid = ldap_get_values (ldap_conn, each, "pgpcertid"); if (certid && certid[0]) { if (! strlist_find (seen, certid[0])) { /* It's not a duplicate, add it */ add_to_strlist (&seen, certid[0]); if (! fp) fp = es_fopenmem(0, "rw"); extract_keys (fp, ldap_conn, certid[0], each); vals = ldap_get_values (ldap_conn, each, attrs[0]); if (! vals) { err = ldap_to_gpg_err (ldap_conn); log_error("ks-ldap: unable to retrieve key %s " "from keyserver\n", certid[0]); goto out; } else { /* We should strip the new lines. */ es_fprintf (fp, "KEY 0x%s BEGIN\n", certid[0]); es_fputs (vals[0], fp); es_fprintf (fp, "\nKEY 0x%s END\n", certid[0]); ldap_value_free (vals); anykey = 1; } } } my_ldap_value_free (certid); } free_strlist (seen); if (! fp) err = gpg_error (GPG_ERR_NO_DATA); if (!err && anykey) err = dirmngr_status_printf (ctrl, "SOURCE", "%s://%s", use_tls? "ldaps" : "ldap", host? host:""); } } out: if (message) ldap_msgfree (message); if (err) { if (fp) es_fclose (fp); } else { if (fp) es_fseek (fp, 0, SEEK_SET); *r_fp = fp; } xfree (basedn); xfree (host); if (ldap_conn) ldap_unbind (ldap_conn); xfree (filter); return err; } /* Search the keyserver identified by URI for keys matching PATTERN. On success R_FP has an open stream to read the data. */ gpg_error_t ks_ldap_search (ctrl_t ctrl, parsed_uri_t uri, const char *pattern, estream_t *r_fp) { gpg_error_t err; int ldap_err; unsigned int serverinfo; char *filter = NULL; LDAP *ldap_conn = NULL; char *basedn = NULL; estream_t fp = NULL; (void) ctrl; if (dirmngr_use_tor ()) { /* For now we do not support LDAP over Tor. */ log_error (_("LDAP access not possible due to Tor mode\n")); return gpg_error (GPG_ERR_NOT_SUPPORTED); } /* Make sure we are talking to an OpenPGP LDAP server. */ err = my_ldap_connect (uri, &ldap_conn, &basedn, NULL, NULL, &serverinfo); if (err || !basedn) { if (!err) err = GPG_ERR_GENERAL; goto out; } /* Now that we have information about the server we can construct a * query best suited for the capabilities of the server. */ err = keyspec_to_ldap_filter (pattern, &filter, 0, serverinfo); if (err) { log_error ("Bad search pattern: '%s'\n", pattern); goto out; } /* Even if we have no results, we want to return a stream. */ fp = es_fopenmem(0, "rw"); if (!fp) { err = gpg_error_from_syserror (); goto out; } { char **vals; LDAPMessage *res, *each; int count = 0; strlist_t dupelist = NULL; /* The maximum size of the search, including the optional stuff and the trailing \0 */ char *attrs[] = { "pgpcertid", "pgpuserid", "pgprevoked", "pgpdisabled", "pgpkeycreatetime", "pgpkeyexpiretime", "modifytimestamp", "pgpkeysize", "pgpkeytype", "gpgfingerprint", NULL }; if (opt.debug) log_debug ("SEARCH '%s' => '%s' BEGIN\n", pattern, filter); npth_unprotect (); ldap_err = ldap_search_s (ldap_conn, basedn, LDAP_SCOPE_SUBTREE, filter, attrs, 0, &res); npth_protect (); xfree (filter); filter = NULL; if (ldap_err != LDAP_SUCCESS && ldap_err != LDAP_SIZELIMIT_EXCEEDED) { err = ldap_err_to_gpg_err (ldap_err); log_error ("SEARCH %s FAILED %d\n", pattern, err); log_error ("ks-ldap: LDAP search error: %s\n", ldap_err2string (err)); goto out; } /* The LDAP server doesn't return a real count of unique keys, so we can't use ldap_count_entries here. */ for (npth_unprotect (), each = ldap_first_entry (ldap_conn, res), npth_protect (); each; npth_unprotect (), each = ldap_next_entry (ldap_conn, each), npth_protect ()) { char **certid = ldap_get_values (ldap_conn, each, "pgpcertid"); if (certid && certid[0] && ! strlist_find (dupelist, certid[0])) { add_to_strlist (&dupelist, certid[0]); count++; } my_ldap_value_free (certid); } if (ldap_err == LDAP_SIZELIMIT_EXCEEDED) { if (count == 1) log_error ("ks-ldap: search results exceeded server limit." " First 1 result shown.\n"); else log_error ("ks-ldap: search results exceeded server limit." " First %d results shown.\n", count); } free_strlist (dupelist); dupelist = NULL; if (count < 1) es_fputs ("info:1:0\n", fp); else { es_fprintf (fp, "info:1:%d\n", count); for (each = ldap_first_entry (ldap_conn, res); each; each = ldap_next_entry (ldap_conn, each)) { char **certid; LDAPMessage *uids; certid = ldap_get_values (ldap_conn, each, "pgpcertid"); if (!certid || !certid[0]) { my_ldap_value_free (certid); continue; } /* Have we seen this certid before? */ if (! strlist_find (dupelist, certid[0])) { add_to_strlist (&dupelist, certid[0]); vals = ldap_get_values (ldap_conn, each, "gpgfingerprint"); if (vals && vals[0] && vals[0][0]) es_fprintf (fp, "pub:%s:", vals[0]); else es_fprintf (fp, "pub:%s:", certid[0]); my_ldap_value_free (vals); vals = ldap_get_values (ldap_conn, each, "pgpkeytype"); if (vals && vals[0]) { /* The LDAP server doesn't exactly handle this well. */ if (strcasecmp (vals[0], "RSA") == 0) es_fputs ("1", fp); else if (strcasecmp (vals[0], "DSS/DH") == 0) es_fputs ("17", fp); } my_ldap_value_free (vals); es_fputc (':', fp); vals = ldap_get_values (ldap_conn, each, "pgpkeysize"); if (vals && vals[0]) { /* Not sure why, but some keys are listed with a key size of 0. Treat that like an unknown. */ if (atoi (vals[0]) > 0) es_fprintf (fp, "%d", atoi (vals[0])); } my_ldap_value_free (vals); es_fputc (':', fp); /* YYYYMMDDHHmmssZ */ vals = ldap_get_values (ldap_conn, each, "pgpkeycreatetime"); if(vals && vals[0] && strlen (vals[0]) == 15) { es_fprintf (fp, "%u", (unsigned int) ldap2epochtime(vals[0])); } my_ldap_value_free (vals); es_fputc (':', fp); vals = ldap_get_values (ldap_conn, each, "pgpkeyexpiretime"); if (vals && vals[0] && strlen (vals[0]) == 15) { es_fprintf (fp, "%u", (unsigned int) ldap2epochtime (vals[0])); } my_ldap_value_free (vals); es_fputc (':', fp); vals = ldap_get_values (ldap_conn, each, "pgprevoked"); if (vals && vals[0]) { if (atoi (vals[0]) == 1) es_fprintf (fp, "r"); } my_ldap_value_free (vals); vals = ldap_get_values (ldap_conn, each, "pgpdisabled"); if (vals && vals[0]) { if (atoi (vals[0]) ==1) es_fprintf (fp, "d"); } my_ldap_value_free (vals); #if 0 /* This is not yet specified in the keyserver protocol, but may be someday. */ es_fputc (':', fp); vals = ldap_get_values (ldap_conn, each, "modifytimestamp"); if(vals && vals[0] strlen (vals[0]) == 15) { es_fprintf (fp, "%u", (unsigned int) ldap2epochtime (vals[0])); } my_ldap_value_free (vals); #endif es_fprintf (fp, "\n"); /* Now print all the uids that have this certid */ for (uids = ldap_first_entry (ldap_conn, res); uids; uids = ldap_next_entry (ldap_conn, uids)) { vals = ldap_get_values (ldap_conn, uids, "pgpcertid"); if (!vals || !vals[0]) { my_ldap_value_free (vals); continue; } if (!ascii_strcasecmp (certid[0], vals[0])) { char **uidvals; es_fprintf (fp, "uid:"); uidvals = ldap_get_values (ldap_conn, uids, "pgpuserid"); if (uidvals) { /* Need to percent escape any colons */ char *quoted = try_percent_escape (uidvals[0], NULL); if (quoted) es_fputs (quoted, fp); xfree (quoted); } my_ldap_value_free (uidvals); es_fprintf (fp, "\n"); } ldap_value_free(vals); } } my_ldap_value_free (certid); } } ldap_msgfree (res); free_strlist (dupelist); } if (opt.debug) log_debug ("SEARCH %s END\n", pattern); out: if (err) { es_fclose (fp); } else { /* Return the read stream. */ if (fp) es_fseek (fp, 0, SEEK_SET); *r_fp = fp; } xfree (basedn); if (ldap_conn) ldap_unbind (ldap_conn); xfree (filter); return err; } /* A modlist describes a set of changes to an LDAP entry. (An entry consists of 1 or more attributes. Attributes are pairs. Note: an attribute may be multi-valued in which case multiple values are associated with a single name.) A modlist is a NULL terminated array of struct LDAPMod's. Thus, if we have: LDAPMod **modlist; Then: modlist[i] Is the ith modification. Each LDAPMod describes a change to a single attribute. Further, there is one modification for each attribute that we want to change. The attribute's new value is stored in LDAPMod.mod_values. If the attribute is multi-valued, we still only use a single LDAPMod structure: mod_values is a NULL-terminated array of strings. To delete an attribute from an entry, we set mod_values to NULL. Thus, if: modlist[i]->mod_values == NULL then we remove the attribute. (Using LDAP_MOD_DELETE doesn't work here as we don't know if the attribute in question exists or not.) Note: this function does NOT copy or free ATTR. It does copy VALUE. */ static void modlist_add (LDAPMod ***modlistp, char *attr, const char *value) { LDAPMod **modlist = *modlistp; LDAPMod **m; int nummods = 0; /* Search modlist for the attribute we're playing with. If modlist is NULL, then the list is empty. Recall: modlist is a NULL terminated array. */ for (m = modlist; m && *m; m++, nummods ++) { /* The attribute is already on the list. */ char **ptr; int numvalues = 0; if (strcasecmp ((*m)->mod_type, attr) != 0) continue; /* We have this attribute already, so when the REPLACE happens, the server attributes will be replaced anyway. */ if (! value) return; /* Attributes can be multi-valued. See if the value is already present. mod_values is a NULL terminated array of pointers. Note: mod_values can be NULL. */ for (ptr = (*m)->mod_values; ptr && *ptr; ptr++) { if (strcmp (*ptr, value) == 0) /* Duplicate value, we're done. */ return; numvalues ++; } /* Append the value. */ ptr = xrealloc ((*m)->mod_values, sizeof (char *) * (numvalues + 2)); (*m)->mod_values = ptr; ptr[numvalues] = xstrdup (value); ptr[numvalues + 1] = NULL; return; } /* We didn't find the attr, so make one and add it to the end */ /* Like attribute values, the list of attributes is NULL terminated array of pointers. */ modlist = xrealloc (modlist, sizeof (LDAPMod *) * (nummods + 2)); *modlistp = modlist; modlist[nummods] = xmalloc (sizeof (LDAPMod)); modlist[nummods]->mod_op = LDAP_MOD_REPLACE; modlist[nummods]->mod_type = attr; if (value) { modlist[nummods]->mod_values = xmalloc (sizeof(char *) * 2); modlist[nummods]->mod_values[0] = xstrdup (value); modlist[nummods]->mod_values[1] = NULL; } else modlist[nummods]->mod_values = NULL; modlist[nummods + 1] = NULL; return; } /* Look up the value of an attribute in the specified modlist. If the attribute is not on the mod list, returns NULL. The result is a NULL-terminated array of strings. Don't change it. */ static char ** modlist_lookup (LDAPMod **modlist, const char *attr) { LDAPMod **m; for (m = modlist; m && *m; m++) { if (strcasecmp ((*m)->mod_type, attr) != 0) continue; return (*m)->mod_values; } return NULL; } /* Dump a modlist to a file. This is useful for debugging. */ static estream_t modlist_dump (LDAPMod **modlist, estream_t output) GPGRT_ATTR_USED; static estream_t modlist_dump (LDAPMod **modlist, estream_t output) { LDAPMod **m; int opened = 0; if (! output) { output = es_fopenmem (0, "rw"); if (!output) return NULL; opened = 1; } for (m = modlist; m && *m; m++) { es_fprintf (output, " %s:", (*m)->mod_type); if (! (*m)->mod_values) es_fprintf(output, " delete.\n"); else { char **ptr; int i; int multi = 0; if ((*m)->mod_values[0] && (*m)->mod_values[1]) /* Have at least 2. */ multi = 1; if (multi) es_fprintf (output, "\n"); for ((ptr = (*m)->mod_values), (i = 1); ptr && *ptr; ptr++, i ++) { /* Assuming terminals are about 80 characters wide, display at most about 10 lines of debugging output. If we do trim the buffer, append '...' to the end. */ const int max_len = 10 * 70; size_t value_len = strlen (*ptr); int elide = value_len > max_len; if (multi) es_fprintf (output, " %d. ", i); es_fprintf (output, "`%.*s", max_len, *ptr); if (elide) es_fprintf (output, "...' (%zd bytes elided)", value_len - max_len); else es_fprintf (output, "'"); es_fprintf (output, "\n"); } } } if (opened) es_fseek (output, 0, SEEK_SET); return output; } /* Free all of the memory allocated by the mod list. This assumes that the attribute names don't have to be freed, but the attributes values do. (Which is what modlist_add does.) */ static void modlist_free (LDAPMod **modlist) { LDAPMod **ml; if (! modlist) return; /* Unwind and free the whole modlist structure */ /* The modlist is a NULL terminated array of pointers. */ for (ml = modlist; *ml; ml++) { LDAPMod *mod = *ml; char **ptr; /* The list of values is a NULL termianted array of pointers. If the list is NULL, there are no values. */ if (mod->mod_values) { for (ptr = mod->mod_values; *ptr; ptr++) xfree (*ptr); xfree (mod->mod_values); } xfree (mod); } xfree (modlist); } /* Append two onto the end of one. Two is not freed, but its pointers are now part of one. Make sure you don't free them both! As long as you don't add anything to ONE, TWO is still valid. After that all bets are off. */ static void modlists_join (LDAPMod ***one, LDAPMod **two) { int i, one_count = 0, two_count = 0; LDAPMod **grow; if (!*two) /* two is empty. Nothing to do. */ return; if (!*one) /* one is empty. Just set it equal to *two. */ { *one = two; return; } for (grow = *one; *grow; grow++) one_count ++; for (grow = two; *grow; grow++) two_count ++; grow = xrealloc (*one, sizeof(LDAPMod *) * (one_count + two_count + 1)); for (i = 0; i < two_count; i++) grow[one_count + i] = two[i]; grow[one_count + i] = NULL; *one = grow; } /* Given a string, unescape C escapes. In particular, \xXX. This modifies the string in place. */ static void uncescape (char *str) { size_t r = 0; size_t w = 0; char *first = strchr (str, '\\'); if (! first) /* No backslashes => no escaping. We're done. */ return; /* Start at the first '\\'. */ r = w = (uintptr_t) first - (uintptr_t) str; while (str[r]) { /* XXX: What to do about bad escapes? XXX: hextobyte already checks the string thus the hexdigitp could be removed. */ if (str[r] == '\\' && str[r + 1] == 'x' && str[r+2] && str[r+3] && hexdigitp (str + r + 2) && hexdigitp (str + r + 3)) { int x = hextobyte (&str[r + 2]); - assert (0 <= x && x <= 0xff); + log_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))) { modlist_add (modlist, "gpgMailbox", mbox); xfree (mbox); } } out: xfree (fields); } /* Send the key in {KEY,KEYLEN} with the metadata {INFO,INFOLEN} to the keyserver identified by URI. See server.c:cmd_ks_put for the format of the data and metadata. */ gpg_error_t ks_ldap_put (ctrl_t ctrl, parsed_uri_t uri, void *data, size_t datalen, void *info, size_t infolen) { gpg_error_t err = 0; int ldap_err; unsigned int serverinfo; LDAP *ldap_conn = NULL; char *basedn = NULL; LDAPMod **modlist = NULL; LDAPMod **addlist = NULL; char *data_armored = NULL; int extract_state; /* The last byte of the info block. */ const char *infoend = (const char *) info + infolen - 1; /* Enable this code to dump the modlist to /tmp/modlist.txt. */ #if 0 # warning Disable debug code before checking in. const int dump_modlist = 1; #else const int dump_modlist = 0; #endif estream_t dump = NULL; /* Elide a warning. */ (void) ctrl; if (dirmngr_use_tor ()) { /* For now we do not support LDAP over Tor. */ log_error (_("LDAP access not possible due to Tor mode\n")); return gpg_error (GPG_ERR_NOT_SUPPORTED); } err = my_ldap_connect (uri, &ldap_conn, &basedn, NULL, NULL, &serverinfo); if (err || !basedn) { if (!err) err = GPG_ERR_GENERAL; goto out; } if (!(serverinfo & SERVERINFO_REALLDAP)) { /* We appear to have a PGP.com Keyserver, which can unpack the * key on its own (not just a dump LDAP server). This will * rarely be the case these days. */ LDAPMod mod; LDAPMod *attrs[2]; char *key[2]; char *dn; key[0] = data; key[1] = NULL; memset (&mod, 0, sizeof (mod)); mod.mod_op = LDAP_MOD_ADD; mod.mod_type = (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey"; mod.mod_values = key; attrs[0] = &mod; attrs[1] = NULL; dn = xtryasprintf ("pgpCertid=virtual,%s", basedn); if (!dn) { err = gpg_error_from_syserror (); goto out; } ldap_err = ldap_add_s (ldap_conn, dn, attrs); xfree (dn); if (ldap_err != LDAP_SUCCESS) { err = ldap_err_to_gpg_err (err); goto out; } goto out; } modlist = xtrymalloc (sizeof (LDAPMod *)); if (!modlist) { err = gpg_error_from_syserror (); goto out; } *modlist = NULL; if (dump_modlist) { dump = es_fopen("/tmp/modlist.txt", "w"); if (! dump) - log_error ("Failed to open /tmp/modlist.txt: %s\n", - strerror (errno)); + log_error ("failed to open /tmp/modlist.txt: %s\n", + gpg_strerror (gpg_error_from_syserror ())); 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-misc.c b/dirmngr/ldap-misc.c new file mode 100644 index 000000000..42f9c7afc --- /dev/null +++ b/dirmngr/ldap-misc.c @@ -0,0 +1,332 @@ +/* ldap-misc.c - Miscellaneous helpers for LDAP functions + * Copyright (C) 2015, 2021 g10 Code GmbH + * + * This file is part of GnuPG. + * + * GnuPG is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * GnuPG is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +#include +#include +#include +#include + +#include "dirmngr-err.h" +#include "../common/util.h" +#include "ldap-misc.h" + + +/* Convert an LDAP error to a GPG error. */ +gpg_err_code_t +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. */ +gpg_err_code_t +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 +} + + + +/* Parse an extended filter syntax as used by dirmngr_ldap.c + * For example: + * + * ^CN=foo, OU=My Users&(objectClasses=*) + * + * Uses "CN=foo, OU=My Users" as base DN and "(objectClasses=*)" as + * filter. If the base prefix includes an ampersand, it needs to be + * doubled. The usual escaping rules for DNs (for the base) and + * filters apply. Other examples: + * + * ^CN=foo, OU=My Users& + * + * Use just the base DN. + * + * ^CN=foo, OU=My Users&SCOPE& + * + * Specify the scope which is "base", "one", or "sub". May of course + * also be followed by a filter. + * + * ^&SCOPE&(objectClasses=*) + * + * Give a scope and a filter. Note that R_SCOPE is only changed if a + * STRING has scope parameter. Setting this initally to -1 allows to + * detect this case. + */ +gpg_error_t +ldap_parse_extfilter (const char *string, int silent, + char **r_base, int *r_scope, char **r_filter) +{ + gpg_error_t err = 0; + char *base = NULL; + char *filter = NULL; + const char *s; + char *p; + + if (r_base) + *r_base = NULL; + if (r_filter) + *r_filter = NULL; + + if (*string == '^') + { + string++; + base = xtrymalloc (strlen (string)+1); + if (!base) + { + err = gpg_error_from_syserror (); + goto leave; + } + for (s=string, p=base; *s; s++) + { + *p++ = *s; + if (*s == '&' && s[1] == '&') + s++; /* Skip quoted ampersand. */ + else if (*s == '&') + { + p--; + break; + } + } + *p = 0; + if (!*s) + { + if (!silent) + log_info ("LDAP extended filter is not terminated\n"); + err = gpg_error (GPG_ERR_SYNTAX); + goto leave; + } + string = s + 1; + } + + if (!*string) + goto leave; /* ready. */ + + if (!strncmp (string, "base&", 5)) + { + string += 5; + if (r_scope) + *r_scope = LDAP_SCOPE_BASE; + } + else if (!strncmp (string, "one&", 4)) + { + string += 4; + if (r_scope) + *r_scope = LDAP_SCOPE_ONELEVEL; + } + else if (!strncmp (string, "sub&", 4)) + { + string += 4; + if (r_scope) + *r_scope = LDAP_SCOPE_SUBTREE; + } + + if (!*string) + goto leave; /* ready. */ + + if (*string != '(') + { + if (!silent) + log_info ("LDAP filter does not start with a left parentheses\n"); + return gpg_error (GPG_ERR_SYNTAX); + } + if (string[strlen(string)-1] != ')') + { + if (!silent) + log_info ("LDAP filter does not end with a right parentheses\n"); + return gpg_error (GPG_ERR_SYNTAX); + } + + filter = xtrystrdup (string); + if (!filter) + err = gpg_error_from_syserror (); + + leave: + if (err) + { + xfree (base); + xfree (filter); + } + else + { + if (r_base) + *r_base = base; + else + xfree (base); + if (r_filter) + *r_filter = filter; + else + xfree (filter); + } + return err; +} diff --git a/dirmngr/ldap-misc.h b/dirmngr/ldap-misc.h new file mode 100644 index 000000000..d555caf49 --- /dev/null +++ b/dirmngr/ldap-misc.h @@ -0,0 +1,43 @@ +/* ldap-misc.h - Miscellaneous helpers for LDAP functions + * Copyright (C) 2015, 2021 g10 Code GmbH + * + * This file is part of GnuPG. + * + * GnuPG is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * GnuPG is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +#ifndef DIRMNGR_LDAP_MISC_H +#define DIRMNGR_LDAP_MISC_H + +#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 + + +gpg_err_code_t ldap_err_to_gpg_err (int code); +gpg_err_code_t ldap_to_gpg_err (LDAP *ld); +gpg_error_t ldap_parse_extfilter (const char *string, int silent, + char **r_base, int *r_scope, char **r_filter); + + +#endif /*DIRMNGR_LDAP_MISC_H*/ diff --git a/dirmngr/ldap-wrapper.c b/dirmngr/ldap-wrapper.c index d01c4808e..bbae3b290 100644 --- a/dirmngr/ldap-wrapper.c +++ b/dirmngr/ldap-wrapper.c @@ -1,931 +1,939 @@ /* ldap-wrapper.c - LDAP access via a wrapper process * Copyright (C) 2004, 2005, 2007, 2008, 2018 g10 Code GmbH * Copyright (C) 2010 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ /* * We can't use LDAP directly for these reasons: * * 1. On some systems the LDAP library uses (indirectly) pthreads and * that is not compatible with GNU Pth. Since 2.1 we use nPth * instead of GNU Pth which does not have this problem anymore * because it will use pthreads if the platform supports it. Thus * this was a historical reasons. * * 2. It is huge library in particular if TLS comes into play. So * problems with unfreed memory might turn up and we don't want * this in a long running daemon. * * 3. There is no easy way for timeouts. In particular the timeout * value does not work for DNS lookups (well, this is usual) and it * seems not to work while loading a large attribute like a * CRL. Having a separate process allows us to either tell the * process to commit suicide or have our own housekepping function * kill it after some time. The latter also allows proper * cancellation of a query at any point of time. * * 4. Given that we are going out to the network and usually get back * a long response, the fork/exec overhead is acceptable. * * Note that under WindowsCE the number of processes is strongly * limited (32 processes including the kernel processes) and thus we * don't use the process approach but implement a different wrapper in * ldap-wrapper-ce.c. */ #include #include #include #include #include #include #include #include #include #include "dirmngr.h" #include "../common/exechelp.h" #include "misc.h" #include "ldap-wrapper.h" #ifdef HAVE_W32_SYSTEM #define setenv(a,b,c) SetEnvironmentVariable ((a),(b)) #else #define pth_close(fd) close(fd) #endif #ifndef USE_LDAPWRAPPER # error This module is not expected to be build. #endif /* In case sysconf does not return a value we need to have a limit. */ #ifdef _POSIX_OPEN_MAX #define MAX_OPEN_FDS _POSIX_OPEN_MAX #else #define MAX_OPEN_FDS 20 #endif #define INACTIVITY_TIMEOUT (opt.ldaptimeout + 60*5) /* seconds */ #define TIMERTICK_INTERVAL 2 /* To keep track of the LDAP wrapper state we use this structure. */ struct wrapper_context_s { struct wrapper_context_s *next; pid_t pid; /* The pid of the wrapper process. */ int printable_pid; /* Helper to print diagnostics after the process has * been cleaned up. */ estream_t fp; /* Connected with stdout of the ldap wrapper. */ gpg_error_t fp_err; /* Set to the gpg_error of the last read error * if any. */ estream_t log_fp; /* Connected with stderr of the ldap wrapper. */ ctrl_t ctrl; /* Connection data. */ int ready; /* Internally used to mark to be removed contexts. */ ksba_reader_t reader;/* The ksba reader object or NULL. */ char *line; /* Used to print the log lines (malloced). */ size_t linesize; /* Allocated size of LINE. */ size_t linelen; /* Use size of LINE. */ time_t stamp; /* The last time we noticed ativity. */ int reaper_idx; /* Private to ldap_wrapper_thread. */ }; /* We keep a global list of spawned wrapper process. A separate * thread makes use of this list to log error messages and to watch * out for finished processes. Access to list is protected by a * mutex. The condition variable is used to wakeup the reaper * thread. */ static struct wrapper_context_s *reaper_list; static npth_mutex_t reaper_list_mutex = NPTH_MUTEX_INITIALIZER; static npth_cond_t reaper_run_cond = NPTH_COND_INITIALIZER; /* We need to know whether we are shutting down the process. */ static int shutting_down; /* Close the estream fp and set it to NULL. */ #define SAFE_CLOSE(fp) \ do { estream_t _fp = fp; es_fclose (_fp); fp = NULL; } while (0) static void lock_reaper_list (void) { if (npth_mutex_lock (&reaper_list_mutex)) log_fatal ("%s: failed to acquire mutex: %s\n", __func__, gpg_strerror (gpg_error_from_syserror ())); } static void unlock_reaper_list (void) { if (npth_mutex_unlock (&reaper_list_mutex)) log_fatal ("%s: failed to release mutex: %s\n", __func__, gpg_strerror (gpg_error_from_syserror ())); } /* 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; } /* Release the wrapper context and kill a running wrapper process. */ static void destroy_wrapper (struct wrapper_context_s *ctx) { if (ctx->pid != (pid_t)(-1)) { gnupg_kill_process (ctx->pid); gnupg_release_process (ctx->pid); } ksba_reader_release (ctx->reader); SAFE_CLOSE (ctx->fp); SAFE_CLOSE (ctx->log_fp); xfree (ctx->line); xfree (ctx); } /* Print the content of LINE to thye log stream but make sure to only print complete lines. Using NULL for LINE will flush any pending output. LINE may be modified by this function. */ static void print_log_line (struct wrapper_context_s *ctx, char *line) { char *s; size_t n; if (!line) { if (ctx->line && ctx->linelen) { log_info ("%s\n", ctx->line); ctx->linelen = 0; } return; } while ((s = strchr (line, '\n'))) { *s = 0; if (ctx->line && ctx->linelen) { log_info ("%s", ctx->line); ctx->linelen = 0; log_printf ("%s\n", line); } else log_info ("%s\n", line); line = s + 1; } n = strlen (line); if (n) { if (ctx->linelen + n + 1 >= ctx->linesize) { char *tmp; size_t newsize; newsize = ctx->linesize + ((n + 255) & ~255) + 1; tmp = (ctx->line ? xtryrealloc (ctx->line, newsize) : xtrymalloc (newsize)); if (!tmp) { log_error (_("error printing log line: %s\n"), strerror (errno)); return; } ctx->line = tmp; ctx->linesize = newsize; } memcpy (ctx->line + ctx->linelen, line, n); ctx->linelen += n; ctx->line[ctx->linelen] = 0; } } /* Read data from the log stream. Returns true if the log stream * indicated EOF or error. */ static int read_log_data (struct wrapper_context_s *ctx) { int rc; size_t n; char line[256]; rc = es_read (ctx->log_fp, line, sizeof line - 1, &n); if (rc || !n) /* Error or EOF. */ { if (rc) { gpg_error_t err = gpg_error_from_syserror (); if (gpg_err_code (err) == GPG_ERR_EAGAIN) return 0; log_error (_("error reading log from ldap wrapper %d: %s\n"), (int)ctx->pid, gpg_strerror (err)); } print_log_line (ctx, NULL); /* Flush. */ SAFE_CLOSE (ctx->log_fp); return 1; } line[n] = 0; print_log_line (ctx, line); if (ctx->stamp != (time_t)(-1)) ctx->stamp = time (NULL); return 0; } /* This function is run by a separate thread to maintain the list of wrappers and to log error messages from these wrappers. */ void * ldap_reaper_thread (void *dummy) { gpg_error_t err; struct wrapper_context_s *ctx; struct wrapper_context_s *ctx_prev; struct timespec abstime; struct timespec curtime; struct timespec timeout; int millisecs; gpgrt_poll_t *fparray = NULL; int fparraysize = 0; int count, i; int ret; time_t exptime; (void)dummy; npth_clock_gettime (&abstime); abstime.tv_sec += TIMERTICK_INTERVAL; for (;;) { int any_action = 0; /* Wait until we are needed and then setup the FPARRAY. */ /* Note: There is one unlock inside the block! */ lock_reaper_list (); { while (!reaper_list && !shutting_down) { if (npth_cond_wait (&reaper_run_cond, &reaper_list_mutex)) log_error ("ldap-reaper: waiting on condition failed: %s\n", gpg_strerror (gpg_error_from_syserror ())); } for (count = 0, ctx = reaper_list; ctx; ctx = ctx->next) if (ctx->log_fp) count++; if (count > fparraysize || !fparray) { /* Need to realloc the array. We simply discard it and * replace it by a new one. */ xfree (fparray); fparray = xtrycalloc (count? count : 1, sizeof *fparray); if (!fparray) { err = gpg_error_from_syserror (); log_error ("ldap-reaper can't allocate poll array: %s" " - waiting 1s\n", gpg_strerror (err)); /* Note: Here we unlock and continue! */ unlock_reaper_list (); npth_sleep (1); continue; } fparraysize = count; } for (count = 0, ctx = reaper_list; ctx; ctx = ctx->next) { if (ctx->log_fp) { log_assert (count < fparraysize); fparray[count].stream = ctx->log_fp; fparray[count].want_read = 1; fparray[count].ignore = 0; ctx->reaper_idx = count; count++; } else { ctx->reaper_idx = -1; fparray[count].ignore = 1; } } for (i=count; i < fparraysize; i++) fparray[i].ignore = 1; } unlock_reaper_list (); /* Note the one unlock inside the block. */ /* Compute the next timeout. */ npth_clock_gettime (&curtime); if (!(npth_timercmp (&curtime, &abstime, <))) { /* Inactivity is checked below. Nothing else to do. */ npth_clock_gettime (&abstime); abstime.tv_sec += TIMERTICK_INTERVAL; } npth_timersub (&abstime, &curtime, &timeout); millisecs = timeout.tv_sec * 1000; millisecs += timeout.tv_nsec / 1000000; if (millisecs < 0) millisecs = 1; if (DBG_EXTPROG) { log_debug ("ldap-reaper: next run (count=%d size=%d, timeout=%d)\n", count, fparraysize, millisecs); for (count=0; count < fparraysize; count++) if (!fparray[count].ignore) log_debug ("ldap-reaper: fp[%d] stream=%p want=%d\n", count, fparray[count].stream,fparray[count].want_read); } ret = es_poll (fparray, fparraysize, millisecs); if (ret < 0) { err = gpg_error_from_syserror (); log_error ("ldap-reaper failed to poll: %s" " - waiting 1s\n", gpg_strerror (err)); /* In case the reason for the error is a too large array, we * release it so that it will be allocated smaller in the * next round. */ xfree (fparray); fparray = NULL; fparraysize = 0; npth_sleep (1); continue; } if (DBG_EXTPROG) { for (count=0; count < fparraysize; count++) if (!fparray[count].ignore) log_debug ("ldap-reaper: fp[%d] stream=%p r=%d %c%c%c%c%c%c%c\n", count, fparray[count].stream, ret, fparray[count].got_read? 'r':'-', fparray[count].got_write?'w':'-', fparray[count].got_oob? 'o':'-', fparray[count].got_rdhup?'H':'-', fparray[count].got_err? 'e':'-', fparray[count].got_hup? 'h':'-', fparray[count].got_nval? 'n':'-'); } /* All timestamps before exptime should be considered expired. */ exptime = time (NULL); if (exptime > INACTIVITY_TIMEOUT) exptime -= INACTIVITY_TIMEOUT; lock_reaper_list (); { for (ctx = reaper_list; ctx; ctx = ctx->next) { /* Check whether there is any logging to be done. We need * to check FPARRAYSIZE because it can be 0 in case * es_poll returned a timeout. */ if (fparraysize && ctx->log_fp && ctx->reaper_idx >= 0) { log_assert (ctx->reaper_idx < fparraysize); if (fparray[ctx->reaper_idx].got_read) { if (read_log_data (ctx)) { SAFE_CLOSE (ctx->log_fp); any_action = 1; } } } /* Check whether the process is still running. */ if (ctx->pid != (pid_t)(-1)) { int status; err = gnupg_wait_process ("[dirmngr_ldap]", ctx->pid, 0, &status); if (!err) { if (DBG_EXTPROG) log_info (_("ldap wrapper %d ready"), (int)ctx->pid); ctx->ready = 1; gnupg_release_process (ctx->pid); ctx->pid = (pid_t)(-1); any_action = 1; } else if (gpg_err_code (err) == GPG_ERR_GENERAL) { if (status == 10) log_info (_("ldap wrapper %d ready: timeout\n"), (int)ctx->pid); else log_info (_("ldap wrapper %d ready: exitcode=%d\n"), (int)ctx->pid, status); ctx->ready = 1; gnupg_release_process (ctx->pid); ctx->pid = (pid_t)(-1); any_action = 1; } else if (gpg_err_code (err) != GPG_ERR_TIMEOUT) { log_error (_("waiting for ldap wrapper %d failed: %s\n"), (int)ctx->pid, gpg_strerror (err)); any_action = 1; } } /* Check whether we should terminate the process. */ if (ctx->pid != (pid_t)(-1) && ctx->stamp != (time_t)(-1) && ctx->stamp < exptime) { gnupg_kill_process (ctx->pid); ctx->stamp = (time_t)(-1); log_info (_("ldap wrapper %d stalled - killing\n"), (int)ctx->pid); /* We need to close the log stream because the cleanup * loop waits for it. */ SAFE_CLOSE (ctx->log_fp); any_action = 1; } } /* If something has been printed to the log file or we got an * EOF from a wrapper, we now print the list of active * wrappers. */ if (any_action && DBG_EXTPROG) { log_debug ("ldap worker stati:\n"); for (ctx = reaper_list; ctx; ctx = ctx->next) log_debug (" c=%p pid=%d/%d rdr=%p logfp=%p" " ctrl=%p/%d la=%lu rdy=%d\n", ctx, (int)ctx->pid, (int)ctx->printable_pid, ctx->reader, ctx->log_fp, ctx->ctrl, ctx->ctrl? ctx->ctrl->refcount:0, (unsigned long)ctx->stamp, ctx->ready); } /* An extra loop to check whether ready marked wrappers may be * removed. We may only do so if the ksba reader object is * not anymore in use or we are in shutdown state. */ again: for (ctx_prev=NULL, ctx=reaper_list; ctx; ctx_prev=ctx, ctx=ctx->next) { if (ctx->ready && ((!ctx->log_fp && !ctx->reader) || shutting_down)) { if (ctx_prev) ctx_prev->next = ctx->next; else reaper_list = ctx->next; destroy_wrapper (ctx); goto again; } } } unlock_reaper_list (); } /*NOTREACHED*/ return NULL; /* Make the compiler happy. */ } /* Start the reaper thread for the ldap wrapper. */ void ldap_reaper_launch_thread (void) { static int done; npth_attr_t tattr; npth_t thread; int err; if (done) return; done = 1; #ifdef HAVE_W32_SYSTEM /* Static init does not yet work in W32 nPth. */ if (npth_cond_init (&reaper_run_cond, NULL)) - log_fatal ("%s: failed to init condition variabale: %s\n", + log_fatal ("%s: failed to init condition variable: %s\n", __func__, gpg_strerror (gpg_error_from_syserror ())); #endif npth_attr_init (&tattr); npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED); if (npth_create (&thread, &tattr, ldap_reaper_thread, NULL)) { err = gpg_error_from_syserror (); log_error ("error spawning ldap reaper reaper thread: %s\n", gpg_strerror (err) ); dirmngr_exit (1); } npth_setname_np (thread, "ldap-reaper"); npth_attr_destroy (&tattr); } /* Wait until all ldap wrappers have terminated. We assume that the kill has already been sent to all of them. */ void ldap_wrapper_wait_connections () { lock_reaper_list (); { shutting_down = 1; if (npth_cond_signal (&reaper_run_cond)) log_error ("%s: Ooops: signaling condition failed: %s\n", __func__, gpg_strerror (gpg_error_from_syserror ())); } unlock_reaper_list (); while (reaper_list) npth_usleep (200); } /* This function is to be used to release a context associated with the given reader object. */ void ldap_wrapper_release_context (ksba_reader_t reader) { struct wrapper_context_s *ctx; if (!reader ) return; lock_reaper_list (); { for (ctx=reaper_list; ctx; ctx=ctx->next) if (ctx->reader == reader) { if (DBG_EXTPROG) log_debug ("releasing ldap worker c=%p pid=%d/%d rdr=%p" " ctrl=%p/%d\n", ctx, (int)ctx->pid, (int)ctx->printable_pid, ctx->reader, ctx->ctrl, ctx->ctrl? ctx->ctrl->refcount:0); ctx->reader = NULL; SAFE_CLOSE (ctx->fp); if (ctx->ctrl) { ctx->ctrl->refcount--; ctx->ctrl = NULL; } if (ctx->fp_err) log_info ("%s: reading from ldap wrapper %d failed: %s\n", __func__, ctx->printable_pid, gpg_strerror (ctx->fp_err)); break; } } unlock_reaper_list (); } /* Cleanup all resources held by the connection associated with CTRL. This is used after a cancel to kill running wrappers. */ void ldap_wrapper_connection_cleanup (ctrl_t ctrl) { struct wrapper_context_s *ctx; lock_reaper_list (); { for (ctx=reaper_list; ctx; ctx=ctx->next) if (ctx->ctrl && ctx->ctrl == ctrl) { ctx->ctrl->refcount--; ctx->ctrl = NULL; if (ctx->pid != (pid_t)(-1)) gnupg_kill_process (ctx->pid); if (ctx->fp_err) log_info ("%s: reading from ldap wrapper %d failed: %s\n", __func__, ctx->printable_pid, gpg_strerror (ctx->fp_err)); } } unlock_reaper_list (); } /* This is the callback used by the ldap wrapper to feed the ksba * reader with the wrapper's stdout. See the description of * ksba_reader_set_cb for details. */ static int reader_callback (void *cb_value, char *buffer, size_t count, size_t *nread) { struct wrapper_context_s *ctx = cb_value; size_t nleft = count; struct timespec abstime; struct timespec curtime; struct timespec timeout; int millisecs; gpgrt_poll_t fparray[1]; int ret; gpg_error_t err; /* FIXME: We might want to add some internal buffering because the ksba code does not do any buffering for itself (because a ksba reader may be detached from another stream to read other data and then it would be cumbersome to get back already buffered stuff). */ if (!buffer && !count && !nread) return -1; /* Rewind is not supported. */ /* If we ever encountered a read error, don't continue (we don't want to possibly overwrite the last error cause). Bail out also if the file descriptor has been closed. */ if (ctx->fp_err || !ctx->fp) { *nread = 0; return -1; } memset (fparray, 0, sizeof fparray); fparray[0].stream = ctx->fp; fparray[0].want_read = 1; npth_clock_gettime (&abstime); abstime.tv_sec += TIMERTICK_INTERVAL; while (nleft > 0) { npth_clock_gettime (&curtime); if (!(npth_timercmp (&curtime, &abstime, <))) { err = dirmngr_tick (ctx->ctrl); if (err) { ctx->fp_err = err; SAFE_CLOSE (ctx->fp); return -1; } npth_clock_gettime (&abstime); abstime.tv_sec += TIMERTICK_INTERVAL; } npth_timersub (&abstime, &curtime, &timeout); millisecs = timeout.tv_sec * 1000; millisecs += timeout.tv_nsec / 1000000; if (millisecs < 0) millisecs = 1; if (DBG_EXTPROG) { log_debug ("%s: fp[0] stream=%p want=%d\n", __func__, fparray[0].stream,fparray[0].want_read); } ret = es_poll (fparray, DIM (fparray), millisecs); if (ret < 0) { ctx->fp_err = gpg_error_from_syserror (); log_error ("error polling stdout of ldap wrapper %d: %s\n", ctx->printable_pid, gpg_strerror (ctx->fp_err)); SAFE_CLOSE (ctx->fp); return -1; } if (DBG_EXTPROG) { log_debug ("%s: fp[0] stream=%p r=%d %c%c%c%c%c%c%c\n", __func__, fparray[0].stream, ret, fparray[0].got_read? 'r':'-', fparray[0].got_write?'w':'-', fparray[0].got_oob? 'o':'-', fparray[0].got_rdhup?'H':'-', fparray[0].got_err? 'e':'-', fparray[0].got_hup? 'h':'-', fparray[0].got_nval? 'n':'-'); } if (!ret) { /* Timeout. Will be handled when calculating the next timeout. */ continue; } if (fparray[0].got_read) { size_t n; if (es_read (ctx->fp, buffer, nleft, &n)) { ctx->fp_err = gpg_error_from_syserror (); if (gpg_err_code (ctx->fp_err) == GPG_ERR_EAGAIN) ctx->fp_err = 0; else { log_error ("%s: error reading: %s (%d)\n", __func__, gpg_strerror (ctx->fp_err), ctx->fp_err); SAFE_CLOSE (ctx->fp); return -1; } } else if (!n) /* EOF */ { if (nleft == count) return -1; /* EOF. */ break; } nleft -= n; buffer += n; if (n > 0 && ctx->stamp != (time_t)(-1)) ctx->stamp = time (NULL); } } *nread = count - nleft; return 0; } /* Fork and exec the LDAP wrapper and return a new libksba reader object at READER. ARGV is a NULL terminated list of arguments for the wrapper. The function returns 0 on success or an error code. Special hack to avoid passing a password through the command line which is globally visible: If the first element of ARGV is "--pass" it will be removed and instead the environment variable DIRMNGR_LDAP_PASS will be set to the next value of ARGV. On modern OSes the environment is not visible to other users. For those old systems where it can't be avoided, we don't want to go into the hassle of passing the password via stdin; it's just too complicated and an LDAP password used for public directory lookups should not be that confidential. */ gpg_error_t ldap_wrapper (ctrl_t ctrl, ksba_reader_t *reader, const char *argv[]) { gpg_error_t err; pid_t pid; struct wrapper_context_s *ctx; int i; int j; const char **arg_list; const char *pgmname; estream_t outfp, errfp; /* It would be too simple to connect stderr just to our logging stream. The problem is that if we are running multi-threaded everything gets intermixed. Clearly we don't want this. So the only viable solutions are either to have another thread responsible for logging the messages or to add an option to the wrapper module to do the logging on its own. Given that we anyway need a way to reap the child process and this is best done using a general reaping thread, that thread can do the logging too. */ ldap_reaper_launch_thread (); *reader = NULL; /* Files: We need to prepare stdin and stdout. We get stderr from the function. */ if (!opt.ldap_wrapper_program || !*opt.ldap_wrapper_program) pgmname = gnupg_module_name (GNUPG_MODULE_NAME_DIRMNGR_LDAP); else pgmname = opt.ldap_wrapper_program; /* Create command line argument array. */ for (i = 0; argv[i]; i++) ; arg_list = xtrycalloc (i + 2, sizeof *arg_list); if (!arg_list) { err = gpg_error_from_syserror (); log_error (_("error allocating memory: %s\n"), strerror (errno)); return err; } for (i = j = 0; argv[i]; i++, j++) if (!i && argv[i + 1] && !strcmp (*argv, "--pass")) { arg_list[j] = "--env-pass"; setenv ("DIRMNGR_LDAP_PASS", argv[1], 1); i++; } else arg_list[j] = (char*) argv[i]; ctx = xtrycalloc (1, sizeof *ctx); if (!ctx) { err = gpg_error_from_syserror (); log_error (_("error allocating memory: %s\n"), strerror (errno)); xfree (arg_list); return err; } err = gnupg_spawn_process (pgmname, arg_list, NULL, NULL, GNUPG_SPAWN_NONBLOCK, NULL, &outfp, &errfp, &pid); - xfree (arg_list); if (err) { + xfree (arg_list); xfree (ctx); log_error ("error running '%s': %s\n", pgmname, gpg_strerror (err)); return err; } ctx->pid = pid; ctx->printable_pid = (int) pid; ctx->fp = outfp; ctx->log_fp = errfp; ctx->ctrl = ctrl; ctrl->refcount++; ctx->stamp = time (NULL); err = ksba_reader_new (reader); if (!err) err = ksba_reader_set_cb (*reader, reader_callback, ctx); if (err) { + xfree (arg_list); log_error (_("error initializing reader object: %s\n"), gpg_strerror (err)); destroy_wrapper (ctx); ksba_reader_release (*reader); *reader = NULL; return err; } /* Hook the context into our list of running wrappers. */ lock_reaper_list (); { ctx->reader = *reader; ctx->next = reaper_list; reaper_list = ctx; if (npth_cond_signal (&reaper_run_cond)) log_error ("ldap-wrapper: Ooops: signaling condition failed: %s (%d)\n", gpg_strerror (gpg_error_from_syserror ()), errno); } unlock_reaper_list (); if (DBG_EXTPROG) - log_debug ("ldap wrapper %d started (%p, %s)\n", - (int)ctx->pid, ctx->reader, pgmname); + { + log_debug ("ldap wrapper %d started (%p, %s)", + (int)ctx->pid, ctx->reader, pgmname); + for (i=0; arg_list[i]; i++) + log_printf (" [%s]", arg_list[i]); + log_printf ("\n"); + } + xfree (arg_list); + /* Need to wait for the first byte so we are able to detect an empty output and not let the consumer see an EOF without further error indications. The CRL loading logic assumes that after return from this function, a failed search (e.g. host not found ) is indicated right away. */ { unsigned char c; err = read_buffer (*reader, &c, 1); if (err) { ldap_wrapper_release_context (*reader); ksba_reader_release (*reader); *reader = NULL; if (gpg_err_code (err) == GPG_ERR_EOF) return gpg_error (GPG_ERR_NO_DATA); else return err; } ksba_reader_unread (*reader, &c, 1); } return 0; } diff --git a/dirmngr/ldap.c b/dirmngr/ldap.c index e016f6415..86c2060f2 100644 --- a/dirmngr/ldap.c +++ b/dirmngr/ldap.c @@ -1,874 +1,1004 @@ /* ldap.c - LDAP access * Copyright (C) 2002 Klarälvdalens Datakonsult AB - * Copyright (C) 2003, 2004, 2005, 2007, 2008, 2010 g10 Code GmbH + * Copyright (C) 2003, 2004, 2005, 2007, 2008, 2010, 2021 g10 Code GmbH * - * This file is part of DirMngr. + * This file is part of GnuPG. * - * DirMngr is free software; you can redistribute it and/or modify + * 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 2 of the License, or + * the Free Software Foundation; either version 3 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 + * along with this program; if not, see . + * SPDX-License-Identifier: GPL-3.0-or-later */ #include #include #include #include #include #include #include #include #include #include "dirmngr.h" #include "../common/exechelp.h" #include "crlfetch.h" #include "ldapserver.h" #include "misc.h" #include "ldap-wrapper.h" +#include "ldap-url.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, + int tls_mode, + int ntds, 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, + const char *base, const char *filter, const char *attr, ksba_reader_t *reader) { - const char *argv[40]; + const char *argv[50]; int argc; char portbuf[30], timeoutbuf[30]; *reader = NULL; argc = 0; - if (pass) /* Note, that the password must be the first item. */ + if (pass && *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 (tls_mode == 1) + argv[argc++] = "--starttls"; + else if (tls_mode) + argv[argc++] = "--ldaptls"; + + if (ntds) + argv[argc++] = "--ntds"; + if (opt.ldaptimeout) { - sprintf (timeoutbuf, "%u", opt.ldaptimeout); + snprintf (timeoutbuf, sizeof 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) + if (host && *host) { argv[argc++] = "--host"; argv[argc++] = host; } if (port) { sprintf (portbuf, "%d", port); argv[argc++] = "--port"; argv[argc++] = portbuf; } - if (user) + if (user && *user) { argv[argc++] = "--user"; argv[argc++] = user; } - if (dn) - { - argv[argc++] = "--dn"; - argv[argc++] = dn; - } - if (filter) + if (base && *base) { - argv[argc++] = "--filter"; - argv[argc++] = filter; + argv[argc++] = "--base"; + argv[argc++] = base; } if (attr) { argv[argc++] = "--attr"; argv[argc++] = attr; } - argv[argc++] = url? url : "ldap://"; + + if (filter) + argv[argc++] = filter; 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) +url_fetch_ldap (ctrl_t ctrl, const char *url, ksba_reader_t *reader) { gpg_error_t err; + LDAPURLDesc *ludp = NULL; + int tls_mode; + + if (!ldap_is_ldap_url (url)) + { + log_error (_("'%s' is not an LDAP URL\n"), url); + return gpg_error (GPG_ERR_INV_URI); + } + + if (ldap_url_parse (url, &ludp)) + { + log_error (_("'%s' is an invalid LDAP URL\n"), url); + return gpg_error (GPG_ERR_INV_URI); + } + + if (ludp->lud_filter && ludp->lud_filter[0] != '(') + { + log_error (_("'%s' is an invalid LDAP URL\n"), url); + err = gpg_error (GPG_ERR_BAD_URI); + goto leave; + } + + if (ludp->lud_scheme && !strcmp (ludp->lud_scheme, "ldaps")) + tls_mode = 2; /* LDAP-over-TLS here becuase we get it from certs. */ + else + tls_mode = 0; err = run_ldap_wrapper (ctrl, 1, /* Ignore explicit timeout because CRLs might be very large. */ - 0, + 0, /* No Multi-mode. */ + tls_mode, + 0, /* No AD authentication. */ opt.ldap_proxy, - host, port, - NULL, NULL, - NULL, NULL, NULL, url, + ludp->lud_host, ludp->lud_port, + NULL, NULL, /* user, password */ + ludp->lud_dn, /* Base DN */ + ludp->lud_filter, + ludp->lud_attrs? ludp->lud_attrs[0] : NULL, 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 (ludp->lud_host) + add_server_to_servers (ludp->lud_host, ludp->lud_port); } /* 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; + if (server->starttls) + tls_mode = 1; + else if (server->ldap_over_tls) + tls_mode = 2; + else + tls_mode = 0; + err = run_ldap_wrapper (ctrl, 0, - 0, + 0, /* No Multi-mode */ + tls_mode, + server->ntds, NULL, server->host, server->port, - NULL, NULL, - NULL, NULL, NULL, url, + server->user, server->pass, + server->base, + ludp->lud_filter, + ludp->lud_attrs? ludp->lud_attrs[0] : NULL, reader); if (!err) break; } } + leave: + ldap_free_urldesc (ludp); 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 + /* FIXME; we might want to look at the Base DN 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; + int tls_mode; + + if (server->starttls) + tls_mode = 1; + else if (server->ldap_over_tls) + tls_mode = 2; + else + tls_mode = 0; err = run_ldap_wrapper (ctrl, 0, 0, + tls_mode, + server->ntds, opt.ldap_proxy, server->host, server->port, server->user, server->pass, - dn, "objectClass=*", attr, NULL, + dn, + "(objectClass=*)", + attr, 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. +/* Return true if VALUE needs escaping. */ +static int +rfc2254_need_escape (const char *value) +{ + /* NUL needs to be escaped as well but we can represent that in + * VALUE, so no need for it. */ + return !!strpbrk (value, "*()\\"); +} + +/* Escape VALUE using RFC-2254 rules. Returns NULL on error. */ +static char * +rfc2254_escape (const char *value) +{ + const char *s; + char *buffer, *p; + size_t length = 0; - * Possible patterns: + for (s=value; *s; s++) + switch (*s) + { + case '*': + case '(': + case ')': + case '\\': length += 3; break; + default: length++; break; + } + + buffer = xtrymalloc (length+1); + if (!buffer) + return NULL; + p = buffer; + for (s=value; *s; s++) + switch (*s) + { + case '*': p = stpcpy (p, "\\2a"); break; + case '(': p = stpcpy (p, "\\28"); break; + case ')': p = stpcpy (p, "\\29"); break; + case '\\': p = stpcpy (p, "\\5c"); break; + default: *p++ = *s; break; + } + *p = 0; + return buffer; +} + + +/* Return true if VALUE needs escaping. */ +static int +extfilt_need_escape (const char *value) +{ + /* NUL needs to be escaped as well but we can represent that in + * VALUE, so no need for it. */ + return !!strchr (value, '&'); +} + +/* Escape VALUE using our extended filter rules from dirmngr_ldap.c. + * Returns NULL on error. */ +static char * +extfilt_escape (const char *value) +{ + const char *s; + char *buffer, *p; + size_t length = 0; + + for (s=value; *s; s++) + { + length++; + if (*s == '&') + length++; + } + + buffer = xtrymalloc (length+1); + if (!buffer) + return NULL; + p = buffer; + for (s=value; *s; s++) + { + *p++ = *s; + if (*s == '&') + *p++ = '&'; + } + *p = 0; + return buffer; +} + + +/* Parse PATTERN and return a new filter expression for an LDAP query. + * The extended filter syntax as known by dirmngr_ldap.c is used. + * Caller must release the returned value. R_RESULT is set to NULL on + * error. * - * 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. + * Supported patterns: + * + * | Ok | gpg style user id type | + * |-----+------------------------------------------------------| + * | no | KeyID | + * | no | Fingerprint | + * | no | OpenPGP userid | + * | yes | Email address Indicated by a left angle bracket. | + * | no | Exact word match in user id or subj. name | + * | yes | Subj. DN indicated by a leading slash | + * | no | Issuer DN | + * | no | Serial number + subj. DN | + * | yes | Substring match indicated by a leading '*; (default) | */ - -strlist_t -parse_one_pattern (const char *pattern) +static gpg_error_t +make_one_filter (const char *pattern, char **r_result) { - strlist_t result = NULL; - char *p; + gpg_error_t err = 0; + char *pattern_buffer = NULL; + char *result = NULL; + size_t n; + + *r_result = NULL; 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. */ + if (rfc2254_need_escape (pattern) + && !(pattern = pattern_buffer = rfc2254_escape (pattern))) + { + err = gpg_error_from_syserror (); + goto leave; + } + result = strconcat ("(mail=", pattern, ")", NULL); + if (!result) + { + err = gpg_error_from_syserror (); + goto leave; + } + n = strlen (result); + if (result[n-2] == '>') /* Strip trailing '>' */ { - xfree (result); - result = NULL; + result[n-2] = ')'; + result[n-1] = 0; } 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); + /* We need just the BaseDN. This assumes that the Subject + * is correcly stored in the DT. This is however not always + * the case and the actual DN is different ffrom the + * subject. In this case we won't find anything. */ + if (extfilt_need_escape (pattern) + && !(pattern = pattern_buffer = extfilt_escape (pattern))) + { + err = gpg_error_from_syserror (); + goto leave; + } + result = strconcat ("^", pattern, "&base&", NULL); + if (!result) + { + err = gpg_error_from_syserror (); + goto leave; + } } break; - case '#': /* Issuer DN. */ + case '#': /* Issuer DN - Not yet working. */ pattern++; if (*pattern == '/') /* Just issuer DN. */ { pattern++; + if (extfilt_need_escape (pattern) + && !(pattern = pattern_buffer = extfilt_escape (pattern))) + { + err = gpg_error_from_syserror (); + goto leave; + } + result = strconcat ("^", pattern, "&base&", NULL); + if (!result) + { + err = gpg_error_from_syserror (); + goto leave; + } } 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); - } - } + if (*pattern) + { + if (rfc2254_need_escape (pattern) + && !(pattern = pattern_buffer = rfc2254_escape (pattern))) + { + err = gpg_error_from_syserror (); + goto leave; + } + result = strconcat ("(|(sn=*", pattern, + "*)(|(cn=*", pattern, + "*)(mail=*", pattern, + "*)))", NULL); + if (!result) + { + err = gpg_error_from_syserror (); + goto leave; + } + } break; } - return result; -} - -/* Take the string STRING and escape it according to the URL rules. - Retun 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; -} + if (!result) + err = gpg_error (GPG_ERR_INV_USER_ID); - - -/* 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 "," -/* 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 (); + leave: + xfree (pattern_buffer); + if (err) + xfree (result); else - err = 0; - - xfree (u_dn); - xfree (u_filter); + *r_result = result; 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 + /* FIXME; we might want to look at the Base DN 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) */ + 0, /* No TLS */ + 0, /* No AD authentication. */ opt.ldap_proxy, server->host, server->port, server->user, server->pass, - dn, "objectClass=*", "cACertificate", NULL, + dn, "objectClass=*", "cACertificate", &(*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 *base = NULL; char *argv[50]; int argc = 0; int argc_malloced = 0; char portbuf[30], timeoutbuf[30]; + int starttls, ldaptls, ntds; *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; + if (server->base && !(base = xtrystrdup (server->base))) + { + err = gpg_error_from_syserror (); + goto leave; + } + starttls = server->starttls; + ldaptls = server->ldap_over_tls; + ntds = server->ntds; } else /* Use a default server. */ - return gpg_error (GPG_ERR_NOT_IMPLEMENTED); - + { + err = gpg_error (GPG_ERR_NOT_IMPLEMENTED); + goto leave; + } - if (!base) - base = ""; - if (pass) /* Note: Must be the first item. */ + if (pass && *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 (starttls) + argv[argc++] = "--starttls"; + else if (ldaptls) + argv[argc++] = "--ldaptls"; + + if (ntds) + argv[argc++] = "--ntds"; + if (opt.ldaptimeout) { snprintf (timeoutbuf, sizeof timeoutbuf, "%u", opt.ldaptimeout); argv[argc++] = "--timeout"; argv[argc++] = timeoutbuf; } - if (opt.ldap_proxy) + if (proxy && *proxy) { argv[argc++] = "--proxy"; argv[argc++] = proxy; } - if (host) + if (host && *host) { argv[argc++] = "--host"; argv[argc++] = host; } if (port) { snprintf (portbuf, sizeof portbuf, "%d", port); argv[argc++] = "--port"; argv[argc++] = portbuf; } - if (user) + if (user && *user) { argv[argc++] = "--user"; argv[argc++] = user; } + if (base && *base) + { + argv[argc++] = "--base"; + argv[argc++] = base; + } + /* 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); + err = gpg_error (GPG_ERR_RESOURCE_LIMIT); + goto leave; } - sl = parse_one_pattern (patterns->d); - if (!sl) + if (*patterns->d) { - log_error (_("start_cert_fetch: invalid pattern '%s'\n"), - patterns->d); - err = gpg_error (GPG_ERR_INV_USER_ID); - goto leave; + err = make_one_filter (patterns->d, &argv[argc]); + if (err) + goto leave; + argc++; } - 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); + err = gpg_error_from_syserror (); 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 (base); 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/server.c b/dirmngr/server.c index dfcfbff09..c3bd3e51f 100644 --- a/dirmngr/server.c +++ b/dirmngr/server.c @@ -1,3212 +1,3213 @@ /* 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); 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 (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); 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 (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 (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 [--clear] \n" "\n" "Add a new LDAP server to the list of configured LDAP servers.\n" "DATA is in the same format as expected in the configure file.\n" "An optional prefix \"ldap:\" is allowed. With no args all\n" "configured ldapservers are listed. Option --clear removes all\n" "servers configured in this session."; static gpg_error_t cmd_ldapserver (assuan_context_t ctx, char *line) { #if USE_LDAP ctrl_t ctrl = assuan_get_pointer (ctx); ldap_server_t server; ldap_server_t *last_next_p; int clear_flag; clear_flag = has_option (line, "--clear"); line = skip_options (line); while (spacep (line)) line++; if (clear_flag) { #if USE_LDAP ldapserver_list_free (ctrl->server_local->ldapservers); #endif /*USE_LDAP*/ ctrl->server_local->ldapservers = NULL; } if (!*line && clear_flag) return leave_cmd (ctx, 0); if (!*line) { /* List all ldapservers. */ struct ldapserver_iter ldapserver_iter; char *tmpstr; char portstr[20]; for (ldapserver_iter_begin (&ldapserver_iter, ctrl); !ldapserver_iter_end_p (&ldapserver_iter); ldapserver_iter_next (&ldapserver_iter)) { server = ldapserver_iter.server; if (server->port) snprintf (portstr, sizeof portstr, "%d", server->port); else *portstr = 0; tmpstr = xtryasprintf ("ldap:%s:%s:%s:%s:%s:%s%s:", server->host? server->host : "", portstr, server->user? server->user : "", server->pass? "*****": "", server->base? server->base : "", server->starttls ? "starttls" : server->ldap_over_tls ? "ldaptls" : "none", server->ntds ? ",ntds" : ""); if (!tmpstr) return leave_cmd (ctx, gpg_error_from_syserror ()); dirmngr_status (ctrl, "LDAPSERVER", tmpstr, NULL); xfree (tmpstr); } return leave_cmd (ctx, 0); } /* Skip an "ldap:" prefix unless it is a valid ldap url. */ if (!strncmp (line, "ldap:", 5) && !(line[5] == '/' && line[6] == '/')) line += 5; server = ldapserver_parse_one (line, NULL, 0); if (! server) return leave_cmd (ctx, gpg_error (GPG_ERR_INV_ARG)); last_next_p = &ctrl->server_local->ldapservers; while (*last_next_p) last_next_p = &(*last_next_p)->next; *last_next_p = server; return leave_cmd (ctx, 0); #else (void)line; return leave_cmd (ctx, gpg_error (GPG_ERR_NOT_IMPLEMENTED)); #endif } static const char hlp_isvalid[] = "ISVALID [--only-ocsp] [--force-default-responder]" " []\n" "\n" "This command checks whether the certificate identified by the\n" "certificate_id is valid. This is done by consulting CRLs or\n" "whatever has been configured. Note, that the returned error codes\n" "are from gpg-error.h. The command may callback using the inquire\n" "function. See the manual for details.\n" "\n" "The CERTIFICATE_ID is a hex encoded string consisting of two parts,\n" "delimited by a single dot. The first part is the SHA-1 hash of the\n" "issuer name and the second part the serial number.\n" "\n" "If an OCSP check is desired CERTIFICATE_FPR with the hex encoded\n" "fingerprint of the certificate is required. In this case an OCSP\n" "request is done before consulting the CRL.\n" "\n" "If the option --only-ocsp is given, no fallback to a CRL check will\n" "be used.\n" "\n" "If the option --force-default-responder is given, only the default\n" "OCSP responder will be used and any other methods of obtaining an\n" "OCSP responder URL won't be used."; static gpg_error_t cmd_isvalid (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); char *issuerhash, *serialno, *fpr; gpg_error_t err; int did_inquire = 0; int ocsp_mode = 0; int only_ocsp; int force_default_responder; only_ocsp = has_option (line, "--only-ocsp"); force_default_responder = has_option (line, "--force-default-responder"); line = skip_options (line); /* We need to work on a copy of the line because that same Assuan * context may be used for an inquiry. That is because Assuan * reuses its line buffer. */ issuerhash = xstrdup (line); serialno = strchr (issuerhash, '.'); if (!serialno) { xfree (issuerhash); return leave_cmd (ctx, PARM_ERROR (_("serialno missing in cert ID"))); } *serialno++ = 0; if (strlen (issuerhash) != 40) { xfree (issuerhash); return leave_cmd (ctx, PARM_ERROR ("cert ID is too short")); } fpr = strchr (serialno, ' '); while (fpr && spacep (fpr)) fpr++; if (fpr && *fpr) { char *endp = strchr (fpr, ' '); if (endp) *endp = 0; if (strlen (fpr) != 40) { xfree (issuerhash); return leave_cmd (ctx, PARM_ERROR ("fingerprint too short")); } ocsp_mode = 1; } again: if (ocsp_mode) { /* Note, that we currently ignore the supplied fingerprint FPR; * instead ocsp_isvalid does an inquire to ask for the cert. * The fingerprint may eventually be used to lookup the * certificate in a local cache. */ if (!opt.allow_ocsp) err = gpg_error (GPG_ERR_NOT_SUPPORTED); else err = ocsp_isvalid (ctrl, NULL, NULL, force_default_responder); if (gpg_err_code (err) == GPG_ERR_CONFIGURATION && gpg_err_source (err) == GPG_ERR_SOURCE_DIRMNGR) { /* No default responder configured - fallback to CRL. */ if (!only_ocsp) log_info ("falling back to CRL check\n"); ocsp_mode = 0; goto again; } } else if (only_ocsp) err = gpg_error (GPG_ERR_NO_CRL_KNOWN); else { switch (crl_cache_isvalid (ctrl, issuerhash, serialno, ctrl->force_crl_refresh)) { case CRL_CACHE_VALID: err = 0; break; case CRL_CACHE_INVALID: err = gpg_error (GPG_ERR_CERT_REVOKED); break; case CRL_CACHE_DONTKNOW: if (did_inquire) err = gpg_error (GPG_ERR_NO_CRL_KNOWN); else if (!(err = inquire_cert_and_load_crl (ctx))) { did_inquire = 1; goto again; } break; case CRL_CACHE_CANTUSE: err = gpg_error (GPG_ERR_NO_CRL_KNOWN); break; default: log_fatal ("crl_cache_isvalid returned invalid code\n"); } } xfree (issuerhash); return leave_cmd (ctx, err); } /* If the line contains a SHA-1 fingerprint as the first argument, return the FPR vuffer on success. The function checks that the fingerprint consists of valid characters and prints and error message if it does not and returns NULL. Fingerprints are considered optional and thus no explicit error is returned. NULL is also returned if there is no fingerprint at all available. FPR must be a caller provided buffer of at least 20 bytes. Note that colons within the fingerprint are allowed to separate 2 hex digits; this allows for easier cutting and pasting using the usual fingerprint rendering. */ static unsigned char * get_fingerprint_from_line (const char *line, unsigned char *fpr) { const char *s; int i; for (s=line, i=0; *s && *s != ' '; s++ ) { if ( hexdigitp (s) && hexdigitp (s+1) ) { if ( i >= 20 ) return NULL; /* Fingerprint too long. */ fpr[i++] = xtoi_2 (s); s++; } else if ( *s != ':' ) return NULL; /* Invalid. */ } if ( i != 20 ) return NULL; /* Fingerprint to short. */ return fpr; } static const char hlp_checkcrl[] = "CHECKCRL []\n" "\n" "Check whether the certificate with FINGERPRINT (SHA-1 hash of the\n" "entire X.509 certificate blob) is valid or not by consulting the\n" "CRL responsible for this certificate. If the fingerprint has not\n" "been given or the certificate is not known, the function \n" "inquires the certificate using an\n" "\n" " INQUIRE TARGETCERT\n" "\n" "and the caller is expected to return the certificate for the\n" "request (which should match FINGERPRINT) as a binary blob.\n" "Processing then takes place without further interaction; in\n" "particular dirmngr tries to locate other required certificate by\n" "its own mechanism which includes a local certificate store as well\n" "as a list of trusted root certificates.\n" "\n" "The return value is the usual gpg-error code or 0 for ducesss;\n" "i.e. the certificate validity has been confirmed by a valid CRL."; static gpg_error_t cmd_checkcrl (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; unsigned char fprbuffer[20], *fpr; ksba_cert_t cert; fpr = get_fingerprint_from_line (line, fprbuffer); cert = fpr? get_cert_byfpr (fpr) : NULL; if (!cert) { /* We do not have this certificate yet or the fingerprint has not been given. Inquire it from the client. */ unsigned char *value = NULL; size_t valuelen; err = assuan_inquire (ctrl->server_local->assuan_ctx, "TARGETCERT", &value, &valuelen, MAX_CERT_LENGTH); if (err) { log_error (_("assuan_inquire failed: %s\n"), gpg_strerror (err)); goto leave; } if (!valuelen) /* No data returned; return a comprehensible error. */ err = gpg_error (GPG_ERR_MISSING_CERT); else { err = ksba_cert_new (&cert); if (!err) err = ksba_cert_init_from_mem (cert, value, valuelen); } xfree (value); if(err) goto leave; } assert (cert); err = crl_cache_cert_isvalid (ctrl, cert, ctrl->force_crl_refresh); if (gpg_err_code (err) == GPG_ERR_NO_CRL_KNOWN) { err = crl_cache_reload_crl (ctrl, cert); if (!err) err = crl_cache_cert_isvalid (ctrl, cert, 0); } leave: ksba_cert_release (cert); return leave_cmd (ctx, err); } static const char hlp_checkocsp[] = "CHECKOCSP [--force-default-responder] []\n" "\n" "Check whether the certificate with FINGERPRINT (SHA-1 hash of the\n" "entire X.509 certificate blob) is valid or not by asking an OCSP\n" "responder responsible for this certificate. The optional\n" "fingerprint may be used for a quick check in case an OCSP check has\n" "been done for this certificate recently (we always cache OCSP\n" "responses for a couple of minutes). If the fingerprint has not been\n" "given or there is no cached result, the function inquires the\n" "certificate using an\n" "\n" " INQUIRE TARGETCERT\n" "\n" "and the caller is expected to return the certificate for the\n" "request (which should match FINGERPRINT) as a binary blob.\n" "Processing then takes place without further interaction; in\n" "particular dirmngr tries to locate other required certificates by\n" "its own mechanism which includes a local certificate store as well\n" "as a list of trusted root certificates.\n" "\n" "If the option --force-default-responder is given, only the default\n" "OCSP responder will be used and any other methods of obtaining an\n" "OCSP responder URL won't be used.\n" "\n" "The return value is the usual gpg-error code or 0 for ducesss;\n" "i.e. the certificate validity has been confirmed by a valid CRL."; static gpg_error_t cmd_checkocsp (assuan_context_t ctx, char *line) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err; unsigned char fprbuffer[20], *fpr; ksba_cert_t cert; int force_default_responder; force_default_responder = has_option (line, "--force-default-responder"); line = skip_options (line); fpr = get_fingerprint_from_line (line, fprbuffer); cert = fpr? get_cert_byfpr (fpr) : NULL; if (!cert) { /* We do not have this certificate yet or the fingerprint has not been given. Inquire it from the client. */ unsigned char *value = NULL; size_t valuelen; err = assuan_inquire (ctrl->server_local->assuan_ctx, "TARGETCERT", &value, &valuelen, MAX_CERT_LENGTH); if (err) { log_error (_("assuan_inquire failed: %s\n"), gpg_strerror (err)); goto leave; } if (!valuelen) /* No data returned; return a comprehensible error. */ err = gpg_error (GPG_ERR_MISSING_CERT); else { err = ksba_cert_new (&cert); if (!err) err = ksba_cert_init_from_mem (cert, value, valuelen); } xfree (value); if(err) goto leave; } assert (cert); if (!opt.allow_ocsp) err = gpg_error (GPG_ERR_NOT_SUPPORTED); else err = ocsp_isvalid (ctrl, cert, NULL, force_default_responder); leave: ksba_cert_release (cert); return leave_cmd (ctx, err); } static int lookup_cert_by_url (assuan_context_t ctx, const char *url) { ctrl_t ctrl = assuan_get_pointer (ctx); gpg_error_t err = 0; unsigned char *value = NULL; size_t valuelen; /* Fetch single certificate given it's URL. */ err = fetch_cert_by_url (ctrl, url, &value, &valuelen); if (err) { log_error (_("fetch_cert_by_url failed: %s\n"), gpg_strerror (err)); goto leave; } /* Send the data, flush the buffer and then send an END. */ err = assuan_send_data (ctx, value, valuelen); if (!err) err = assuan_send_data (ctx, NULL, 0); if (!err) err = assuan_write_line (ctx, "END"); if (err) { log_error (_("error sending data: %s\n"), gpg_strerror (err)); goto leave; } leave: return err; } /* Send the certificate, flush the buffer and then send an END. */ static gpg_error_t return_one_cert (void *opaque, ksba_cert_t cert) { assuan_context_t ctx = opaque; gpg_error_t err; const unsigned char *der; size_t derlen; der = ksba_cert_get_image (cert, &derlen); if (!der) err = gpg_error (GPG_ERR_INV_CERT_OBJ); else { err = assuan_send_data (ctx, der, derlen); if (!err) err = assuan_send_data (ctx, NULL, 0); if (!err) err = assuan_write_line (ctx, "END"); } if (err) log_error (_("error sending data: %s\n"), gpg_strerror (err)); return err; } /* Lookup certificates from the internal cache or using the ldap servers. */ static int lookup_cert_by_pattern (assuan_context_t ctx, char *line, int single, int cache_only) { gpg_error_t err = 0; char *p; strlist_t sl, list = NULL; int truncated = 0, truncation_forced = 0; int count = 0; int local_count = 0; #if USE_LDAP ctrl_t ctrl = assuan_get_pointer (ctx); unsigned char *value = NULL; size_t valuelen; struct ldapserver_iter ldapserver_iter; cert_fetch_context_t fetch_context; #endif /*USE_LDAP*/ int any_no_data = 0; /* Break the line down into an STRLIST */ for (p=line; *p; line = p) { while (*p && *p != ' ') p++; if (*p) *p++ = 0; if (*line) { sl = xtrymalloc (sizeof *sl + strlen (line)); if (!sl) { err = gpg_error_from_errno (errno); goto leave; } memset (sl, 0, sizeof *sl); strcpy_escaped_plus (sl->d, line); sl->next = list; list = sl; } } /* First look through the internal cache. The certificates returned here are not counted towards the truncation limit. */ if (single && !cache_only) ; /* Do not read from the local cache in this case. */ else { for (sl=list; sl; sl = sl->next) { err = get_certs_bypattern (sl->d, return_one_cert, ctx); if (!err) local_count++; if (!err && single) goto ready; - if (gpg_err_code (err) == GPG_ERR_NO_DATA) + if (gpg_err_code (err) == GPG_ERR_NO_DATA + || gpg_err_code (err) == GPG_ERR_NOT_FOUND) { 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; char *tmpstr = NULL; *r_item = NULL; /* We used to have DNS CNAME redirection from the URLs below to * sks-keyserver. pools. The idea was to allow for a quick way to * switch to a different set of pools. The problem with that * approach is that TLS needs to verify the hostname and - because * DNS is not secured - it can only check the user supplied hostname * and not a hostname from a CNAME RR. Thus the final server all * need to have certificates with the actual pool name as well as * for keys.gnupg.net - that would render the advantage of * keys.gnupg.net useless and so we better give up on this. Because * the keys.gnupg.net URL are still in widespread use we do a static * mapping here. */ if (!strcmp (uri, "hkps://keys.gnupg.net") || !strcmp (uri, "keys.gnupg.net")) uri = "hkps://hkps.pool.sks-keyservers.net"; else if (!strcmp (uri, "https://keys.gnupg.net")) uri = "https://hkps.pool.sks-keyservers.net"; else if (!strcmp (uri, "hkp://keys.gnupg.net")) uri = "hkp://hkps.pool.sks-keyservers.net"; else if (!strcmp (uri, "http://keys.gnupg.net")) uri = "http://hkps.pool.sks-keyservers.net"; else if (!strcmp (uri, "hkps://http-keys.gnupg.net") || !strcmp (uri, "http-keys.gnupg.net")) uri = "hkps://ha.pool.sks-keyservers.net"; else if (!strcmp (uri, "https://http-keys.gnupg.net")) uri = "https://ha.pool.sks-keyservers.net"; else if (!strcmp (uri, "hkp://http-keys.gnupg.net")) uri = "hkp://ha.pool.sks-keyservers.net"; else if (!strcmp (uri, "http://http-keys.gnupg.net")) uri = "http://ha.pool.sks-keyservers.net"; item = xtrymalloc (sizeof *item + strlen (uri)); if (!item) return gpg_error_from_syserror (); item->next = NULL; item->parsed_uri = NULL; strcpy (item->uri, uri); #if USE_LDAP if (!strncmp (uri, "ldap:", 5) && !(uri[5] == '/' && uri[6] == '/')) { /* 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 err = http_parse_uri (&item->parsed_uri, tmpstr, 0); } else if ((s=strchr (uri, ':')) && !(s[1] == '/' && s[2] == '/')) { /* 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 err = http_parse_uri (&item->parsed_uri, tmpstr, 0); } else if (ldap_uri_p (uri)) { int fixup = 0; /* Fixme: We should get rid of that parser and repalce it with * our generic (http) URI parser. */ /* If no port has been specified and the scheme ist ldaps we use * our idea of the default port because the standard LDAP URL * parser would use 636 here. This is because we redefined * ldaps to mean starttls. */ #ifdef HAVE_W32_SYSTEM if (!strcmp (uri, "ldap:///")) fixup = 1; else #endif if (!http_parse_uri (&item->parsed_uri,uri,HTTP_PARSE_NO_SCHEME_CHECK)) { if (!item->parsed_uri->port && !strcmp (item->parsed_uri->scheme, "ldaps")) fixup = 2; http_release_parsed_uri (item->parsed_uri); item->parsed_uri = NULL; } err = ldap_parse_uri (&item->parsed_uri, uri); if (!err && fixup == 1) item->parsed_uri->ad_current = 1; else if (!err && fixup == 2) item->parsed_uri->port = 389; } else #endif /* USE_LDAP */ { err = http_parse_uri (&item->parsed_uri, uri, HTTP_PARSE_NO_SCHEME_CHECK); } xfree (tmpstr); 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->server_local || !(ctx = ctrl->server_local->assuan_ctx)) return 0; va_start (arg_ptr, format); err = vprint_assuan_status (ctx, keyword, format, arg_ptr); va_end (arg_ptr); return err; } /* Send a tick progress indicator back. Fixme: This is only done for the currently active channel. */ gpg_error_t dirmngr_tick (ctrl_t ctrl) { static time_t next_tick = 0; gpg_error_t err = 0; time_t now = time (NULL); if (!next_tick) { next_tick = now + 1; } else if ( now > next_tick ) { if (ctrl) { err = dirmngr_status (ctrl, "PROGRESS", "tick", "? 0 0", NULL); if (err) { /* Take this as in indication for a cancel request. */ err = gpg_error (GPG_ERR_CANCELED); } now = time (NULL); } next_tick = now + 1; } return err; } diff --git a/dirmngr/t-ldap-misc.c b/dirmngr/t-ldap-misc.c new file mode 100644 index 000000000..afba1025f --- /dev/null +++ b/dirmngr/t-ldap-misc.c @@ -0,0 +1,158 @@ +/* t-ldap-parse-uri.c - Tests for ldap-parse-uri.c and ldap-misc.c + * 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 "../common/util.h" +#include "t-support.h" +#include "ldap-misc.h" + + +static void +test_ldap_parse_extfilter (void) +{ + struct { + const char *string; + const char *base; + const char *filter; + int scope; + gpg_err_code_t ec; + } tests[] = + { + { "^CN=foo, OU=My Users&(objectClasses=*)", + "CN=foo, OU=My Users", "(objectClasses=*)", + -1 }, + { "^CN=foo, OU=My Users&base&(objectClasses=*)", + "CN=foo, OU=My Users", "(objectClasses=*)", + LDAP_SCOPE_BASE }, + { "^CN=foo, OU=My Users&one&(objectClasses=*)", + "CN=foo, OU=My Users", "(objectClasses=*)", + LDAP_SCOPE_ONELEVEL }, + { "^CN=foo, OU=My Users&sub&(objectClasses=*)", + "CN=foo, OU=My Users", "(objectClasses=*)", + LDAP_SCOPE_SUBTREE }, + /* { "^CN=foo, OU=My Users&children&(objectClasses=*)", */ + /* "CN=foo, OU=My Users", "(objectClasses=*)", */ + /* LDAP_SCOPE_CHILDREN }, */ + { "^CN=foo, OU=My Users&", + "CN=foo, OU=My Users", NULL, + -1 }, + { "^CN=foo, OU=My Users&sub&", + "CN=foo, OU=My Users", NULL, + LDAP_SCOPE_SUBTREE }, + /* { "^&children&(objectClasses=*)", */ + /* "", "(objectClasses=*)", */ + /* LDAP_SCOPE_CHILDREN }, */ + { "^CN=foo, OU=My &&Users&base&(objectClasses=*)", + "CN=foo, OU=My &Users", "(objectClasses=*)", + LDAP_SCOPE_BASE }, + { "^CN=foo, OU=My Users&&&base&(objectClasses=*)", + "CN=foo, OU=My Users&", "(objectClasses=*)", + LDAP_SCOPE_BASE }, + { "^CN=foo, OU=My Users", + NULL, NULL, + LDAP_SCOPE_BASE, GPG_ERR_SYNTAX }, + { "^CN=foo, OU=My Users&base(objectClasses=*)", + NULL, NULL, + LDAP_SCOPE_BASE, GPG_ERR_SYNTAX }, + { "^CN=foo, OU=My Users&base&objectClasses=*)", + NULL, NULL, + LDAP_SCOPE_BASE, GPG_ERR_SYNTAX }, + { "^CN=foo, OU=My Users&base&(objectClasses=*", + NULL, NULL, + LDAP_SCOPE_BASE, GPG_ERR_SYNTAX } + }; + int idx; + gpg_error_t err; + int errcount = 0; + char *base, *filter; + int scope; + + for (idx= 0; idx < DIM (tests); idx++) + { + scope = -1; + err = ldap_parse_extfilter (tests[idx].string, 1, &base, &scope, &filter); + if (err && tests[idx].ec) + { + if (gpg_err_code (err) != tests[idx].ec) + { + fprintf (stderr, "%s: test %d failed: wrong error code %d\n", + __func__, idx, err); + errcount++; + } + continue; + } + if (err) + { + fprintf (stderr, "%s: test %d failed: %s\n", + __func__, idx, gpg_strerror (err)); + errcount++; + continue; + } + if (tests[idx].ec) + { + fprintf (stderr, "%s: test %d failed: error not detected\n", + __func__, idx); + errcount++; + continue; + } + if ((!tests[idx].base ^ !base) + || (tests[idx].base && strcmp (tests[idx].base, base))) + { + fprintf (stderr, "%s: test %d failed: base mismatch ('%s')\n", + __func__, idx, base? base : "(null"); + errcount++; + } + if ((!tests[idx].filter ^ !filter) + || (tests[idx].filter && strcmp (tests[idx].filter, filter))) + { + fprintf (stderr, "%s: test %d failed: filter mismatch ('%s')\n", + __func__, idx, filter? filter : "(null"); + errcount++; + } + if (tests[idx].scope != scope) + { + fprintf (stderr, "%s: test %d failed: scope mismatch (%d)\n", + __func__, idx, scope); + errcount++; + } + xfree (base); + xfree (filter); + } + if (errcount) + exit (1); +} + + + + +int +main (int argc, char **argv) +{ + (void)argc; + (void)argv; + + test_ldap_parse_extfilter (); + + return 0; +} diff --git a/dirmngr/t-support.h b/dirmngr/t-support.h index f773f1efb..7f60c942b 100644 --- a/dirmngr/t-support.h +++ b/dirmngr/t-support.h @@ -1,42 +1,48 @@ /* t-support.h - Helper for the regression tests * Copyright (C) 2007 Free Software Foundation, Inc. * * This file is part of JNLIB, which is a subsystem of GnuPG. * * JNLIB is free software; you can redistribute it and/or modify it * under the terms of either * * - the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at * your option) any later version. * * or * * - the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at * your option) any later version. * * or both in parallel, as here. * * JNLIB 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 copies of the GNU General Public License * and the GNU Lesser General Public License along with this program; * if not, see . */ #ifndef DIRMNGR_T_SUPPORT_H #define DIRMNGR_T_SUPPORT_H 1 +#ifndef DIM +# define DIM(v) (sizeof(v)/sizeof((v)[0])) +# define DIMof(type,member) DIM(((type *)0)->member) +#endif + + /* Macros to print the result of a test. */ #define pass() do { ; } while(0) #define fail(a) do { fprintf (stderr, "%s:%d: test %d failed\n",\ __FILE__,__LINE__, (a)); \ exit (1); \ } while(0) #endif /* DIRMNGR_T_SUPPORT_H */