1 /* ks-engine-ldap.c - talk to a LDAP keyserver
2 * Copyright (C) 2001, 2002, 2004, 2005, 2006
3 * 2007 Free Software Foundation, Inc.
4 * Copyright (C) 2015, 2020 g10 Code GmbH
6 * This file is part of GnuPG.
8 * GnuPG is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * GnuPG is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <https://www.gnu.org/licenses/>.
33 #include "../common/userids.h"
34 #include "../common/mbox-util.h"
35 #include "ks-engine.h"
36 #include "ldap-misc.h"
37 #include "ldap-parse-uri.h"
38 #include "ldapserver.h"
41 /* Flags with infos from the connected server. */
42 #define SERVERINFO_REALLDAP 1 /* This is not the PGP keyserver. */
43 #define SERVERINFO_PGPKEYV2 2 /* Needs "pgpKeyV2" instead of "pgpKey"*/
44 #define SERVERINFO_SCHEMAV2 4 /* Version 2 of the Schema. */
45 #define SERVERINFO_NTDS 8 /* Server is an Active Directory. */
48 /* The page size requested from the server. */
53 time_t timegm(struct tm *tm);
57 /* Object to keep state pertaining to this module. */
58 struct ks_engine_ldap_local_s
62 LDAPMessage *msg_iter; /* Iterator for message. */
63 unsigned int serverinfo;
67 struct berval *pagecookie;
68 unsigned int pageno; /* Current page number (starting at 1). */
69 unsigned int total; /* Total number of attributes read. */
70 int more_pages; /* More pages announced by server. */
77 ldap2epochtime (const char *timestr)
82 memset (&pgptime, 0, sizeof(pgptime));
86 sscanf (timestr, "%4d%2d%2d%2d%2d%2d",
94 pgptime.tm_year -= 1900;
95 pgptime.tm_isdst = -1;
98 /* mktime() takes the timezone into account, so we use timegm() */
100 answer = timegm (&pgptime);
105 /* Caller must free the result. */
107 tm2ldaptime (struct tm *tm)
112 /* YYYYMMDDHHmmssZ */
117 snprintf (buf, sizeof buf, "%04d%02d%02d%02d%02d%02dZ",
125 return xstrdup (buf);
129 /* Caller must free */
131 epoch2ldaptime (time_t stamp)
134 if (gmtime_r (&stamp, &tm))
135 return tm2ldaptime (&tm);
137 return xstrdup ("INVALID TIME");
143 my_ldap_value_free (char **vals)
146 ldap_value_free (vals);
151 /* Print a help output for the schemata supported by this module. */
153 ks_ldap_help (ctrl_t ctrl, parsed_uri_t uri)
156 "Handler for LDAP URLs:\n"
157 " ldap://HOST:PORT/[BASEDN]????[bindname=BINDNAME,password=PASSWORD]\n"
159 "Note: basedn, bindname and password need to be percent escaped. In\n"
160 "particular, spaces need to be replaced with %20 and commas with %2c.\n"
161 "Thus bindname will typically be of the form:\n"
163 " uid=user%2cou=PGP%20Users%2cdc=EXAMPLE%2cdc=ORG\n"
165 "The ldaps:// and ldapi:// schemes are also supported. If ldaps is used\n"
166 "then the server's certificate will be checked. If it is not valid, any\n"
167 "operation will be aborted. Note that ldaps means LDAP with STARTTLS\n"
169 "As an alternative to an URL a string in this form may be used:\n"
171 " HOST:PORT:BINDNAME:PASSWORD:BASEDN:FLAGS:\n"
173 "The use of the percent sign or a colon in one of the string values is\n"
174 "currently not supported.\n"
176 "Supported methods: search, get, put\n";
180 err = ks_print_help (ctrl, " ldap");
181 else if (uri->is_ldap || uri->opaque)
182 err = ks_print_help (ctrl, data);
191 /* Create a new empty state object. Returns NULL on error */
192 static struct ks_engine_ldap_local_s *
193 ks_ldap_new_state (void)
195 return xtrycalloc (1, sizeof(struct ks_engine_ldap_local_s));
199 /* Clear the state object STATE. Returns the STATE object. */
200 static struct ks_engine_ldap_local_s *
201 ks_ldap_clear_state (struct ks_engine_ldap_local_s *state)
203 if (state->ldap_conn)
205 ldap_unbind (state->ldap_conn);
206 state->ldap_conn = NULL;
210 ldap_msgfree (state->message);
211 state->message = NULL;
213 if (state->pagecookie)
215 ber_bvfree (state->pagecookie);
216 state->pagecookie = NULL;
218 state->serverinfo = 0;
219 xfree (state->basedn);
220 state->basedn = NULL;
221 xfree (state->keyspec);
222 state->keyspec = NULL;
223 xfree (state->filter);
224 state->filter = NULL;
227 state->more_pages = 0;
232 /* Release a state object. */
234 ks_ldap_free_state (struct ks_engine_ldap_local_s *state)
238 ks_ldap_clear_state (state);
244 /* Convert a keyspec to a filter. Return an error if the keyspec is
245 bad or is not supported. The filter is escaped and returned in
246 *filter. It is the caller's responsibility to free *filter.
247 *filter is only set if this function returns success (i.e., 0). */
249 keyspec_to_ldap_filter (const char *keyspec, char **filter, int only_exact,
250 unsigned int serverinfo)
252 /* Remove search type indicator and adjust PATTERN accordingly.
253 Note: don't include a preceding 0x when searching by keyid. */
255 /* XXX: Should we include disabled / revoke options? */
256 KEYDB_SEARCH_DESC desc;
261 gpg_error_t err = classify_user_id (keyspec, &desc, 1);
267 case KEYDB_SEARCH_MODE_EXACT:
268 f = xasprintf ("(pgpUserID=%s)",
269 (freeme = ldap_escape_filter (desc.u.name)));
272 case KEYDB_SEARCH_MODE_SUBSTR:
274 f = xasprintf ("(pgpUserID=*%s*)",
275 (freeme = ldap_escape_filter (desc.u.name)));
278 case KEYDB_SEARCH_MODE_MAIL:
279 freeme = ldap_escape_filter (desc.u.name);
282 if (*freeme == '<' && freeme[1] && freeme[2])
284 /* Strip angle brackets. Note that it is does not
285 * matter whether we work on the plan or LDAP escaped
286 * version of the mailbox. */
288 if (p[strlen(p)-1] == '>')
293 if ((serverinfo & SERVERINFO_SCHEMAV2))
294 f = xasprintf ("(&(gpgMailbox=%s)(!(|(pgpRevoked=1)(pgpDisabled=1))))",
296 else if (!only_exact)
297 f = xasprintf ("(pgpUserID=*<%s>*)", p);
300 case KEYDB_SEARCH_MODE_MAILSUB:
301 if ((serverinfo & SERVERINFO_SCHEMAV2))
302 f = xasprintf("(&(gpgMailbox=*%s*)(!(|(pgpRevoked=1)(pgpDisabled=1))))",
303 (freeme = ldap_escape_filter (desc.u.name)));
304 else if (!only_exact)
305 f = xasprintf ("(pgpUserID=*<*%s*>*)",
306 (freeme = ldap_escape_filter (desc.u.name)));
309 case KEYDB_SEARCH_MODE_MAILEND:
310 if ((serverinfo & SERVERINFO_SCHEMAV2))
311 f = xasprintf("(&(gpgMailbox=*%s)(!(|(pgpRevoked=1)(pgpDisabled=1))))",
312 (freeme = ldap_escape_filter (desc.u.name)));
313 else if (!only_exact)
314 f = xasprintf ("(pgpUserID=*<*%s>*)",
315 (freeme = ldap_escape_filter (desc.u.name)));
318 case KEYDB_SEARCH_MODE_SHORT_KID:
319 f = xasprintf ("(pgpKeyID=%08lX)", (ulong) desc.u.kid[1]);
321 case KEYDB_SEARCH_MODE_LONG_KID:
322 f = xasprintf ("(pgpCertID=%08lX%08lX)",
323 (ulong) desc.u.kid[0], (ulong) desc.u.kid[1]);
326 case KEYDB_SEARCH_MODE_FPR:
327 if ((serverinfo & SERVERINFO_SCHEMAV2))
329 freeme = bin2hex (desc.u.fpr, desc.fprlen, NULL);
331 return gpg_error_from_syserror ();
332 f = xasprintf ("(|(gpgFingerprint=%s)(gpgSubFingerprint=%s))",
334 /* FIXME: For an exact search and in case of a match on
335 * gpgSubFingerprint we need to check that there is only one
340 case KEYDB_SEARCH_MODE_ISSUER:
341 case KEYDB_SEARCH_MODE_ISSUER_SN:
342 case KEYDB_SEARCH_MODE_SN:
343 case KEYDB_SEARCH_MODE_SUBJECT:
344 case KEYDB_SEARCH_MODE_KEYGRIP:
345 case KEYDB_SEARCH_MODE_WORDS:
346 case KEYDB_SEARCH_MODE_FIRST:
347 case KEYDB_SEARCH_MODE_NEXT:
356 log_error ("Unsupported search mode.\n");
357 return gpg_error (GPG_ERR_NOT_SUPPORTED);
367 /* Helper for my_ldap_connect. */
369 interrogate_ldap_dn (LDAP *ldap_conn, const char *basedn_search,
370 unsigned int *r_serverinfo)
377 char *attr2[] = { "pgpBaseKeySpaceDN", "pgpVersion", "pgpSoftware", NULL };
381 object = xasprintf ("cn=pgpServerInfo,%s", basedn_search);
384 lerr = ldap_search_s (ldap_conn, object, LDAP_SCOPE_BASE,
385 "(objectClass=*)", attr2, 0, &si_res);
389 if (lerr == LDAP_SUCCESS)
391 vals = ldap_get_values (ldap_conn, si_res, "pgpBaseKeySpaceDN");
393 basedn = xtrystrdup (vals[0]);
394 my_ldap_value_free (vals);
396 vals = ldap_get_values (ldap_conn, si_res, "pgpSoftware");
400 log_debug ("Server: \t%s\n", vals[0]);
401 if (!ascii_strcasecmp (vals[0], "GnuPG"))
404 my_ldap_value_free (vals);
406 vals = ldap_get_values (ldap_conn, si_res, "pgpVersion");
410 log_debug ("Version:\t%s\n", vals[0]);
413 const char *fields[2];
415 nfields = split_fields (vals[0], fields, DIM(fields));
416 if (nfields > 0 && atoi(fields[0]) > 1)
417 *r_serverinfo |= SERVERINFO_SCHEMAV2;
419 && !ascii_strcasecmp (fields[1], "ntds"))
420 *r_serverinfo |= SERVERINFO_NTDS;
423 my_ldap_value_free (vals);
426 /* From man ldap_search_s: "res parameter of
427 ldap_search_ext_s() and ldap_search_s() should be
428 freed with ldap_msgfree() regardless of return
429 value of these functions. */
430 ldap_msgfree (si_res);
436 /* Connect to an LDAP server and interrogate it.
438 * URI describes the server to connect to and various options
439 * including whether to use TLS and the username and password (see
440 * ldap_parse_uri for a description of the various fields).
442 * Returns: The ldap connection handle in *LDAP_CONNP, R_BASEDN is set
443 * to the base DN for the PGP key space, several flags will be stored
444 * at SERVERINFO, If you pass NULL, then the value won't be returned.
445 * It is the caller's responsibility to release *LDAP_CONNP with
446 * ldap_unbind and to xfree *BASEDNP. On error these variables are
449 * Note: On success, you still need to check that *BASEDNP is valid.
450 * If it is NULL, then the server does not appear to be an OpenPGP
453 my_ldap_connect (parsed_uri_t uri, LDAP **ldap_connp,
454 char **r_basedn, char **r_host, int *r_use_tls,
455 unsigned int *r_serverinfo)
459 ldap_server_t server = NULL;
460 LDAP *ldap_conn = NULL;
462 char *host = NULL; /* Host to use. */
463 int port; /* Port to use. */
464 int use_tls; /* 1 = starttls, 2 = ldap-over-tls */
465 int use_ntds; /* Use Active Directory authentication. */
466 int use_areconly; /* Lookup only via A record (Windows). */
467 const char *bindname;
468 const char *password;
469 const char *basedn_arg;
470 #ifndef HAVE_W32_SYSTEM
484 server = ldapserver_parse_one (uri->path, NULL, 0);
486 return gpg_error (GPG_ERR_LDAP_OTHER);
489 bindname = server->user;
490 password = bindname? server->pass : NULL;
491 basedn_arg = server->base;
492 use_tls = server->starttls? 1 : server->ldap_over_tls? 2 : 0;
493 use_ntds = server->ntds;
494 use_areconly = server->areconly;
500 bindname = uri->auth;
501 password = bindname? uri_query_value (uri, "password") : NULL;
502 basedn_arg = uri->path;
503 use_tls = uri->use_tls ? 1 : 0;
504 use_ntds = uri->ad_current;
509 port = use_tls == 2? 636 : 389;
513 host = xtrystrdup (host);
516 err = gpg_error_from_syserror ();
522 log_info ("ldap connect to '%s:%d:%s:%s:%s:%s%s%s'\n",
524 basedn_arg ? basedn_arg : "",
525 bindname ? bindname : "",
526 password ? "*****" : "",
527 use_tls == 1? "starttls" : use_tls == 2? "ldaptls" : "plain",
528 use_ntds ? ",ntds":"",
529 use_areconly? ",areconly":"");
532 /* If the uri specifies a secure connection and we don't support
533 TLS, then fail; don't silently revert to an insecure
537 #ifndef HAVE_LDAP_START_TLS_S
538 log_error ("ldap: can't connect to the server: no TLS support.");
539 err = GPG_ERR_LDAP_NOT_SUPPORTED;
545 #ifdef HAVE_W32_SYSTEM
546 /* Note that host==NULL uses the default domain controller. */
548 ldap_conn = ldap_sslinit (host, port, (use_tls == 2));
552 lerr = LdapGetLastError ();
553 err = ldap_err_to_gpg_err (lerr);
554 log_error ("error initializing LDAP '%s:%d': %s\n",
555 host, port, ldap_err2string (lerr));
560 lerr = ldap_set_option (ldap_conn, LDAP_OPT_AREC_EXCLUSIVE, LDAP_OPT_ON);
561 if (lerr != LDAP_SUCCESS)
563 log_error ("ks-ldap: unable to set LDAP_OPT_AREC_EXLUSIVE: %s\n",
564 ldap_err2string (lerr));
565 err = ldap_err_to_gpg_err (lerr);
571 tmpstr = xtryasprintf ("%s://%s:%d",
572 use_tls == 2? "ldaps" : "ldap",
576 err = gpg_error_from_syserror ();
580 lerr = ldap_initialize (&ldap_conn, tmpstr);
582 if (lerr != LDAP_SUCCESS || !ldap_conn)
584 err = ldap_err_to_gpg_err (lerr);
585 log_error ("error initializing LDAP '%s': %s\n",
586 tmpstr, ldap_err2string (lerr));
593 #ifdef HAVE_LDAP_SET_OPTION
595 int ver = LDAP_VERSION3;
597 lerr = ldap_set_option (ldap_conn, LDAP_OPT_PROTOCOL_VERSION, &ver);
598 if (lerr != LDAP_SUCCESS)
600 log_error ("ks-ldap: unable to go to LDAP 3: %s\n",
601 ldap_err2string (lerr));
602 err = ldap_err_to_gpg_err (lerr);
608 int ver = opt.ldaptimeout;
610 lerr = ldap_set_option (ldap_conn, LDAP_OPT_TIMELIMIT, &ver);
611 if (lerr != LDAP_SUCCESS)
613 log_error ("ks-ldap: unable to set LDAP timelimit to %us: %s\n",
614 opt.ldaptimeout, ldap_err2string (lerr));
615 err = ldap_err_to_gpg_err (lerr);
619 log_info ("ldap timeout set to %us\n", opt.ldaptimeout);
624 #ifdef HAVE_LDAP_START_TLS_S
627 #ifndef HAVE_W32_SYSTEM
628 int check_cert = LDAP_OPT_X_TLS_HARD; /* LDAP_OPT_X_TLS_NEVER */
630 lerr = ldap_set_option (ldap_conn,
631 LDAP_OPT_X_TLS_REQUIRE_CERT, &check_cert);
634 log_error ("ldap: error setting an TLS option: %s\n",
635 ldap_err2string (lerr));
636 err = ldap_err_to_gpg_err (lerr);
640 /* On Windows, the certificates are checked by default. If the
641 option to disable checking mentioned above is ever
642 implemented, the way to do that on Windows is to install a
643 callback routine using ldap_set_option (..,
644 LDAP_OPT_SERVER_CERTIFICATE, ..); */
648 lerr = ldap_start_tls_s (ldap_conn,
649 #ifdef HAVE_W32_SYSTEM
650 /* ServerReturnValue, result */
653 /* ServerControls, ClientControls */
658 log_error ("ldap: error switching to STARTTLS mode: %s\n",
659 ldap_err2string (lerr));
660 err = ldap_err_to_gpg_err (lerr);
668 #ifdef HAVE_W32_SYSTEM
670 lerr = ldap_bind_s (ldap_conn, NULL, NULL, LDAP_AUTH_NEGOTIATE);
672 if (lerr != LDAP_SUCCESS)
674 log_error ("error binding to LDAP via AD: %s\n",
675 ldap_err2string (lerr));
676 err = ldap_err_to_gpg_err (lerr);
680 log_error ("ldap: no Active Directory support but 'ntds' requested\n");
681 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
688 lerr = ldap_simple_bind_s (ldap_conn, bindname, password);
690 if (lerr != LDAP_SUCCESS)
692 log_error ("error binding to LDAP: %s\n", ldap_err2string (lerr));
693 err = ldap_err_to_gpg_err (lerr);
699 /* By default we don't bind as there is usually no need to. */
702 if (basedn_arg && *basedn_arg)
704 /* User specified base DN. In this case we know the server is a
705 * real LDAP server. */
706 const char *user_basedn = basedn_arg;
708 *r_serverinfo |= SERVERINFO_REALLDAP;
710 /* First try with provided basedn, else retry up one level.
711 * Retry assumes that provided entry is for keyspace,
712 * matching old behavior */
713 basedn = interrogate_ldap_dn (ldap_conn, user_basedn, r_serverinfo);
716 const char *basedn_parent = strchr (user_basedn, ',');
717 if (basedn_parent && *basedn_parent)
718 basedn = interrogate_ldap_dn (ldap_conn, basedn_parent + 1,
723 { /* Look for namingContexts. */
724 LDAPMessage *res = NULL;
725 char *attr[] = { "namingContexts", NULL };
728 lerr = ldap_search_s (ldap_conn, "", LDAP_SCOPE_BASE,
729 "(objectClass=*)", attr, 0, &res);
732 if (lerr == LDAP_SUCCESS)
737 context = ldap_get_values (ldap_conn, res, "namingContexts");
741 /* We found some, so try each namingContext as the
742 * search base and look for pgpBaseKeySpaceDN. Because
743 * we found this, we know we're talking to a regular-ish
744 * LDAP server and not an LDAP keyserver. */
747 *r_serverinfo |= SERVERINFO_REALLDAP;
749 for (i = 0; context[i] && !basedn; i++)
750 basedn = interrogate_ldap_dn (ldap_conn, context[i],
753 ldap_value_free (context);
756 else /* ldap_search failed. */
758 /* We don't have an answer yet, which means the server might
759 be a PGP.com keyserver. */
761 LDAPMessage *si_res = NULL;
763 char *attr2[] = { "pgpBaseKeySpaceDN", "version", "software", NULL };
766 lerr = ldap_search_s (ldap_conn, "cn=pgpServerInfo", LDAP_SCOPE_BASE,
767 "(objectClass=*)", attr2, 0, &si_res);
769 if (lerr == LDAP_SUCCESS)
771 /* For the PGP LDAP keyserver, this is always
772 * "OU=ACTIVE,O=PGP KEYSPACE,C=US", but it might not be
775 vals = ldap_get_values (ldap_conn, si_res, "baseKeySpaceDN");
778 basedn = xtrystrdup (vals[0]);
780 my_ldap_value_free (vals);
782 vals = ldap_get_values (ldap_conn, si_res, "software");
786 log_debug ("ks-ldap: PGP Server: \t%s\n", vals[0]);
788 my_ldap_value_free (vals);
790 vals = ldap_get_values (ldap_conn, si_res, "version");
794 log_debug ("ks-ldap: PGP Server Version:\t%s\n", vals[0]);
796 /* If the version is high enough, use the new
797 pgpKeyV2 attribute. This design is iffy at best,
798 but it matches how PGP does it. I figure the NAI
799 folks assumed that there would never be an LDAP
800 keyserver vendor with a different numbering
802 if (atoi (vals[0]) > 1)
803 *r_serverinfo |= SERVERINFO_PGPKEYV2;
806 my_ldap_value_free (vals);
809 ldap_msgfree (si_res);
812 /* From man ldap_search_s: "res parameter of ldap_search_ext_s()
813 and ldap_search_s() should be freed with ldap_msgfree()
814 regardless of return value of these functions. */
819 if (!err && opt.debug)
821 log_debug ("ldap_conn: %p\n", ldap_conn);
822 log_debug ("server_type: %s\n", ((*r_serverinfo & SERVERINFO_REALLDAP)
823 ? "LDAP" : "PGP.com keyserver") );
824 log_debug ("basedn: %s\n", basedn);
825 log_debug ("pgpkeyattr: %s\n",
826 (*r_serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey");
829 ldapserver_list_free (server);
835 ldap_unbind (ldap_conn);
848 *ldap_connp = ldap_conn;
854 /* Extract keys from an LDAP reply and write them out to the output
855 stream OUTPUT in a format GnuPG can import (either the OpenPGP
856 binary format or armored format). */
858 extract_keys (estream_t output,
859 LDAP *ldap_conn, const char *certid, LDAPMessage *message)
863 es_fprintf (output, "INFO %s BEGIN\n", certid);
865 /* Note: ldap_get_values returns a NULL terminated array of
868 vals = ldap_get_values (ldap_conn, message, "gpgfingerprint");
869 if (vals && vals[0] && vals[0][0])
870 es_fprintf (output, "pub:%s:", vals[0]);
872 es_fprintf (output, "pub:%s:", certid);
873 my_ldap_value_free (vals);
875 vals = ldap_get_values (ldap_conn, message, "pgpkeytype");
878 if (strcmp (vals[0], "RSA") == 0)
879 es_fprintf (output, "1");
880 else if (strcmp (vals[0],"DSS/DH") == 0)
881 es_fprintf (output, "17");
883 my_ldap_value_free (vals);
885 es_fprintf (output, ":");
887 vals = ldap_get_values (ldap_conn, message, "pgpkeysize");
890 int v = atoi (vals[0]);
892 es_fprintf (output, "%d", v);
894 my_ldap_value_free (vals);
896 es_fprintf (output, ":");
898 vals = ldap_get_values (ldap_conn, message, "pgpkeycreatetime");
901 if (strlen (vals[0]) == 15)
902 es_fprintf (output, "%u", (unsigned int) ldap2epochtime (vals[0]));
904 my_ldap_value_free (vals);
906 es_fprintf (output, ":");
908 vals = ldap_get_values (ldap_conn, message, "pgpkeyexpiretime");
911 if (strlen (vals[0]) == 15)
912 es_fprintf (output, "%u", (unsigned int) ldap2epochtime (vals[0]));
914 my_ldap_value_free (vals);
916 es_fprintf (output, ":");
918 vals = ldap_get_values (ldap_conn, message, "pgprevoked");
921 if (atoi (vals[0]) == 1)
922 es_fprintf (output, "r");
924 my_ldap_value_free (vals);
926 es_fprintf (output, "\n");
928 vals = ldap_get_values (ldap_conn, message, "pgpuserid");
932 for (i = 0; vals[i]; i++)
933 es_fprintf (output, "uid:%s\n", vals[i]);
935 my_ldap_value_free (vals);
937 es_fprintf (output, "INFO %s END\n", certid);
941 /* For now we do not support LDAP over Tor. */
943 no_ldap_due_to_tor (ctrl_t ctrl)
945 gpg_error_t err = gpg_error (GPG_ERR_NOT_SUPPORTED);
946 const char *msg = _("LDAP access not possible due to Tor mode");
948 log_error ("%s", msg);
949 dirmngr_status_printf (ctrl, "NOTE", "no_ldap_due_to_tor %u %s", err, msg);
950 return gpg_error (GPG_ERR_NOT_SUPPORTED);
954 /* Helper for ks_ldap_get. Returns 0 if a key was fetched and printed
955 * to FP. The error code GPG_ERR_NO_DATA is returned if no key was
956 * printed. Note that FP is updated by this function. */
958 return_one_keyblock (LDAP *ldap_conn, LDAPMessage *msg, unsigned int serverinfo,
959 estream_t *fp, strlist_t *seenp)
965 /* Use the long keyid to remove duplicates. The LDAP server returns
966 * the same keyid more than once if there are multiple user IDs on
967 * the key. Note that this does NOT mean that a keyid that exists
968 * multiple times on the keyserver will not be fetched. It means
969 * that each KEY, no matter how many user IDs share its keyid, will
970 * be fetched only once. If a keyid that belongs to more than one
971 * key is fetched, the server quite properly responds with all
974 * Note that in --first/--next mode we don't do any duplicate
978 certid = ldap_get_values (ldap_conn, msg, "pgpcertid");
979 if (certid && certid[0])
981 if (!seenp || !strlist_find (*seenp, certid[0]))
983 /* It's not a duplicate, add it */
985 add_to_strlist (seenp, certid[0]);
989 *fp = es_fopenmem(0, "rw");
992 err = gpg_error_from_syserror ();
997 extract_keys (*fp, ldap_conn, certid[0], msg);
999 vals = ldap_get_values (ldap_conn, msg,
1000 (serverinfo & SERVERINFO_PGPKEYV2)?
1001 "pgpKeyV2" : "pgpKey");
1004 err = ldap_to_gpg_err (ldap_conn);
1005 log_error("ks-ldap: unable to retrieve key %s "
1006 "from keyserver\n", certid[0]);
1010 /* We should strip the new lines. */
1011 es_fprintf (*fp, "KEY 0x%s BEGIN\n", certid[0]);
1012 es_fputs (vals[0], *fp);
1013 es_fprintf (*fp, "\nKEY 0x%s END\n", certid[0]);
1015 ldap_value_free (vals);
1019 else /* Duplicate. */
1020 err = gpg_error (GPG_ERR_NO_DATA);
1023 err = gpg_error (GPG_ERR_NO_DATA);
1026 my_ldap_value_free (certid);
1031 /* Helper for ks_ldap_get. Note that KEYSPEC is only used for
1034 search_and_parse (ctrl_t ctrl, const char *keyspec,
1035 LDAP *ldap_conn, char *basedn, char *filter,
1036 char **attrs, LDAPMessage **r_message)
1038 gpg_error_t err = 0;
1039 int l_err, l_reserr;
1040 LDAPControl *srvctrls[2] = { NULL, NULL };
1042 unsigned int totalcount = 0;
1043 LDAPControl *pagectrl = NULL;
1044 LDAPControl **resctrls = NULL;
1046 /* first/next mode is used to retrieve many entries; thus we should
1047 * use paged results. We assume first/next mode if we have a state.
1048 * We make the paged mode non-critical so that we get at least as
1049 * many entries the server delivers anyway. */
1050 if (ctrl->ks_get_state)
1052 l_err = ldap_create_page_control (ldap_conn, PAGE_SIZE,
1053 ctrl->ks_get_state->pagecookie, 0,
1057 err = ldap_err_to_gpg_err (l_err);
1058 log_error ("ks-ldap: create_page_control failed: %s\n",
1059 ldap_err2string (l_err));
1063 ctrl->ks_get_state->more_pages = 0;
1064 srvctrls[0] = pagectrl;
1068 l_err = ldap_search_ext_s (ldap_conn, basedn, LDAP_SCOPE_SUBTREE,
1070 srvctrls[0]? srvctrls : NULL, NULL, NULL, 0,
1075 err = ldap_err_to_gpg_err (l_err);
1076 log_error ("ks-ldap: LDAP search error: %s\n", ldap_err2string (l_err));
1080 if (ctrl->ks_get_state)
1082 l_err = ldap_parse_result (ldap_conn, *r_message, &l_reserr,
1083 NULL, NULL, NULL, &resctrls, 0);
1086 err = ldap_err_to_gpg_err (l_err);
1087 log_error ("ks-ldap: LDAP parse result error: %s\n",
1088 ldap_err2string (l_err));
1091 /* Get the current cookie. */
1092 if (ctrl->ks_get_state->pagecookie)
1094 ber_bvfree (ctrl->ks_get_state->pagecookie);
1095 ctrl->ks_get_state->pagecookie = NULL;
1097 l_err = ldap_parse_page_control (ldap_conn, resctrls,
1099 &ctrl->ks_get_state->pagecookie);
1102 err = ldap_err_to_gpg_err (l_err);
1103 log_error ("ks-ldap: LDAP parse page control error: %s\n",
1104 ldap_err2string (l_err));
1108 ctrl->ks_get_state->pageno++;
1110 /* Decide whether there will be more pages. */
1111 ctrl->ks_get_state->more_pages =
1112 (ctrl->ks_get_state->pagecookie
1113 && ctrl->ks_get_state->pagecookie->bv_val
1114 && *ctrl->ks_get_state->pagecookie->bv_val);
1119 count = ldap_count_entries (ldap_conn, *r_message);
1120 if (ctrl->ks_get_state)
1123 ctrl->ks_get_state->total += count;
1125 log_info ("ks-ldap: received result page %u%s (%d/%u/%u)\n",
1126 ctrl->ks_get_state->pageno,
1127 ctrl->ks_get_state->more_pages? "":" (last)",
1128 count, ctrl->ks_get_state->total, totalcount);
1132 if (!ctrl->ks_get_state || ctrl->ks_get_state->pageno == 1)
1133 log_info ("ks-ldap: key %s not found on keyserver\n", keyspec);
1136 err = ldap_to_gpg_err (ldap_conn);
1138 err = gpg_error (GPG_ERR_NO_DATA);
1146 ldap_controls_free (resctrls);
1148 ldap_control_free (pagectrl);
1153 /* Get the key described key the KEYSPEC string from the keyserver
1154 * identified by URI. On success R_FP has an open stream to read the
1155 * data. KS_GET_FLAGS conveys flags from the client. */
1157 ks_ldap_get (ctrl_t ctrl, parsed_uri_t uri, const char *keyspec,
1158 unsigned int ks_get_flags, estream_t *r_fp)
1160 gpg_error_t err = 0;
1161 unsigned int serverinfo;
1164 char *filter = NULL;
1165 LDAP *ldap_conn = NULL;
1166 char *basedn = NULL;
1167 estream_t fp = NULL;
1168 LDAPMessage *message = NULL;
1174 strlist_t seen = NULL; /* The set of entries that we've seen. */
1175 /* The ordering is significant. Specifically, "pgpcertid" needs to
1176 * be the second item in the list, since everything after it may be
1177 * discarded if we aren't in verbose mode. */
1180 "dummy", /* (to be be replaced.) */
1181 "pgpcertid", "pgpuserid", "pgpkeyid", "pgprevoked", "pgpdisabled",
1182 "pgpkeycreatetime", "modifytimestamp", "pgpkeysize", "pgpkeytype",
1189 if (dirmngr_use_tor ())
1191 return no_ldap_due_to_tor (ctrl);
1194 /* Make sure we got a state. */
1195 if ((ks_get_flags & KS_GET_FLAG_FIRST))
1197 if (ctrl->ks_get_state)
1198 ks_ldap_clear_state (ctrl->ks_get_state);
1199 else if (!(ctrl->ks_get_state = ks_ldap_new_state ()))
1200 return gpg_error_from_syserror ();
1204 if ((ks_get_flags & KS_GET_FLAG_NEXT))
1206 if (!ctrl->ks_get_state || !ctrl->ks_get_state->ldap_conn
1207 || !ctrl->ks_get_state->message)
1209 log_error ("ks_ldap: --next requested but no state\n");
1210 return gpg_error (GPG_ERR_INV_STATE);
1215 /* Do not keep an old state around if not needed. */
1216 if (!(first_mode || next_mode))
1218 ks_ldap_free_state (ctrl->ks_get_state);
1219 ctrl->ks_get_state = NULL;
1226 if (!ctrl->ks_get_state->msg_iter && ctrl->ks_get_state->more_pages)
1228 /* Get the next page of results. */
1229 if (ctrl->ks_get_state->message)
1231 ldap_msgfree (ctrl->ks_get_state->message);
1232 ctrl->ks_get_state->message = NULL;
1234 attrs[0] = ((ctrl->ks_get_state->serverinfo & SERVERINFO_PGPKEYV2)?
1235 "pgpKeyV2" : "pgpKey");
1236 err = search_and_parse (ctrl, ctrl->ks_get_state->keyspec,
1237 ctrl->ks_get_state->ldap_conn,
1238 ctrl->ks_get_state->basedn,
1239 ctrl->ks_get_state->filter,
1241 &ctrl->ks_get_state->message);
1244 ctrl->ks_get_state->msg_iter = ctrl->ks_get_state->message;
1250 while (ctrl->ks_get_state->msg_iter)
1253 ctrl->ks_get_state->msg_iter
1254 = get_first? ldap_first_entry (ctrl->ks_get_state->ldap_conn,
1255 ctrl->ks_get_state->msg_iter)
1256 /* */ : ldap_next_entry (ctrl->ks_get_state->ldap_conn,
1257 ctrl->ks_get_state->msg_iter);
1260 if (ctrl->ks_get_state->msg_iter)
1262 err = return_one_keyblock (ctrl->ks_get_state->ldap_conn,
1263 ctrl->ks_get_state->msg_iter,
1264 ctrl->ks_get_state->serverinfo,
1268 else if (gpg_err_code (err) == GPG_ERR_NO_DATA)
1269 err = 0; /* Skip empty attributes. */
1275 if (!ctrl->ks_get_state->msg_iter || !fp)
1277 ctrl->ks_get_state->msg_iter = NULL;
1278 if (ctrl->ks_get_state->more_pages)
1280 err = gpg_error (GPG_ERR_NO_DATA);
1284 else /* Not in --next mode. */
1286 /* Make sure we are talking to an OpenPGP LDAP server. */
1287 err = my_ldap_connect (uri, &ldap_conn,
1288 &basedn, &host, &use_tls, &serverinfo);
1292 err = gpg_error (GPG_ERR_GENERAL);
1296 /* Now that we have information about the server we can construct a
1297 * query best suited for the capabilities of the server. */
1298 if (first_mode && !*keyspec)
1300 filter = xtrystrdup("(!(|(pgpRevoked=1)(pgpDisabled=1)))");
1301 err = filter? 0 : gpg_error_from_syserror ();
1304 err = keyspec_to_ldap_filter (keyspec, &filter, 1, serverinfo);
1309 log_debug ("ks-ldap: using filter: %s\n", filter);
1311 /* Replace "dummy". */
1312 attrs[0] = (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2" : "pgpKey";
1314 err = search_and_parse (ctrl, keyspec, ldap_conn, basedn, filter, attrs,
1320 for (npth_unprotect (),
1321 msg = ldap_first_entry (ldap_conn, message),
1325 msg = ldap_next_entry (ldap_conn, msg),
1328 err = return_one_keyblock (ldap_conn, msg, serverinfo,
1329 &fp, first_mode? NULL : &seen);
1336 else if (gpg_err_code (err) == GPG_ERR_NO_DATA)
1337 err = 0; /* Skip empty/duplicate attributes. */
1342 if (ctrl->ks_get_state) /* Save the iterator. */
1343 ctrl->ks_get_state->msg_iter = msg;
1345 if (!fp) /* Nothing was found. */
1346 err = gpg_error (GPG_ERR_NO_DATA);
1349 err = dirmngr_status_printf (ctrl, "SOURCE", "%s://%s",
1350 use_tls? "ldaps" : "ldap",
1356 /* Store our state if needed. */
1357 if (!err && (ks_get_flags & KS_GET_FLAG_FIRST))
1359 log_assert (!ctrl->ks_get_state->ldap_conn);
1360 ctrl->ks_get_state->ldap_conn = ldap_conn;
1362 log_assert (!ctrl->ks_get_state->message);
1363 ctrl->ks_get_state->message = message;
1365 ctrl->ks_get_state->serverinfo = serverinfo;
1366 ctrl->ks_get_state->basedn = basedn;
1368 ctrl->ks_get_state->keyspec = keyspec? xtrystrdup (keyspec) : NULL;
1369 ctrl->ks_get_state->filter = filter;
1372 if ((ks_get_flags & KS_GET_FLAG_NEXT))
1374 /* Keep the state in --next mode even with errors. */
1380 ldap_msgfree (message);
1387 es_fseek (fp, 0, SEEK_SET);
1391 free_strlist (seen);
1396 ldap_unbind (ldap_conn);
1404 /* Search the keyserver identified by URI for keys matching PATTERN.
1405 On success R_FP has an open stream to read the data. */
1407 ks_ldap_search (ctrl_t ctrl, parsed_uri_t uri, const char *pattern,
1412 unsigned int serverinfo;
1413 char *filter = NULL;
1414 LDAP *ldap_conn = NULL;
1415 char *basedn = NULL;
1416 estream_t fp = NULL;
1420 if (dirmngr_use_tor ())
1422 return no_ldap_due_to_tor (ctrl);
1425 /* Make sure we are talking to an OpenPGP LDAP server. */
1426 err = my_ldap_connect (uri, &ldap_conn, &basedn, NULL, NULL, &serverinfo);
1430 err = GPG_ERR_GENERAL;
1434 /* Now that we have information about the server we can construct a
1435 * query best suited for the capabilities of the server. */
1436 err = keyspec_to_ldap_filter (pattern, &filter, 0, serverinfo);
1439 log_error ("Bad search pattern: '%s'\n", pattern);
1443 /* Even if we have no results, we want to return a stream. */
1444 fp = es_fopenmem(0, "rw");
1447 err = gpg_error_from_syserror ();
1453 LDAPMessage *res, *each;
1455 strlist_t dupelist = NULL;
1457 /* The maximum size of the search, including the optional stuff
1458 and the trailing \0 */
1461 "pgpcertid", "pgpuserid", "pgprevoked", "pgpdisabled",
1462 "pgpkeycreatetime", "pgpkeyexpiretime", "modifytimestamp",
1463 "pgpkeysize", "pgpkeytype", "gpgfingerprint",
1468 log_debug ("SEARCH '%s' => '%s' BEGIN\n", pattern, filter);
1471 ldap_err = ldap_search_s (ldap_conn, basedn,
1472 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &res);
1478 if (ldap_err != LDAP_SUCCESS && ldap_err != LDAP_SIZELIMIT_EXCEEDED)
1480 err = ldap_err_to_gpg_err (ldap_err);
1482 log_error ("SEARCH %s FAILED %d\n", pattern, err);
1483 log_error ("ks-ldap: LDAP search error: %s\n",
1484 ldap_err2string (err));
1488 /* The LDAP server doesn't return a real count of unique keys, so we
1489 can't use ldap_count_entries here. */
1490 for (npth_unprotect (),
1491 each = ldap_first_entry (ldap_conn, res),
1495 each = ldap_next_entry (ldap_conn, each),
1498 char **certid = ldap_get_values (ldap_conn, each, "pgpcertid");
1499 if (certid && certid[0] && ! strlist_find (dupelist, certid[0]))
1501 add_to_strlist (&dupelist, certid[0]);
1504 my_ldap_value_free (certid);
1507 if (ldap_err == LDAP_SIZELIMIT_EXCEEDED)
1510 log_error ("ks-ldap: search results exceeded server limit."
1511 " First 1 result shown.\n");
1513 log_error ("ks-ldap: search results exceeded server limit."
1514 " First %d results shown.\n", count);
1517 free_strlist (dupelist);
1521 es_fputs ("info:1:0\n", fp);
1524 es_fprintf (fp, "info:1:%d\n", count);
1526 for (each = ldap_first_entry (ldap_conn, res);
1528 each = ldap_next_entry (ldap_conn, each))
1533 certid = ldap_get_values (ldap_conn, each, "pgpcertid");
1534 if (!certid || !certid[0])
1536 my_ldap_value_free (certid);
1540 /* Have we seen this certid before? */
1541 if (! strlist_find (dupelist, certid[0]))
1543 add_to_strlist (&dupelist, certid[0]);
1545 vals = ldap_get_values (ldap_conn, each, "gpgfingerprint");
1546 if (vals && vals[0] && vals[0][0])
1547 es_fprintf (fp, "pub:%s:", vals[0]);
1549 es_fprintf (fp, "pub:%s:", certid[0]);
1550 my_ldap_value_free (vals);
1552 vals = ldap_get_values (ldap_conn, each, "pgpkeytype");
1553 if (vals && vals[0])
1555 /* The LDAP server doesn't exactly handle this
1557 if (strcasecmp (vals[0], "RSA") == 0)
1559 else if (strcasecmp (vals[0], "DSS/DH") == 0)
1560 es_fputs ("17", fp);
1562 my_ldap_value_free (vals);
1566 vals = ldap_get_values (ldap_conn, each, "pgpkeysize");
1567 if (vals && vals[0])
1569 /* Not sure why, but some keys are listed with a
1570 key size of 0. Treat that like an unknown. */
1571 if (atoi (vals[0]) > 0)
1572 es_fprintf (fp, "%d", atoi (vals[0]));
1574 my_ldap_value_free (vals);
1578 /* YYYYMMDDHHmmssZ */
1580 vals = ldap_get_values (ldap_conn, each, "pgpkeycreatetime");
1581 if(vals && vals[0] && strlen (vals[0]) == 15)
1583 es_fprintf (fp, "%u",
1584 (unsigned int) ldap2epochtime(vals[0]));
1586 my_ldap_value_free (vals);
1590 vals = ldap_get_values (ldap_conn, each, "pgpkeyexpiretime");
1591 if (vals && vals[0] && strlen (vals[0]) == 15)
1593 es_fprintf (fp, "%u",
1594 (unsigned int) ldap2epochtime (vals[0]));
1596 my_ldap_value_free (vals);
1600 vals = ldap_get_values (ldap_conn, each, "pgprevoked");
1601 if (vals && vals[0])
1603 if (atoi (vals[0]) == 1)
1604 es_fprintf (fp, "r");
1606 my_ldap_value_free (vals);
1608 vals = ldap_get_values (ldap_conn, each, "pgpdisabled");
1609 if (vals && vals[0])
1611 if (atoi (vals[0]) ==1)
1612 es_fprintf (fp, "d");
1614 my_ldap_value_free (vals);
1617 /* This is not yet specified in the keyserver
1618 protocol, but may be someday. */
1621 vals = ldap_get_values (ldap_conn, each, "modifytimestamp");
1622 if(vals && vals[0] strlen (vals[0]) == 15)
1624 es_fprintf (fp, "%u",
1625 (unsigned int) ldap2epochtime (vals[0]));
1627 my_ldap_value_free (vals);
1630 es_fprintf (fp, "\n");
1632 /* Now print all the uids that have this certid */
1633 for (uids = ldap_first_entry (ldap_conn, res);
1635 uids = ldap_next_entry (ldap_conn, uids))
1637 vals = ldap_get_values (ldap_conn, uids, "pgpcertid");
1638 if (!vals || !vals[0])
1640 my_ldap_value_free (vals);
1644 if (!ascii_strcasecmp (certid[0], vals[0]))
1648 es_fprintf (fp, "uid:");
1650 uidvals = ldap_get_values (ldap_conn,
1654 /* Need to percent escape any colons */
1655 char *quoted = try_percent_escape (uidvals[0],
1658 es_fputs (quoted, fp);
1661 my_ldap_value_free (uidvals);
1663 es_fprintf (fp, "\n");
1666 ldap_value_free(vals);
1670 my_ldap_value_free (certid);
1675 free_strlist (dupelist);
1679 log_debug ("SEARCH %s END\n", pattern);
1688 /* Return the read stream. */
1690 es_fseek (fp, 0, SEEK_SET);
1698 ldap_unbind (ldap_conn);
1707 /* A modlist describes a set of changes to an LDAP entry. (An entry
1708 consists of 1 or more attributes. Attributes are <name, value>
1709 pairs. Note: an attribute may be multi-valued in which case
1710 multiple values are associated with a single name.)
1712 A modlist is a NULL terminated array of struct LDAPMod's.
1722 Is the ith modification.
1724 Each LDAPMod describes a change to a single attribute. Further,
1725 there is one modification for each attribute that we want to
1726 change. The attribute's new value is stored in LDAPMod.mod_values.
1727 If the attribute is multi-valued, we still only use a single
1728 LDAPMod structure: mod_values is a NULL-terminated array of
1729 strings. To delete an attribute from an entry, we set mod_values
1734 modlist[i]->mod_values == NULL
1736 then we remove the attribute.
1738 (Using LDAP_MOD_DELETE doesn't work here as we don't know if the
1739 attribute in question exists or not.)
1741 Note: this function does NOT copy or free ATTR. It does copy
1744 modlist_add (LDAPMod ***modlistp, char *attr, const char *value)
1746 LDAPMod **modlist = *modlistp;
1751 /* Search modlist for the attribute we're playing with. If modlist
1752 is NULL, then the list is empty. Recall: modlist is a NULL
1753 terminated array. */
1754 for (m = modlist; m && *m; m++, nummods ++)
1756 /* The attribute is already on the list. */
1760 if (strcasecmp ((*m)->mod_type, attr) != 0)
1763 /* We have this attribute already, so when the REPLACE happens,
1764 the server attributes will be replaced anyway. */
1768 /* Attributes can be multi-valued. See if the value is already
1769 present. mod_values is a NULL terminated array of pointers.
1770 Note: mod_values can be NULL. */
1771 for (ptr = (*m)->mod_values; ptr && *ptr; ptr++)
1773 if (strcmp (*ptr, value) == 0)
1774 /* Duplicate value, we're done. */
1779 /* Append the value. */
1780 ptr = xrealloc ((*m)->mod_values, sizeof (char *) * (numvalues + 2));
1782 (*m)->mod_values = ptr;
1783 ptr[numvalues] = xstrdup (value);
1785 ptr[numvalues + 1] = NULL;
1790 /* We didn't find the attr, so make one and add it to the end */
1792 /* Like attribute values, the list of attributes is NULL terminated
1793 array of pointers. */
1794 modlist = xrealloc (modlist, sizeof (LDAPMod *) * (nummods + 2));
1796 *modlistp = modlist;
1797 modlist[nummods] = xmalloc (sizeof (LDAPMod));
1799 modlist[nummods]->mod_op = LDAP_MOD_REPLACE;
1800 modlist[nummods]->mod_type = attr;
1803 modlist[nummods]->mod_values = xmalloc (sizeof(char *) * 2);
1805 modlist[nummods]->mod_values[0] = xstrdup (value);
1806 modlist[nummods]->mod_values[1] = NULL;
1809 modlist[nummods]->mod_values = NULL;
1811 modlist[nummods + 1] = NULL;
1816 /* Look up the value of an attribute in the specified modlist. If the
1817 attribute is not on the mod list, returns NULL. The result is a
1818 NULL-terminated array of strings. Don't change it. */
1820 modlist_lookup (LDAPMod **modlist, const char *attr)
1823 for (m = modlist; m && *m; m++)
1825 if (strcasecmp ((*m)->mod_type, attr) != 0)
1828 return (*m)->mod_values;
1834 /* Dump a modlist to a file. This is useful for debugging. */
1835 static estream_t modlist_dump (LDAPMod **modlist, estream_t output)
1839 modlist_dump (LDAPMod **modlist, estream_t output)
1847 output = es_fopenmem (0, "rw");
1853 for (m = modlist; m && *m; m++)
1855 es_fprintf (output, " %s:", (*m)->mod_type);
1857 if (! (*m)->mod_values)
1858 es_fprintf(output, " delete.\n");
1865 if ((*m)->mod_values[0] && (*m)->mod_values[1])
1866 /* Have at least 2. */
1870 es_fprintf (output, "\n");
1872 for ((ptr = (*m)->mod_values), (i = 1); ptr && *ptr; ptr++, i ++)
1874 /* Assuming terminals are about 80 characters wide,
1875 display at most about 10 lines of debugging
1876 output. If we do trim the buffer, append '...' to
1878 const int max_len = 10 * 70;
1879 size_t value_len = strlen (*ptr);
1880 int elide = value_len > max_len;
1883 es_fprintf (output, " %d. ", i);
1884 es_fprintf (output, "`%.*s", max_len, *ptr);
1886 es_fprintf (output, "...' (%zd bytes elided)",
1887 value_len - max_len);
1889 es_fprintf (output, "'");
1890 es_fprintf (output, "\n");
1896 es_fseek (output, 0, SEEK_SET);
1901 /* Free all of the memory allocated by the mod list. This assumes
1902 that the attribute names don't have to be freed, but the attributes
1903 values do. (Which is what modlist_add does.) */
1905 modlist_free (LDAPMod **modlist)
1912 /* Unwind and free the whole modlist structure */
1914 /* The modlist is a NULL terminated array of pointers. */
1915 for (ml = modlist; *ml; ml++)
1920 /* The list of values is a NULL termianted array of pointers.
1921 If the list is NULL, there are no values. */
1923 if (mod->mod_values)
1925 for (ptr = mod->mod_values; *ptr; ptr++)
1928 xfree (mod->mod_values);
1936 /* Append two onto the end of one. Two is not freed, but its pointers
1937 are now part of one. Make sure you don't free them both!
1939 As long as you don't add anything to ONE, TWO is still valid.
1940 After that all bets are off. */
1942 modlists_join (LDAPMod ***one, LDAPMod **two)
1944 int i, one_count = 0, two_count = 0;
1948 /* two is empty. Nothing to do. */
1952 /* one is empty. Just set it equal to *two. */
1958 for (grow = *one; *grow; grow++)
1961 for (grow = two; *grow; grow++)
1964 grow = xrealloc (*one, sizeof(LDAPMod *) * (one_count + two_count + 1));
1966 for (i = 0; i < two_count; i++)
1967 grow[one_count + i] = two[i];
1969 grow[one_count + i] = NULL;
1974 /* Given a string, unescape C escapes. In particular, \xXX. This
1975 modifies the string in place. */
1977 uncescape (char *str)
1982 char *first = strchr (str, '\\');
1984 /* No backslashes => no escaping. We're done. */
1987 /* Start at the first '\\'. */
1988 r = w = (uintptr_t) first - (uintptr_t) str;
1992 /* XXX: What to do about bad escapes?
1993 XXX: hextobyte already checks the string thus the hexdigitp
1994 could be removed. */
1995 if (str[r] == '\\' && str[r + 1] == 'x'
1996 && str[r+2] && str[r+3]
1997 && hexdigitp (str + r + 2)
1998 && hexdigitp (str + r + 3))
2000 int x = hextobyte (&str[r + 2]);
2001 log_assert (0 <= x && x <= 0xff);
2005 /* We consumed 4 characters and wrote 1. */
2010 str[w ++] = str[r ++];
2016 /* Given one line from an info block (`gpg --list-{keys,sigs}
2017 --with-colons KEYID'), pull it apart and fill in the modlist with
2018 the relevant (for the LDAP schema) attributes. EXTRACT_STATE
2019 should initally be set to 0 by the caller. SCHEMAV2 is set if the
2020 server supports the version 2 schema. */
2022 extract_attributes (LDAPMod ***modlist, int *extract_state,
2023 char *line, int schemav2)
2028 int is_pub, is_sub, is_uid, is_sig;
2030 /* Remove trailing whitespace */
2031 trim_trailing_spaces (line);
2033 fields = strsplit (line, ':', '\0', &field_count);
2034 if (field_count == 1)
2035 /* We only have a single field. There is definitely nothing to
2039 if (field_count < 7)
2042 is_pub = !ascii_strcasecmp ("pub", fields[0]);
2043 is_sub = !ascii_strcasecmp ("sub", fields[0]);
2044 is_uid = !ascii_strcasecmp ("uid", fields[0]);
2045 is_sig = !ascii_strcasecmp ("sig", fields[0]);
2046 if (!ascii_strcasecmp ("fpr", fields[0]))
2048 /* Special treatment for a fingerprint. */
2049 if (!(*extract_state & 1))
2050 goto out; /* Stray fingerprint line - ignore. */
2051 *extract_state &= ~1;
2052 if (field_count >= 10 && schemav2)
2054 if ((*extract_state & 2))
2055 modlist_add (modlist, "gpgFingerprint", fields[9]);
2057 modlist_add (modlist, "gpgSubFingerprint", fields[9]);
2062 *extract_state &= ~(1|2);
2064 *extract_state |= (1|2);
2066 *extract_state |= 1;
2068 if (!is_pub && !is_sub && !is_uid && !is_sig)
2069 goto out; /* Not a relevant line. */
2073 if (is_uid && strlen (keyid) == 0)
2074 ; /* The uid record type can have an empty keyid. */
2075 else if (strlen (keyid) == 16
2076 && strspn (keyid, "0123456789aAbBcCdDeEfF") == 16)
2077 ; /* Otherwise, we expect exactly 16 hex characters. */
2080 log_error ("malformed record!\n");
2089 for (flags = fields[1]; *flags; flags ++)
2103 /* Note: we always create the pgpDisabled and pgpRevoked
2104 attributes, regardless of whether the key is disabled/revoked
2105 or not. This is because a very common search is like
2106 "(&(pgpUserID=*isabella*)(pgpDisabled=0))" */
2110 modlist_add (modlist,"pgpDisabled", disabled ? "1" : "0");
2111 modlist_add (modlist,"pgpRevoked", revoked ? "1" : "0");
2115 if (is_pub || is_sub)
2120 val = atoi (fields[2]);
2121 if (val < 99999 && val > 0)
2123 /* We zero pad this on the left to make PGP happy. */
2124 snprintf (padded, sizeof padded, "%05u", val);
2125 modlist_add (modlist, "pgpKeySize", padded);
2131 char *algo = fields[3];
2132 int val = atoi (algo);
2149 modlist_add (modlist, "pgpKeyType", algo);
2152 if (is_pub || is_sub || is_sig)
2156 modlist_add (modlist, "pgpCertID", keyid); /* Long keyid(!) */
2157 modlist_add (modlist, "pgpKeyID", &keyid[8]); /* Short keyid */
2161 modlist_add (modlist, "pgpSubKeyID", keyid); /* Long keyid(!) */
2166 char *create_time = fields[5];
2168 if (strlen (create_time) == 0)
2172 char *create_time_orig = create_time;
2177 memset (&tm, 0, sizeof (tm));
2179 /* parse_timestamp handles both seconds fromt he epoch and
2180 ISO 8601 format. We also need to handle YYYY-MM-DD
2181 format (as generated by gpg1 --with-colons --list-key).
2182 Check that first and then if it fails, then try
2185 if (!isodate_human_to_tm (create_time, &tm))
2186 create_time = tm2ldaptime (&tm);
2187 else if ((t = parse_timestamp (create_time, &end)) != (time_t) -1
2191 if (!gnupg_gmtime (&t, &tm))
2194 create_time = tm2ldaptime (&tm);
2200 /* Failed to parse string. */
2201 log_error ("Failed to parse creation time ('%s')",
2207 modlist_add (modlist, "pgpKeyCreateTime", create_time);
2208 xfree (create_time);
2214 char *expire_time = fields[6];
2216 if (strlen (expire_time) == 0)
2220 char *expire_time_orig = expire_time;
2225 memset (&tm, 0, sizeof (tm));
2227 /* parse_timestamp handles both seconds fromt he epoch and
2228 ISO 8601 format. We also need to handle YYYY-MM-DD
2229 format (as generated by gpg1 --with-colons --list-key).
2230 Check that first and then if it fails, then try
2233 if (!isodate_human_to_tm (expire_time, &tm))
2234 expire_time = tm2ldaptime (&tm);
2235 else if ((t = parse_timestamp (expire_time, &end)) != (time_t) -1
2238 if (!gnupg_gmtime (&t, &tm))
2241 expire_time = tm2ldaptime (&tm);
2247 /* Failed to parse string. */
2248 log_error ("Failed to parse creation time ('%s')",
2254 modlist_add (modlist, "pgpKeyExpireTime", expire_time);
2255 xfree (expire_time);
2259 if (is_uid && field_count >= 10)
2261 char *uid = fields[9];
2265 modlist_add (modlist, "pgpUserID", uid);
2266 if (schemav2 && (mbox = mailbox_from_userid (uid, 0)))
2268 modlist_add (modlist, "gpgMailbox", mbox);
2277 /* Send the key in {KEY,KEYLEN} with the metadata {INFO,INFOLEN} to
2278 the keyserver identified by URI. See server.c:cmd_ks_put for the
2279 format of the data and metadata. */
2281 ks_ldap_put (ctrl_t ctrl, parsed_uri_t uri,
2282 void *data, size_t datalen,
2283 void *info, size_t infolen)
2285 gpg_error_t err = 0;
2287 unsigned int serverinfo;
2288 LDAP *ldap_conn = NULL;
2289 char *basedn = NULL;
2290 LDAPMod **modlist = NULL;
2291 LDAPMod **addlist = NULL;
2292 char *data_armored = NULL;
2295 /* The last byte of the info block. */
2296 const char *infoend = (const char *) info + infolen - 1;
2298 /* Enable this code to dump the modlist to /tmp/modlist.txt. */
2300 # warning Disable debug code before checking in.
2301 const int dump_modlist = 1;
2303 const int dump_modlist = 0;
2305 estream_t dump = NULL;
2307 /* Elide a warning. */
2310 if (dirmngr_use_tor ())
2312 return no_ldap_due_to_tor (ctrl);
2315 err = my_ldap_connect (uri, &ldap_conn, &basedn, NULL, NULL, &serverinfo);
2319 err = GPG_ERR_GENERAL;
2323 if (!(serverinfo & SERVERINFO_REALLDAP))
2325 /* We appear to have a PGP.com Keyserver, which can unpack the
2326 * key on its own (not just a dump LDAP server). This will
2327 * rarely be the case these days. */
2335 memset (&mod, 0, sizeof (mod));
2336 mod.mod_op = LDAP_MOD_ADD;
2337 mod.mod_type = (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey";
2338 mod.mod_values = key;
2342 dn = xtryasprintf ("pgpCertid=virtual,%s", basedn);
2345 err = gpg_error_from_syserror ();
2348 ldap_err = ldap_add_s (ldap_conn, dn, attrs);
2351 if (ldap_err != LDAP_SUCCESS)
2353 err = ldap_err_to_gpg_err (err);
2360 modlist = xtrymalloc (sizeof (LDAPMod *));
2363 err = gpg_error_from_syserror ();
2370 dump = es_fopen("/tmp/modlist.txt", "w");
2372 log_error ("failed to open /tmp/modlist.txt: %s\n",
2373 gpg_strerror (gpg_error_from_syserror ()));
2377 es_fprintf(dump, "data (%zd bytes)\n", datalen);
2378 es_fprintf(dump, "info (%zd bytes): '\n", infolen);
2379 es_fwrite(info, infolen, 1, dump);
2380 es_fprintf(dump, "'\n");
2384 /* Start by nulling out all attributes. We try and do a modify
2385 operation first, so this ensures that we don't leave old
2386 attributes lying around. */
2387 modlist_add (&modlist, "pgpDisabled", NULL);
2388 modlist_add (&modlist, "pgpKeyID", NULL);
2389 modlist_add (&modlist, "pgpKeyType", NULL);
2390 modlist_add (&modlist, "pgpUserID", NULL);
2391 modlist_add (&modlist, "pgpKeyCreateTime", NULL);
2392 modlist_add (&modlist, "pgpRevoked", NULL);
2393 modlist_add (&modlist, "pgpSubKeyID", NULL);
2394 modlist_add (&modlist, "pgpKeySize", NULL);
2395 modlist_add (&modlist, "pgpKeyExpireTime", NULL);
2396 modlist_add (&modlist, "pgpCertID", NULL);
2397 if ((serverinfo & SERVERINFO_SCHEMAV2))
2399 modlist_add (&modlist, "gpgFingerprint", NULL);
2400 modlist_add (&modlist, "gpgSubFingerprint", NULL);
2401 modlist_add (&modlist, "gpgMailbox", NULL);
2404 /* Assemble the INFO stuff into LDAP attributes */
2410 char *newline = memchr (info, '\n', infolen);
2412 /* The last line is not \n terminated! Make a copy so we can
2413 add a NUL terminator. */
2415 temp = xmalloc (infolen + 1);
2416 memcpy (temp, info, infolen);
2418 newline = (char *) info + infolen;
2423 extract_attributes (&addlist, &extract_state, info,
2424 (serverinfo & SERVERINFO_SCHEMAV2));
2426 infolen = infolen - ((uintptr_t) newline - (uintptr_t) info + 1);
2431 log_assert ((char *) info + infolen - 1 == infoend);
2434 log_assert (infolen == -1);
2439 modlist_add (&addlist, "objectClass", "pgpKeyInfo");
2441 err = armor_data (&data_armored, data, datalen);
2445 modlist_add (&addlist,
2446 (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey",
2449 /* Now append addlist onto modlist. */
2450 modlists_join (&modlist, addlist);
2454 estream_t input = modlist_dump (modlist, NULL);
2457 copy_stream (input, dump);
2462 /* Going on the assumption that modify operations are more frequent
2463 than adds, we try a modify first. If it's not there, we just
2464 turn around and send an add command for the same key. Otherwise,
2465 the modify brings the server copy into compliance with our copy.
2466 Note that unlike the LDAP keyserver (and really, any other
2467 keyserver) this does NOT merge signatures, but replaces the whole
2468 key. This should make some people very happy. */
2473 if ((serverinfo & SERVERINFO_NTDS))
2475 /* The modern way using a CN RDN with the fingerprint. This
2476 * has the advantage that we won't have duplicate 64 bit
2477 * keyids in the store. In particular NTDS requires the
2478 * DN to be unique. */
2479 attrval = modlist_lookup (addlist, "gpgFingerprint");
2480 /* We should have exactly one value. */
2481 if (!attrval || !(attrval[0] && !attrval[1]))
2483 log_error ("ks-ldap: bad gpgFingerprint provided\n");
2484 err = GPG_ERR_GENERAL;
2487 dn = xtryasprintf ("CN=%s,%s", attrval[0], basedn);
2489 else /* The old style way. */
2491 attrval = modlist_lookup (addlist, "pgpCertID");
2492 /* We should have exactly one value. */
2493 if (!attrval || !(attrval[0] && !attrval[1]))
2495 log_error ("ks-ldap: bad pgpCertID provided\n");
2496 err = GPG_ERR_GENERAL;
2499 dn = xtryasprintf ("pgpCertID=%s,%s", attrval[0], basedn);
2503 err = gpg_error_from_syserror ();
2507 log_debug ("ks-ldap: using DN: %s\n", dn);
2510 err = ldap_modify_s (ldap_conn, dn, modlist);
2511 if (err == LDAP_NO_SUCH_OBJECT)
2512 err = ldap_add_s (ldap_conn, dn, addlist);
2517 if (err != LDAP_SUCCESS)
2519 log_error ("ks-ldap: error adding key to keyserver: %s\n",
2520 ldap_err2string (err));
2521 err = ldap_err_to_gpg_err (err);
2530 ldap_unbind (ldap_conn);
2534 modlist_free (modlist);
2537 xfree (data_armored);