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 (uri->is_ldap)
323 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_FPR:
408 if ((serverinfo & SERVERINFO_SCHEMAV2))
410 freeme = bin2hex (desc.u.fpr, desc.fprlen, NULL);
412 return gpg_error_from_syserror ();
413 f = xasprintf ("(|(gpgFingerprint=%s)(gpgSubFingerprint=%s))",
415 /* FIXME: For an exact search and in case of a match on
416 * gpgSubFingerprint we need to check that there is only one
421 case KEYDB_SEARCH_MODE_ISSUER:
422 case KEYDB_SEARCH_MODE_ISSUER_SN:
423 case KEYDB_SEARCH_MODE_SN:
424 case KEYDB_SEARCH_MODE_SUBJECT:
425 case KEYDB_SEARCH_MODE_KEYGRIP:
426 case KEYDB_SEARCH_MODE_WORDS:
427 case KEYDB_SEARCH_MODE_FIRST:
428 case KEYDB_SEARCH_MODE_NEXT:
437 log_error ("Unsupported search mode.\n");
438 return gpg_error (GPG_ERR_NOT_SUPPORTED);
448 /* Connect to an LDAP server and interrogate it.
450 - uri describes the server to connect to and various options
451 including whether to use TLS and the username and password (see
452 ldap_parse_uri for a description of the various fields).
454 This function returns:
456 - The ldap connection handle in *LDAP_CONNP.
458 - The base DN for the PGP key space by querying the
459 pgpBaseKeySpaceDN attribute (This is normally
460 'ou=PGP Keys,dc=EXAMPLE,dc=ORG').
462 - The attribute to lookup to find the pgp key. This is either
463 'pgpKey' or 'pgpKeyV2'.
465 - Whether this is a real ldap server. (It's unclear what this
468 The values are returned in the passed variables. If you pass NULL,
469 then the value won't be returned. It is the caller's
470 responsibility to release *LDAP_CONNP with ldap_unbind and xfree
473 If this function successfully interrogated the server, it returns
474 0. If there was an LDAP error, it returns the LDAP error code. If
475 an error occurred, *basednp, etc., are undefined (and don't need to
478 R_SERVERINFO receives information about the server.
480 If no LDAP error occurred, you still need to check that *basednp is
481 valid. If it is NULL, then the server does not appear to be an
482 OpenPGP Keyserver. */
484 my_ldap_connect (parsed_uri_t uri, LDAP **ldap_connp,
485 char **basednp, unsigned int *r_serverinfo)
488 LDAP *ldap_conn = NULL;
489 char *user = uri->auth;
490 struct uri_tuple_s *password_param;
496 password_param = uri_query_lookup (uri, "password");
497 password = password_param ? password_param->value : NULL;
500 log_debug ("my_ldap_connect(%s:%d/%s????%s%s%s%s%s%s)\n",
501 uri->host, uri->port,
502 uri->path ? uri->path : "",
503 uri->auth ? "bindname=" : "",
504 uri->auth ? uri->auth : "",
505 uri->auth && password ? "," : "",
506 password ? "password=" : "",
507 password ? ">not shown<": "",
508 uri->ad_current? " auth=>current_user<":"");
510 /* If the uri specifies a secure connection and we don't support
511 TLS, then fail; don't silently revert to an insecure
515 #ifndef HAVE_LDAP_START_TLS_S
516 log_error ("Can't use LDAP to connect to the server: no TLS support.");
517 err = GPG_ERR_LDAP_NOT_SUPPORTED;
522 ldap_conn = ldap_init (uri->host, uri->port);
525 err = gpg_err_code_from_syserror ();
526 log_error ("error initializing LDAP for (%s://%s:%d)\n",
527 uri->scheme, uri->host, uri->port);
531 #ifdef HAVE_LDAP_SET_OPTION
533 int ver = LDAP_VERSION3;
535 err = ldap_set_option (ldap_conn, LDAP_OPT_PROTOCOL_VERSION, &ver);
536 if (err != LDAP_SUCCESS)
538 log_error ("ks-ldap: unable to go to LDAP 3: %s\n",
539 ldap_err2string (err));
545 /* XXX: It would be nice to have an option to provide the server's
548 #if defined(LDAP_OPT_X_TLS_CACERTFILE) && defined(HAVE_LDAP_SET_OPTION)
549 err = ldap_set_option (NULL, LDAP_OPT_X_TLS_CACERTFILE, ca_cert_file);
552 log_error ("unable to set ca-cert-file to '%s': %s\n",
553 ca_cert_file, ldap_err2string (err));
556 #endif /* LDAP_OPT_X_TLS_CACERTFILE && HAVE_LDAP_SET_OPTION */
559 #ifdef HAVE_LDAP_START_TLS_S
562 /* XXX: We need an option to determine whether to abort if the
563 certificate is bad or not. Right now we conservatively
564 default to checking the certificate and aborting. */
565 #ifndef HAVE_W32_SYSTEM
566 int check_cert = LDAP_OPT_X_TLS_HARD; /* LDAP_OPT_X_TLS_NEVER */
568 err = ldap_set_option (ldap_conn,
569 LDAP_OPT_X_TLS_REQUIRE_CERT, &check_cert);
572 log_error ("error setting TLS option on LDAP connection\n");
576 /* On Windows, the certificates are checked by default. If the
577 option to disable checking mentioned above is ever
578 implemented, the way to do that on Windows is to install a
579 callback routine using ldap_set_option (..,
580 LDAP_OPT_SERVER_CERTIFICATE, ..); */
584 err = ldap_start_tls_s (ldap_conn,
585 #ifdef HAVE_W32_SYSTEM
586 /* ServerReturnValue, result */
589 /* ServerControls, ClientControls */
594 log_error ("error connecting to LDAP server with TLS\n");
603 log_debug ("LDAP bind to current user via AD\n");
604 #ifdef HAVE_W32_SYSTEM
606 err = ldap_bind_s (ldap_conn, NULL, NULL, LDAP_AUTH_NEGOTIATE);
608 if (err != LDAP_SUCCESS)
610 log_error ("error binding to LDAP via AD: %s\n",
611 ldap_err2string (err));
615 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
622 log_debug ("LDAP bind to %s, password %s\n",
623 user, password ? ">not shown<" : ">none<");
626 err = ldap_simple_bind_s (ldap_conn, user, password);
628 if (err != LDAP_SUCCESS)
630 log_error ("error binding to LDAP: %s\n", ldap_err2string (err));
636 /* By default we don't bind as there is usually no need to. */
639 if (uri->path && *uri->path)
641 /* User specified base DN. */
642 basedn = xstrdup (uri->path);
644 /* If the user specifies a base DN, then we know the server is a
645 * real LDAP server. */
646 *r_serverinfo |= SERVERINFO_REALLDAP;
649 { /* Look for namingContexts. */
650 LDAPMessage *res = NULL;
651 char *attr[] = { "namingContexts", NULL };
654 err = ldap_search_s (ldap_conn, "", LDAP_SCOPE_BASE,
655 "(objectClass=*)", attr, 0, &res);
658 if (err == LDAP_SUCCESS)
663 context = ldap_get_values (ldap_conn, res, "namingContexts");
667 /* We found some, so try each namingContext as the
668 * search base and look for pgpBaseKeySpaceDN. Because
669 * we found this, we know we're talking to a regular-ish
670 * LDAP server and not an LDAP keyserver. */
673 { "pgpBaseKeySpaceDN", "pgpVersion", "pgpSoftware", NULL };
675 *r_serverinfo |= SERVERINFO_REALLDAP;
677 for (i = 0; context[i] && ! basedn; i++)
684 char *object = xasprintf ("cn=pgpServerInfo,%s",
687 err = ldap_search_s (ldap_conn, object, LDAP_SCOPE_BASE,
688 "(objectClass=*)", attr2, 0, &si_res);
693 if (err == LDAP_SUCCESS)
695 vals = ldap_get_values (ldap_conn, si_res,
696 "pgpBaseKeySpaceDN");
699 basedn = xtrystrdup (vals[0]);
700 ldap_value_free (vals);
703 vals = ldap_get_values (ldap_conn, si_res,
708 log_debug ("Server: \t%s\n", vals[0]);
709 if (!ascii_strcasecmp (vals[0], "GnuPG"))
711 ldap_value_free (vals);
714 vals = ldap_get_values (ldap_conn, si_res,
719 log_debug ("Version:\t%s\n", vals[0]);
722 const char *fields[2];
724 nfields = split_fields (vals[0],
725 fields, DIM(fields));
726 if (nfields > 0 && atoi(fields[0]) > 1)
727 *r_serverinfo |= SERVERINFO_SCHEMAV2;
729 && !ascii_strcasecmp (fields[1], "ntds"))
730 *r_serverinfo |= SERVERINFO_NTDS;
732 ldap_value_free (vals);
736 /* From man ldap_search_s: "res parameter of
737 ldap_search_ext_s() and ldap_search_s() should be
738 freed with ldap_msgfree() regardless of return
739 value of these functions. */
740 ldap_msgfree (si_res);
743 ldap_value_free (context);
748 /* We don't have an answer yet, which means the server might
749 be a PGP.com keyserver. */
751 LDAPMessage *si_res = NULL;
753 char *attr2[] = { "pgpBaseKeySpaceDN", "version", "software", NULL };
756 err = ldap_search_s (ldap_conn, "cn=pgpServerInfo", LDAP_SCOPE_BASE,
757 "(objectClass=*)", attr2, 0, &si_res);
759 if (err == LDAP_SUCCESS)
761 /* For the PGP LDAP keyserver, this is always
762 * "OU=ACTIVE,O=PGP KEYSPACE,C=US", but it might not be
765 vals = ldap_get_values (ldap_conn, si_res, "baseKeySpaceDN");
768 basedn = xtrystrdup (vals[0]);
769 ldap_value_free (vals);
772 vals = ldap_get_values (ldap_conn, si_res, "software");
776 log_debug ("ks-ldap: PGP Server: \t%s\n", vals[0]);
777 ldap_value_free (vals);
780 vals = ldap_get_values (ldap_conn, si_res, "version");
784 log_debug ("ks-ldap: PGP Server Version:\t%s\n", vals[0]);
786 /* If the version is high enough, use the new
787 pgpKeyV2 attribute. This design is iffy at best,
788 but it matches how PGP does it. I figure the NAI
789 folks assumed that there would never be an LDAP
790 keyserver vendor with a different numbering
792 if (atoi (vals[0]) > 1)
793 *r_serverinfo |= SERVERINFO_PGPKEYV2;
795 ldap_value_free (vals);
799 ldap_msgfree (si_res);
802 /* From man ldap_search_s: "res parameter of ldap_search_ext_s()
803 and ldap_search_s() should be freed with ldap_msgfree()
804 regardless of return value of these functions. */
809 if (!err && opt.debug)
811 log_debug ("ldap_conn: %p\n", ldap_conn);
812 log_debug ("server_type: %s\n", ((*r_serverinfo & SERVERINFO_REALLDAP)
813 ? "LDAP" : "PGP.com keyserver") );
814 log_debug ("basedn: %s\n", basedn);
815 log_debug ("pgpkeyattr: %s\n",
816 (*r_serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey");
832 ldap_unbind (ldap_conn);
835 *ldap_connp = ldap_conn;
840 /* Extract keys from an LDAP reply and write them out to the output
841 stream OUTPUT in a format GnuPG can import (either the OpenPGP
842 binary format or armored format). */
844 extract_keys (estream_t output,
845 LDAP *ldap_conn, const char *certid, LDAPMessage *message)
849 es_fprintf (output, "INFO %s BEGIN\n", certid);
850 es_fprintf (output, "pub:%s:", certid);
852 /* Note: ldap_get_values returns a NULL terminated array of
854 vals = ldap_get_values (ldap_conn, message, "pgpkeytype");
857 if (strcmp (vals[0], "RSA") == 0)
858 es_fprintf (output, "1");
859 else if (strcmp (vals[0],"DSS/DH") == 0)
860 es_fprintf (output, "17");
861 ldap_value_free (vals);
864 es_fprintf (output, ":");
866 vals = ldap_get_values (ldap_conn, message, "pgpkeysize");
869 int v = atoi (vals[0]);
871 es_fprintf (output, "%d", v);
872 ldap_value_free (vals);
875 es_fprintf (output, ":");
877 vals = ldap_get_values (ldap_conn, message, "pgpkeycreatetime");
880 if (strlen (vals[0]) == 15)
881 es_fprintf (output, "%u", (unsigned int) ldap2epochtime (vals[0]));
882 ldap_value_free (vals);
885 es_fprintf (output, ":");
887 vals = ldap_get_values (ldap_conn, message, "pgpkeyexpiretime");
890 if (strlen (vals[0]) == 15)
891 es_fprintf (output, "%u", (unsigned int) ldap2epochtime (vals[0]));
892 ldap_value_free (vals);
895 es_fprintf (output, ":");
897 vals = ldap_get_values (ldap_conn, message, "pgprevoked");
900 if (atoi (vals[0]) == 1)
901 es_fprintf (output, "r");
902 ldap_value_free (vals);
905 es_fprintf (output, "\n");
907 vals = ldap_get_values (ldap_conn, message, "pgpuserid");
911 for (i = 0; vals[i]; i++)
912 es_fprintf (output, "uid:%s\n", vals[i]);
913 ldap_value_free (vals);
916 es_fprintf (output, "INFO %s END\n", certid);
919 /* Get the key described key the KEYSPEC string from the keyserver
920 identified by URI. On success R_FP has an open stream to read the
923 ks_ldap_get (ctrl_t ctrl, parsed_uri_t uri, const char *keyspec,
928 unsigned int serverinfo;
930 LDAP *ldap_conn = NULL;
933 LDAPMessage *message = NULL;
937 if (dirmngr_use_tor ())
939 /* For now we do not support LDAP over Tor. */
940 log_error (_("LDAP access not possible due to Tor mode\n"));
941 return gpg_error (GPG_ERR_NOT_SUPPORTED);
944 /* Make sure we are talking to an OpenPGP LDAP server. */
945 ldap_err = my_ldap_connect (uri, &ldap_conn, &basedn, &serverinfo);
946 if (ldap_err || !basedn)
949 err = ldap_err_to_gpg_err (ldap_err);
951 err = gpg_error (GPG_ERR_GENERAL);
955 /* Now that we have information about the server we can construct a
956 * query best suited for the capabilities of the server. */
957 err = keyspec_to_ldap_filter (keyspec, &filter, 1, serverinfo);
962 log_debug ("ks-ldap: using filter: %s\n", filter);
965 /* The ordering is significant. Specifically, "pgpcertid" needs
966 to be the second item in the list, since everything after it
967 may be discarded we aren't in verbose mode. */
971 "pgpcertid", "pgpuserid", "pgpkeyid", "pgprevoked", "pgpdisabled",
972 "pgpkeycreatetime", "modifytimestamp", "pgpkeysize", "pgpkeytype",
975 /* 1 if we want just attribute types; 0 if we want both attribute
976 * types and values. */
980 /* Replace "dummy". */
981 attrs[0] = (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2" : "pgpKey";
984 ldap_err = ldap_search_s (ldap_conn, basedn, LDAP_SCOPE_SUBTREE,
985 filter, attrs, attrsonly, &message);
989 err = ldap_err_to_gpg_err (ldap_err);
991 log_error ("ks-ldap: LDAP search error: %s\n",
992 ldap_err2string (ldap_err));
996 count = ldap_count_entries (ldap_conn, message);
999 log_info ("ks-ldap: key %s not found on keyserver\n", keyspec);
1002 err = ldap_to_gpg_err (ldap_conn);
1004 err = gpg_error (GPG_ERR_NO_DATA);
1010 /* There may be more than one unique result for a given keyID,
1011 so we should fetch them all (test this by fetching short key
1014 /* The set of entries that we've seen. */
1015 strlist_t seen = NULL;
1018 for (npth_unprotect (),
1019 each = ldap_first_entry (ldap_conn, message),
1023 each = ldap_next_entry (ldap_conn, each),
1029 /* Use the long keyid to remove duplicates. The LDAP
1030 server returns the same keyid more than once if there
1031 are multiple user IDs on the key. Note that this does
1032 NOT mean that a keyid that exists multiple times on the
1033 keyserver will not be fetched. It means that each KEY,
1034 no matter how many user IDs share its keyid, will be
1035 fetched only once. If a keyid that belongs to more
1036 than one key is fetched, the server quite properly
1037 responds with all matching keys. -ds */
1039 certid = ldap_get_values (ldap_conn, each, "pgpcertid");
1040 if (certid && certid[0])
1042 if (! strlist_find (seen, certid[0]))
1044 /* It's not a duplicate, add it */
1046 add_to_strlist (&seen, certid[0]);
1049 fp = es_fopenmem(0, "rw");
1051 extract_keys (fp, ldap_conn, certid[0], each);
1053 vals = ldap_get_values (ldap_conn, each, attrs[0]);
1056 err = ldap_to_gpg_err (ldap_conn);
1057 log_error("ks-ldap: unable to retrieve key %s "
1058 "from keyserver\n", certid[0]);
1063 /* We should strip the new lines. */
1064 es_fprintf (fp, "KEY 0x%s BEGIN\n", certid[0]);
1065 es_fputs (vals[0], fp);
1066 es_fprintf (fp, "\nKEY 0x%s END\n", certid[0]);
1068 ldap_value_free (vals);
1073 ldap_value_free (certid);
1076 free_strlist (seen);
1079 err = gpg_error (GPG_ERR_NO_DATA);
1085 ldap_msgfree (message);
1095 es_fseek (fp, 0, SEEK_SET);
1103 ldap_unbind (ldap_conn);
1111 /* Search the keyserver identified by URI for keys matching PATTERN.
1112 On success R_FP has an open stream to read the data. */
1114 ks_ldap_search (ctrl_t ctrl, parsed_uri_t uri, const char *pattern,
1119 unsigned int serverinfo;
1120 char *filter = NULL;
1121 LDAP *ldap_conn = NULL;
1122 char *basedn = NULL;
1123 estream_t fp = NULL;
1127 if (dirmngr_use_tor ())
1129 /* For now we do not support LDAP over Tor. */
1130 log_error (_("LDAP access not possible due to Tor mode\n"));
1131 return gpg_error (GPG_ERR_NOT_SUPPORTED);
1134 /* Make sure we are talking to an OpenPGP LDAP server. */
1135 ldap_err = my_ldap_connect (uri, &ldap_conn, &basedn, &serverinfo);
1136 if (ldap_err || !basedn)
1139 err = ldap_err_to_gpg_err (ldap_err);
1141 err = GPG_ERR_GENERAL;
1145 /* Now that we have information about the server we can construct a
1146 * query best suited for the capabilities of the server. */
1147 err = keyspec_to_ldap_filter (pattern, &filter, 0, serverinfo);
1150 log_error ("Bad search pattern: '%s'\n", pattern);
1154 /* Even if we have no results, we want to return a stream. */
1155 fp = es_fopenmem(0, "rw");
1158 err = gpg_error_from_syserror ();
1164 LDAPMessage *res, *each;
1166 strlist_t dupelist = NULL;
1168 /* The maximum size of the search, including the optional stuff
1169 and the trailing \0 */
1172 "pgpcertid", "pgpuserid", "pgprevoked", "pgpdisabled",
1173 "pgpkeycreatetime", "pgpkeyexpiretime", "modifytimestamp",
1174 "pgpkeysize", "pgpkeytype", NULL
1178 log_debug ("SEARCH '%s' => '%s' BEGIN\n", pattern, filter);
1181 ldap_err = ldap_search_s (ldap_conn, basedn,
1182 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &res);
1188 if (ldap_err != LDAP_SUCCESS && ldap_err != LDAP_SIZELIMIT_EXCEEDED)
1190 err = ldap_err_to_gpg_err (ldap_err);
1192 log_error ("SEARCH %s FAILED %d\n", pattern, err);
1193 log_error ("ks-ldap: LDAP search error: %s\n",
1194 ldap_err2string (err));
1198 /* The LDAP server doesn't return a real count of unique keys, so we
1199 can't use ldap_count_entries here. */
1200 for (npth_unprotect (),
1201 each = ldap_first_entry (ldap_conn, res),
1205 each = ldap_next_entry (ldap_conn, each),
1208 char **certid = ldap_get_values (ldap_conn, each, "pgpcertid");
1209 if (certid && certid[0] && ! strlist_find (dupelist, certid[0]))
1211 add_to_strlist (&dupelist, certid[0]);
1216 if (ldap_err == LDAP_SIZELIMIT_EXCEEDED)
1219 log_error ("ks-ldap: search results exceeded server limit."
1220 " First 1 result shown.\n");
1222 log_error ("ks-ldap: search results exceeded server limit."
1223 " First %d results shown.\n", count);
1226 free_strlist (dupelist);
1230 es_fputs ("info:1:0\n", fp);
1233 es_fprintf (fp, "info:1:%d\n", count);
1235 for (each = ldap_first_entry (ldap_conn, res);
1237 each = ldap_next_entry (ldap_conn, each))
1242 certid = ldap_get_values (ldap_conn, each, "pgpcertid");
1243 if (! certid || ! certid[0])
1246 /* Have we seen this certid before? */
1247 if (! strlist_find (dupelist, certid[0]))
1249 add_to_strlist (&dupelist, certid[0]);
1251 es_fprintf (fp, "pub:%s:",certid[0]);
1253 vals = ldap_get_values (ldap_conn, each, "pgpkeytype");
1256 /* The LDAP server doesn't exactly handle this
1258 if (strcasecmp (vals[0], "RSA") == 0)
1260 else if (strcasecmp (vals[0], "DSS/DH") == 0)
1261 es_fputs ("17", fp);
1262 ldap_value_free (vals);
1267 vals = ldap_get_values (ldap_conn, each, "pgpkeysize");
1270 /* Not sure why, but some keys are listed with a
1271 key size of 0. Treat that like an unknown. */
1272 if (atoi (vals[0]) > 0)
1273 es_fprintf (fp, "%d", atoi (vals[0]));
1274 ldap_value_free (vals);
1279 /* YYYYMMDDHHmmssZ */
1281 vals = ldap_get_values (ldap_conn, each, "pgpkeycreatetime");
1282 if(vals && strlen (vals[0]) == 15)
1284 es_fprintf (fp, "%u",
1285 (unsigned int) ldap2epochtime(vals[0]));
1286 ldap_value_free (vals);
1291 vals = ldap_get_values (ldap_conn, each, "pgpkeyexpiretime");
1292 if (vals && strlen (vals[0]) == 15)
1294 es_fprintf (fp, "%u",
1295 (unsigned int) ldap2epochtime (vals[0]));
1296 ldap_value_free (vals);
1301 vals = ldap_get_values (ldap_conn, each, "pgprevoked");
1304 if (atoi (vals[0]) == 1)
1305 es_fprintf (fp, "r");
1306 ldap_value_free (vals);
1309 vals = ldap_get_values (ldap_conn, each, "pgpdisabled");
1312 if (atoi (vals[0]) ==1)
1313 es_fprintf (fp, "d");
1314 ldap_value_free (vals);
1318 /* This is not yet specified in the keyserver
1319 protocol, but may be someday. */
1322 vals = ldap_get_values (ldap_conn, each, "modifytimestamp");
1323 if(vals && strlen (vals[0]) == 15)
1325 es_fprintf (fp, "%u",
1326 (unsigned int) ldap2epochtime (vals[0]));
1327 ldap_value_free (vals);
1331 es_fprintf (fp, "\n");
1333 /* Now print all the uids that have this certid */
1334 for (uids = ldap_first_entry (ldap_conn, res);
1336 uids = ldap_next_entry (ldap_conn, uids))
1338 vals = ldap_get_values (ldap_conn, uids, "pgpcertid");
1342 if (strcasecmp (certid[0], vals[0]) == 0)
1346 es_fprintf (fp, "uid:");
1348 uidvals = ldap_get_values (ldap_conn,
1352 /* Need to escape any colons */
1353 char *quoted = percent_escape (uidvals[0], NULL);
1354 es_fputs (quoted, fp);
1356 ldap_value_free (uidvals);
1359 es_fprintf (fp, "\n");
1362 ldap_value_free(vals);
1366 ldap_value_free (certid);
1371 free_strlist (dupelist);
1375 log_debug ("SEARCH %s END\n", pattern);
1385 /* Return the read stream. */
1387 es_fseek (fp, 0, SEEK_SET);
1395 ldap_unbind (ldap_conn);
1404 /* A modlist describes a set of changes to an LDAP entry. (An entry
1405 consists of 1 or more attributes. Attributes are <name, value>
1406 pairs. Note: an attribute may be multi-valued in which case
1407 multiple values are associated with a single name.)
1409 A modlist is a NULL terminated array of struct LDAPMod's.
1419 Is the ith modification.
1421 Each LDAPMod describes a change to a single attribute. Further,
1422 there is one modification for each attribute that we want to
1423 change. The attribute's new value is stored in LDAPMod.mod_values.
1424 If the attribute is multi-valued, we still only use a single
1425 LDAPMod structure: mod_values is a NULL-terminated array of
1426 strings. To delete an attribute from an entry, we set mod_values
1431 modlist[i]->mod_values == NULL
1433 then we remove the attribute.
1435 (Using LDAP_MOD_DELETE doesn't work here as we don't know if the
1436 attribute in question exists or not.)
1438 Note: this function does NOT copy or free ATTR. It does copy
1441 modlist_add (LDAPMod ***modlistp, char *attr, const char *value)
1443 LDAPMod **modlist = *modlistp;
1448 /* Search modlist for the attribute we're playing with. If modlist
1449 is NULL, then the list is empty. Recall: modlist is a NULL
1450 terminated array. */
1451 for (m = modlist; m && *m; m++, nummods ++)
1453 /* The attribute is already on the list. */
1457 if (strcasecmp ((*m)->mod_type, attr) != 0)
1460 /* We have this attribute already, so when the REPLACE happens,
1461 the server attributes will be replaced anyway. */
1465 /* Attributes can be multi-valued. See if the value is already
1466 present. mod_values is a NULL terminated array of pointers.
1467 Note: mod_values can be NULL. */
1468 for (ptr = (*m)->mod_values; ptr && *ptr; ptr++)
1470 if (strcmp (*ptr, value) == 0)
1471 /* Duplicate value, we're done. */
1476 /* Append the value. */
1477 ptr = xrealloc ((*m)->mod_values, sizeof (char *) * (numvalues + 2));
1479 (*m)->mod_values = ptr;
1480 ptr[numvalues] = xstrdup (value);
1482 ptr[numvalues + 1] = NULL;
1487 /* We didn't find the attr, so make one and add it to the end */
1489 /* Like attribute values, the list of attributes is NULL terminated
1490 array of pointers. */
1491 modlist = xrealloc (modlist, sizeof (LDAPMod *) * (nummods + 2));
1493 *modlistp = modlist;
1494 modlist[nummods] = xmalloc (sizeof (LDAPMod));
1496 modlist[nummods]->mod_op = LDAP_MOD_REPLACE;
1497 modlist[nummods]->mod_type = attr;
1500 modlist[nummods]->mod_values = xmalloc (sizeof(char *) * 2);
1502 modlist[nummods]->mod_values[0] = xstrdup (value);
1503 modlist[nummods]->mod_values[1] = NULL;
1506 modlist[nummods]->mod_values = NULL;
1508 modlist[nummods + 1] = NULL;
1513 /* Look up the value of an attribute in the specified modlist. If the
1514 attribute is not on the mod list, returns NULL. The result is a
1515 NULL-terminated array of strings. Don't change it. */
1517 modlist_lookup (LDAPMod **modlist, const char *attr)
1520 for (m = modlist; m && *m; m++)
1522 if (strcasecmp ((*m)->mod_type, attr) != 0)
1525 return (*m)->mod_values;
1531 /* Dump a modlist to a file. This is useful for debugging. */
1532 static estream_t modlist_dump (LDAPMod **modlist, estream_t output)
1536 modlist_dump (LDAPMod **modlist, estream_t output)
1544 output = es_fopenmem (0, "rw");
1550 for (m = modlist; m && *m; m++)
1552 es_fprintf (output, " %s:", (*m)->mod_type);
1554 if (! (*m)->mod_values)
1555 es_fprintf(output, " delete.\n");
1562 if ((*m)->mod_values[0] && (*m)->mod_values[1])
1563 /* Have at least 2. */
1567 es_fprintf (output, "\n");
1569 for ((ptr = (*m)->mod_values), (i = 1); ptr && *ptr; ptr++, i ++)
1571 /* Assuming terminals are about 80 characters wide,
1572 display at most about 10 lines of debugging
1573 output. If we do trim the buffer, append '...' to
1575 const int max_len = 10 * 70;
1576 size_t value_len = strlen (*ptr);
1577 int elide = value_len > max_len;
1580 es_fprintf (output, " %d. ", i);
1581 es_fprintf (output, "`%.*s", max_len, *ptr);
1583 es_fprintf (output, "...' (%zd bytes elided)",
1584 value_len - max_len);
1586 es_fprintf (output, "'");
1587 es_fprintf (output, "\n");
1593 es_fseek (output, 0, SEEK_SET);
1598 /* Free all of the memory allocated by the mod list. This assumes
1599 that the attribute names don't have to be freed, but the attributes
1600 values do. (Which is what modlist_add does.) */
1602 modlist_free (LDAPMod **modlist)
1609 /* Unwind and free the whole modlist structure */
1611 /* The modlist is a NULL terminated array of pointers. */
1612 for (ml = modlist; *ml; ml++)
1617 /* The list of values is a NULL termianted array of pointers.
1618 If the list is NULL, there are no values. */
1620 if (mod->mod_values)
1622 for (ptr = mod->mod_values; *ptr; ptr++)
1625 xfree (mod->mod_values);
1633 /* Append two onto the end of one. Two is not freed, but its pointers
1634 are now part of one. Make sure you don't free them both!
1636 As long as you don't add anything to ONE, TWO is still valid.
1637 After that all bets are off. */
1639 modlists_join (LDAPMod ***one, LDAPMod **two)
1641 int i, one_count = 0, two_count = 0;
1645 /* two is empty. Nothing to do. */
1649 /* one is empty. Just set it equal to *two. */
1655 for (grow = *one; *grow; grow++)
1658 for (grow = two; *grow; grow++)
1661 grow = xrealloc (*one, sizeof(LDAPMod *) * (one_count + two_count + 1));
1663 for (i = 0; i < two_count; i++)
1664 grow[one_count + i] = two[i];
1666 grow[one_count + i] = NULL;
1671 /* Given a string, unescape C escapes. In particular, \xXX. This
1672 modifies the string in place. */
1674 uncescape (char *str)
1679 char *first = strchr (str, '\\');
1681 /* No backslashes => no escaping. We're done. */
1684 /* Start at the first '\\'. */
1685 r = w = (uintptr_t) first - (uintptr_t) str;
1689 /* XXX: What to do about bad escapes?
1690 XXX: hextobyte already checks the string thus the hexdigitp
1691 could be removed. */
1692 if (str[r] == '\\' && str[r + 1] == 'x'
1693 && str[r+2] && str[r+3]
1694 && hexdigitp (str + r + 2)
1695 && hexdigitp (str + r + 3))
1697 int x = hextobyte (&str[r + 2]);
1698 assert (0 <= x && x <= 0xff);
1702 /* We consumed 4 characters and wrote 1. */
1707 str[w ++] = str[r ++];
1713 /* Given one line from an info block (`gpg --list-{keys,sigs}
1714 --with-colons KEYID'), pull it apart and fill in the modlist with
1715 the relevant (for the LDAP schema) attributes. EXTRACT_STATE
1716 should initally be set to 0 by the caller. SCHEMAV2 is set if the
1717 server supports the version 2 schema. */
1719 extract_attributes (LDAPMod ***modlist, int *extract_state,
1720 char *line, int schemav2)
1725 int is_pub, is_sub, is_uid, is_sig;
1727 /* Remove trailing whitespace */
1728 trim_trailing_spaces (line);
1730 fields = strsplit (line, ':', '\0', &field_count);
1731 if (field_count == 1)
1732 /* We only have a single field. There is definitely nothing to
1736 if (field_count < 7)
1739 is_pub = !ascii_strcasecmp ("pub", fields[0]);
1740 is_sub = !ascii_strcasecmp ("sub", fields[0]);
1741 is_uid = !ascii_strcasecmp ("uid", fields[0]);
1742 is_sig = !ascii_strcasecmp ("sig", fields[0]);
1743 if (!ascii_strcasecmp ("fpr", fields[0]))
1745 /* Special treatment for a fingerprint. */
1746 if (!(*extract_state & 1))
1747 goto out; /* Stray fingerprint line - ignore. */
1748 *extract_state &= ~1;
1749 if (field_count >= 10 && schemav2)
1751 if ((*extract_state & 2))
1752 modlist_add (modlist, "gpgFingerprint", fields[9]);
1754 modlist_add (modlist, "gpgSubFingerprint", fields[9]);
1759 *extract_state &= ~(1|2);
1761 *extract_state |= (1|2);
1763 *extract_state |= 1;
1765 if (!is_pub && !is_sub && !is_uid && !is_sig)
1766 goto out; /* Not a relevant line. */
1770 if (is_uid && strlen (keyid) == 0)
1771 ; /* The uid record type can have an empty keyid. */
1772 else if (strlen (keyid) == 16
1773 && strspn (keyid, "0123456789aAbBcCdDeEfF") == 16)
1774 ; /* Otherwise, we expect exactly 16 hex characters. */
1777 log_error ("malformed record!\n");
1786 for (flags = fields[1]; *flags; flags ++)
1800 /* Note: we always create the pgpDisabled and pgpRevoked
1801 attributes, regardless of whether the key is disabled/revoked
1802 or not. This is because a very common search is like
1803 "(&(pgpUserID=*isabella*)(pgpDisabled=0))" */
1807 modlist_add (modlist,"pgpDisabled", disabled ? "1" : "0");
1808 modlist_add (modlist,"pgpRevoked", revoked ? "1" : "0");
1812 if (is_pub || is_sub)
1817 val = atoi (fields[2]);
1818 if (val < 99999 && val > 0)
1820 /* We zero pad this on the left to make PGP happy. */
1821 snprintf (padded, sizeof padded, "%05u", val);
1822 modlist_add (modlist, "pgpKeySize", padded);
1828 char *algo = fields[3];
1829 int val = atoi (algo);
1846 modlist_add (modlist, "pgpKeyType", algo);
1849 if (is_pub || is_sub || is_sig)
1853 modlist_add (modlist, "pgpCertID", keyid); /* Long keyid(!) */
1854 modlist_add (modlist, "pgpKeyID", &keyid[8]); /* Short keyid */
1858 modlist_add (modlist, "pgpSubKeyID", keyid); /* Long keyid(!) */
1863 char *create_time = fields[5];
1865 if (strlen (create_time) == 0)
1869 char *create_time_orig = create_time;
1874 memset (&tm, 0, sizeof (tm));
1876 /* parse_timestamp handles both seconds fromt he epoch and
1877 ISO 8601 format. We also need to handle YYYY-MM-DD
1878 format (as generated by gpg1 --with-colons --list-key).
1879 Check that first and then if it fails, then try
1882 if (!isodate_human_to_tm (create_time, &tm))
1883 create_time = tm2ldaptime (&tm);
1884 else if ((t = parse_timestamp (create_time, &end)) != (time_t) -1
1888 if (!gnupg_gmtime (&t, &tm))
1891 create_time = tm2ldaptime (&tm);
1897 /* Failed to parse string. */
1898 log_error ("Failed to parse creation time ('%s')",
1904 modlist_add (modlist, "pgpKeyCreateTime", create_time);
1905 xfree (create_time);
1911 char *expire_time = fields[6];
1913 if (strlen (expire_time) == 0)
1917 char *expire_time_orig = expire_time;
1922 memset (&tm, 0, sizeof (tm));
1924 /* parse_timestamp handles both seconds fromt he epoch and
1925 ISO 8601 format. We also need to handle YYYY-MM-DD
1926 format (as generated by gpg1 --with-colons --list-key).
1927 Check that first and then if it fails, then try
1930 if (!isodate_human_to_tm (expire_time, &tm))
1931 expire_time = tm2ldaptime (&tm);
1932 else if ((t = parse_timestamp (expire_time, &end)) != (time_t) -1
1935 if (!gnupg_gmtime (&t, &tm))
1938 expire_time = tm2ldaptime (&tm);
1944 /* Failed to parse string. */
1945 log_error ("Failed to parse creation time ('%s')",
1951 modlist_add (modlist, "pgpKeyExpireTime", expire_time);
1952 xfree (expire_time);
1956 if (is_uid && field_count >= 10)
1958 char *uid = fields[9];
1962 modlist_add (modlist, "pgpUserID", uid);
1963 if (schemav2 && (mbox = mailbox_from_userid (uid, 0)))
1965 modlist_add (modlist, "gpgMailbox", mbox);
1974 /* Send the key in {KEY,KEYLEN} with the metadata {INFO,INFOLEN} to
1975 the keyserver identified by URI. See server.c:cmd_ks_put for the
1976 format of the data and metadata. */
1978 ks_ldap_put (ctrl_t ctrl, parsed_uri_t uri,
1979 void *data, size_t datalen,
1980 void *info, size_t infolen)
1982 gpg_error_t err = 0;
1984 unsigned int serverinfo;
1985 LDAP *ldap_conn = NULL;
1986 char *basedn = NULL;
1987 LDAPMod **modlist = NULL;
1988 LDAPMod **addlist = NULL;
1989 char *data_armored = NULL;
1992 /* The last byte of the info block. */
1993 const char *infoend = (const char *) info + infolen - 1;
1995 /* Enable this code to dump the modlist to /tmp/modlist.txt. */
1997 # warning Disable debug code before checking in.
1998 const int dump_modlist = 1;
2000 const int dump_modlist = 0;
2002 estream_t dump = NULL;
2004 /* Elide a warning. */
2007 if (dirmngr_use_tor ())
2009 /* For now we do not support LDAP over Tor. */
2010 log_error (_("LDAP access not possible due to Tor mode\n"));
2011 return gpg_error (GPG_ERR_NOT_SUPPORTED);
2014 ldap_err = my_ldap_connect (uri, &ldap_conn, &basedn, &serverinfo);
2015 if (ldap_err || !basedn)
2018 err = ldap_err_to_gpg_err (ldap_err);
2020 err = GPG_ERR_GENERAL;
2024 if (!(serverinfo & SERVERINFO_REALLDAP))
2026 /* We appear to have a PGP.com Keyserver, which can unpack the
2027 * key on its own (not just a dump LDAP server). This will
2028 * rarely be the case these days. */
2036 memset (&mod, 0, sizeof (mod));
2037 mod.mod_op = LDAP_MOD_ADD;
2038 mod.mod_type = (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey";
2039 mod.mod_values = key;
2043 dn = xtryasprintf ("pgpCertid=virtual,%s", basedn);
2046 err = gpg_error_from_syserror ();
2049 ldap_err = ldap_add_s (ldap_conn, dn, attrs);
2052 if (ldap_err != LDAP_SUCCESS)
2054 err = ldap_err_to_gpg_err (err);
2061 modlist = xtrymalloc (sizeof (LDAPMod *));
2064 err = gpg_error_from_syserror ();
2071 dump = es_fopen("/tmp/modlist.txt", "w");
2073 log_error ("Failed to open /tmp/modlist.txt: %s\n",
2078 es_fprintf(dump, "data (%zd bytes)\n", datalen);
2079 es_fprintf(dump, "info (%zd bytes): '\n", infolen);
2080 es_fwrite(info, infolen, 1, dump);
2081 es_fprintf(dump, "'\n");
2085 /* Start by nulling out all attributes. We try and do a modify
2086 operation first, so this ensures that we don't leave old
2087 attributes lying around. */
2088 modlist_add (&modlist, "pgpDisabled", NULL);
2089 modlist_add (&modlist, "pgpKeyID", NULL);
2090 modlist_add (&modlist, "pgpKeyType", NULL);
2091 modlist_add (&modlist, "pgpUserID", NULL);
2092 modlist_add (&modlist, "pgpKeyCreateTime", NULL);
2093 modlist_add (&modlist, "pgpRevoked", NULL);
2094 modlist_add (&modlist, "pgpSubKeyID", NULL);
2095 modlist_add (&modlist, "pgpKeySize", NULL);
2096 modlist_add (&modlist, "pgpKeyExpireTime", NULL);
2097 modlist_add (&modlist, "pgpCertID", NULL);
2098 if ((serverinfo & SERVERINFO_SCHEMAV2))
2100 modlist_add (&modlist, "gpgFingerprint", NULL);
2101 modlist_add (&modlist, "gpgSubFingerprint", NULL);
2102 modlist_add (&modlist, "gpgMailbox", NULL);
2105 /* Assemble the INFO stuff into LDAP attributes */
2111 char *newline = memchr (info, '\n', infolen);
2113 /* The last line is not \n terminated! Make a copy so we can
2114 add a NUL terminator. */
2116 temp = xmalloc (infolen + 1);
2117 memcpy (temp, info, infolen);
2119 newline = (char *) info + infolen;
2124 extract_attributes (&addlist, &extract_state, info,
2125 (serverinfo & SERVERINFO_SCHEMAV2));
2127 infolen = infolen - ((uintptr_t) newline - (uintptr_t) info + 1);
2132 log_assert ((char *) info + infolen - 1 == infoend);
2135 log_assert (infolen == -1);
2140 modlist_add (&addlist, "objectClass", "pgpKeyInfo");
2142 err = armor_data (&data_armored, data, datalen);
2146 modlist_add (&addlist,
2147 (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey",
2150 /* Now append addlist onto modlist. */
2151 modlists_join (&modlist, addlist);
2155 estream_t input = modlist_dump (modlist, NULL);
2158 copy_stream (input, dump);
2163 /* Going on the assumption that modify operations are more frequent
2164 than adds, we try a modify first. If it's not there, we just
2165 turn around and send an add command for the same key. Otherwise,
2166 the modify brings the server copy into compliance with our copy.
2167 Note that unlike the LDAP keyserver (and really, any other
2168 keyserver) this does NOT merge signatures, but replaces the whole
2169 key. This should make some people very happy. */
2174 if ((serverinfo & SERVERINFO_NTDS))
2176 /* The modern way using a CN RDN with the fingerprint. This
2177 * has the advantage that we won't have duplicate 64 bit
2178 * keyids in the store. In particular NTDS requires the
2179 * DN to be unique. */
2180 attrval = modlist_lookup (addlist, "gpgFingerprint");
2181 /* We should have exactly one value. */
2182 if (!attrval || !(attrval[0] && !attrval[1]))
2184 log_error ("ks-ldap: bad gpgFingerprint provided\n");
2185 err = GPG_ERR_GENERAL;
2188 dn = xtryasprintf ("CN=%s,%s", attrval[0], basedn);
2190 else /* The old style way. */
2192 attrval = modlist_lookup (addlist, "pgpCertID");
2193 /* We should have exactly one value. */
2194 if (!attrval || !(attrval[0] && !attrval[1]))
2196 log_error ("ks-ldap: bad pgpCertID provided\n");
2197 err = GPG_ERR_GENERAL;
2200 dn = xtryasprintf ("pgpCertID=%s,%s", attrval[0], basedn);
2204 err = gpg_error_from_syserror ();
2208 log_debug ("ks-ldap: using DN: %s\n", dn);
2211 err = ldap_modify_s (ldap_conn, dn, modlist);
2212 if (err == LDAP_NO_SUCH_OBJECT)
2213 err = ldap_add_s (ldap_conn, dn, addlist);
2218 if (err != LDAP_SUCCESS)
2220 log_error ("ks-ldap: error adding key to keyserver: %s\n",
2221 ldap_err2string (err));
2222 err = ldap_err_to_gpg_err (err);
2231 ldap_unbind (ldap_conn);
2235 modlist_free (modlist);
2238 xfree (data_armored);