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/>.
35 # include <winsock2.h>
41 /* For OpenLDAP, to enable the API that we're using. */
42 # define LDAP_DEPRECATED 1
49 #include "../common/userids.h"
50 #include "../common/mbox-util.h"
51 #include "ks-engine.h"
52 #include "ldap-parse-uri.h"
55 /* Flags with infos from the connected server. */
56 #define SERVERINFO_REALLDAP 1 /* This is not the PGP keyserver. */
57 #define SERVERINFO_PGPKEYV2 2 /* Needs "pgpeyV2" instead of "pgpKey" */
58 #define SERVERINFO_SCHEMAV2 4 /* Version 2 of the Schema. */
59 #define SERVERINFO_NTDS 8 /* Server is an Active Directory. */
64 time_t timegm(struct tm *tm);
67 /* Convert an LDAP error to a GPG error. */
69 ldap_err_to_gpg_err (int code)
75 #ifdef LDAP_X_CONNECTING
76 case LDAP_X_CONNECTING: ec = GPG_ERR_LDAP_X_CONNECTING; break;
79 case LDAP_REFERRAL_LIMIT_EXCEEDED: ec = GPG_ERR_LDAP_REFERRAL_LIMIT; break;
80 case LDAP_CLIENT_LOOP: ec = GPG_ERR_LDAP_CLIENT_LOOP; break;
81 case LDAP_NO_RESULTS_RETURNED: ec = GPG_ERR_LDAP_NO_RESULTS; break;
82 case LDAP_CONTROL_NOT_FOUND: ec = GPG_ERR_LDAP_CONTROL_NOT_FOUND; break;
83 case LDAP_NOT_SUPPORTED: ec = GPG_ERR_LDAP_NOT_SUPPORTED; break;
84 case LDAP_CONNECT_ERROR: ec = GPG_ERR_LDAP_CONNECT; break;
85 case LDAP_NO_MEMORY: ec = GPG_ERR_LDAP_NO_MEMORY; break;
86 case LDAP_PARAM_ERROR: ec = GPG_ERR_LDAP_PARAM; break;
87 case LDAP_USER_CANCELLED: ec = GPG_ERR_LDAP_USER_CANCELLED; break;
88 case LDAP_FILTER_ERROR: ec = GPG_ERR_LDAP_FILTER; break;
89 case LDAP_AUTH_UNKNOWN: ec = GPG_ERR_LDAP_AUTH_UNKNOWN; break;
90 case LDAP_TIMEOUT: ec = GPG_ERR_LDAP_TIMEOUT; break;
91 case LDAP_DECODING_ERROR: ec = GPG_ERR_LDAP_DECODING; break;
92 case LDAP_ENCODING_ERROR: ec = GPG_ERR_LDAP_ENCODING; break;
93 case LDAP_LOCAL_ERROR: ec = GPG_ERR_LDAP_LOCAL; break;
94 case LDAP_SERVER_DOWN: ec = GPG_ERR_LDAP_SERVER_DOWN; break;
96 case LDAP_SUCCESS: ec = GPG_ERR_LDAP_SUCCESS; break;
98 case LDAP_OPERATIONS_ERROR: ec = GPG_ERR_LDAP_OPERATIONS; break;
99 case LDAP_PROTOCOL_ERROR: ec = GPG_ERR_LDAP_PROTOCOL; break;
100 case LDAP_TIMELIMIT_EXCEEDED: ec = GPG_ERR_LDAP_TIMELIMIT; break;
101 case LDAP_SIZELIMIT_EXCEEDED: ec = GPG_ERR_LDAP_SIZELIMIT; break;
102 case LDAP_COMPARE_FALSE: ec = GPG_ERR_LDAP_COMPARE_FALSE; break;
103 case LDAP_COMPARE_TRUE: ec = GPG_ERR_LDAP_COMPARE_TRUE; break;
104 case LDAP_AUTH_METHOD_NOT_SUPPORTED: ec=GPG_ERR_LDAP_UNSUPPORTED_AUTH;break;
105 case LDAP_STRONG_AUTH_REQUIRED: ec = GPG_ERR_LDAP_STRONG_AUTH_RQRD; break;
106 case LDAP_PARTIAL_RESULTS: ec = GPG_ERR_LDAP_PARTIAL_RESULTS; break;
107 case LDAP_REFERRAL: ec = GPG_ERR_LDAP_REFERRAL; break;
109 #ifdef LDAP_ADMINLIMIT_EXCEEDED
110 case LDAP_ADMINLIMIT_EXCEEDED: ec = GPG_ERR_LDAP_ADMINLIMIT; break;
113 #ifdef LDAP_UNAVAILABLE_CRITICAL_EXTENSION
114 case LDAP_UNAVAILABLE_CRITICAL_EXTENSION:
115 ec = GPG_ERR_LDAP_UNAVAIL_CRIT_EXTN; break;
118 case LDAP_CONFIDENTIALITY_REQUIRED: ec = GPG_ERR_LDAP_CONFIDENT_RQRD; break;
119 case LDAP_SASL_BIND_IN_PROGRESS: ec = GPG_ERR_LDAP_SASL_BIND_INPROG; break;
120 case LDAP_NO_SUCH_ATTRIBUTE: ec = GPG_ERR_LDAP_NO_SUCH_ATTRIBUTE; break;
121 case LDAP_UNDEFINED_TYPE: ec = GPG_ERR_LDAP_UNDEFINED_TYPE; break;
122 case LDAP_INAPPROPRIATE_MATCHING: ec = GPG_ERR_LDAP_BAD_MATCHING; break;
123 case LDAP_CONSTRAINT_VIOLATION: ec = GPG_ERR_LDAP_CONST_VIOLATION; break;
125 #ifdef LDAP_TYPE_OR_VALUE_EXISTS
126 case LDAP_TYPE_OR_VALUE_EXISTS: ec = GPG_ERR_LDAP_TYPE_VALUE_EXISTS; break;
129 case LDAP_INVALID_SYNTAX: ec = GPG_ERR_LDAP_INV_SYNTAX; break;
130 case LDAP_NO_SUCH_OBJECT: ec = GPG_ERR_LDAP_NO_SUCH_OBJ; break;
131 case LDAP_ALIAS_PROBLEM: ec = GPG_ERR_LDAP_ALIAS_PROBLEM; break;
132 case LDAP_INVALID_DN_SYNTAX: ec = GPG_ERR_LDAP_INV_DN_SYNTAX; break;
133 case LDAP_IS_LEAF: ec = GPG_ERR_LDAP_IS_LEAF; break;
134 case LDAP_ALIAS_DEREF_PROBLEM: ec = GPG_ERR_LDAP_ALIAS_DEREF; break;
136 #ifdef LDAP_X_PROXY_AUTHZ_FAILURE
137 case LDAP_X_PROXY_AUTHZ_FAILURE: ec = GPG_ERR_LDAP_X_PROXY_AUTH_FAIL; break;
140 case LDAP_INAPPROPRIATE_AUTH: ec = GPG_ERR_LDAP_BAD_AUTH; break;
141 case LDAP_INVALID_CREDENTIALS: ec = GPG_ERR_LDAP_INV_CREDENTIALS; break;
143 #ifdef LDAP_INSUFFICIENT_ACCESS
144 case LDAP_INSUFFICIENT_ACCESS: ec = GPG_ERR_LDAP_INSUFFICIENT_ACC; break;
147 case LDAP_BUSY: ec = GPG_ERR_LDAP_BUSY; break;
148 case LDAP_UNAVAILABLE: ec = GPG_ERR_LDAP_UNAVAILABLE; break;
149 case LDAP_UNWILLING_TO_PERFORM: ec = GPG_ERR_LDAP_UNWILL_TO_PERFORM; break;
150 case LDAP_LOOP_DETECT: ec = GPG_ERR_LDAP_LOOP_DETECT; break;
151 case LDAP_NAMING_VIOLATION: ec = GPG_ERR_LDAP_NAMING_VIOLATION; break;
152 case LDAP_OBJECT_CLASS_VIOLATION: ec = GPG_ERR_LDAP_OBJ_CLS_VIOLATION; break;
153 case LDAP_NOT_ALLOWED_ON_NONLEAF: ec=GPG_ERR_LDAP_NOT_ALLOW_NONLEAF;break;
154 case LDAP_NOT_ALLOWED_ON_RDN: ec = GPG_ERR_LDAP_NOT_ALLOW_ON_RDN; break;
155 case LDAP_ALREADY_EXISTS: ec = GPG_ERR_LDAP_ALREADY_EXISTS; break;
156 case LDAP_NO_OBJECT_CLASS_MODS: ec = GPG_ERR_LDAP_NO_OBJ_CLASS_MODS; break;
157 case LDAP_RESULTS_TOO_LARGE: ec = GPG_ERR_LDAP_RESULTS_TOO_LARGE; break;
158 case LDAP_AFFECTS_MULTIPLE_DSAS: ec = GPG_ERR_LDAP_AFFECTS_MULT_DSAS; break;
160 #ifdef LDAP_VLV_ERROR
161 case LDAP_VLV_ERROR: ec = GPG_ERR_LDAP_VLV; break;
164 case LDAP_OTHER: ec = GPG_ERR_LDAP_OTHER; break;
166 #ifdef LDAP_CUP_RESOURCES_EXHAUSTED
167 case LDAP_CUP_RESOURCES_EXHAUSTED: ec=GPG_ERR_LDAP_CUP_RESOURCE_LIMIT;break;
168 case LDAP_CUP_SECURITY_VIOLATION: ec=GPG_ERR_LDAP_CUP_SEC_VIOLATION; break;
169 case LDAP_CUP_INVALID_DATA: ec = GPG_ERR_LDAP_CUP_INV_DATA; break;
170 case LDAP_CUP_UNSUPPORTED_SCHEME: ec = GPG_ERR_LDAP_CUP_UNSUP_SCHEME; break;
171 case LDAP_CUP_RELOAD_REQUIRED: ec = GPG_ERR_LDAP_CUP_RELOAD; break;
174 #ifdef LDAP_CANCELLED
175 case LDAP_CANCELLED: ec = GPG_ERR_LDAP_CANCELLED; break;
178 #ifdef LDAP_NO_SUCH_OPERATION
179 case LDAP_NO_SUCH_OPERATION: ec = GPG_ERR_LDAP_NO_SUCH_OPERATION; break;
183 case LDAP_TOO_LATE: ec = GPG_ERR_LDAP_TOO_LATE; break;
186 #ifdef LDAP_CANNOT_CANCEL
187 case LDAP_CANNOT_CANCEL: ec = GPG_ERR_LDAP_CANNOT_CANCEL; break;
190 #ifdef LDAP_ASSERTION_FAILED
191 case LDAP_ASSERTION_FAILED: ec = GPG_ERR_LDAP_ASSERTION_FAILED; break;
194 #ifdef LDAP_PROXIED_AUTHORIZATION_DENIED
195 case LDAP_PROXIED_AUTHORIZATION_DENIED:
196 ec = GPG_ERR_LDAP_PROX_AUTH_DENIED; break;
200 #if defined(LDAP_E_ERROR) && defined(LDAP_X_ERROR)
201 if (LDAP_E_ERROR (code))
202 ec = GPG_ERR_LDAP_E_GENERAL;
203 else if (LDAP_X_ERROR (code))
204 ec = GPG_ERR_LDAP_X_GENERAL;
207 ec = GPG_ERR_LDAP_GENERAL;
214 /* Retrieve an LDAP error and return it's GPG equivalent. */
216 ldap_to_gpg_err (LDAP *ld)
218 #if defined(HAVE_LDAP_GET_OPTION) && defined(LDAP_OPT_ERROR_NUMBER)
221 if (ldap_get_option (ld, LDAP_OPT_ERROR_NUMBER, &err) == 0)
222 return ldap_err_to_gpg_err (err);
224 return GPG_ERR_GENERAL;
225 #elif defined(HAVE_LDAP_LD_ERRNO)
226 return ldap_err_to_gpg_err (ld->ld_errno);
228 /* We should never get here since the LDAP library should always
229 have either ldap_get_option or ld_errno, but just in case... */
230 return GPG_ERR_INTERNAL;
235 ldap2epochtime (const char *timestr)
240 memset (&pgptime, 0, sizeof(pgptime));
242 /* YYYYMMDDHHmmssZ */
244 sscanf (timestr, "%4d%2d%2d%2d%2d%2d",
252 pgptime.tm_year -= 1900;
253 pgptime.tm_isdst = -1;
256 /* mktime() takes the timezone into account, so we use timegm() */
258 answer = timegm (&pgptime);
263 /* Caller must free the result. */
265 tm2ldaptime (struct tm *tm)
270 /* YYYYMMDDHHmmssZ */
275 snprintf (buf, sizeof buf, "%04d%02d%02d%02d%02d%02dZ",
283 return xstrdup (buf);
287 /* Caller must free */
289 epoch2ldaptime (time_t stamp)
292 if (gmtime_r (&stamp, &tm))
293 return tm2ldaptime (&tm);
295 return xstrdup ("INVALID TIME");
299 /* Print a help output for the schemata supported by this module. */
301 ks_ldap_help (ctrl_t ctrl, parsed_uri_t uri)
304 "Handler for LDAP URLs:\n"
305 " ldap://host:port/[BASEDN]???[bindname=BINDNAME,password=PASSWORD]\n"
307 "Note: basedn, bindname and password need to be percent escaped. In\n"
308 "particular, spaces need to be replaced with %20 and commas with %2c.\n"
309 "bindname will typically be of the form:\n"
311 " uid=user%2cou=PGP%20Users%2cdc=EXAMPLE%2cdc=ORG\n"
313 "The ldaps:// and ldapi:// schemes are also supported. If ldaps is used\n"
314 "then the server's certificate will be checked. If it is not valid, any\n"
315 "operation will be aborted.\n"
317 "Supported methods: search, get, put\n";
321 err = ks_print_help (ctrl, " ldap");
322 else if (strcmp (uri->scheme, "ldap") == 0
323 || strcmp (uri->scheme, "ldaps") == 0
324 || strcmp (uri->scheme, "ldapi") == 0)
325 err = ks_print_help (ctrl, data);
332 /* Convert a keyspec to a filter. Return an error if the keyspec is
333 bad or is not supported. The filter is escaped and returned in
334 *filter. It is the caller's responsibility to free *filter.
335 *filter is only set if this function returns success (i.e., 0). */
337 keyspec_to_ldap_filter (const char *keyspec, char **filter, int only_exact,
338 unsigned int serverinfo)
340 /* Remove search type indicator and adjust PATTERN accordingly.
341 Note: don't include a preceding 0x when searching by keyid. */
343 /* XXX: Should we include disabled / revoke options? */
344 KEYDB_SEARCH_DESC desc;
349 gpg_error_t err = classify_user_id (keyspec, &desc, 1);
355 case KEYDB_SEARCH_MODE_EXACT:
356 f = xasprintf ("(pgpUserID=%s)",
357 (freeme = ldap_escape_filter (desc.u.name)));
360 case KEYDB_SEARCH_MODE_SUBSTR:
362 f = xasprintf ("(pgpUserID=*%s*)",
363 (freeme = ldap_escape_filter (desc.u.name)));
366 case KEYDB_SEARCH_MODE_MAIL:
367 freeme = ldap_escape_filter (desc.u.name);
370 if (*freeme == '<' && freeme[1] && freeme[2])
372 /* Strip angle brackets. Note that it is does not
373 * matter whether we work on the plan or LDAP escaped
374 * version of the mailbox. */
376 if (p[strlen(p)-1] == '>')
381 if ((serverinfo & SERVERINFO_SCHEMAV2))
382 f = xasprintf ("(gpgMailbox=%s)", p);
383 else if (!only_exact)
384 f = xasprintf ("(pgpUserID=*<%s>*)", p);
387 case KEYDB_SEARCH_MODE_MAILSUB:
389 f = xasprintf ("(pgpUserID=*<*%s*>*)",
390 (freeme = ldap_escape_filter (desc.u.name)));
393 case KEYDB_SEARCH_MODE_MAILEND:
395 f = xasprintf ("(pgpUserID=*<*%s>*)",
396 (freeme = ldap_escape_filter (desc.u.name)));
399 case KEYDB_SEARCH_MODE_SHORT_KID:
400 f = xasprintf ("(pgpKeyID=%08lX)", (ulong) desc.u.kid[1]);
402 case KEYDB_SEARCH_MODE_LONG_KID:
403 f = xasprintf ("(pgpCertID=%08lX%08lX)",
404 (ulong) desc.u.kid[0], (ulong) desc.u.kid[1]);
407 case KEYDB_SEARCH_MODE_FPR16:
408 case KEYDB_SEARCH_MODE_FPR20:
409 case KEYDB_SEARCH_MODE_FPR:
410 if ((serverinfo & SERVERINFO_SCHEMAV2))
412 freeme = bin2hex (desc.u.fpr, 20, NULL);
414 return gpg_error_from_syserror ();
415 f = xasprintf ("(|(gpgFingerprint=%s)(gpgSubFingerprint=%s))",
417 /* FIXME: For an exact search and in case of a match on
418 * gpgSubFingerprint we need to check that there is only one
423 case KEYDB_SEARCH_MODE_ISSUER:
424 case KEYDB_SEARCH_MODE_ISSUER_SN:
425 case KEYDB_SEARCH_MODE_SN:
426 case KEYDB_SEARCH_MODE_SUBJECT:
427 case KEYDB_SEARCH_MODE_KEYGRIP:
428 case KEYDB_SEARCH_MODE_WORDS:
429 case KEYDB_SEARCH_MODE_FIRST:
430 case KEYDB_SEARCH_MODE_NEXT:
439 log_error ("Unsupported search mode.\n");
440 return gpg_error (GPG_ERR_NOT_SUPPORTED);
450 /* Connect to an LDAP server and interrogate it.
452 - uri describes the server to connect to and various options
453 including whether to use TLS and the username and password (see
454 ldap_parse_uri for a description of the various fields).
456 This function returns:
458 - The ldap connection handle in *LDAP_CONNP.
460 - The base DN for the PGP key space by querying the
461 pgpBaseKeySpaceDN attribute (This is normally
462 'ou=PGP Keys,dc=EXAMPLE,dc=ORG').
464 - The attribute to lookup to find the pgp key. This is either
465 'pgpKey' or 'pgpKeyV2'.
467 - Whether this is a real ldap server. (It's unclear what this
470 The values are returned in the passed variables. If you pass NULL,
471 then the value won't be returned. It is the caller's
472 responsibility to release *LDAP_CONNP with ldap_unbind and xfree
475 If this function successfully interrogated the server, it returns
476 0. If there was an LDAP error, it returns the LDAP error code. If
477 an error occurred, *basednp, etc., are undefined (and don't need to
480 R_SERVERINFO receives information about the server.
482 If no LDAP error occurred, you still need to check that *basednp is
483 valid. If it is NULL, then the server does not appear to be an
484 OpenPGP Keyserver. */
486 my_ldap_connect (parsed_uri_t uri, LDAP **ldap_connp,
487 char **basednp, unsigned int *r_serverinfo)
490 LDAP *ldap_conn = NULL;
491 char *user = uri->auth;
492 struct uri_tuple_s *password_param;
498 password_param = uri_query_lookup (uri, "password");
499 password = password_param ? password_param->value : NULL;
502 log_debug ("my_ldap_connect(%s:%d/%s????%s%s%s%s%s%s)\n",
503 uri->host, uri->port,
504 uri->path ? uri->path : "",
505 uri->auth ? "bindname=" : "",
506 uri->auth ? uri->auth : "",
507 uri->auth && password ? "," : "",
508 password ? "password=" : "",
509 password ? ">not shown<": "",
510 uri->ad_current? " auth=>current_user<":"");
512 /* If the uri specifies a secure connection and we don't support
513 TLS, then fail; don't silently revert to an insecure
517 #ifndef HAVE_LDAP_START_TLS_S
518 log_error ("Can't use LDAP to connect to the server: no TLS support.");
519 err = GPG_ERR_LDAP_NOT_SUPPORTED;
525 ldap_conn = ldap_init (NULL, uri->port);
527 ldap_conn = ldap_init (uri->host, uri->port);
530 err = gpg_err_code_from_syserror ();
532 log_error ("error initializing LDAP for current user\n");
534 log_error ("error initializing LDAP for (%s://%s:%d)\n",
535 uri->scheme, uri->host, uri->port);
539 #ifdef HAVE_LDAP_SET_OPTION
541 int ver = LDAP_VERSION3;
543 err = ldap_set_option (ldap_conn, LDAP_OPT_PROTOCOL_VERSION, &ver);
544 if (err != LDAP_SUCCESS)
546 log_error ("ks-ldap: unable to go to LDAP 3: %s\n",
547 ldap_err2string (err));
553 /* XXX: It would be nice to have an option to provide the server's
556 #if defined(LDAP_OPT_X_TLS_CACERTFILE) && defined(HAVE_LDAP_SET_OPTION)
557 err = ldap_set_option (NULL, LDAP_OPT_X_TLS_CACERTFILE, ca_cert_file);
560 log_error ("unable to set ca-cert-file to '%s': %s\n",
561 ca_cert_file, ldap_err2string (err));
564 #endif /* LDAP_OPT_X_TLS_CACERTFILE && HAVE_LDAP_SET_OPTION */
567 #ifdef HAVE_LDAP_START_TLS_S
570 /* XXX: We need an option to determine whether to abort if the
571 certificate is bad or not. Right now we conservatively
572 default to checking the certificate and aborting. */
573 #ifndef HAVE_W32_SYSTEM
574 int check_cert = LDAP_OPT_X_TLS_HARD; /* LDAP_OPT_X_TLS_NEVER */
576 err = ldap_set_option (ldap_conn,
577 LDAP_OPT_X_TLS_REQUIRE_CERT, &check_cert);
580 log_error ("error setting TLS option on LDAP connection\n");
584 /* On Windows, the certificates are checked by default. If the
585 option to disable checking mentioned above is ever
586 implemented, the way to do that on Windows is to install a
587 callback routine using ldap_set_option (..,
588 LDAP_OPT_SERVER_CERTIFICATE, ..); */
592 err = ldap_start_tls_s (ldap_conn,
593 #ifdef HAVE_W32_SYSTEM
594 /* ServerReturnValue, result */
597 /* ServerControls, ClientControls */
602 log_error ("error connecting to LDAP server with TLS\n");
611 log_debug ("LDAP bind to current user via AD\n");
612 #ifdef HAVE_W32_SYSTEM
614 err = ldap_bind_s (ldap_conn, NULL, NULL, LDAP_AUTH_NEGOTIATE);
617 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
619 if (err != LDAP_SUCCESS)
621 log_error ("error binding to LDAP via AD: %s\n",
622 ldap_err2string (err));
629 log_debug ("LDAP bind to %s, password %s\n",
630 user, password ? ">not shown<" : ">none<");
633 err = ldap_simple_bind_s (ldap_conn, user, password);
635 if (err != LDAP_SUCCESS)
637 log_error ("error binding to LDAP: %s\n", ldap_err2string (err));
643 /* By default we don't bind as there is usually no need to. */
646 if (uri->path && *uri->path)
648 /* User specified base DN. */
649 basedn = xstrdup (uri->path);
651 /* If the user specifies a base DN, then we know the server is a
652 * real LDAP server. */
653 *r_serverinfo |= SERVERINFO_REALLDAP;
656 { /* Look for namingContexts. */
657 LDAPMessage *res = NULL;
658 char *attr[] = { "namingContexts", NULL };
661 err = ldap_search_s (ldap_conn, "", LDAP_SCOPE_BASE,
662 "(objectClass=*)", attr, 0, &res);
665 if (err == LDAP_SUCCESS)
670 context = ldap_get_values (ldap_conn, res, "namingContexts");
674 /* We found some, so try each namingContext as the
675 * search base and look for pgpBaseKeySpaceDN. Because
676 * we found this, we know we're talking to a regular-ish
677 * LDAP server and not an LDAP keyserver. */
680 { "pgpBaseKeySpaceDN", "pgpVersion", "pgpSoftware", NULL };
682 *r_serverinfo |= SERVERINFO_REALLDAP;
684 for (i = 0; context[i] && ! basedn; i++)
691 char *object = xasprintf ("cn=pgpServerInfo,%s",
694 err = ldap_search_s (ldap_conn, object, LDAP_SCOPE_BASE,
695 "(objectClass=*)", attr2, 0, &si_res);
700 if (err == LDAP_SUCCESS)
702 vals = ldap_get_values (ldap_conn, si_res,
703 "pgpBaseKeySpaceDN");
706 basedn = xtrystrdup (vals[0]);
707 ldap_value_free (vals);
710 vals = ldap_get_values (ldap_conn, si_res,
715 log_debug ("Server: \t%s\n", vals[0]);
716 if (!ascii_strcasecmp (vals[0], "GnuPG"))
718 ldap_value_free (vals);
721 vals = ldap_get_values (ldap_conn, si_res,
726 log_debug ("Version:\t%s\n", vals[0]);
731 nfields = split_fields (vals[0],
732 fields, DIM(fields));
733 if (nfields > 0 && atoi(fields[0]) > 1)
734 *r_serverinfo |= SERVERINFO_SCHEMAV2;
736 && !ascii_strcasecmp (fields[1], "ntds"))
737 *r_serverinfo |= SERVERINFO_NTDS;
739 ldap_value_free (vals);
743 /* From man ldap_search_s: "res parameter of
744 ldap_search_ext_s() and ldap_search_s() should be
745 freed with ldap_msgfree() regardless of return
746 value of these functions. */
747 ldap_msgfree (si_res);
750 ldap_value_free (context);
755 /* We don't have an answer yet, which means the server might
756 be a PGP.com keyserver. */
758 LDAPMessage *si_res = NULL;
760 char *attr2[] = { "pgpBaseKeySpaceDN", "version", "software", NULL };
763 err = ldap_search_s (ldap_conn, "cn=pgpServerInfo", LDAP_SCOPE_BASE,
764 "(objectClass=*)", attr2, 0, &si_res);
766 if (err == LDAP_SUCCESS)
768 /* For the PGP LDAP keyserver, this is always
769 * "OU=ACTIVE,O=PGP KEYSPACE,C=US", but it might not be
772 vals = ldap_get_values (ldap_conn, si_res, "baseKeySpaceDN");
775 basedn = xtrystrdup (vals[0]);
776 ldap_value_free (vals);
779 vals = ldap_get_values (ldap_conn, si_res, "software");
783 log_debug ("ks-ldap: PGP Server: \t%s\n", vals[0]);
784 ldap_value_free (vals);
787 vals = ldap_get_values (ldap_conn, si_res, "version");
791 log_debug ("ks-ldap: PGP Server Version:\t%s\n", vals[0]);
793 /* If the version is high enough, use the new
794 pgpKeyV2 attribute. This design is iffy at best,
795 but it matches how PGP does it. I figure the NAI
796 folks assumed that there would never be an LDAP
797 keyserver vendor with a different numbering
799 if (atoi (vals[0]) > 1)
800 *r_serverinfo |= SERVERINFO_PGPKEYV2;
802 ldap_value_free (vals);
806 ldap_msgfree (si_res);
809 /* From man ldap_search_s: "res parameter of ldap_search_ext_s()
810 and ldap_search_s() should be freed with ldap_msgfree()
811 regardless of return value of these functions. */
816 if (!err && opt.debug)
818 log_debug ("ldap_conn: %p\n", ldap_conn);
819 log_debug ("server_type: %s\n", ((*r_serverinfo & SERVERINFO_REALLDAP)
820 ? "LDAP" : "PGP.com keyserver") );
821 log_debug ("basedn: %s\n", basedn);
822 log_debug ("pgpkeyattr: %s\n",
823 (*r_serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey");
839 ldap_unbind (ldap_conn);
842 *ldap_connp = ldap_conn;
847 /* Extract keys from an LDAP reply and write them out to the output
848 stream OUTPUT in a format GnuPG can import (either the OpenPGP
849 binary format or armored format). */
851 extract_keys (estream_t output,
852 LDAP *ldap_conn, const char *certid, LDAPMessage *message)
856 es_fprintf (output, "INFO %s BEGIN\n", certid);
857 es_fprintf (output, "pub:%s:", certid);
859 /* Note: ldap_get_values returns a NULL terminated array of
861 vals = ldap_get_values (ldap_conn, message, "pgpkeytype");
864 if (strcmp (vals[0], "RSA") == 0)
865 es_fprintf (output, "1");
866 else if (strcmp (vals[0],"DSS/DH") == 0)
867 es_fprintf (output, "17");
868 ldap_value_free (vals);
871 es_fprintf (output, ":");
873 vals = ldap_get_values (ldap_conn, message, "pgpkeysize");
876 int v = atoi (vals[0]);
878 es_fprintf (output, "%d", v);
879 ldap_value_free (vals);
882 es_fprintf (output, ":");
884 vals = ldap_get_values (ldap_conn, message, "pgpkeycreatetime");
887 if (strlen (vals[0]) == 15)
888 es_fprintf (output, "%u", (unsigned int) ldap2epochtime (vals[0]));
889 ldap_value_free (vals);
892 es_fprintf (output, ":");
894 vals = ldap_get_values (ldap_conn, message, "pgpkeyexpiretime");
897 if (strlen (vals[0]) == 15)
898 es_fprintf (output, "%u", (unsigned int) ldap2epochtime (vals[0]));
899 ldap_value_free (vals);
902 es_fprintf (output, ":");
904 vals = ldap_get_values (ldap_conn, message, "pgprevoked");
907 if (atoi (vals[0]) == 1)
908 es_fprintf (output, "r");
909 ldap_value_free (vals);
912 es_fprintf (output, "\n");
914 vals = ldap_get_values (ldap_conn, message, "pgpuserid");
918 for (i = 0; vals[i]; i++)
919 es_fprintf (output, "uid:%s\n", vals[i]);
920 ldap_value_free (vals);
923 es_fprintf (output, "INFO %s END\n", certid);
926 /* Get the key described key the KEYSPEC string from the keyserver
927 identified by URI. On success R_FP has an open stream to read the
930 ks_ldap_get (ctrl_t ctrl, parsed_uri_t uri, const char *keyspec,
935 unsigned int serverinfo;
937 LDAP *ldap_conn = NULL;
940 LDAPMessage *message = NULL;
944 if (dirmngr_use_tor ())
946 /* For now we do not support LDAP over Tor. */
947 log_error (_("LDAP access not possible due to Tor mode\n"));
948 return gpg_error (GPG_ERR_NOT_SUPPORTED);
951 /* Make sure we are talking to an OpenPGP LDAP server. */
952 ldap_err = my_ldap_connect (uri, &ldap_conn, &basedn, &serverinfo);
953 if (ldap_err || !basedn)
956 err = ldap_err_to_gpg_err (ldap_err);
958 err = gpg_error (GPG_ERR_GENERAL);
962 /* Now that we have information about the server we can construct a
963 * query best suited for the capabilities of the server. */
964 err = keyspec_to_ldap_filter (keyspec, &filter, 1, serverinfo);
969 log_debug ("ks-ldap: using filter: %s\n", filter);
972 /* The ordering is significant. Specifically, "pgpcertid" needs
973 to be the second item in the list, since everything after it
974 may be discarded we aren't in verbose mode. */
978 "pgpcertid", "pgpuserid", "pgpkeyid", "pgprevoked", "pgpdisabled",
979 "pgpkeycreatetime", "modifytimestamp", "pgpkeysize", "pgpkeytype",
982 /* 1 if we want just attribute types; 0 if we want both attribute
983 * types and values. */
987 /* Replace "dummy". */
988 attrs[0] = (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2" : "pgpKey";
991 ldap_err = ldap_search_s (ldap_conn, basedn, LDAP_SCOPE_SUBTREE,
992 filter, attrs, attrsonly, &message);
996 err = ldap_err_to_gpg_err (ldap_err);
998 log_error ("ks-ldap: LDAP search error: %s\n",
999 ldap_err2string (ldap_err));
1003 count = ldap_count_entries (ldap_conn, message);
1006 log_info ("ks-ldap: key %s not found on keyserver\n", keyspec);
1009 err = ldap_to_gpg_err (ldap_conn);
1011 err = gpg_error (GPG_ERR_NO_DATA);
1017 /* There may be more than one unique result for a given keyID,
1018 so we should fetch them all (test this by fetching short key
1021 /* The set of entries that we've seen. */
1022 strlist_t seen = NULL;
1025 for (npth_unprotect (),
1026 each = ldap_first_entry (ldap_conn, message),
1030 each = ldap_next_entry (ldap_conn, each),
1036 /* Use the long keyid to remove duplicates. The LDAP
1037 server returns the same keyid more than once if there
1038 are multiple user IDs on the key. Note that this does
1039 NOT mean that a keyid that exists multiple times on the
1040 keyserver will not be fetched. It means that each KEY,
1041 no matter how many user IDs share its keyid, will be
1042 fetched only once. If a keyid that belongs to more
1043 than one key is fetched, the server quite properly
1044 responds with all matching keys. -ds */
1046 certid = ldap_get_values (ldap_conn, each, "pgpcertid");
1047 if (certid && certid[0])
1049 if (! strlist_find (seen, certid[0]))
1051 /* It's not a duplicate, add it */
1053 add_to_strlist (&seen, certid[0]);
1056 fp = es_fopenmem(0, "rw");
1058 extract_keys (fp, ldap_conn, certid[0], each);
1060 vals = ldap_get_values (ldap_conn, each, attrs[0]);
1063 err = ldap_to_gpg_err (ldap_conn);
1064 log_error("ks-ldap: unable to retrieve key %s "
1065 "from keyserver\n", certid[0]);
1070 /* We should strip the new lines. */
1071 es_fprintf (fp, "KEY 0x%s BEGIN\n", certid[0]);
1072 es_fputs (vals[0], fp);
1073 es_fprintf (fp, "\nKEY 0x%s END\n", certid[0]);
1075 ldap_value_free (vals);
1080 ldap_value_free (certid);
1083 free_strlist (seen);
1086 err = gpg_error (GPG_ERR_NO_DATA);
1092 ldap_msgfree (message);
1102 es_fseek (fp, 0, SEEK_SET);
1110 ldap_unbind (ldap_conn);
1118 /* Search the keyserver identified by URI for keys matching PATTERN.
1119 On success R_FP has an open stream to read the data. */
1121 ks_ldap_search (ctrl_t ctrl, parsed_uri_t uri, const char *pattern,
1126 unsigned int serverinfo;
1127 char *filter = NULL;
1128 LDAP *ldap_conn = NULL;
1129 char *basedn = NULL;
1130 estream_t fp = NULL;
1134 if (dirmngr_use_tor ())
1136 /* For now we do not support LDAP over Tor. */
1137 log_error (_("LDAP access not possible due to Tor mode\n"));
1138 return gpg_error (GPG_ERR_NOT_SUPPORTED);
1141 /* Make sure we are talking to an OpenPGP LDAP server. */
1142 ldap_err = my_ldap_connect (uri, &ldap_conn, &basedn, &serverinfo);
1143 if (ldap_err || !basedn)
1146 err = ldap_err_to_gpg_err (ldap_err);
1148 err = GPG_ERR_GENERAL;
1152 /* Now that we have information about the server we can construct a
1153 * query best suited for the capabilities of the server. */
1154 err = keyspec_to_ldap_filter (pattern, &filter, 0, serverinfo);
1157 log_error ("Bad search pattern: '%s'\n", pattern);
1161 /* Even if we have no results, we want to return a stream. */
1162 fp = es_fopenmem(0, "rw");
1165 err = gpg_error_from_syserror ();
1171 LDAPMessage *res, *each;
1173 strlist_t dupelist = NULL;
1175 /* The maximum size of the search, including the optional stuff
1176 and the trailing \0 */
1179 "pgpcertid", "pgpuserid", "pgprevoked", "pgpdisabled",
1180 "pgpkeycreatetime", "pgpkeyexpiretime", "modifytimestamp",
1181 "pgpkeysize", "pgpkeytype", NULL
1185 log_debug ("SEARCH '%s' => '%s' BEGIN\n", pattern, filter);
1188 ldap_err = ldap_search_s (ldap_conn, basedn,
1189 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &res);
1195 if (ldap_err != LDAP_SUCCESS && ldap_err != LDAP_SIZELIMIT_EXCEEDED)
1197 err = ldap_err_to_gpg_err (ldap_err);
1199 log_error ("SEARCH %s FAILED %d\n", pattern, err);
1200 log_error ("ks-ldap: LDAP search error: %s\n",
1201 ldap_err2string (err));
1205 /* The LDAP server doesn't return a real count of unique keys, so we
1206 can't use ldap_count_entries here. */
1207 for (npth_unprotect (),
1208 each = ldap_first_entry (ldap_conn, res),
1212 each = ldap_next_entry (ldap_conn, each),
1215 char **certid = ldap_get_values (ldap_conn, each, "pgpcertid");
1216 if (certid && certid[0] && ! strlist_find (dupelist, certid[0]))
1218 add_to_strlist (&dupelist, certid[0]);
1223 if (ldap_err == LDAP_SIZELIMIT_EXCEEDED)
1226 log_error ("ks-ldap: search results exceeded server limit."
1227 " First 1 result shown.\n");
1229 log_error ("ks-ldap: search results exceeded server limit."
1230 " First %d results shown.\n", count);
1233 free_strlist (dupelist);
1237 es_fputs ("info:1:0\n", fp);
1240 es_fprintf (fp, "info:1:%d\n", count);
1242 for (each = ldap_first_entry (ldap_conn, res);
1244 each = ldap_next_entry (ldap_conn, each))
1249 certid = ldap_get_values (ldap_conn, each, "pgpcertid");
1250 if (! certid || ! certid[0])
1253 /* Have we seen this certid before? */
1254 if (! strlist_find (dupelist, certid[0]))
1256 add_to_strlist (&dupelist, certid[0]);
1258 es_fprintf (fp, "pub:%s:",certid[0]);
1260 vals = ldap_get_values (ldap_conn, each, "pgpkeytype");
1263 /* The LDAP server doesn't exactly handle this
1265 if (strcasecmp (vals[0], "RSA") == 0)
1267 else if (strcasecmp (vals[0], "DSS/DH") == 0)
1268 es_fputs ("17", fp);
1269 ldap_value_free (vals);
1274 vals = ldap_get_values (ldap_conn, each, "pgpkeysize");
1277 /* Not sure why, but some keys are listed with a
1278 key size of 0. Treat that like an unknown. */
1279 if (atoi (vals[0]) > 0)
1280 es_fprintf (fp, "%d", atoi (vals[0]));
1281 ldap_value_free (vals);
1286 /* YYYYMMDDHHmmssZ */
1288 vals = ldap_get_values (ldap_conn, each, "pgpkeycreatetime");
1289 if(vals && strlen (vals[0]) == 15)
1291 es_fprintf (fp, "%u",
1292 (unsigned int) ldap2epochtime(vals[0]));
1293 ldap_value_free (vals);
1298 vals = ldap_get_values (ldap_conn, each, "pgpkeyexpiretime");
1299 if (vals && strlen (vals[0]) == 15)
1301 es_fprintf (fp, "%u",
1302 (unsigned int) ldap2epochtime (vals[0]));
1303 ldap_value_free (vals);
1308 vals = ldap_get_values (ldap_conn, each, "pgprevoked");
1311 if (atoi (vals[0]) == 1)
1312 es_fprintf (fp, "r");
1313 ldap_value_free (vals);
1316 vals = ldap_get_values (ldap_conn, each, "pgpdisabled");
1319 if (atoi (vals[0]) ==1)
1320 es_fprintf (fp, "d");
1321 ldap_value_free (vals);
1325 /* This is not yet specified in the keyserver
1326 protocol, but may be someday. */
1329 vals = ldap_get_values (ldap_conn, each, "modifytimestamp");
1330 if(vals && strlen (vals[0]) == 15)
1332 es_fprintf (fp, "%u",
1333 (unsigned int) ldap2epochtime (vals[0]));
1334 ldap_value_free (vals);
1338 es_fprintf (fp, "\n");
1340 /* Now print all the uids that have this certid */
1341 for (uids = ldap_first_entry (ldap_conn, res);
1343 uids = ldap_next_entry (ldap_conn, uids))
1345 vals = ldap_get_values (ldap_conn, uids, "pgpcertid");
1349 if (strcasecmp (certid[0], vals[0]) == 0)
1353 es_fprintf (fp, "uid:");
1355 uidvals = ldap_get_values (ldap_conn,
1359 /* Need to escape any colons */
1360 char *quoted = percent_escape (uidvals[0], NULL);
1361 es_fputs (quoted, fp);
1363 ldap_value_free (uidvals);
1366 es_fprintf (fp, "\n");
1369 ldap_value_free(vals);
1373 ldap_value_free (certid);
1378 free_strlist (dupelist);
1382 log_debug ("SEARCH %s END\n", pattern);
1392 /* Return the read stream. */
1394 es_fseek (fp, 0, SEEK_SET);
1402 ldap_unbind (ldap_conn);
1411 /* A modlist describes a set of changes to an LDAP entry. (An entry
1412 consists of 1 or more attributes. Attributes are <name, value>
1413 pairs. Note: an attribute may be multi-valued in which case
1414 multiple values are associated with a single name.)
1416 A modlist is a NULL terminated array of struct LDAPMod's.
1426 Is the ith modification.
1428 Each LDAPMod describes a change to a single attribute. Further,
1429 there is one modification for each attribute that we want to
1430 change. The attribute's new value is stored in LDAPMod.mod_values.
1431 If the attribute is multi-valued, we still only use a single
1432 LDAPMod structure: mod_values is a NULL-terminated array of
1433 strings. To delete an attribute from an entry, we set mod_values
1438 modlist[i]->mod_values == NULL
1440 then we remove the attribute.
1442 (Using LDAP_MOD_DELETE doesn't work here as we don't know if the
1443 attribute in question exists or not.)
1445 Note: this function does NOT copy or free ATTR. It does copy
1448 modlist_add (LDAPMod ***modlistp, char *attr, const char *value)
1450 LDAPMod **modlist = *modlistp;
1455 /* Search modlist for the attribute we're playing with. If modlist
1456 is NULL, then the list is empty. Recall: modlist is a NULL
1457 terminated array. */
1458 for (m = modlist; m && *m; m++, nummods ++)
1460 /* The attribute is already on the list. */
1464 if (strcasecmp ((*m)->mod_type, attr) != 0)
1467 /* We have this attribute already, so when the REPLACE happens,
1468 the server attributes will be replaced anyway. */
1472 /* Attributes can be multi-valued. See if the value is already
1473 present. mod_values is a NULL terminated array of pointers.
1474 Note: mod_values can be NULL. */
1475 for (ptr = (*m)->mod_values; ptr && *ptr; ptr++)
1477 if (strcmp (*ptr, value) == 0)
1478 /* Duplicate value, we're done. */
1483 /* Append the value. */
1484 ptr = xrealloc ((*m)->mod_values, sizeof (char *) * (numvalues + 2));
1486 (*m)->mod_values = ptr;
1487 ptr[numvalues] = xstrdup (value);
1489 ptr[numvalues + 1] = NULL;
1494 /* We didn't find the attr, so make one and add it to the end */
1496 /* Like attribute values, the list of attributes is NULL terminated
1497 array of pointers. */
1498 modlist = xrealloc (modlist, sizeof (LDAPMod *) * (nummods + 2));
1500 *modlistp = modlist;
1501 modlist[nummods] = xmalloc (sizeof (LDAPMod));
1503 modlist[nummods]->mod_op = LDAP_MOD_REPLACE;
1504 modlist[nummods]->mod_type = attr;
1507 modlist[nummods]->mod_values = xmalloc (sizeof(char *) * 2);
1509 modlist[nummods]->mod_values[0] = xstrdup (value);
1510 modlist[nummods]->mod_values[1] = NULL;
1513 modlist[nummods]->mod_values = NULL;
1515 modlist[nummods + 1] = NULL;
1520 /* Look up the value of an attribute in the specified modlist. If the
1521 attribute is not on the mod list, returns NULL. The result is a
1522 NULL-terminated array of strings. Don't change it. */
1524 modlist_lookup (LDAPMod **modlist, const char *attr)
1527 for (m = modlist; m && *m; m++)
1529 if (strcasecmp ((*m)->mod_type, attr) != 0)
1532 return (*m)->mod_values;
1538 /* Dump a modlist to a file. This is useful for debugging. */
1539 static estream_t modlist_dump (LDAPMod **modlist, estream_t output)
1543 modlist_dump (LDAPMod **modlist, estream_t output)
1551 output = es_fopenmem (0, "rw");
1557 for (m = modlist; m && *m; m++)
1559 es_fprintf (output, " %s:", (*m)->mod_type);
1561 if (! (*m)->mod_values)
1562 es_fprintf(output, " delete.\n");
1569 if ((*m)->mod_values[0] && (*m)->mod_values[1])
1570 /* Have at least 2. */
1574 es_fprintf (output, "\n");
1576 for ((ptr = (*m)->mod_values), (i = 1); ptr && *ptr; ptr++, i ++)
1578 /* Assuming terminals are about 80 characters wide,
1579 display at most about 10 lines of debugging
1580 output. If we do trim the buffer, append '...' to
1582 const int max_len = 10 * 70;
1583 size_t value_len = strlen (*ptr);
1584 int elide = value_len > max_len;
1587 es_fprintf (output, " %d. ", i);
1588 es_fprintf (output, "`%.*s", max_len, *ptr);
1590 es_fprintf (output, "...' (%zd bytes elided)",
1591 value_len - max_len);
1593 es_fprintf (output, "'");
1594 es_fprintf (output, "\n");
1600 es_fseek (output, 0, SEEK_SET);
1605 /* Free all of the memory allocated by the mod list. This assumes
1606 that the attribute names don't have to be freed, but the attributes
1607 values do. (Which is what modlist_add does.) */
1609 modlist_free (LDAPMod **modlist)
1616 /* Unwind and free the whole modlist structure */
1618 /* The modlist is a NULL terminated array of pointers. */
1619 for (ml = modlist; *ml; ml++)
1624 /* The list of values is a NULL termianted array of pointers.
1625 If the list is NULL, there are no values. */
1627 if (mod->mod_values)
1629 for (ptr = mod->mod_values; *ptr; ptr++)
1632 xfree (mod->mod_values);
1640 /* Append two onto the end of one. Two is not freed, but its pointers
1641 are now part of one. Make sure you don't free them both!
1643 As long as you don't add anything to ONE, TWO is still valid.
1644 After that all bets are off. */
1646 modlists_join (LDAPMod ***one, LDAPMod **two)
1648 int i, one_count = 0, two_count = 0;
1652 /* two is empty. Nothing to do. */
1656 /* one is empty. Just set it equal to *two. */
1662 for (grow = *one; *grow; grow++)
1665 for (grow = two; *grow; grow++)
1668 grow = xrealloc (*one, sizeof(LDAPMod *) * (one_count + two_count + 1));
1670 for (i = 0; i < two_count; i++)
1671 grow[one_count + i] = two[i];
1673 grow[one_count + i] = NULL;
1678 /* Given a string, unescape C escapes. In particular, \xXX. This
1679 modifies the string in place. */
1681 uncescape (char *str)
1686 char *first = strchr (str, '\\');
1688 /* No backslashes => no escaping. We're done. */
1691 /* Start at the first '\\'. */
1692 r = w = (uintptr_t) first - (uintptr_t) str;
1696 /* XXX: What to do about bad escapes?
1697 XXX: hextobyte already checks the string thus the hexdigitp
1698 could be removed. */
1699 if (str[r] == '\\' && str[r + 1] == 'x'
1700 && str[r+2] && str[r+3]
1701 && hexdigitp (str + r + 2)
1702 && hexdigitp (str + r + 3))
1704 int x = hextobyte (&str[r + 2]);
1705 assert (0 <= x && x <= 0xff);
1709 /* We consumed 4 characters and wrote 1. */
1714 str[w ++] = str[r ++];
1720 /* Given one line from an info block (`gpg --list-{keys,sigs}
1721 --with-colons KEYID'), pull it apart and fill in the modlist with
1722 the relevant (for the LDAP schema) attributes. EXTRACT_STATE
1723 should initally be set to 0 by the caller. SCHEMAV2 is set if the
1724 server supports the version 2 schema. */
1726 extract_attributes (LDAPMod ***modlist, int *extract_state,
1727 char *line, int schemav2)
1732 int is_pub, is_sub, is_uid, is_sig;
1734 /* Remove trailing whitespace */
1735 trim_trailing_spaces (line);
1737 fields = strsplit (line, ':', '\0', &field_count);
1738 if (field_count == 1)
1739 /* We only have a single field. There is definitely nothing to
1743 if (field_count < 7)
1746 is_pub = !ascii_strcasecmp ("pub", fields[0]);
1747 is_sub = !ascii_strcasecmp ("sub", fields[0]);
1748 is_uid = !ascii_strcasecmp ("uid", fields[0]);
1749 is_sig = !ascii_strcasecmp ("sig", fields[0]);
1750 if (!ascii_strcasecmp ("fpr", fields[0]))
1752 /* Special treatment for a fingerprint. */
1753 if (!(*extract_state & 1))
1754 goto out; /* Stray fingerprint line - ignore. */
1755 *extract_state &= ~1;
1756 if (field_count >= 10 && schemav2)
1758 if ((*extract_state & 2))
1759 modlist_add (modlist, "gpgFingerprint", fields[9]);
1761 modlist_add (modlist, "gpgSubFingerprint", fields[9]);
1766 *extract_state &= ~(1|2);
1768 *extract_state |= (1|2);
1770 *extract_state |= 1;
1772 if (!is_pub && !is_sub && !is_uid && !is_sig)
1773 goto out; /* Not a relevant line. */
1777 if (is_uid && strlen (keyid) == 0)
1778 ; /* The uid record type can have an empty keyid. */
1779 else if (strlen (keyid) == 16
1780 && strspn (keyid, "0123456789aAbBcCdDeEfF") == 16)
1781 ; /* Otherwise, we expect exactly 16 hex characters. */
1784 log_error ("malformed record!\n");
1793 for (flags = fields[1]; *flags; flags ++)
1807 /* Note: we always create the pgpDisabled and pgpRevoked
1808 attributes, regardless of whether the key is disabled/revoked
1809 or not. This is because a very common search is like
1810 "(&(pgpUserID=*isabella*)(pgpDisabled=0))" */
1814 modlist_add (modlist,"pgpDisabled", disabled ? "1" : "0");
1815 modlist_add (modlist,"pgpRevoked", revoked ? "1" : "0");
1819 if (is_pub || is_sub)
1824 val = atoi (fields[2]);
1825 if (val < 99999 && val > 0)
1827 /* We zero pad this on the left to make PGP happy. */
1828 snprintf (padded, sizeof padded, "%05u", val);
1829 modlist_add (modlist, "pgpKeySize", padded);
1835 char *algo = fields[3];
1836 int val = atoi (algo);
1853 modlist_add (modlist, "pgpKeyType", algo);
1856 if (is_pub || is_sub || is_sig)
1860 modlist_add (modlist, "pgpCertID", keyid); /* Long keyid(!) */
1861 modlist_add (modlist, "pgpKeyID", &keyid[8]); /* Short keyid */
1865 modlist_add (modlist, "pgpSubKeyID", keyid); /* Long keyid(!) */
1870 char *create_time = fields[5];
1872 if (strlen (create_time) == 0)
1876 char *create_time_orig = create_time;
1881 memset (&tm, 0, sizeof (tm));
1883 /* parse_timestamp handles both seconds fromt he epoch and
1884 ISO 8601 format. We also need to handle YYYY-MM-DD
1885 format (as generated by gpg1 --with-colons --list-key).
1886 Check that first and then if it fails, then try
1889 if (!isodate_human_to_tm (create_time, &tm))
1890 create_time = tm2ldaptime (&tm);
1891 else if ((t = parse_timestamp (create_time, &end)) != (time_t) -1
1895 if (!gnupg_gmtime (&t, &tm))
1898 create_time = tm2ldaptime (&tm);
1904 /* Failed to parse string. */
1905 log_error ("Failed to parse creation time ('%s')",
1911 modlist_add (modlist, "pgpKeyCreateTime", create_time);
1912 xfree (create_time);
1918 char *expire_time = fields[6];
1920 if (strlen (expire_time) == 0)
1924 char *expire_time_orig = expire_time;
1929 memset (&tm, 0, sizeof (tm));
1931 /* parse_timestamp handles both seconds fromt he epoch and
1932 ISO 8601 format. We also need to handle YYYY-MM-DD
1933 format (as generated by gpg1 --with-colons --list-key).
1934 Check that first and then if it fails, then try
1937 if (!isodate_human_to_tm (expire_time, &tm))
1938 expire_time = tm2ldaptime (&tm);
1939 else if ((t = parse_timestamp (expire_time, &end)) != (time_t) -1
1942 if (!gnupg_gmtime (&t, &tm))
1945 expire_time = tm2ldaptime (&tm);
1951 /* Failed to parse string. */
1952 log_error ("Failed to parse creation time ('%s')",
1958 modlist_add (modlist, "pgpKeyExpireTime", expire_time);
1959 xfree (expire_time);
1963 if (is_uid && field_count >= 10)
1965 char *uid = fields[9];
1969 modlist_add (modlist, "pgpUserID", uid);
1970 if (schemav2 && (mbox = mailbox_from_userid (uid)))
1972 modlist_add (modlist, "gpgMailbox", mbox);
1981 /* Send the key in {KEY,KEYLEN} with the metadata {INFO,INFOLEN} to
1982 the keyserver identified by URI. See server.c:cmd_ks_put for the
1983 format of the data and metadata. */
1985 ks_ldap_put (ctrl_t ctrl, parsed_uri_t uri,
1986 void *data, size_t datalen,
1987 void *info, size_t infolen)
1989 gpg_error_t err = 0;
1991 unsigned int serverinfo;
1992 LDAP *ldap_conn = NULL;
1993 char *basedn = NULL;
1994 LDAPMod **modlist = NULL;
1995 LDAPMod **addlist = NULL;
1996 char *data_armored = NULL;
1999 /* The last byte of the info block. */
2000 const char *infoend = (const char *) info + infolen - 1;
2002 /* Enable this code to dump the modlist to /tmp/modlist.txt. */
2004 # warning Disable debug code before checking in.
2005 const int dump_modlist = 1;
2007 const int dump_modlist = 0;
2009 estream_t dump = NULL;
2011 /* Elide a warning. */
2014 if (dirmngr_use_tor ())
2016 /* For now we do not support LDAP over Tor. */
2017 log_error (_("LDAP access not possible due to Tor mode\n"));
2018 return gpg_error (GPG_ERR_NOT_SUPPORTED);
2021 ldap_err = my_ldap_connect (uri, &ldap_conn, &basedn, &serverinfo);
2022 if (ldap_err || !basedn)
2025 err = ldap_err_to_gpg_err (ldap_err);
2027 err = GPG_ERR_GENERAL;
2031 if (!(serverinfo & SERVERINFO_REALLDAP))
2033 /* We appear to have a PGP.com Keyserver, which can unpack the
2034 * key on its own (not just a dump LDAP server). This will
2035 * rarely be the case these days. */
2043 memset (&mod, 0, sizeof (mod));
2044 mod.mod_op = LDAP_MOD_ADD;
2045 mod.mod_type = (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey";
2046 mod.mod_values = key;
2050 dn = xtryasprintf ("pgpCertid=virtual,%s", basedn);
2053 err = gpg_error_from_syserror ();
2056 ldap_err = ldap_add_s (ldap_conn, dn, attrs);
2059 if (ldap_err != LDAP_SUCCESS)
2061 err = ldap_err_to_gpg_err (err);
2068 modlist = xtrymalloc (sizeof (LDAPMod *));
2071 err = gpg_error_from_syserror ();
2078 dump = es_fopen("/tmp/modlist.txt", "w");
2080 log_error ("Failed to open /tmp/modlist.txt: %s\n",
2085 es_fprintf(dump, "data (%zd bytes)\n", datalen);
2086 es_fprintf(dump, "info (%zd bytes): '\n", infolen);
2087 es_fwrite(info, infolen, 1, dump);
2088 es_fprintf(dump, "'\n");
2092 /* Start by nulling out all attributes. We try and do a modify
2093 operation first, so this ensures that we don't leave old
2094 attributes lying around. */
2095 modlist_add (&modlist, "pgpDisabled", NULL);
2096 modlist_add (&modlist, "pgpKeyID", NULL);
2097 modlist_add (&modlist, "pgpKeyType", NULL);
2098 modlist_add (&modlist, "pgpUserID", NULL);
2099 modlist_add (&modlist, "pgpKeyCreateTime", NULL);
2100 modlist_add (&modlist, "pgpRevoked", NULL);
2101 modlist_add (&modlist, "pgpSubKeyID", NULL);
2102 modlist_add (&modlist, "pgpKeySize", NULL);
2103 modlist_add (&modlist, "pgpKeyExpireTime", NULL);
2104 modlist_add (&modlist, "pgpCertID", NULL);
2105 if ((serverinfo & SERVERINFO_SCHEMAV2))
2107 modlist_add (&modlist, "gpgFingerprint", NULL);
2108 modlist_add (&modlist, "gpgSubFingerprint", NULL);
2109 modlist_add (&modlist, "gpgMailbox", NULL);
2112 /* Assemble the INFO stuff into LDAP attributes */
2118 char *newline = memchr (info, '\n', infolen);
2120 /* The last line is not \n terminated! Make a copy so we can
2121 add a NUL terminator. */
2123 temp = xmalloc (infolen + 1);
2124 memcpy (temp, info, infolen);
2126 newline = (char *) info + infolen;
2131 extract_attributes (&addlist, &extract_state, info,
2132 (serverinfo & SERVERINFO_SCHEMAV2));
2134 infolen = infolen - ((uintptr_t) newline - (uintptr_t) info + 1);
2139 log_assert ((char *) info + infolen - 1 == infoend);
2142 log_assert (infolen == -1);
2147 modlist_add (&addlist, "objectClass", "pgpKeyInfo");
2149 err = armor_data (&data_armored, data, datalen);
2153 modlist_add (&addlist,
2154 (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey",
2157 /* Now append addlist onto modlist. */
2158 modlists_join (&modlist, addlist);
2162 estream_t input = modlist_dump (modlist, NULL);
2165 copy_stream (input, dump);
2170 /* Going on the assumption that modify operations are more frequent
2171 than adds, we try a modify first. If it's not there, we just
2172 turn around and send an add command for the same key. Otherwise,
2173 the modify brings the server copy into compliance with our copy.
2174 Note that unlike the LDAP keyserver (and really, any other
2175 keyserver) this does NOT merge signatures, but replaces the whole
2176 key. This should make some people very happy. */
2181 if ((serverinfo & SERVERINFO_NTDS))
2183 /* The modern way using a CN RDN with the fingerprint. This
2184 * has the advantage that we won't have duplicate 64 bit
2185 * keyids in the store. In particular NTDS requires the
2186 * DN to be unique. */
2187 attrval = modlist_lookup (addlist, "gpgFingerprint");
2188 /* We should have exactly one value. */
2189 if (!attrval || !(attrval[0] && !attrval[1]))
2191 log_error ("ks-ldap: bad gpgFingerprint provided\n");
2192 err = GPG_ERR_GENERAL;
2195 dn = xtryasprintf ("CN=%s,%s", attrval[0], basedn);
2197 else /* The old style way. */
2199 attrval = modlist_lookup (addlist, "pgpCertID");
2200 /* We should have exactly one value. */
2201 if (!attrval || !(attrval[0] && !attrval[1]))
2203 log_error ("ks-ldap: bad pgpCertID provided\n");
2204 err = GPG_ERR_GENERAL;
2207 dn = xtryasprintf ("pgpCertID=%s,%s", attrval[0], basedn);
2211 err = gpg_error_from_syserror ();
2215 log_debug ("ks-ldap: using DN: %s\n", dn);
2218 err = ldap_modify_s (ldap_conn, dn, modlist);
2219 if (err == LDAP_NO_SUCH_OBJECT)
2220 err = ldap_add_s (ldap_conn, dn, addlist);
2225 if (err != LDAP_SUCCESS)
2227 log_error ("ks-ldap: error adding key to keyserver: %s\n",
2228 ldap_err2string (err));
2229 err = ldap_err_to_gpg_err (err);
2238 ldap_unbind (ldap_conn);
2242 modlist_free (modlist);
2245 xfree (data_armored);