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 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 <http://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 "ks-engine.h"
50 #include "ldap-parse-uri.h"
53 time_t timegm(struct tm *tm);
56 /* Convert an LDAP error to a GPG error. */
58 ldap_err_to_gpg_err (int code)
64 #ifdef LDAP_X_CONNECTING
65 case LDAP_X_CONNECTING: ec = GPG_ERR_LDAP_X_CONNECTING; break;
68 case LDAP_REFERRAL_LIMIT_EXCEEDED: ec = GPG_ERR_LDAP_REFERRAL_LIMIT; break;
69 case LDAP_CLIENT_LOOP: ec = GPG_ERR_LDAP_CLIENT_LOOP; break;
70 case LDAP_NO_RESULTS_RETURNED: ec = GPG_ERR_LDAP_NO_RESULTS; break;
71 case LDAP_CONTROL_NOT_FOUND: ec = GPG_ERR_LDAP_CONTROL_NOT_FOUND; break;
72 case LDAP_NOT_SUPPORTED: ec = GPG_ERR_LDAP_NOT_SUPPORTED; break;
73 case LDAP_CONNECT_ERROR: ec = GPG_ERR_LDAP_CONNECT; break;
74 case LDAP_NO_MEMORY: ec = GPG_ERR_LDAP_NO_MEMORY; break;
75 case LDAP_PARAM_ERROR: ec = GPG_ERR_LDAP_PARAM; break;
76 case LDAP_USER_CANCELLED: ec = GPG_ERR_LDAP_USER_CANCELLED; break;
77 case LDAP_FILTER_ERROR: ec = GPG_ERR_LDAP_FILTER; break;
78 case LDAP_AUTH_UNKNOWN: ec = GPG_ERR_LDAP_AUTH_UNKNOWN; break;
79 case LDAP_TIMEOUT: ec = GPG_ERR_LDAP_TIMEOUT; break;
80 case LDAP_DECODING_ERROR: ec = GPG_ERR_LDAP_DECODING; break;
81 case LDAP_ENCODING_ERROR: ec = GPG_ERR_LDAP_ENCODING; break;
82 case LDAP_LOCAL_ERROR: ec = GPG_ERR_LDAP_LOCAL; break;
83 case LDAP_SERVER_DOWN: ec = GPG_ERR_LDAP_SERVER_DOWN; break;
85 case LDAP_SUCCESS: ec = GPG_ERR_LDAP_SUCCESS; break;
87 case LDAP_OPERATIONS_ERROR: ec = GPG_ERR_LDAP_OPERATIONS; break;
88 case LDAP_PROTOCOL_ERROR: ec = GPG_ERR_LDAP_PROTOCOL; break;
89 case LDAP_TIMELIMIT_EXCEEDED: ec = GPG_ERR_LDAP_TIMELIMIT; break;
90 case LDAP_SIZELIMIT_EXCEEDED: ec = GPG_ERR_LDAP_SIZELIMIT; break;
91 case LDAP_COMPARE_FALSE: ec = GPG_ERR_LDAP_COMPARE_FALSE; break;
92 case LDAP_COMPARE_TRUE: ec = GPG_ERR_LDAP_COMPARE_TRUE; break;
93 case LDAP_AUTH_METHOD_NOT_SUPPORTED: ec=GPG_ERR_LDAP_UNSUPPORTED_AUTH;break;
94 case LDAP_STRONG_AUTH_REQUIRED: ec = GPG_ERR_LDAP_STRONG_AUTH_RQRD; break;
95 case LDAP_PARTIAL_RESULTS: ec = GPG_ERR_LDAP_PARTIAL_RESULTS; break;
96 case LDAP_REFERRAL: ec = GPG_ERR_LDAP_REFERRAL; break;
98 #ifdef LDAP_ADMINLIMIT_EXCEEDED
99 case LDAP_ADMINLIMIT_EXCEEDED: ec = GPG_ERR_LDAP_ADMINLIMIT; break;
102 #ifdef LDAP_UNAVAILABLE_CRITICAL_EXTENSION
103 case LDAP_UNAVAILABLE_CRITICAL_EXTENSION:
104 ec = GPG_ERR_LDAP_UNAVAIL_CRIT_EXTN; break;
107 case LDAP_CONFIDENTIALITY_REQUIRED: ec = GPG_ERR_LDAP_CONFIDENT_RQRD; break;
108 case LDAP_SASL_BIND_IN_PROGRESS: ec = GPG_ERR_LDAP_SASL_BIND_INPROG; break;
109 case LDAP_NO_SUCH_ATTRIBUTE: ec = GPG_ERR_LDAP_NO_SUCH_ATTRIBUTE; break;
110 case LDAP_UNDEFINED_TYPE: ec = GPG_ERR_LDAP_UNDEFINED_TYPE; break;
111 case LDAP_INAPPROPRIATE_MATCHING: ec = GPG_ERR_LDAP_BAD_MATCHING; break;
112 case LDAP_CONSTRAINT_VIOLATION: ec = GPG_ERR_LDAP_CONST_VIOLATION; break;
114 #ifdef LDAP_TYPE_OR_VALUE_EXISTS
115 case LDAP_TYPE_OR_VALUE_EXISTS: ec = GPG_ERR_LDAP_TYPE_VALUE_EXISTS; break;
118 case LDAP_INVALID_SYNTAX: ec = GPG_ERR_LDAP_INV_SYNTAX; break;
119 case LDAP_NO_SUCH_OBJECT: ec = GPG_ERR_LDAP_NO_SUCH_OBJ; break;
120 case LDAP_ALIAS_PROBLEM: ec = GPG_ERR_LDAP_ALIAS_PROBLEM; break;
121 case LDAP_INVALID_DN_SYNTAX: ec = GPG_ERR_LDAP_INV_DN_SYNTAX; break;
122 case LDAP_IS_LEAF: ec = GPG_ERR_LDAP_IS_LEAF; break;
123 case LDAP_ALIAS_DEREF_PROBLEM: ec = GPG_ERR_LDAP_ALIAS_DEREF; break;
125 #ifdef LDAP_X_PROXY_AUTHZ_FAILURE
126 case LDAP_X_PROXY_AUTHZ_FAILURE: ec = GPG_ERR_LDAP_X_PROXY_AUTH_FAIL; break;
129 case LDAP_INAPPROPRIATE_AUTH: ec = GPG_ERR_LDAP_BAD_AUTH; break;
130 case LDAP_INVALID_CREDENTIALS: ec = GPG_ERR_LDAP_INV_CREDENTIALS; break;
132 #ifdef LDAP_INSUFFICIENT_ACCESS
133 case LDAP_INSUFFICIENT_ACCESS: ec = GPG_ERR_LDAP_INSUFFICIENT_ACC; break;
136 case LDAP_BUSY: ec = GPG_ERR_LDAP_BUSY; break;
137 case LDAP_UNAVAILABLE: ec = GPG_ERR_LDAP_UNAVAILABLE; break;
138 case LDAP_UNWILLING_TO_PERFORM: ec = GPG_ERR_LDAP_UNWILL_TO_PERFORM; break;
139 case LDAP_LOOP_DETECT: ec = GPG_ERR_LDAP_LOOP_DETECT; break;
140 case LDAP_NAMING_VIOLATION: ec = GPG_ERR_LDAP_NAMING_VIOLATION; break;
141 case LDAP_OBJECT_CLASS_VIOLATION: ec = GPG_ERR_LDAP_OBJ_CLS_VIOLATION; break;
142 case LDAP_NOT_ALLOWED_ON_NONLEAF: ec=GPG_ERR_LDAP_NOT_ALLOW_NONLEAF;break;
143 case LDAP_NOT_ALLOWED_ON_RDN: ec = GPG_ERR_LDAP_NOT_ALLOW_ON_RDN; break;
144 case LDAP_ALREADY_EXISTS: ec = GPG_ERR_LDAP_ALREADY_EXISTS; break;
145 case LDAP_NO_OBJECT_CLASS_MODS: ec = GPG_ERR_LDAP_NO_OBJ_CLASS_MODS; break;
146 case LDAP_RESULTS_TOO_LARGE: ec = GPG_ERR_LDAP_RESULTS_TOO_LARGE; break;
147 case LDAP_AFFECTS_MULTIPLE_DSAS: ec = GPG_ERR_LDAP_AFFECTS_MULT_DSAS; break;
149 #ifdef LDAP_VLV_ERROR
150 case LDAP_VLV_ERROR: ec = GPG_ERR_LDAP_VLV; break;
153 case LDAP_OTHER: ec = GPG_ERR_LDAP_OTHER; break;
155 #ifdef LDAP_CUP_RESOURCES_EXHAUSTED
156 case LDAP_CUP_RESOURCES_EXHAUSTED: ec=GPG_ERR_LDAP_CUP_RESOURCE_LIMIT;break;
157 case LDAP_CUP_SECURITY_VIOLATION: ec=GPG_ERR_LDAP_CUP_SEC_VIOLATION; break;
158 case LDAP_CUP_INVALID_DATA: ec = GPG_ERR_LDAP_CUP_INV_DATA; break;
159 case LDAP_CUP_UNSUPPORTED_SCHEME: ec = GPG_ERR_LDAP_CUP_UNSUP_SCHEME; break;
160 case LDAP_CUP_RELOAD_REQUIRED: ec = GPG_ERR_LDAP_CUP_RELOAD; break;
163 #ifdef LDAP_CANCELLED
164 case LDAP_CANCELLED: ec = GPG_ERR_LDAP_CANCELLED; break;
167 #ifdef LDAP_NO_SUCH_OPERATION
168 case LDAP_NO_SUCH_OPERATION: ec = GPG_ERR_LDAP_NO_SUCH_OPERATION; break;
172 case LDAP_TOO_LATE: ec = GPG_ERR_LDAP_TOO_LATE; break;
175 #ifdef LDAP_CANNOT_CANCEL
176 case LDAP_CANNOT_CANCEL: ec = GPG_ERR_LDAP_CANNOT_CANCEL; break;
179 #ifdef LDAP_ASSERTION_FAILED
180 case LDAP_ASSERTION_FAILED: ec = GPG_ERR_LDAP_ASSERTION_FAILED; break;
183 #ifdef LDAP_PROXIED_AUTHORIZATION_DENIED
184 case LDAP_PROXIED_AUTHORIZATION_DENIED:
185 ec = GPG_ERR_LDAP_PROX_AUTH_DENIED; break;
189 #if defined(LDAP_E_ERROR) && defined(LDAP_X_ERROR)
190 if (LDAP_E_ERROR (code))
191 ec = GPG_ERR_LDAP_E_GENERAL;
192 else if (LDAP_X_ERROR (code))
193 ec = GPG_ERR_LDAP_X_GENERAL;
196 ec = GPG_ERR_LDAP_GENERAL;
203 /* Retrieve an LDAP error and return it's GPG equivalent. */
205 ldap_to_gpg_err (LDAP *ld)
207 #if defined(HAVE_LDAP_GET_OPTION) && defined(LDAP_OPT_ERROR_NUMBER)
210 if (ldap_get_option (ld, LDAP_OPT_ERROR_NUMBER, &err) == 0)
211 return ldap_err_to_gpg_err (err);
213 return GPG_ERR_GENERAL;
214 #elif defined(HAVE_LDAP_LD_ERRNO)
215 return ldap_err_to_gpg_err (ld->ld_errno);
217 /* We should never get here since the LDAP library should always
218 have either ldap_get_option or ld_errno, but just in case... */
219 return GPG_ERR_INTERNAL;
224 ldap2epochtime (const char *timestr)
229 memset (&pgptime, 0, sizeof(pgptime));
231 /* YYYYMMDDHHmmssZ */
233 sscanf (timestr, "%4d%2d%2d%2d%2d%2d",
241 pgptime.tm_year -= 1900;
242 pgptime.tm_isdst = -1;
245 /* mktime() takes the timezone into account, so we use timegm() */
247 answer = timegm (&pgptime);
252 /* Caller must free the result. */
254 tm2ldaptime (struct tm *tm)
259 /* YYYYMMDDHHmmssZ */
264 snprintf (buf, sizeof buf, "%04d%02d%02d%02d%02d%02dZ",
272 return xstrdup (buf);
276 /* Caller must free */
278 epoch2ldaptime (time_t stamp)
281 if (gmtime_r (&stamp, &tm))
282 return tm2ldaptime (&tm);
284 return xstrdup ("INVALID TIME");
288 /* Print a help output for the schemata supported by this module. */
290 ks_ldap_help (ctrl_t ctrl, parsed_uri_t uri)
292 const char const data[] =
293 "Handler for LDAP URLs:\n"
294 " ldap://host:port/[BASEDN]???[bindname=BINDNAME,password=PASSWORD]\n"
296 "Note: basedn, bindname and password need to be percent escaped. In\n"
297 "particular, spaces need to be replaced with %20 and commas with %2c.\n"
298 "bindname will typically be of the form:\n"
300 " uid=user%2cou=PGP%20Users%2cdc=EXAMPLE%2cdc=ORG\n"
302 "The ldaps:// and ldapi:// schemes are also supported. If ldaps is used\n"
303 "then the server's certificate will be checked. If it is not valid, any\n"
304 "operation will be aborted.\n"
306 "Supported methods: search, get, put\n";
310 err = ks_print_help (ctrl, " ldap");
311 else if (strcmp (uri->scheme, "ldap") == 0
312 || strcmp (uri->scheme, "ldaps") == 0
313 || strcmp (uri->scheme, "ldapi") == 0)
314 err = ks_print_help (ctrl, data);
321 /* Convert a keyspec to a filter. Return an error if the keyspec is
322 bad or is not supported. The filter is escaped and returned in
323 *filter. It is the caller's responsibility to free *filter.
324 *filter is only set if this function returns success (i.e., 0). */
326 keyspec_to_ldap_filter (const char *keyspec, char **filter, int only_exact)
328 /* Remove search type indicator and adjust PATTERN accordingly.
329 Note: don't include a preceding 0x when searching by keyid. */
331 /* XXX: Should we include disabled / revoke options? */
332 KEYDB_SEARCH_DESC desc;
336 gpg_error_t err = classify_user_id (keyspec, &desc, 1);
342 case KEYDB_SEARCH_MODE_EXACT:
343 f = xasprintf ("(pgpUserID=%s)",
344 (freeme = ldap_escape_filter (desc.u.name)));
347 case KEYDB_SEARCH_MODE_SUBSTR:
349 f = xasprintf ("(pgpUserID=*%s*)",
350 (freeme = ldap_escape_filter (desc.u.name)));
353 case KEYDB_SEARCH_MODE_MAIL:
355 f = xasprintf ("(pgpUserID=*<%s>*)",
356 (freeme = ldap_escape_filter (desc.u.name)));
359 case KEYDB_SEARCH_MODE_MAILSUB:
361 f = xasprintf ("(pgpUserID=*<*%s*>*)",
362 (freeme = ldap_escape_filter (desc.u.name)));
365 case KEYDB_SEARCH_MODE_MAILEND:
367 f = xasprintf ("(pgpUserID=*<*%s>*)",
368 (freeme = ldap_escape_filter (desc.u.name)));
371 case KEYDB_SEARCH_MODE_SHORT_KID:
372 f = xasprintf ("(pgpKeyID=%08lX)", (ulong) desc.u.kid[1]);
374 case KEYDB_SEARCH_MODE_LONG_KID:
375 f = xasprintf ("(pgpCertID=%08lX%08lX)",
376 (ulong) desc.u.kid[0], (ulong) desc.u.kid[1]);
379 case KEYDB_SEARCH_MODE_FPR16:
380 case KEYDB_SEARCH_MODE_FPR20:
381 case KEYDB_SEARCH_MODE_FPR:
382 case KEYDB_SEARCH_MODE_ISSUER:
383 case KEYDB_SEARCH_MODE_ISSUER_SN:
384 case KEYDB_SEARCH_MODE_SN:
385 case KEYDB_SEARCH_MODE_SUBJECT:
386 case KEYDB_SEARCH_MODE_KEYGRIP:
387 case KEYDB_SEARCH_MODE_WORDS:
388 case KEYDB_SEARCH_MODE_FIRST:
389 case KEYDB_SEARCH_MODE_NEXT:
398 log_error ("Unsupported search mode.\n");
399 return gpg_error (GPG_ERR_NOT_SUPPORTED);
409 /* Connect to an LDAP server and interrogate it.
411 - uri describes the server to connect to and various options
412 including whether to use TLS and the username and password (see
413 ldap_parse_uri for a description of the various fields).
415 This function returns:
417 - The ldap connection handle in *LDAP_CONNP.
419 - The base DN for the PGP key space by querying the
420 pgpBaseKeySpaceDN attribute (This is normally
421 'ou=PGP Keys,dc=EXAMPLE,dc=ORG').
423 - The attribute to lookup to find the pgp key. This is either
424 'pgpKey' or 'pgpKeyV2'.
426 - Whether this is a real ldap server. (It's unclear what this
429 The values are returned in the passed variables. If you pass NULL,
430 then the value won't be returned. It is the caller's
431 responsibility to release *LDAP_CONNP with ldap_unbind and xfree
432 *BASEDNP and *PGPKEYATTRP.
434 If this function successfully interrogated the server, it returns
435 0. If there was an LDAP error, it returns the LDAP error code. If
436 an error occured, *basednp, etc., are undefined (and don't need to
439 If no LDAP error occured, you still need to check that *basednp is
440 valid. If it is NULL, then the server does not appear to be an
441 OpenPGP Keyserver. In this case, you also do not need to xfree
444 my_ldap_connect (parsed_uri_t uri, LDAP **ldap_connp,
445 char **basednp, char **pgpkeyattrp, int *real_ldapp)
449 LDAP *ldap_conn = NULL;
451 char *user = uri->auth;
452 struct uri_tuple_s *password_param = uri_query_lookup (uri, "password");
453 char *password = password_param ? password_param->value : NULL;
456 /* Whether to look for the pgpKey or pgpKeyv2 attribute. */
457 char *pgpkeyattr = "pgpKey";
460 log_debug ("my_ldap_connect(%s:%d/%s????%s%s%s%s%s)\n",
461 uri->host, uri->port,
463 uri->auth ? "bindname=" : "", uri->auth ?: "",
464 uri->auth && password ? "," : "",
465 password ? "password=" : "", password ?: "");
467 /* If the uri specifies a secure connection and we don't support
468 TLS, then fail; don't silently revert to an insecure
472 #ifndef HAVE_LDAP_START_TLS_S
473 log_error ("Can't use LDAP to connect to the server: no TLS support.");
474 err = GPG_ERR_LDAP_NOT_SUPPORTED;
479 ldap_conn = ldap_init (uri->host, uri->port);
482 err = gpg_err_code_from_syserror ();
483 log_error ("Failed to open connection to LDAP server (%s://%s:%d)\n",
484 uri->scheme, uri->host, uri->port);
488 #ifdef HAVE_LDAP_SET_OPTION
490 int ver = LDAP_VERSION3;
492 err = ldap_set_option (ldap_conn, LDAP_OPT_PROTOCOL_VERSION, &ver);
493 if (err != LDAP_SUCCESS)
495 log_error ("gpgkeys: unable to go to LDAP 3: %s\n",
496 ldap_err2string (err));
502 /* XXX: It would be nice to have an option to provide the server's
505 #if defined(LDAP_OPT_X_TLS_CACERTFILE) && defined(HAVE_LDAP_SET_OPTION)
506 err = ldap_set_option (NULL, LDAP_OPT_X_TLS_CACERTFILE, ca_cert_file);
509 log_error ("unable to set ca-cert-file to '%s': %s\n",
510 ca_cert_file, ldap_err2string (err));
513 #endif /* LDAP_OPT_X_TLS_CACERTFILE && HAVE_LDAP_SET_OPTION */
516 #ifndef HAVE_LDAP_START_TLS_S
519 /* XXX: We need an option to determine whether to abort if the
520 certificate is bad or not. Right now we conservatively
521 default to checking the certificate and aborting. */
522 int check_cert = LDAP_OPT_X_TLS_HARD; /* LDAP_OPT_X_TLS_NEVER */
524 err = ldap_set_option (ldap_conn,
525 LDAP_OPT_X_TLS_REQUIRE_CERT, &check_cert);
528 log_error ("Failed to set TLS option on LDAP connection.\n");
532 err = ldap_start_tls_s (ldap_conn, NULL, NULL);
535 log_error ("Failed to connect to LDAP server with TLS.\n");
541 /* By default we don't bind as there is usually no need to. */
544 log_debug ("LDAP bind to %s, password %s\n",
545 user, password ? ">not shown<" : ">none<");
547 err = ldap_simple_bind_s (ldap_conn, user, password);
548 if (err != LDAP_SUCCESS)
550 log_error ("Internal LDAP bind error: %s\n",
551 ldap_err2string (err));
556 if (uri->path && *uri->path)
557 /* User specified base DN. */
559 basedn = xstrdup (uri->path);
561 /* If the user specifies a base DN, then we know the server is a
567 LDAPMessage *res = NULL;
568 /* Look for namingContexts. */
569 char *attr[] = { "namingContexts", NULL };
571 err = ldap_search_s (ldap_conn, "", LDAP_SCOPE_BASE,
572 "(objectClass=*)", attr, 0, &res);
573 if (err == LDAP_SUCCESS)
575 char **context = ldap_get_values (ldap_conn, res, "namingContexts");
577 /* We found some, so try each namingContext as the search
578 base and look for pgpBaseKeySpaceDN. Because we found
579 this, we know we're talking to a regular-ish LDAP
580 server and not an LDAP keyserver. */
584 { "pgpBaseKeySpaceDN", "pgpVersion", "pgpSoftware", NULL };
588 for (i = 0; context[i] && ! basedn; i++)
594 char *object = xasprintf ("cn=pgpServerInfo,%s",
596 err = ldap_search_s (ldap_conn, object, LDAP_SCOPE_BASE,
597 "(objectClass=*)", attr2, 0, &si_res);
601 if (err == LDAP_SUCCESS)
603 vals = ldap_get_values (ldap_conn, si_res,
604 "pgpBaseKeySpaceDN");
607 basedn = xtrystrdup (vals[0]);
608 ldap_value_free (vals);
611 vals = ldap_get_values (ldap_conn, si_res,
615 log_debug ("Server: \t%s\n", vals[0]);
616 ldap_value_free (vals);
619 vals = ldap_get_values (ldap_conn, si_res,
623 log_debug ("Version:\t%s\n", vals[0]);
624 ldap_value_free (vals);
628 /* From man ldap_search_s: "res parameter of
629 ldap_search_ext_s() and ldap_search_s() should be
630 freed with ldap_msgfree() regardless of return
631 value of these functions. */
632 ldap_msgfree (si_res);
635 ldap_value_free (context);
640 /* We don't have an answer yet, which means the server might
641 be an LDAP keyserver. */
643 LDAPMessage *si_res = NULL;
645 char *attr2[] = { "pgpBaseKeySpaceDN", "version", "software", NULL };
647 err = ldap_search_s (ldap_conn, "cn=pgpServerInfo", LDAP_SCOPE_BASE,
648 "(objectClass=*)", attr2, 0, &si_res);
649 if (err == LDAP_SUCCESS)
651 /* For the LDAP keyserver, this is always
652 "OU=ACTIVE,O=PGP KEYSPACE,C=US", but it might not be
655 vals = ldap_get_values (ldap_conn, si_res, "baseKeySpaceDN");
658 basedn = xtrystrdup (vals[0]);
659 ldap_value_free (vals);
662 vals = ldap_get_values (ldap_conn, si_res, "software");
665 log_debug ("ldap: Server: \t%s\n", vals[0]);
666 ldap_value_free (vals);
669 vals = ldap_get_values (ldap_conn, si_res, "version");
672 log_debug ("ldap: Version:\t%s\n", vals[0]);
674 /* If the version is high enough, use the new
675 pgpKeyV2 attribute. This design is iffy at best,
676 but it matches how PGP does it. I figure the NAI
677 folks assumed that there would never be an LDAP
678 keyserver vendor with a different numbering
680 if (atoi (vals[0]) > 1)
681 pgpkeyattr = "pgpKeyV2";
683 ldap_value_free (vals);
687 ldap_msgfree (si_res);
690 /* From man ldap_search_s: "res parameter of ldap_search_ext_s()
691 and ldap_search_s() should be freed with ldap_msgfree()
692 regardless of return value of these functions. */
699 log_debug ("ldap_conn: %p\n", ldap_conn);
700 log_debug ("real_ldap: %d\n", real_ldap);
701 log_debug ("basedn: %s\n", basedn);
702 log_debug ("pgpkeyattr: %s\n", pgpkeyattr);
705 if (! err && real_ldapp)
706 *real_ldapp = real_ldap;
715 *pgpkeyattrp = xstrdup (pgpkeyattr);
729 ldap_unbind (ldap_conn);
732 *ldap_connp = ldap_conn;
737 /* Extract keys from an LDAP reply and write them out to the output
738 stream OUTPUT in a format GnuPG can import (either the OpenPGP
739 binary format or armored format). */
741 extract_keys (estream_t output,
742 LDAP *ldap_conn, const char *certid, LDAPMessage *message)
746 es_fprintf (output, "INFO %s BEGIN\n", certid);
747 es_fprintf (output, "pub:%s:", certid);
749 /* Note: ldap_get_values returns a NULL terminates array of
751 vals = ldap_get_values (ldap_conn, message, "pgpkeytype");
754 if (strcmp (vals[0], "RSA") == 0)
755 es_fprintf (output, "1");
756 else if (strcmp (vals[0],"DSS/DH") == 0)
757 es_fprintf (output, "17");
758 ldap_value_free (vals);
761 es_fprintf (output, ":");
763 vals = ldap_get_values (ldap_conn, message, "pgpkeysize");
766 int v = atoi (vals[0]);
768 es_fprintf (output, "%d", v);
769 ldap_value_free (vals);
772 es_fprintf (output, ":");
774 vals = ldap_get_values (ldap_conn, message, "pgpkeycreatetime");
777 if (strlen (vals[0]) == 15)
778 es_fprintf (output, "%u", (unsigned int) ldap2epochtime (vals[0]));
779 ldap_value_free (vals);
782 es_fprintf (output, ":");
784 vals = ldap_get_values (ldap_conn, message, "pgpkeyexpiretime");
787 if (strlen (vals[0]) == 15)
788 es_fprintf (output, "%u", (unsigned int) ldap2epochtime (vals[0]));
789 ldap_value_free (vals);
792 es_fprintf (output, ":");
794 vals = ldap_get_values (ldap_conn, message, "pgprevoked");
797 if (atoi (vals[0]) == 1)
798 es_fprintf (output, "r");
799 ldap_value_free (vals);
802 es_fprintf (output, "\n");
804 vals = ldap_get_values (ldap_conn, message, "pgpuserid");
808 for (i = 0; vals[i]; i++)
809 es_fprintf (output, "uid:%s\n", vals[i]);
810 ldap_value_free (vals);
813 es_fprintf (output, "INFO %s END\n", certid);
816 /* Get the key described key the KEYSPEC string from the keyserver
817 identified by URI. On success R_FP has an open stream to read the
820 ks_ldap_get (ctrl_t ctrl, parsed_uri_t uri, const char *keyspec,
828 LDAP *ldap_conn = NULL;
831 char *pgpkeyattr = NULL;
835 LDAPMessage *message = NULL;
841 /* For now we do not support LDAP over TOR. */
842 log_error (_("LDAP access not possible due to TOR mode\n"));
843 return gpg_error (GPG_ERR_NOT_SUPPORTED);
846 /* Before connecting to the server, make sure we have a sane
847 keyspec. If not, there is no need to establish a network
849 err = keyspec_to_ldap_filter (keyspec, &filter, 1);
853 /* Make sure we are talking to an OpenPGP LDAP server. */
854 ldap_err = my_ldap_connect (uri, &ldap_conn, &basedn, &pgpkeyattr, NULL);
855 if (ldap_err || !basedn)
858 err = ldap_err_to_gpg_err (ldap_err);
860 err = GPG_ERR_GENERAL;
865 /* The ordering is significant. Specifically, "pgpcertid" needs
866 to be the second item in the list, since everything after it
867 may be discarded we aren't in verbose mode. */
871 "pgpcertid", "pgpuserid", "pgpkeyid", "pgprevoked", "pgpdisabled",
872 "pgpkeycreatetime", "modifytimestamp", "pgpkeysize", "pgpkeytype",
875 /* 1 if we want just attribute types; 0 if we want both attribute
881 ldap_err = ldap_search_s (ldap_conn, basedn, LDAP_SCOPE_SUBTREE,
882 filter, attrs, attrsonly, &message);
885 err = ldap_err_to_gpg_err (ldap_err);
887 log_error ("gpgkeys: LDAP search error: %s\n",
888 ldap_err2string (ldap_err));
892 count = ldap_count_entries (ldap_conn, message);
895 log_error ("gpgkeys: key %s not found on keyserver\n", keyspec);
898 err = ldap_to_gpg_err (ldap_conn);
900 err = gpg_error (GPG_ERR_NO_DATA);
906 /* There may be more than one unique result for a given keyID,
907 so we should fetch them all (test this by fetching short key
910 /* The set of entries that we've seen. */
911 strlist_t seen = NULL;
914 for (each = ldap_first_entry (ldap_conn, message);
916 each = ldap_next_entry (ldap_conn, each))
921 /* Use the long keyid to remove duplicates. The LDAP
922 server returns the same keyid more than once if there
923 are multiple user IDs on the key. Note that this does
924 NOT mean that a keyid that exists multiple times on the
925 keyserver will not be fetched. It means that each KEY,
926 no matter how many user IDs share its keyid, will be
927 fetched only once. If a keyid that belongs to more
928 than one key is fetched, the server quite properly
929 responds with all matching keys. -ds */
931 certid = ldap_get_values (ldap_conn, each, "pgpcertid");
932 if (certid && certid[0])
934 if (! strlist_find (seen, certid[0]))
936 /* It's not a duplicate, add it */
938 add_to_strlist (&seen, certid[0]);
941 fp = es_fopenmem(0, "rw");
943 extract_keys (fp, ldap_conn, certid[0], each);
945 vals = ldap_get_values (ldap_conn, each, pgpkeyattr);
948 err = ldap_to_gpg_err (ldap_conn);
949 log_error("gpgkeys: unable to retrieve key %s "
950 "from keyserver\n", certid[0]);
955 /* We should strip the new lines. */
956 es_fprintf (fp, "KEY 0x%s BEGIN\n", certid[0]);
957 es_fputs (vals[0], fp);
958 es_fprintf (fp, "\nKEY 0x%s END\n", certid[0]);
960 ldap_value_free (vals);
965 ldap_value_free (certid);
971 err = gpg_error (GPG_ERR_NO_DATA);
977 ldap_msgfree (message);
987 es_fseek (fp, 0, SEEK_SET);
996 ldap_unbind (ldap_conn);
1003 /* Search the keyserver identified by URI for keys matching PATTERN.
1004 On success R_FP has an open stream to read the data. */
1006 ks_ldap_search (ctrl_t ctrl, parsed_uri_t uri, const char *pattern,
1012 char *filter = NULL;
1014 LDAP *ldap_conn = NULL;
1016 char *basedn = NULL;
1018 estream_t fp = NULL;
1024 /* For now we do not support LDAP over TOR. */
1025 log_error (_("LDAP access not possible due to TOR mode\n"));
1026 return gpg_error (GPG_ERR_NOT_SUPPORTED);
1029 /* Before connecting to the server, make sure we have a sane
1030 keyspec. If not, there is no need to establish a network
1032 err = keyspec_to_ldap_filter (pattern, &filter, 0);
1035 log_error ("Bad search pattern: '%s'\n", pattern);
1039 /* Make sure we are talking to an OpenPGP LDAP server. */
1040 ldap_err = my_ldap_connect (uri, &ldap_conn, &basedn, NULL, NULL);
1041 if (ldap_err || !basedn)
1044 err = ldap_err_to_gpg_err (ldap_err);
1046 err = GPG_ERR_GENERAL;
1050 /* Even if we have no results, we want to return a stream. */
1051 fp = es_fopenmem(0, "rw");
1054 err = gpg_error_from_syserror ();
1060 LDAPMessage *res, *each;
1062 strlist_t dupelist = NULL;
1064 /* The maximum size of the search, including the optional stuff
1065 and the trailing \0 */
1068 "pgpcertid", "pgpuserid", "pgprevoked", "pgpdisabled",
1069 "pgpkeycreatetime", "pgpkeyexpiretime", "modifytimestamp",
1070 "pgpkeysize", "pgpkeytype", NULL
1073 log_debug ("SEARCH '%s' => '%s' BEGIN\n", pattern, filter);
1075 ldap_err = ldap_search_s (ldap_conn, basedn,
1076 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &res);
1081 if (ldap_err != LDAP_SUCCESS && ldap_err != LDAP_SIZELIMIT_EXCEEDED)
1083 err = ldap_err_to_gpg_err (ldap_err);
1085 log_error ("SEARCH %s FAILED %d\n", pattern, err);
1086 log_error ("gpgkeys: LDAP search error: %s\n",
1087 ldap_err2string (err));
1091 /* The LDAP server doesn't return a real count of unique keys, so we
1092 can't use ldap_count_entries here. */
1093 for (each = ldap_first_entry (ldap_conn, res);
1095 each = ldap_next_entry (ldap_conn, each))
1097 char **certid = ldap_get_values (ldap_conn, each, "pgpcertid");
1098 if (certid && certid[0] && ! strlist_find (dupelist, certid[0]))
1100 add_to_strlist (&dupelist, certid[0]);
1105 if (ldap_err == LDAP_SIZELIMIT_EXCEEDED)
1108 log_error ("gpgkeys: search results exceeded server limit."
1109 " First 1 result shown.\n");
1111 log_error ("gpgkeys: search results exceeded server limit."
1112 " First %d results shown.\n", count);
1115 free_strlist (dupelist);
1119 es_fputs ("info:1:0\n", fp);
1122 es_fprintf (fp, "info:1:%d\n", count);
1124 for (each = ldap_first_entry (ldap_conn, res);
1126 each = ldap_next_entry (ldap_conn, each))
1131 certid = ldap_get_values (ldap_conn, each, "pgpcertid");
1132 if (! certid || ! certid[0])
1135 /* Have we seen this certid before? */
1136 if (! strlist_find (dupelist, certid[0]))
1138 add_to_strlist (&dupelist, certid[0]);
1140 es_fprintf (fp, "pub:%s:",certid[0]);
1142 vals = ldap_get_values (ldap_conn, each, "pgpkeytype");
1145 /* The LDAP server doesn't exactly handle this
1147 if (strcasecmp (vals[0], "RSA") == 0)
1149 else if (strcasecmp (vals[0], "DSS/DH") == 0)
1150 es_fputs ("17", fp);
1151 ldap_value_free (vals);
1156 vals = ldap_get_values (ldap_conn, each, "pgpkeysize");
1159 /* Not sure why, but some keys are listed with a
1160 key size of 0. Treat that like an unknown. */
1161 if (atoi (vals[0]) > 0)
1162 es_fprintf (fp, "%d", atoi (vals[0]));
1163 ldap_value_free (vals);
1168 /* YYYYMMDDHHmmssZ */
1170 vals = ldap_get_values (ldap_conn, each, "pgpkeycreatetime");
1171 if(vals && strlen (vals[0]) == 15)
1173 es_fprintf (fp, "%u",
1174 (unsigned int) ldap2epochtime(vals[0]));
1175 ldap_value_free (vals);
1180 vals = ldap_get_values (ldap_conn, each, "pgpkeyexpiretime");
1181 if (vals && strlen (vals[0]) == 15)
1183 es_fprintf (fp, "%u",
1184 (unsigned int) ldap2epochtime (vals[0]));
1185 ldap_value_free (vals);
1190 vals = ldap_get_values (ldap_conn, each, "pgprevoked");
1193 if (atoi (vals[0]) == 1)
1194 es_fprintf (fp, "r");
1195 ldap_value_free (vals);
1198 vals = ldap_get_values (ldap_conn, each, "pgpdisabled");
1201 if (atoi (vals[0]) ==1)
1202 es_fprintf (fp, "d");
1203 ldap_value_free (vals);
1207 /* This is not yet specified in the keyserver
1208 protocol, but may be someday. */
1211 vals = ldap_get_values (ldap_conn, each, "modifytimestamp");
1212 if(vals && strlen (vals[0]) == 15)
1214 es_fprintf (fp, "%u",
1215 (unsigned int) ldap2epochtime (vals[0]));
1216 ldap_value_free (vals);
1220 es_fprintf (fp, "\n");
1222 /* Now print all the uids that have this certid */
1223 for (uids = ldap_first_entry (ldap_conn, res);
1225 uids = ldap_next_entry (ldap_conn, uids))
1227 vals = ldap_get_values (ldap_conn, uids, "pgpcertid");
1231 if (strcasecmp (certid[0], vals[0]) == 0)
1235 es_fprintf (fp, "uid:");
1237 uidvals = ldap_get_values (ldap_conn,
1241 /* Need to escape any colons */
1242 char *quoted = percent_escape (uidvals[0], NULL);
1243 es_fputs (quoted, fp);
1245 ldap_value_free (uidvals);
1248 es_fprintf (fp, "\n");
1251 ldap_value_free(vals);
1255 ldap_value_free (certid);
1260 free_strlist (dupelist);
1263 log_debug ("SEARCH %s END\n", pattern);
1273 /* Return the read stream. */
1275 es_fseek (fp, 0, SEEK_SET);
1283 ldap_unbind (ldap_conn);
1292 /* A modlist describes a set of changes to an LDAP entry. (An entry
1293 consists of 1 or more attributes. Attributes are <name, value>
1294 pairs. Note: an attribute may be multi-valued in which case
1295 multiple values are associated with a single name.)
1297 A modlist is a NULL terminated array of struct LDAPMod's.
1307 Is the ith modification.
1309 Each LDAPMod describes a change to a single attribute. Further,
1310 there is one modification for each attribute that we want to
1311 change. The attribute's new value is stored in LDAPMod.mod_values.
1312 If the attribute is multi-valued, we still only use a single
1313 LDAPMod structure: mod_values is a NULL-terminated array of
1314 strings. To delete an attribute from an entry, we set mod_values
1319 modlist[i]->mod_values == NULL
1321 then we remove the attribute.
1323 (Using LDAP_MOD_DELETE doesn't work here as we don't know if the
1324 attribute in question exists or not.)
1326 Note: this function does NOT copy or free ATTR. It does copy
1329 modlist_add (LDAPMod ***modlistp, char *attr, const char *value)
1331 LDAPMod **modlist = *modlistp;
1336 /* Search modlist for the attribute we're playing with. If modlist
1337 is NULL, then the list is empty. Recall: modlist is a NULL
1338 terminated array. */
1339 for (m = modlist; m && *m; m++, nummods ++)
1341 /* The attribute is already on the list. */
1345 if (strcasecmp ((*m)->mod_type, attr) != 0)
1348 /* We have this attribute already, so when the REPLACE happens,
1349 the server attributes will be replaced anyway. */
1353 /* Attributes can be multi-valued. See if the value is already
1354 present. mod_values is a NULL terminated array of pointers.
1355 Note: mod_values can be NULL. */
1356 for (ptr = (*m)->mod_values; ptr && *ptr; ptr++)
1358 if (strcmp (*ptr, value) == 0)
1359 /* Duplicate value, we're done. */
1364 /* Append the value. */
1365 ptr = xrealloc ((*m)->mod_values, sizeof (char *) * (numvalues + 2));
1367 (*m)->mod_values = ptr;
1368 ptr[numvalues] = xstrdup (value);
1370 ptr[numvalues + 1] = NULL;
1375 /* We didn't find the attr, so make one and add it to the end */
1377 /* Like attribute values, the list of attributes is NULL terminated
1378 array of pointers. */
1379 modlist = xrealloc (modlist, sizeof (LDAPMod *) * (nummods + 2));
1381 *modlistp = modlist;
1382 modlist[nummods] = xmalloc (sizeof (LDAPMod));
1384 modlist[nummods]->mod_op = LDAP_MOD_REPLACE;
1385 modlist[nummods]->mod_type = attr;
1388 modlist[nummods]->mod_values = xmalloc (sizeof(char *) * 2);
1390 modlist[nummods]->mod_values[0] = xstrdup (value);
1391 modlist[nummods]->mod_values[1] = NULL;
1394 modlist[nummods]->mod_values = NULL;
1396 modlist[nummods + 1] = NULL;
1401 /* Look up the value of an attribute in the specified modlist. If the
1402 attribute is not on the mod list, returns NULL. The result is a
1403 NULL-terminated array of strings. Don't change it. */
1405 modlist_lookup (LDAPMod **modlist, const char *attr)
1408 for (m = modlist; m && *m; m++)
1410 if (strcasecmp ((*m)->mod_type, attr) != 0)
1413 return (*m)->mod_values;
1419 /* Dump a modlist to a file. This is useful for debugging. */
1420 static estream_t modlist_dump (LDAPMod **modlist, estream_t output)
1424 modlist_dump (LDAPMod **modlist, estream_t output)
1432 output = es_fopenmem (0, "rw");
1438 for (m = modlist; m && *m; m++)
1440 es_fprintf (output, " %s:", (*m)->mod_type);
1442 if (! (*m)->mod_values)
1443 es_fprintf(output, " delete.\n");
1450 if ((*m)->mod_values[0] && (*m)->mod_values[1])
1451 /* Have at least 2. */
1455 es_fprintf (output, "\n");
1457 for ((ptr = (*m)->mod_values), (i = 1); ptr && *ptr; ptr++, i ++)
1459 /* Assuming terminals are about 80 characters wide,
1460 display at most most about 10 lines of debugging
1461 output. If we do trim the buffer, append '...' to
1463 const int max_len = 10 * 70;
1464 size_t value_len = strlen (*ptr);
1465 int elide = value_len > max_len;
1468 es_fprintf (output, " %d. ", i);
1469 es_fprintf (output, "`%.*s", max_len, *ptr);
1471 es_fprintf (output, "...' (%zd bytes elided)",
1472 value_len - max_len);
1474 es_fprintf (output, "'");
1475 es_fprintf (output, "\n");
1481 es_fseek (output, 0, SEEK_SET);
1486 /* Free all of the memory allocated by the mod list. This assumes
1487 that the attribute names don't have to be freed, but the attributes
1488 values do. (Which is what modlist_add does.) */
1490 modlist_free (LDAPMod **modlist)
1497 /* Unwind and free the whole modlist structure */
1499 /* The modlist is a NULL terminated array of pointers. */
1500 for (ml = modlist; *ml; ml++)
1505 /* The list of values is a NULL termianted array of pointers.
1506 If the list is NULL, there are no values. */
1508 if (mod->mod_values)
1510 for (ptr = mod->mod_values; *ptr; ptr++)
1513 xfree (mod->mod_values);
1521 /* Append two onto the end of one. Two is not freed, but its pointers
1522 are now part of one. Make sure you don't free them both!
1524 As long as you don't add anything to ONE, TWO is still valid.
1525 After that all bets are off. */
1527 modlists_join (LDAPMod ***one, LDAPMod **two)
1529 int i, one_count = 0, two_count = 0;
1533 /* two is empty. Nothing to do. */
1537 /* one is empty. Just set it equal to *two. */
1543 for (grow = *one; *grow; grow++)
1546 for (grow = two; *grow; grow++)
1549 grow = xrealloc (*one, sizeof(LDAPMod *) * (one_count + two_count + 1));
1551 for (i = 0; i < two_count; i++)
1552 grow[one_count + i] = two[i];
1554 grow[one_count + i] = NULL;
1559 /* Given a string, unescape C escapes. In particular, \xXX. This
1560 modifies the string in place. */
1562 uncescape (char *str)
1567 char *first = strchr (str, '\\');
1569 /* No backslashes => no escaping. We're done. */
1572 /* Start at the first '\\'. */
1573 r = w = (uintptr_t) first - (uintptr_t) str;
1577 /* XXX: What to do about bad escapes?
1578 XXX: hextobyte already checks the string thus the hexdigitp
1579 could be removed. */
1580 if (str[r] == '\\' && str[r + 1] == 'x'
1581 && str[r+2] && str[r+3]
1582 && hexdigitp (str + r + 2)
1583 && hexdigitp (str + r + 3))
1585 int x = hextobyte (&str[r + 2]);
1586 assert (0 <= x && x <= 0xff);
1590 /* We consumed 4 characters and wrote 1. */
1595 str[w ++] = str[r ++];
1601 /* Given one line from an info block (`gpg --list-{keys,sigs}
1602 --with-colons KEYID'), pull it apart and fill in the modlist with
1603 the relevant (for the LDAP schema) attributes. */
1605 extract_attributes (LDAPMod ***modlist, char *line)
1612 int is_pub, is_sub, is_uid, is_sig;
1614 /* Remove trailing whitespace */
1615 trim_trailing_spaces (line);
1617 fields = strsplit (line, ':', '\0', &field_count);
1618 if (field_count == 1)
1619 /* We only have a single field. There is definately nothing to
1623 if (field_count < 7)
1626 is_pub = strcasecmp ("pub", fields[0]) == 0;
1627 is_sub = strcasecmp ("sub", fields[0]) == 0;
1628 is_uid = strcasecmp ("uid", fields[0]) == 0;
1629 is_sig = strcasecmp ("sig", fields[0]) == 0;
1631 if (!is_pub && !is_sub && !is_uid && !is_sig)
1632 /* Not a relevant line. */
1637 if (is_uid && strlen (keyid) == 0)
1638 /* The uid record type can have an empty keyid. */
1640 else if (strlen (keyid) == 16
1641 && strspn (keyid, "0123456789aAbBcCdDeEfF") == 16)
1642 /* Otherwise, we expect exactly 16 hex characters. */
1646 log_error ("malformed record!\n");
1655 for (flags = fields[1]; *flags; flags ++)
1669 /* Note: we always create the pgpDisabled and pgpRevoked
1670 attributes, regardless of whether the key is disabled/revoked
1671 or not. This is because a very common search is like
1672 "(&(pgpUserID=*isabella*)(pgpDisabled=0))" */
1676 modlist_add (modlist,"pgpDisabled", disabled ? "1" : "0");
1677 modlist_add (modlist,"pgpRevoked", revoked ? "1" : "0");
1681 if (is_pub || is_sub)
1683 char *size = fields[2];
1684 int val = atoi (size);
1689 /* We zero pad this on the left to make PGP happy. */
1691 if (val < 99999 && val > 0)
1693 snprintf (padded, sizeof padded, "%05u", val);
1700 if (is_pub || is_sub)
1701 modlist_add (modlist, "pgpKeySize", size);
1707 char *algo = fields[3];
1708 int val = atoi (algo);
1727 modlist_add (modlist, "pgpKeyType", algo);
1731 if (is_pub || is_sub || is_sig)
1735 modlist_add (modlist, "pgpCertID", keyid);
1736 modlist_add (modlist, "pgpKeyID", &keyid[8]);
1740 modlist_add (modlist, "pgpSubKeyID", keyid);
1743 modlist_add (modlist, "pgpSignerID", keyid);
1748 char *create_time = fields[5];
1750 if (strlen (create_time) == 0)
1754 char *create_time_orig = create_time;
1759 memset (&tm, 0, sizeof (tm));
1761 /* parse_timestamp handles both seconds fromt he epoch and
1762 ISO 8601 format. We also need to handle YYYY-MM-DD
1763 format (as generated by gpg1 --with-colons --list-key).
1764 Check that first and then if it fails, then try
1767 if (!isodate_human_to_tm (create_time, &tm))
1768 create_time = tm2ldaptime (&tm);
1769 else if ((t = parse_timestamp (create_time, &end)) != (time_t) -1
1773 if (!gnupg_gmtime (&t, &tm))
1776 create_time = tm2ldaptime (&tm);
1782 /* Failed to parse string. */
1783 log_error ("Failed to parse creation time ('%s')",
1789 modlist_add (modlist, "pgpKeyCreateTime", create_time);
1790 xfree (create_time);
1796 char *expire_time = fields[6];
1798 if (strlen (expire_time) == 0)
1802 char *expire_time_orig = expire_time;
1807 memset (&tm, 0, sizeof (tm));
1809 /* parse_timestamp handles both seconds fromt he epoch and
1810 ISO 8601 format. We also need to handle YYYY-MM-DD
1811 format (as generated by gpg1 --with-colons --list-key).
1812 Check that first and then if it fails, then try
1815 if (!isodate_human_to_tm (expire_time, &tm))
1816 expire_time = tm2ldaptime (&tm);
1817 else if ((t = parse_timestamp (expire_time, &end)) != (time_t) -1
1820 if (!gnupg_gmtime (&t, &tm))
1823 expire_time = tm2ldaptime (&tm);
1829 /* Failed to parse string. */
1830 log_error ("Failed to parse creation time ('%s')",
1836 modlist_add (modlist, "pgpKeyExpireTime", expire_time);
1837 xfree (expire_time);
1841 if ((is_uid || is_pub) && field_count >= 10)
1843 char *uid = fields[9];
1845 if (is_pub && strlen (uid) == 0)
1846 /* When using gpg --list-keys, the uid is included. When
1847 passed via gpg, it is not. It is important to process it
1848 when it is present, because gpg 1 won't print a UID record
1849 if there is only one key. */
1854 modlist_add (modlist, "pgpUserID", uid);
1862 /* Send the key in {KEY,KEYLEN} with the metadata {INFO,INFOLEN} to
1863 the keyserver identified by URI. See server.c:cmd_ks_put for the
1864 format of the data and metadata. */
1866 ks_ldap_put (ctrl_t ctrl, parsed_uri_t uri,
1867 void *data, size_t datalen,
1868 void *info, size_t infolen)
1870 gpg_error_t err = 0;
1873 LDAP *ldap_conn = NULL;
1874 char *basedn = NULL;
1875 char *pgpkeyattr = NULL;
1878 LDAPMod **modlist = NULL;
1879 LDAPMod **addlist = NULL;
1881 char *data_armored = NULL;
1883 /* The last byte of the info block. */
1884 const char *infoend = (const char *) info + infolen - 1;
1886 /* Enable this code to dump the modlist to /tmp/modlist.txt. */
1888 # warning Disable debug code before checking in.
1889 const int dump_modlist = 1;
1891 const int dump_modlist = 0;
1893 estream_t dump = NULL;
1895 /* Elide a warning. */
1900 /* For now we do not support LDAP over TOR. */
1901 log_error (_("LDAP access not possible due to TOR mode\n"));
1902 return gpg_error (GPG_ERR_NOT_SUPPORTED);
1905 ldap_err = my_ldap_connect (uri,
1906 &ldap_conn, &basedn, &pgpkeyattr, &real_ldap);
1907 if (ldap_err || !basedn)
1910 err = ldap_err_to_gpg_err (ldap_err);
1912 err = GPG_ERR_GENERAL;
1917 /* We appear to have an OpenPGP Keyserver, which can unpack the key
1918 on its own (not just a dumb LDAP server). */
1920 LDAPMod mod, *attrs[2];
1921 char *key[] = { data, NULL };
1924 memset (&mod, 0, sizeof (mod));
1925 mod.mod_op = LDAP_MOD_ADD;
1926 mod.mod_type = pgpkeyattr;
1927 mod.mod_values = key;
1931 dn = xasprintf ("pgpCertid=virtual,%s", basedn);
1932 ldap_err = ldap_add_s (ldap_conn, dn, attrs);
1935 if (ldap_err != LDAP_SUCCESS)
1937 err = ldap_err_to_gpg_err (err);
1944 modlist = xmalloc (sizeof (LDAPMod *));
1949 dump = es_fopen("/tmp/modlist.txt", "w");
1951 log_error ("Failed to open /tmp/modlist.txt: %s\n",
1956 es_fprintf(dump, "data (%zd bytes)\n", datalen);
1957 es_fprintf(dump, "info (%zd bytes): '\n", infolen);
1958 es_fwrite(info, infolen, 1, dump);
1959 es_fprintf(dump, "'\n");
1963 /* Start by nulling out all attributes. We try and do a modify
1964 operation first, so this ensures that we don't leave old
1965 attributes lying around. */
1966 modlist_add (&modlist, "pgpDisabled", NULL);
1967 modlist_add (&modlist, "pgpKeyID", NULL);
1968 modlist_add (&modlist, "pgpKeyType", NULL);
1969 modlist_add (&modlist, "pgpUserID", NULL);
1970 modlist_add (&modlist, "pgpKeyCreateTime", NULL);
1971 modlist_add (&modlist, "pgpSignerID", NULL);
1972 modlist_add (&modlist, "pgpRevoked", NULL);
1973 modlist_add (&modlist, "pgpSubKeyID", NULL);
1974 modlist_add (&modlist, "pgpKeySize", NULL);
1975 modlist_add (&modlist, "pgpKeyExpireTime", NULL);
1976 modlist_add (&modlist, "pgpCertID", NULL);
1978 /* Assemble the INFO stuff into LDAP attributes */
1984 char *newline = memchr (info, '\n', infolen);
1986 /* The last line is not \n terminated! Make a copy so we can
1987 add a NUL terminator. */
1989 temp = xmalloc (infolen + 1);
1990 memcpy (temp, info, infolen);
1992 newline = (char *) info + infolen;
1997 extract_attributes (&modlist, info);
1999 infolen = infolen - ((uintptr_t) newline - (uintptr_t) info + 1);
2004 assert ((char *) info + infolen - 1 == infoend);
2007 assert (infolen == -1);
2012 modlist_add (&addlist, "objectClass", "pgpKeyInfo");
2014 err = armor_data (&data_armored, data, datalen);
2018 modlist_add (&addlist, pgpkeyattr, data_armored);
2020 /* Now append addlist onto modlist. */
2021 modlists_join (&modlist, addlist);
2025 estream_t input = modlist_dump (modlist, NULL);
2028 copy_stream (input, dump);
2033 /* Going on the assumption that modify operations are more frequent
2034 than adds, we try a modify first. If it's not there, we just
2035 turn around and send an add command for the same key. Otherwise,
2036 the modify brings the server copy into compliance with our copy.
2037 Note that unlike the LDAP keyserver (and really, any other
2038 keyserver) this does NOT merge signatures, but replaces the whole
2039 key. This should make some people very happy. */
2044 certid = modlist_lookup (modlist, "pgpCertID");
2045 if (/* We should have a value. */
2048 || !(certid[0] && !certid[1]))
2050 log_error ("Bad certid.\n");
2051 err = GPG_ERR_GENERAL;
2055 dn = xasprintf ("pgpCertID=%s,%s", certid[0], basedn);
2057 err = ldap_modify_s (ldap_conn, dn, modlist);
2058 if (err == LDAP_NO_SUCH_OBJECT)
2059 err = ldap_add_s (ldap_conn, dn, addlist);
2063 if (err != LDAP_SUCCESS)
2065 log_error ("gpgkeys: error adding key to keyserver: %s\n",
2066 ldap_err2string (err));
2067 err = ldap_err_to_gpg_err (err);
2076 ldap_unbind (ldap_conn);
2081 modlist_free (modlist);
2084 xfree (data_armored);