1 /* ks-engine-ldap.c - talk to a LDAP keyserver
2 * Copyright (C) 2001, 2002, 2004, 2005, 2006
3 * 2007 Free Software Foundation, Inc.
4 * Copyright (C) 2015, 2020 g10 Code GmbH
6 * This file is part of GnuPG.
8 * GnuPG is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * GnuPG is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <https://www.gnu.org/licenses/>.
33 #include "../common/userids.h"
34 #include "../common/mbox-util.h"
35 #include "ks-engine.h"
36 #include "ldap-misc.h"
37 #include "ldap-parse-uri.h"
38 #include "ldapserver.h"
41 /* Flags with infos from the connected server. */
42 #define SERVERINFO_REALLDAP 1 /* This is not the PGP keyserver. */
43 #define SERVERINFO_PGPKEYV2 2 /* Needs "pgpeyV2" instead of "pgpKey" */
44 #define SERVERINFO_SCHEMAV2 4 /* Version 2 of the Schema. */
45 #define SERVERINFO_NTDS 8 /* Server is an Active Directory. */
49 time_t timegm(struct tm *tm);
55 ldap2epochtime (const char *timestr)
60 memset (&pgptime, 0, sizeof(pgptime));
64 sscanf (timestr, "%4d%2d%2d%2d%2d%2d",
72 pgptime.tm_year -= 1900;
73 pgptime.tm_isdst = -1;
76 /* mktime() takes the timezone into account, so we use timegm() */
78 answer = timegm (&pgptime);
83 /* Caller must free the result. */
85 tm2ldaptime (struct tm *tm)
95 snprintf (buf, sizeof buf, "%04d%02d%02d%02d%02d%02dZ",
103 return xstrdup (buf);
107 /* Caller must free */
109 epoch2ldaptime (time_t stamp)
112 if (gmtime_r (&stamp, &tm))
113 return tm2ldaptime (&tm);
115 return xstrdup ("INVALID TIME");
121 my_ldap_value_free (char **vals)
124 ldap_value_free (vals);
129 /* Print a help output for the schemata supported by this module. */
131 ks_ldap_help (ctrl_t ctrl, parsed_uri_t uri)
134 "Handler for LDAP URLs:\n"
135 " ldap://HOST:PORT/[BASEDN]????[bindname=BINDNAME,password=PASSWORD]\n"
137 "Note: basedn, bindname and password need to be percent escaped. In\n"
138 "particular, spaces need to be replaced with %20 and commas with %2c.\n"
139 "Thus bindname will typically be of the form:\n"
141 " uid=user%2cou=PGP%20Users%2cdc=EXAMPLE%2cdc=ORG\n"
143 "The ldaps:// and ldapi:// schemes are also supported. If ldaps is used\n"
144 "then the server's certificate will be checked. If it is not valid, any\n"
145 "operation will be aborted. Note that ldaps means LDAP with STARTTLS\n"
147 "As an alternative to an URL a string in this form may be used:\n"
149 " HOST:PORT:BINDNAME:PASSWORD:BASEDN:FLAGS:\n"
151 "The use of the percent sign or a colon in one of the string values is\n"
152 "currently not supported.\n"
154 "Supported methods: search, get, put\n";
158 err = ks_print_help (ctrl, " ldap");
159 else if (uri->is_ldap || uri->opaque)
160 err = ks_print_help (ctrl, data);
169 /* Convert a keyspec to a filter. Return an error if the keyspec is
170 bad or is not supported. The filter is escaped and returned in
171 *filter. It is the caller's responsibility to free *filter.
172 *filter is only set if this function returns success (i.e., 0). */
174 keyspec_to_ldap_filter (const char *keyspec, char **filter, int only_exact,
175 unsigned int serverinfo)
177 /* Remove search type indicator and adjust PATTERN accordingly.
178 Note: don't include a preceding 0x when searching by keyid. */
180 /* XXX: Should we include disabled / revoke options? */
181 KEYDB_SEARCH_DESC desc;
186 gpg_error_t err = classify_user_id (keyspec, &desc, 1);
192 case KEYDB_SEARCH_MODE_EXACT:
193 f = xasprintf ("(pgpUserID=%s)",
194 (freeme = ldap_escape_filter (desc.u.name)));
197 case KEYDB_SEARCH_MODE_SUBSTR:
199 f = xasprintf ("(pgpUserID=*%s*)",
200 (freeme = ldap_escape_filter (desc.u.name)));
203 case KEYDB_SEARCH_MODE_MAIL:
204 freeme = ldap_escape_filter (desc.u.name);
207 if (*freeme == '<' && freeme[1] && freeme[2])
209 /* Strip angle brackets. Note that it is does not
210 * matter whether we work on the plan or LDAP escaped
211 * version of the mailbox. */
213 if (p[strlen(p)-1] == '>')
218 if ((serverinfo & SERVERINFO_SCHEMAV2))
219 f = xasprintf ("(&(gpgMailbox=%s)(!(|(pgpRevoked=1)(pgpDisabled=1))))",
221 else if (!only_exact)
222 f = xasprintf ("(pgpUserID=*<%s>*)", p);
225 case KEYDB_SEARCH_MODE_MAILSUB:
227 f = xasprintf ("(pgpUserID=*<*%s*>*)",
228 (freeme = ldap_escape_filter (desc.u.name)));
231 case KEYDB_SEARCH_MODE_MAILEND:
233 f = xasprintf ("(pgpUserID=*<*%s>*)",
234 (freeme = ldap_escape_filter (desc.u.name)));
237 case KEYDB_SEARCH_MODE_SHORT_KID:
238 f = xasprintf ("(pgpKeyID=%08lX)", (ulong) desc.u.kid[1]);
240 case KEYDB_SEARCH_MODE_LONG_KID:
241 f = xasprintf ("(pgpCertID=%08lX%08lX)",
242 (ulong) desc.u.kid[0], (ulong) desc.u.kid[1]);
245 case KEYDB_SEARCH_MODE_FPR:
246 if ((serverinfo & SERVERINFO_SCHEMAV2))
248 freeme = bin2hex (desc.u.fpr, desc.fprlen, NULL);
250 return gpg_error_from_syserror ();
251 f = xasprintf ("(|(gpgFingerprint=%s)(gpgSubFingerprint=%s))",
253 /* FIXME: For an exact search and in case of a match on
254 * gpgSubFingerprint we need to check that there is only one
259 case KEYDB_SEARCH_MODE_ISSUER:
260 case KEYDB_SEARCH_MODE_ISSUER_SN:
261 case KEYDB_SEARCH_MODE_SN:
262 case KEYDB_SEARCH_MODE_SUBJECT:
263 case KEYDB_SEARCH_MODE_KEYGRIP:
264 case KEYDB_SEARCH_MODE_WORDS:
265 case KEYDB_SEARCH_MODE_FIRST:
266 case KEYDB_SEARCH_MODE_NEXT:
275 log_error ("Unsupported search mode.\n");
276 return gpg_error (GPG_ERR_NOT_SUPPORTED);
286 /* Connect to an LDAP server and interrogate it.
288 - uri describes the server to connect to and various options
289 including whether to use TLS and the username and password (see
290 ldap_parse_uri for a description of the various fields).
292 This function returns:
294 - The ldap connection handle in *LDAP_CONNP.
296 - The base DN for the PGP key space by querying the
297 pgpBaseKeySpaceDN attribute (This is normally
298 'ou=PGP Keys,dc=EXAMPLE,dc=ORG').
300 - The attribute to lookup to find the pgp key. This is either
301 'pgpKey' or 'pgpKeyV2'.
303 - Whether this is a real ldap server. (It's unclear what this
306 The values are returned in the passed variables. If you pass NULL,
307 then the value won't be returned. It is the caller's
308 responsibility to release *LDAP_CONNP with ldap_unbind and xfree
311 If this function successfully interrogated the server, it returns
312 0. If there was an LDAP error, it returns the LDAP error code. If
313 an error occurred, *basednp, etc., are undefined (and don't need to
316 R_SERVERINFO receives information about the server.
318 If no LDAP error occurred, you still need to check that *basednp is
319 valid. If it is NULL, then the server does not appear to be an
320 OpenPGP Keyserver. */
322 my_ldap_connect (parsed_uri_t uri, LDAP **ldap_connp,
323 char **r_basedn, char **r_host, int *r_use_tls,
324 unsigned int *r_serverinfo)
328 ldap_server_t server = NULL;
329 LDAP *ldap_conn = NULL;
331 char *host = NULL; /* Host to use. */
332 int port; /* Port to use. */
333 int use_tls; /* 1 = starttls, 2 = ldap-over-tls */
334 int use_ntds; /* Use Active Directory authentication. */
335 const char *bindname;
336 const char *password;
337 const char *basedn_arg;
338 #ifndef HAVE_W32_SYSTEM
352 server = ldapserver_parse_one (uri->path, NULL, 0);
354 return gpg_error (GPG_ERR_LDAP_OTHER);
357 bindname = server->user;
358 password = bindname? server->pass : NULL;
359 basedn_arg = server->base;
360 use_tls = server->starttls? 1 : server->ldap_over_tls? 2 : 0;
361 use_ntds = server->ntds;
367 bindname = uri->auth;
368 password = bindname? uri_query_value (uri, "password") : NULL;
369 basedn_arg = uri->path;
370 use_tls = uri->use_tls ? 1 : 0;
371 use_ntds = uri->ad_current;
375 port = use_tls == 2? 636 : 389;
380 host = xtrystrdup (host);
383 err = gpg_error_from_syserror ();
389 log_info ("ldap connect to '%s:%d:%s:%s:%s:%s%s'\n",
391 basedn_arg ? basedn_arg : "",
392 bindname ? bindname : "",
393 password ? "*****" : "",
394 use_tls == 1? "starttls" : use_tls == 2? "ldaptls" : "plain",
395 use_ntds ? ",ntds":"");
398 /* If the uri specifies a secure connection and we don't support
399 TLS, then fail; don't silently revert to an insecure
403 #ifndef HAVE_LDAP_START_TLS_S
404 log_error ("ldap: can't connect to the server: no TLS support.");
405 err = GPG_ERR_LDAP_NOT_SUPPORTED;
411 #ifdef HAVE_W32_SYSTEM
412 /* Note that host==NULL uses the default domain controller. */
414 ldap_conn = ldap_sslinit (host, port, (use_tls == 2));
418 lerr = LdapGetLastError ();
419 err = ldap_err_to_gpg_err (lerr);
420 log_error ("error initializing LDAP '%s:%d': %s\n",
421 host, port, ldap_err2string (lerr));
425 tmpstr = xtryasprintf ("%s://%s:%d",
426 use_tls == 2? "ldaps" : "ldap",
430 err = gpg_error_from_syserror ();
434 lerr = ldap_initialize (&ldap_conn, tmpstr);
436 if (lerr != LDAP_SUCCESS || !ldap_conn)
438 err = ldap_err_to_gpg_err (lerr);
439 log_error ("error initializing LDAP '%s': %s\n",
440 tmpstr, ldap_err2string (lerr));
447 #ifdef HAVE_LDAP_SET_OPTION
449 int ver = LDAP_VERSION3;
451 lerr = ldap_set_option (ldap_conn, LDAP_OPT_PROTOCOL_VERSION, &ver);
452 if (lerr != LDAP_SUCCESS)
454 log_error ("ks-ldap: unable to go to LDAP 3: %s\n",
455 ldap_err2string (lerr));
456 err = ldap_err_to_gpg_err (lerr);
462 int ver = opt.ldaptimeout;
464 lerr = ldap_set_option (ldap_conn, LDAP_OPT_TIMELIMIT, &ver);
465 if (lerr != LDAP_SUCCESS)
467 log_error ("ks-ldap: unable to set LDAP timelimit to %us: %s\n",
468 opt.ldaptimeout, ldap_err2string (lerr));
469 err = ldap_err_to_gpg_err (lerr);
473 log_info ("ldap timeout set to %us\n", opt.ldaptimeout);
478 #ifdef HAVE_LDAP_START_TLS_S
481 #ifndef HAVE_W32_SYSTEM
482 int check_cert = LDAP_OPT_X_TLS_HARD; /* LDAP_OPT_X_TLS_NEVER */
484 lerr = ldap_set_option (ldap_conn,
485 LDAP_OPT_X_TLS_REQUIRE_CERT, &check_cert);
488 log_error ("ldap: error setting an TLS option: %s\n",
489 ldap_err2string (lerr));
490 err = ldap_err_to_gpg_err (lerr);
494 /* On Windows, the certificates are checked by default. If the
495 option to disable checking mentioned above is ever
496 implemented, the way to do that on Windows is to install a
497 callback routine using ldap_set_option (..,
498 LDAP_OPT_SERVER_CERTIFICATE, ..); */
502 lerr = ldap_start_tls_s (ldap_conn,
503 #ifdef HAVE_W32_SYSTEM
504 /* ServerReturnValue, result */
507 /* ServerControls, ClientControls */
512 log_error ("ldap: error switching to STARTTLS mode: %s\n",
513 ldap_err2string (lerr));
514 err = ldap_err_to_gpg_err (lerr);
522 #ifdef HAVE_W32_SYSTEM
524 lerr = ldap_bind_s (ldap_conn, NULL, NULL, LDAP_AUTH_NEGOTIATE);
526 if (lerr != LDAP_SUCCESS)
528 log_error ("error binding to LDAP via AD: %s\n",
529 ldap_err2string (lerr));
530 err = ldap_err_to_gpg_err (lerr);
534 log_error ("ldap: no Active Directory support but 'ntds' requested\n");
535 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
542 lerr = ldap_simple_bind_s (ldap_conn, bindname, password);
544 if (lerr != LDAP_SUCCESS)
546 log_error ("error binding to LDAP: %s\n", ldap_err2string (lerr));
547 err = ldap_err_to_gpg_err (lerr);
553 /* By default we don't bind as there is usually no need to. */
556 if (basedn_arg && *basedn_arg)
558 /* User specified base DN. In this case we know the server is a
559 * real LDAP server. */
560 basedn = xtrystrdup (basedn_arg);
563 err = gpg_error_from_syserror ();
566 *r_serverinfo |= SERVERINFO_REALLDAP;
569 { /* Look for namingContexts. */
570 LDAPMessage *res = NULL;
571 char *attr[] = { "namingContexts", NULL };
574 lerr = ldap_search_s (ldap_conn, "", LDAP_SCOPE_BASE,
575 "(objectClass=*)", attr, 0, &res);
578 if (lerr == LDAP_SUCCESS)
583 context = ldap_get_values (ldap_conn, res, "namingContexts");
587 /* We found some, so try each namingContext as the
588 * search base and look for pgpBaseKeySpaceDN. Because
589 * we found this, we know we're talking to a regular-ish
590 * LDAP server and not an LDAP keyserver. */
593 { "pgpBaseKeySpaceDN", "pgpVersion", "pgpSoftware", NULL };
595 *r_serverinfo |= SERVERINFO_REALLDAP;
597 for (i = 0; context[i] && !basedn; i++)
604 char *object = xasprintf ("cn=pgpServerInfo,%s",
607 lerr = ldap_search_s (ldap_conn, object, LDAP_SCOPE_BASE,
608 "(objectClass=*)", attr2, 0, &si_res);
613 if (lerr == LDAP_SUCCESS)
615 vals = ldap_get_values (ldap_conn, si_res,
616 "pgpBaseKeySpaceDN");
619 basedn = xtrystrdup (vals[0]);
621 my_ldap_value_free (vals);
623 vals = ldap_get_values (ldap_conn, si_res,
628 log_debug ("Server: \t%s\n", vals[0]);
629 if (!ascii_strcasecmp (vals[0], "GnuPG"))
632 my_ldap_value_free (vals);
634 vals = ldap_get_values (ldap_conn, si_res,
639 log_debug ("Version:\t%s\n", vals[0]);
642 const char *fields[2];
644 nfields = split_fields (vals[0],
645 fields, DIM(fields));
646 if (nfields > 0 && atoi(fields[0]) > 1)
647 *r_serverinfo |= SERVERINFO_SCHEMAV2;
649 && !ascii_strcasecmp (fields[1], "ntds"))
650 *r_serverinfo |= SERVERINFO_NTDS;
653 my_ldap_value_free (vals);
656 /* From man ldap_search_s: "res parameter of
657 ldap_search_ext_s() and ldap_search_s() should be
658 freed with ldap_msgfree() regardless of return
659 value of these functions. */
660 ldap_msgfree (si_res);
663 ldap_value_free (context);
666 else /* ldap_search failed. */
668 /* We don't have an answer yet, which means the server might
669 be a PGP.com keyserver. */
671 LDAPMessage *si_res = NULL;
673 char *attr2[] = { "pgpBaseKeySpaceDN", "version", "software", NULL };
676 lerr = ldap_search_s (ldap_conn, "cn=pgpServerInfo", LDAP_SCOPE_BASE,
677 "(objectClass=*)", attr2, 0, &si_res);
679 if (lerr == LDAP_SUCCESS)
681 /* For the PGP LDAP keyserver, this is always
682 * "OU=ACTIVE,O=PGP KEYSPACE,C=US", but it might not be
685 vals = ldap_get_values (ldap_conn, si_res, "baseKeySpaceDN");
688 basedn = xtrystrdup (vals[0]);
690 my_ldap_value_free (vals);
692 vals = ldap_get_values (ldap_conn, si_res, "software");
696 log_debug ("ks-ldap: PGP Server: \t%s\n", vals[0]);
698 my_ldap_value_free (vals);
700 vals = ldap_get_values (ldap_conn, si_res, "version");
704 log_debug ("ks-ldap: PGP Server Version:\t%s\n", vals[0]);
706 /* If the version is high enough, use the new
707 pgpKeyV2 attribute. This design is iffy at best,
708 but it matches how PGP does it. I figure the NAI
709 folks assumed that there would never be an LDAP
710 keyserver vendor with a different numbering
712 if (atoi (vals[0]) > 1)
713 *r_serverinfo |= SERVERINFO_PGPKEYV2;
716 my_ldap_value_free (vals);
719 ldap_msgfree (si_res);
722 /* From man ldap_search_s: "res parameter of ldap_search_ext_s()
723 and ldap_search_s() should be freed with ldap_msgfree()
724 regardless of return value of these functions. */
729 if (!err && opt.debug)
731 log_debug ("ldap_conn: %p\n", ldap_conn);
732 log_debug ("server_type: %s\n", ((*r_serverinfo & SERVERINFO_REALLDAP)
733 ? "LDAP" : "PGP.com keyserver") );
734 log_debug ("basedn: %s\n", basedn);
735 log_debug ("pgpkeyattr: %s\n",
736 (*r_serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey");
739 ldapserver_list_free (server);
745 ldap_unbind (ldap_conn);
758 *ldap_connp = ldap_conn;
764 /* Extract keys from an LDAP reply and write them out to the output
765 stream OUTPUT in a format GnuPG can import (either the OpenPGP
766 binary format or armored format). */
768 extract_keys (estream_t output,
769 LDAP *ldap_conn, const char *certid, LDAPMessage *message)
773 es_fprintf (output, "INFO %s BEGIN\n", certid);
775 /* Note: ldap_get_values returns a NULL terminated array of
778 vals = ldap_get_values (ldap_conn, message, "gpgfingerprint");
779 if (vals && vals[0] && vals[0][0])
780 es_fprintf (output, "pub:%s:", vals[0]);
782 es_fprintf (output, "pub:%s:", certid);
783 my_ldap_value_free (vals);
785 vals = ldap_get_values (ldap_conn, message, "pgpkeytype");
788 if (strcmp (vals[0], "RSA") == 0)
789 es_fprintf (output, "1");
790 else if (strcmp (vals[0],"DSS/DH") == 0)
791 es_fprintf (output, "17");
793 my_ldap_value_free (vals);
795 es_fprintf (output, ":");
797 vals = ldap_get_values (ldap_conn, message, "pgpkeysize");
800 int v = atoi (vals[0]);
802 es_fprintf (output, "%d", v);
804 my_ldap_value_free (vals);
806 es_fprintf (output, ":");
808 vals = ldap_get_values (ldap_conn, message, "pgpkeycreatetime");
811 if (strlen (vals[0]) == 15)
812 es_fprintf (output, "%u", (unsigned int) ldap2epochtime (vals[0]));
814 my_ldap_value_free (vals);
816 es_fprintf (output, ":");
818 vals = ldap_get_values (ldap_conn, message, "pgpkeyexpiretime");
821 if (strlen (vals[0]) == 15)
822 es_fprintf (output, "%u", (unsigned int) ldap2epochtime (vals[0]));
824 my_ldap_value_free (vals);
826 es_fprintf (output, ":");
828 vals = ldap_get_values (ldap_conn, message, "pgprevoked");
831 if (atoi (vals[0]) == 1)
832 es_fprintf (output, "r");
834 my_ldap_value_free (vals);
836 es_fprintf (output, "\n");
838 vals = ldap_get_values (ldap_conn, message, "pgpuserid");
842 for (i = 0; vals[i]; i++)
843 es_fprintf (output, "uid:%s\n", vals[i]);
845 my_ldap_value_free (vals);
847 es_fprintf (output, "INFO %s END\n", certid);
851 /* For now we do not support LDAP over Tor. */
853 no_ldap_due_to_tor (ctrl_t ctrl)
855 gpg_error_t err = gpg_error (GPG_ERR_NOT_SUPPORTED);
856 const char *msg = _("LDAP access not possible due to Tor mode");
858 log_error ("%s", msg);
859 dirmngr_status_printf (ctrl, "NOTE", "no_ldap_due_to_tor %u %s", err, msg);
860 return gpg_error (GPG_ERR_NOT_SUPPORTED);
864 /* Get the key described key the KEYSPEC string from the keyserver
865 identified by URI. On success R_FP has an open stream to read the
868 ks_ldap_get (ctrl_t ctrl, parsed_uri_t uri, const char *keyspec,
873 unsigned int serverinfo;
877 LDAP *ldap_conn = NULL;
880 LDAPMessage *message = NULL;
884 if (dirmngr_use_tor ())
886 return no_ldap_due_to_tor (ctrl);
889 /* Make sure we are talking to an OpenPGP LDAP server. */
890 err = my_ldap_connect (uri, &ldap_conn,
891 &basedn, &host, &use_tls, &serverinfo);
895 err = gpg_error (GPG_ERR_GENERAL);
899 /* Now that we have information about the server we can construct a
900 * query best suited for the capabilities of the server. */
901 err = keyspec_to_ldap_filter (keyspec, &filter, 1, serverinfo);
906 log_debug ("ks-ldap: using filter: %s\n", filter);
909 /* The ordering is significant. Specifically, "pgpcertid" needs
910 to be the second item in the list, since everything after it
911 may be discarded if we aren't in verbose mode. */
915 "pgpcertid", "pgpuserid", "pgpkeyid", "pgprevoked", "pgpdisabled",
916 "pgpkeycreatetime", "modifytimestamp", "pgpkeysize", "pgpkeytype",
920 /* 1 if we want just attribute types; 0 if we want both attribute
921 * types and values. */
925 /* Replace "dummy". */
926 attrs[0] = (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2" : "pgpKey";
929 ldap_err = ldap_search_s (ldap_conn, basedn, LDAP_SCOPE_SUBTREE,
930 filter, attrs, attrsonly, &message);
934 err = ldap_err_to_gpg_err (ldap_err);
936 log_error ("ks-ldap: LDAP search error: %s\n",
937 ldap_err2string (ldap_err));
941 count = ldap_count_entries (ldap_conn, message);
944 log_info ("ks-ldap: key %s not found on keyserver\n", keyspec);
947 err = ldap_to_gpg_err (ldap_conn);
949 err = gpg_error (GPG_ERR_NO_DATA);
955 /* There may be more than one unique result for a given keyID,
956 so we should fetch them all (test this by fetching short key
959 /* The set of entries that we've seen. */
960 strlist_t seen = NULL;
964 for (npth_unprotect (),
965 each = ldap_first_entry (ldap_conn, message),
969 each = ldap_next_entry (ldap_conn, each),
975 /* Use the long keyid to remove duplicates. The LDAP
976 server returns the same keyid more than once if there
977 are multiple user IDs on the key. Note that this does
978 NOT mean that a keyid that exists multiple times on the
979 keyserver will not be fetched. It means that each KEY,
980 no matter how many user IDs share its keyid, will be
981 fetched only once. If a keyid that belongs to more
982 than one key is fetched, the server quite properly
983 responds with all matching keys. -ds */
985 certid = ldap_get_values (ldap_conn, each, "pgpcertid");
986 if (certid && certid[0])
988 if (! strlist_find (seen, certid[0]))
990 /* It's not a duplicate, add it */
992 add_to_strlist (&seen, certid[0]);
995 fp = es_fopenmem(0, "rw");
997 extract_keys (fp, ldap_conn, certid[0], each);
999 vals = ldap_get_values (ldap_conn, each, attrs[0]);
1002 err = ldap_to_gpg_err (ldap_conn);
1003 log_error("ks-ldap: unable to retrieve key %s "
1004 "from keyserver\n", certid[0]);
1009 /* We should strip the new lines. */
1010 es_fprintf (fp, "KEY 0x%s BEGIN\n", certid[0]);
1011 es_fputs (vals[0], fp);
1012 es_fprintf (fp, "\nKEY 0x%s END\n", certid[0]);
1014 ldap_value_free (vals);
1020 my_ldap_value_free (certid);
1023 free_strlist (seen);
1026 err = gpg_error (GPG_ERR_NO_DATA);
1029 err = dirmngr_status_printf (ctrl, "SOURCE", "%s://%s",
1030 use_tls? "ldaps" : "ldap",
1037 ldap_msgfree (message);
1047 es_fseek (fp, 0, SEEK_SET);
1056 ldap_unbind (ldap_conn);
1064 /* Search the keyserver identified by URI for keys matching PATTERN.
1065 On success R_FP has an open stream to read the data. */
1067 ks_ldap_search (ctrl_t ctrl, parsed_uri_t uri, const char *pattern,
1072 unsigned int serverinfo;
1073 char *filter = NULL;
1074 LDAP *ldap_conn = NULL;
1075 char *basedn = NULL;
1076 estream_t fp = NULL;
1080 if (dirmngr_use_tor ())
1082 return no_ldap_due_to_tor (ctrl);
1085 /* Make sure we are talking to an OpenPGP LDAP server. */
1086 err = my_ldap_connect (uri, &ldap_conn, &basedn, NULL, NULL, &serverinfo);
1090 err = GPG_ERR_GENERAL;
1094 /* Now that we have information about the server we can construct a
1095 * query best suited for the capabilities of the server. */
1096 err = keyspec_to_ldap_filter (pattern, &filter, 0, serverinfo);
1099 log_error ("Bad search pattern: '%s'\n", pattern);
1103 /* Even if we have no results, we want to return a stream. */
1104 fp = es_fopenmem(0, "rw");
1107 err = gpg_error_from_syserror ();
1113 LDAPMessage *res, *each;
1115 strlist_t dupelist = NULL;
1117 /* The maximum size of the search, including the optional stuff
1118 and the trailing \0 */
1121 "pgpcertid", "pgpuserid", "pgprevoked", "pgpdisabled",
1122 "pgpkeycreatetime", "pgpkeyexpiretime", "modifytimestamp",
1123 "pgpkeysize", "pgpkeytype", "gpgfingerprint",
1128 log_debug ("SEARCH '%s' => '%s' BEGIN\n", pattern, filter);
1131 ldap_err = ldap_search_s (ldap_conn, basedn,
1132 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &res);
1138 if (ldap_err != LDAP_SUCCESS && ldap_err != LDAP_SIZELIMIT_EXCEEDED)
1140 err = ldap_err_to_gpg_err (ldap_err);
1142 log_error ("SEARCH %s FAILED %d\n", pattern, err);
1143 log_error ("ks-ldap: LDAP search error: %s\n",
1144 ldap_err2string (err));
1148 /* The LDAP server doesn't return a real count of unique keys, so we
1149 can't use ldap_count_entries here. */
1150 for (npth_unprotect (),
1151 each = ldap_first_entry (ldap_conn, res),
1155 each = ldap_next_entry (ldap_conn, each),
1158 char **certid = ldap_get_values (ldap_conn, each, "pgpcertid");
1159 if (certid && certid[0] && ! strlist_find (dupelist, certid[0]))
1161 add_to_strlist (&dupelist, certid[0]);
1164 my_ldap_value_free (certid);
1167 if (ldap_err == LDAP_SIZELIMIT_EXCEEDED)
1170 log_error ("ks-ldap: search results exceeded server limit."
1171 " First 1 result shown.\n");
1173 log_error ("ks-ldap: search results exceeded server limit."
1174 " First %d results shown.\n", count);
1177 free_strlist (dupelist);
1181 es_fputs ("info:1:0\n", fp);
1184 es_fprintf (fp, "info:1:%d\n", count);
1186 for (each = ldap_first_entry (ldap_conn, res);
1188 each = ldap_next_entry (ldap_conn, each))
1193 certid = ldap_get_values (ldap_conn, each, "pgpcertid");
1194 if (!certid || !certid[0])
1196 my_ldap_value_free (certid);
1200 /* Have we seen this certid before? */
1201 if (! strlist_find (dupelist, certid[0]))
1203 add_to_strlist (&dupelist, certid[0]);
1205 vals = ldap_get_values (ldap_conn, each, "gpgfingerprint");
1206 if (vals && vals[0] && vals[0][0])
1207 es_fprintf (fp, "pub:%s:", vals[0]);
1209 es_fprintf (fp, "pub:%s:", certid[0]);
1210 my_ldap_value_free (vals);
1212 vals = ldap_get_values (ldap_conn, each, "pgpkeytype");
1213 if (vals && vals[0])
1215 /* The LDAP server doesn't exactly handle this
1217 if (strcasecmp (vals[0], "RSA") == 0)
1219 else if (strcasecmp (vals[0], "DSS/DH") == 0)
1220 es_fputs ("17", fp);
1222 my_ldap_value_free (vals);
1226 vals = ldap_get_values (ldap_conn, each, "pgpkeysize");
1227 if (vals && vals[0])
1229 /* Not sure why, but some keys are listed with a
1230 key size of 0. Treat that like an unknown. */
1231 if (atoi (vals[0]) > 0)
1232 es_fprintf (fp, "%d", atoi (vals[0]));
1234 my_ldap_value_free (vals);
1238 /* YYYYMMDDHHmmssZ */
1240 vals = ldap_get_values (ldap_conn, each, "pgpkeycreatetime");
1241 if(vals && vals[0] && strlen (vals[0]) == 15)
1243 es_fprintf (fp, "%u",
1244 (unsigned int) ldap2epochtime(vals[0]));
1246 my_ldap_value_free (vals);
1250 vals = ldap_get_values (ldap_conn, each, "pgpkeyexpiretime");
1251 if (vals && vals[0] && strlen (vals[0]) == 15)
1253 es_fprintf (fp, "%u",
1254 (unsigned int) ldap2epochtime (vals[0]));
1256 my_ldap_value_free (vals);
1260 vals = ldap_get_values (ldap_conn, each, "pgprevoked");
1261 if (vals && vals[0])
1263 if (atoi (vals[0]) == 1)
1264 es_fprintf (fp, "r");
1266 my_ldap_value_free (vals);
1268 vals = ldap_get_values (ldap_conn, each, "pgpdisabled");
1269 if (vals && vals[0])
1271 if (atoi (vals[0]) ==1)
1272 es_fprintf (fp, "d");
1274 my_ldap_value_free (vals);
1277 /* This is not yet specified in the keyserver
1278 protocol, but may be someday. */
1281 vals = ldap_get_values (ldap_conn, each, "modifytimestamp");
1282 if(vals && vals[0] strlen (vals[0]) == 15)
1284 es_fprintf (fp, "%u",
1285 (unsigned int) ldap2epochtime (vals[0]));
1287 my_ldap_value_free (vals);
1290 es_fprintf (fp, "\n");
1292 /* Now print all the uids that have this certid */
1293 for (uids = ldap_first_entry (ldap_conn, res);
1295 uids = ldap_next_entry (ldap_conn, uids))
1297 vals = ldap_get_values (ldap_conn, uids, "pgpcertid");
1298 if (!vals || !vals[0])
1300 my_ldap_value_free (vals);
1304 if (!ascii_strcasecmp (certid[0], vals[0]))
1308 es_fprintf (fp, "uid:");
1310 uidvals = ldap_get_values (ldap_conn,
1314 /* Need to percent escape any colons */
1315 char *quoted = try_percent_escape (uidvals[0],
1318 es_fputs (quoted, fp);
1321 my_ldap_value_free (uidvals);
1323 es_fprintf (fp, "\n");
1326 ldap_value_free(vals);
1330 my_ldap_value_free (certid);
1335 free_strlist (dupelist);
1339 log_debug ("SEARCH %s END\n", pattern);
1348 /* Return the read stream. */
1350 es_fseek (fp, 0, SEEK_SET);
1358 ldap_unbind (ldap_conn);
1367 /* A modlist describes a set of changes to an LDAP entry. (An entry
1368 consists of 1 or more attributes. Attributes are <name, value>
1369 pairs. Note: an attribute may be multi-valued in which case
1370 multiple values are associated with a single name.)
1372 A modlist is a NULL terminated array of struct LDAPMod's.
1382 Is the ith modification.
1384 Each LDAPMod describes a change to a single attribute. Further,
1385 there is one modification for each attribute that we want to
1386 change. The attribute's new value is stored in LDAPMod.mod_values.
1387 If the attribute is multi-valued, we still only use a single
1388 LDAPMod structure: mod_values is a NULL-terminated array of
1389 strings. To delete an attribute from an entry, we set mod_values
1394 modlist[i]->mod_values == NULL
1396 then we remove the attribute.
1398 (Using LDAP_MOD_DELETE doesn't work here as we don't know if the
1399 attribute in question exists or not.)
1401 Note: this function does NOT copy or free ATTR. It does copy
1404 modlist_add (LDAPMod ***modlistp, char *attr, const char *value)
1406 LDAPMod **modlist = *modlistp;
1411 /* Search modlist for the attribute we're playing with. If modlist
1412 is NULL, then the list is empty. Recall: modlist is a NULL
1413 terminated array. */
1414 for (m = modlist; m && *m; m++, nummods ++)
1416 /* The attribute is already on the list. */
1420 if (strcasecmp ((*m)->mod_type, attr) != 0)
1423 /* We have this attribute already, so when the REPLACE happens,
1424 the server attributes will be replaced anyway. */
1428 /* Attributes can be multi-valued. See if the value is already
1429 present. mod_values is a NULL terminated array of pointers.
1430 Note: mod_values can be NULL. */
1431 for (ptr = (*m)->mod_values; ptr && *ptr; ptr++)
1433 if (strcmp (*ptr, value) == 0)
1434 /* Duplicate value, we're done. */
1439 /* Append the value. */
1440 ptr = xrealloc ((*m)->mod_values, sizeof (char *) * (numvalues + 2));
1442 (*m)->mod_values = ptr;
1443 ptr[numvalues] = xstrdup (value);
1445 ptr[numvalues + 1] = NULL;
1450 /* We didn't find the attr, so make one and add it to the end */
1452 /* Like attribute values, the list of attributes is NULL terminated
1453 array of pointers. */
1454 modlist = xrealloc (modlist, sizeof (LDAPMod *) * (nummods + 2));
1456 *modlistp = modlist;
1457 modlist[nummods] = xmalloc (sizeof (LDAPMod));
1459 modlist[nummods]->mod_op = LDAP_MOD_REPLACE;
1460 modlist[nummods]->mod_type = attr;
1463 modlist[nummods]->mod_values = xmalloc (sizeof(char *) * 2);
1465 modlist[nummods]->mod_values[0] = xstrdup (value);
1466 modlist[nummods]->mod_values[1] = NULL;
1469 modlist[nummods]->mod_values = NULL;
1471 modlist[nummods + 1] = NULL;
1476 /* Look up the value of an attribute in the specified modlist. If the
1477 attribute is not on the mod list, returns NULL. The result is a
1478 NULL-terminated array of strings. Don't change it. */
1480 modlist_lookup (LDAPMod **modlist, const char *attr)
1483 for (m = modlist; m && *m; m++)
1485 if (strcasecmp ((*m)->mod_type, attr) != 0)
1488 return (*m)->mod_values;
1494 /* Dump a modlist to a file. This is useful for debugging. */
1495 static estream_t modlist_dump (LDAPMod **modlist, estream_t output)
1499 modlist_dump (LDAPMod **modlist, estream_t output)
1507 output = es_fopenmem (0, "rw");
1513 for (m = modlist; m && *m; m++)
1515 es_fprintf (output, " %s:", (*m)->mod_type);
1517 if (! (*m)->mod_values)
1518 es_fprintf(output, " delete.\n");
1525 if ((*m)->mod_values[0] && (*m)->mod_values[1])
1526 /* Have at least 2. */
1530 es_fprintf (output, "\n");
1532 for ((ptr = (*m)->mod_values), (i = 1); ptr && *ptr; ptr++, i ++)
1534 /* Assuming terminals are about 80 characters wide,
1535 display at most about 10 lines of debugging
1536 output. If we do trim the buffer, append '...' to
1538 const int max_len = 10 * 70;
1539 size_t value_len = strlen (*ptr);
1540 int elide = value_len > max_len;
1543 es_fprintf (output, " %d. ", i);
1544 es_fprintf (output, "`%.*s", max_len, *ptr);
1546 es_fprintf (output, "...' (%zd bytes elided)",
1547 value_len - max_len);
1549 es_fprintf (output, "'");
1550 es_fprintf (output, "\n");
1556 es_fseek (output, 0, SEEK_SET);
1561 /* Free all of the memory allocated by the mod list. This assumes
1562 that the attribute names don't have to be freed, but the attributes
1563 values do. (Which is what modlist_add does.) */
1565 modlist_free (LDAPMod **modlist)
1572 /* Unwind and free the whole modlist structure */
1574 /* The modlist is a NULL terminated array of pointers. */
1575 for (ml = modlist; *ml; ml++)
1580 /* The list of values is a NULL termianted array of pointers.
1581 If the list is NULL, there are no values. */
1583 if (mod->mod_values)
1585 for (ptr = mod->mod_values; *ptr; ptr++)
1588 xfree (mod->mod_values);
1596 /* Append two onto the end of one. Two is not freed, but its pointers
1597 are now part of one. Make sure you don't free them both!
1599 As long as you don't add anything to ONE, TWO is still valid.
1600 After that all bets are off. */
1602 modlists_join (LDAPMod ***one, LDAPMod **two)
1604 int i, one_count = 0, two_count = 0;
1608 /* two is empty. Nothing to do. */
1612 /* one is empty. Just set it equal to *two. */
1618 for (grow = *one; *grow; grow++)
1621 for (grow = two; *grow; grow++)
1624 grow = xrealloc (*one, sizeof(LDAPMod *) * (one_count + two_count + 1));
1626 for (i = 0; i < two_count; i++)
1627 grow[one_count + i] = two[i];
1629 grow[one_count + i] = NULL;
1634 /* Given a string, unescape C escapes. In particular, \xXX. This
1635 modifies the string in place. */
1637 uncescape (char *str)
1642 char *first = strchr (str, '\\');
1644 /* No backslashes => no escaping. We're done. */
1647 /* Start at the first '\\'. */
1648 r = w = (uintptr_t) first - (uintptr_t) str;
1652 /* XXX: What to do about bad escapes?
1653 XXX: hextobyte already checks the string thus the hexdigitp
1654 could be removed. */
1655 if (str[r] == '\\' && str[r + 1] == 'x'
1656 && str[r+2] && str[r+3]
1657 && hexdigitp (str + r + 2)
1658 && hexdigitp (str + r + 3))
1660 int x = hextobyte (&str[r + 2]);
1661 log_assert (0 <= x && x <= 0xff);
1665 /* We consumed 4 characters and wrote 1. */
1670 str[w ++] = str[r ++];
1676 /* Given one line from an info block (`gpg --list-{keys,sigs}
1677 --with-colons KEYID'), pull it apart and fill in the modlist with
1678 the relevant (for the LDAP schema) attributes. EXTRACT_STATE
1679 should initally be set to 0 by the caller. SCHEMAV2 is set if the
1680 server supports the version 2 schema. */
1682 extract_attributes (LDAPMod ***modlist, int *extract_state,
1683 char *line, int schemav2)
1688 int is_pub, is_sub, is_uid, is_sig;
1690 /* Remove trailing whitespace */
1691 trim_trailing_spaces (line);
1693 fields = strsplit (line, ':', '\0', &field_count);
1694 if (field_count == 1)
1695 /* We only have a single field. There is definitely nothing to
1699 if (field_count < 7)
1702 is_pub = !ascii_strcasecmp ("pub", fields[0]);
1703 is_sub = !ascii_strcasecmp ("sub", fields[0]);
1704 is_uid = !ascii_strcasecmp ("uid", fields[0]);
1705 is_sig = !ascii_strcasecmp ("sig", fields[0]);
1706 if (!ascii_strcasecmp ("fpr", fields[0]))
1708 /* Special treatment for a fingerprint. */
1709 if (!(*extract_state & 1))
1710 goto out; /* Stray fingerprint line - ignore. */
1711 *extract_state &= ~1;
1712 if (field_count >= 10 && schemav2)
1714 if ((*extract_state & 2))
1715 modlist_add (modlist, "gpgFingerprint", fields[9]);
1717 modlist_add (modlist, "gpgSubFingerprint", fields[9]);
1722 *extract_state &= ~(1|2);
1724 *extract_state |= (1|2);
1726 *extract_state |= 1;
1728 if (!is_pub && !is_sub && !is_uid && !is_sig)
1729 goto out; /* Not a relevant line. */
1733 if (is_uid && strlen (keyid) == 0)
1734 ; /* The uid record type can have an empty keyid. */
1735 else if (strlen (keyid) == 16
1736 && strspn (keyid, "0123456789aAbBcCdDeEfF") == 16)
1737 ; /* Otherwise, we expect exactly 16 hex characters. */
1740 log_error ("malformed record!\n");
1749 for (flags = fields[1]; *flags; flags ++)
1763 /* Note: we always create the pgpDisabled and pgpRevoked
1764 attributes, regardless of whether the key is disabled/revoked
1765 or not. This is because a very common search is like
1766 "(&(pgpUserID=*isabella*)(pgpDisabled=0))" */
1770 modlist_add (modlist,"pgpDisabled", disabled ? "1" : "0");
1771 modlist_add (modlist,"pgpRevoked", revoked ? "1" : "0");
1775 if (is_pub || is_sub)
1780 val = atoi (fields[2]);
1781 if (val < 99999 && val > 0)
1783 /* We zero pad this on the left to make PGP happy. */
1784 snprintf (padded, sizeof padded, "%05u", val);
1785 modlist_add (modlist, "pgpKeySize", padded);
1791 char *algo = fields[3];
1792 int val = atoi (algo);
1809 modlist_add (modlist, "pgpKeyType", algo);
1812 if (is_pub || is_sub || is_sig)
1816 modlist_add (modlist, "pgpCertID", keyid); /* Long keyid(!) */
1817 modlist_add (modlist, "pgpKeyID", &keyid[8]); /* Short keyid */
1821 modlist_add (modlist, "pgpSubKeyID", keyid); /* Long keyid(!) */
1826 char *create_time = fields[5];
1828 if (strlen (create_time) == 0)
1832 char *create_time_orig = create_time;
1837 memset (&tm, 0, sizeof (tm));
1839 /* parse_timestamp handles both seconds fromt he epoch and
1840 ISO 8601 format. We also need to handle YYYY-MM-DD
1841 format (as generated by gpg1 --with-colons --list-key).
1842 Check that first and then if it fails, then try
1845 if (!isodate_human_to_tm (create_time, &tm))
1846 create_time = tm2ldaptime (&tm);
1847 else if ((t = parse_timestamp (create_time, &end)) != (time_t) -1
1851 if (!gnupg_gmtime (&t, &tm))
1854 create_time = tm2ldaptime (&tm);
1860 /* Failed to parse string. */
1861 log_error ("Failed to parse creation time ('%s')",
1867 modlist_add (modlist, "pgpKeyCreateTime", create_time);
1868 xfree (create_time);
1874 char *expire_time = fields[6];
1876 if (strlen (expire_time) == 0)
1880 char *expire_time_orig = expire_time;
1885 memset (&tm, 0, sizeof (tm));
1887 /* parse_timestamp handles both seconds fromt he epoch and
1888 ISO 8601 format. We also need to handle YYYY-MM-DD
1889 format (as generated by gpg1 --with-colons --list-key).
1890 Check that first and then if it fails, then try
1893 if (!isodate_human_to_tm (expire_time, &tm))
1894 expire_time = tm2ldaptime (&tm);
1895 else if ((t = parse_timestamp (expire_time, &end)) != (time_t) -1
1898 if (!gnupg_gmtime (&t, &tm))
1901 expire_time = tm2ldaptime (&tm);
1907 /* Failed to parse string. */
1908 log_error ("Failed to parse creation time ('%s')",
1914 modlist_add (modlist, "pgpKeyExpireTime", expire_time);
1915 xfree (expire_time);
1919 if (is_uid && field_count >= 10)
1921 char *uid = fields[9];
1925 modlist_add (modlist, "pgpUserID", uid);
1926 if (schemav2 && (mbox = mailbox_from_userid (uid, 0)))
1928 modlist_add (modlist, "gpgMailbox", mbox);
1937 /* Send the key in {KEY,KEYLEN} with the metadata {INFO,INFOLEN} to
1938 the keyserver identified by URI. See server.c:cmd_ks_put for the
1939 format of the data and metadata. */
1941 ks_ldap_put (ctrl_t ctrl, parsed_uri_t uri,
1942 void *data, size_t datalen,
1943 void *info, size_t infolen)
1945 gpg_error_t err = 0;
1947 unsigned int serverinfo;
1948 LDAP *ldap_conn = NULL;
1949 char *basedn = NULL;
1950 LDAPMod **modlist = NULL;
1951 LDAPMod **addlist = NULL;
1952 char *data_armored = NULL;
1955 /* The last byte of the info block. */
1956 const char *infoend = (const char *) info + infolen - 1;
1958 /* Enable this code to dump the modlist to /tmp/modlist.txt. */
1960 # warning Disable debug code before checking in.
1961 const int dump_modlist = 1;
1963 const int dump_modlist = 0;
1965 estream_t dump = NULL;
1967 /* Elide a warning. */
1970 if (dirmngr_use_tor ())
1972 return no_ldap_due_to_tor (ctrl);
1975 err = my_ldap_connect (uri, &ldap_conn, &basedn, NULL, NULL, &serverinfo);
1979 err = GPG_ERR_GENERAL;
1983 if (!(serverinfo & SERVERINFO_REALLDAP))
1985 /* We appear to have a PGP.com Keyserver, which can unpack the
1986 * key on its own (not just a dump LDAP server). This will
1987 * rarely be the case these days. */
1995 memset (&mod, 0, sizeof (mod));
1996 mod.mod_op = LDAP_MOD_ADD;
1997 mod.mod_type = (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey";
1998 mod.mod_values = key;
2002 dn = xtryasprintf ("pgpCertid=virtual,%s", basedn);
2005 err = gpg_error_from_syserror ();
2008 ldap_err = ldap_add_s (ldap_conn, dn, attrs);
2011 if (ldap_err != LDAP_SUCCESS)
2013 err = ldap_err_to_gpg_err (err);
2020 modlist = xtrymalloc (sizeof (LDAPMod *));
2023 err = gpg_error_from_syserror ();
2030 dump = es_fopen("/tmp/modlist.txt", "w");
2032 log_error ("failed to open /tmp/modlist.txt: %s\n",
2033 gpg_strerror (gpg_error_from_syserror ()));
2037 es_fprintf(dump, "data (%zd bytes)\n", datalen);
2038 es_fprintf(dump, "info (%zd bytes): '\n", infolen);
2039 es_fwrite(info, infolen, 1, dump);
2040 es_fprintf(dump, "'\n");
2044 /* Start by nulling out all attributes. We try and do a modify
2045 operation first, so this ensures that we don't leave old
2046 attributes lying around. */
2047 modlist_add (&modlist, "pgpDisabled", NULL);
2048 modlist_add (&modlist, "pgpKeyID", NULL);
2049 modlist_add (&modlist, "pgpKeyType", NULL);
2050 modlist_add (&modlist, "pgpUserID", NULL);
2051 modlist_add (&modlist, "pgpKeyCreateTime", NULL);
2052 modlist_add (&modlist, "pgpRevoked", NULL);
2053 modlist_add (&modlist, "pgpSubKeyID", NULL);
2054 modlist_add (&modlist, "pgpKeySize", NULL);
2055 modlist_add (&modlist, "pgpKeyExpireTime", NULL);
2056 modlist_add (&modlist, "pgpCertID", NULL);
2057 if ((serverinfo & SERVERINFO_SCHEMAV2))
2059 modlist_add (&modlist, "gpgFingerprint", NULL);
2060 modlist_add (&modlist, "gpgSubFingerprint", NULL);
2061 modlist_add (&modlist, "gpgMailbox", NULL);
2064 /* Assemble the INFO stuff into LDAP attributes */
2070 char *newline = memchr (info, '\n', infolen);
2072 /* The last line is not \n terminated! Make a copy so we can
2073 add a NUL terminator. */
2075 temp = xmalloc (infolen + 1);
2076 memcpy (temp, info, infolen);
2078 newline = (char *) info + infolen;
2083 extract_attributes (&addlist, &extract_state, info,
2084 (serverinfo & SERVERINFO_SCHEMAV2));
2086 infolen = infolen - ((uintptr_t) newline - (uintptr_t) info + 1);
2091 log_assert ((char *) info + infolen - 1 == infoend);
2094 log_assert (infolen == -1);
2099 modlist_add (&addlist, "objectClass", "pgpKeyInfo");
2101 err = armor_data (&data_armored, data, datalen);
2105 modlist_add (&addlist,
2106 (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey",
2109 /* Now append addlist onto modlist. */
2110 modlists_join (&modlist, addlist);
2114 estream_t input = modlist_dump (modlist, NULL);
2117 copy_stream (input, dump);
2122 /* Going on the assumption that modify operations are more frequent
2123 than adds, we try a modify first. If it's not there, we just
2124 turn around and send an add command for the same key. Otherwise,
2125 the modify brings the server copy into compliance with our copy.
2126 Note that unlike the LDAP keyserver (and really, any other
2127 keyserver) this does NOT merge signatures, but replaces the whole
2128 key. This should make some people very happy. */
2133 if ((serverinfo & SERVERINFO_NTDS))
2135 /* The modern way using a CN RDN with the fingerprint. This
2136 * has the advantage that we won't have duplicate 64 bit
2137 * keyids in the store. In particular NTDS requires the
2138 * DN to be unique. */
2139 attrval = modlist_lookup (addlist, "gpgFingerprint");
2140 /* We should have exactly one value. */
2141 if (!attrval || !(attrval[0] && !attrval[1]))
2143 log_error ("ks-ldap: bad gpgFingerprint provided\n");
2144 err = GPG_ERR_GENERAL;
2147 dn = xtryasprintf ("CN=%s,%s", attrval[0], basedn);
2149 else /* The old style way. */
2151 attrval = modlist_lookup (addlist, "pgpCertID");
2152 /* We should have exactly one value. */
2153 if (!attrval || !(attrval[0] && !attrval[1]))
2155 log_error ("ks-ldap: bad pgpCertID provided\n");
2156 err = GPG_ERR_GENERAL;
2159 dn = xtryasprintf ("pgpCertID=%s,%s", attrval[0], basedn);
2163 err = gpg_error_from_syserror ();
2167 log_debug ("ks-ldap: using DN: %s\n", dn);
2170 err = ldap_modify_s (ldap_conn, dn, modlist);
2171 if (err == LDAP_NO_SUCH_OBJECT)
2172 err = ldap_add_s (ldap_conn, dn, addlist);
2177 if (err != LDAP_SUCCESS)
2179 log_error ("ks-ldap: error adding key to keyserver: %s\n",
2180 ldap_err2string (err));
2181 err = ldap_err_to_gpg_err (err);
2190 ldap_unbind (ldap_conn);
2194 modlist_free (modlist);
2197 xfree (data_armored);