Imported Upstream version 2.3.5
[platform/upstream/gpg2.git] / dirmngr / ks-engine-ldap.c
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
5  *
6  * This file is part of GnuPG.
7  *
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.
12  *
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.
17  *
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/>.
20  */
21
22 #include <config.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <time.h>
26 #include <unistd.h>
27 #include <stdlib.h>
28 #include <npth.h>
29
30
31 #include "dirmngr.h"
32 #include "misc.h"
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"
39
40
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.      */
46
47
48 #ifndef HAVE_TIMEGM
49 time_t timegm(struct tm *tm);
50 #endif
51
52
53 \f
54 static time_t
55 ldap2epochtime (const char *timestr)
56 {
57   struct tm pgptime;
58   time_t answer;
59
60   memset (&pgptime, 0, sizeof(pgptime));
61
62   /* YYYYMMDDHHmmssZ */
63
64   sscanf (timestr, "%4d%2d%2d%2d%2d%2d",
65           &pgptime.tm_year,
66           &pgptime.tm_mon,
67           &pgptime.tm_mday,
68           &pgptime.tm_hour,
69           &pgptime.tm_min,
70           &pgptime.tm_sec);
71
72   pgptime.tm_year -= 1900;
73   pgptime.tm_isdst = -1;
74   pgptime.tm_mon--;
75
76   /* mktime() takes the timezone into account, so we use timegm() */
77
78   answer = timegm (&pgptime);
79
80   return answer;
81 }
82
83 /* Caller must free the result.  */
84 static char *
85 tm2ldaptime (struct tm *tm)
86 {
87   struct tm tmp = *tm;
88   char buf[16];
89
90   /* YYYYMMDDHHmmssZ */
91
92   tmp.tm_year += 1900;
93   tmp.tm_mon ++;
94
95   snprintf (buf, sizeof buf, "%04d%02d%02d%02d%02d%02dZ",
96            tmp.tm_year,
97            tmp.tm_mon,
98            tmp.tm_mday,
99            tmp.tm_hour,
100            tmp.tm_min,
101            tmp.tm_sec);
102
103   return xstrdup (buf);
104 }
105
106 #if 0
107 /* Caller must free */
108 static char *
109 epoch2ldaptime (time_t stamp)
110 {
111   struct tm tm;
112   if (gmtime_r (&stamp, &tm))
113     return tm2ldaptime (&tm);
114   else
115     return xstrdup ("INVALID TIME");
116 }
117 #endif
118
119
120 static void
121 my_ldap_value_free (char **vals)
122 {
123   if (vals)
124     ldap_value_free (vals);
125 }
126
127
128 \f
129 /* Print a help output for the schemata supported by this module. */
130 gpg_error_t
131 ks_ldap_help (ctrl_t ctrl, parsed_uri_t uri)
132 {
133   const char data[] =
134     "Handler for LDAP URLs:\n"
135     "  ldap://HOST:PORT/[BASEDN]????[bindname=BINDNAME,password=PASSWORD]\n"
136     "\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"
140     "\n"
141     "  uid=user%2cou=PGP%20Users%2cdc=EXAMPLE%2cdc=ORG\n"
142     "\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"
146     "\n"
147     "As an alternative to an URL a string in this form may be used:\n"
148     "\n"
149     "  HOST:PORT:BINDNAME:PASSWORD:BASEDN:FLAGS:\n"
150     "\n"
151     "The use of the percent sign or a colon in one of the string values is\n"
152     "currently not supported.\n"
153     "\n"
154     "Supported methods: search, get, put\n";
155   gpg_error_t err;
156
157   if(!uri)
158     err = ks_print_help (ctrl, "  ldap");
159   else if (uri->is_ldap || uri->opaque)
160     err = ks_print_help (ctrl, data);
161   else
162     err = 0;
163
164   return err;
165 }
166
167
168 \f
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).  */
173 static gpg_error_t
174 keyspec_to_ldap_filter (const char *keyspec, char **filter, int only_exact,
175                         unsigned int serverinfo)
176 {
177   /* Remove search type indicator and adjust PATTERN accordingly.
178      Note: don't include a preceding 0x when searching by keyid.  */
179
180   /* XXX: Should we include disabled / revoke options?  */
181   KEYDB_SEARCH_DESC desc;
182   char *f = NULL;
183   char *freeme = NULL;
184   char *p;
185
186   gpg_error_t err = classify_user_id (keyspec, &desc, 1);
187   if (err)
188     return err;
189
190   switch (desc.mode)
191     {
192     case KEYDB_SEARCH_MODE_EXACT:
193       f = xasprintf ("(pgpUserID=%s)",
194                      (freeme = ldap_escape_filter (desc.u.name)));
195       break;
196
197     case KEYDB_SEARCH_MODE_SUBSTR:
198       if (! only_exact)
199         f = xasprintf ("(pgpUserID=*%s*)",
200                        (freeme = ldap_escape_filter (desc.u.name)));
201       break;
202
203     case KEYDB_SEARCH_MODE_MAIL:
204       freeme = ldap_escape_filter (desc.u.name);
205       if (!freeme)
206         break;
207       if (*freeme == '<' && freeme[1] && freeme[2])
208         {
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.  */
212           p = freeme + 1;
213           if (p[strlen(p)-1] == '>')
214             p[strlen(p)-1] = 0;
215         }
216       else
217         p = freeme;
218       if ((serverinfo & SERVERINFO_SCHEMAV2))
219         f = xasprintf ("(&(gpgMailbox=%s)(!(|(pgpRevoked=1)(pgpDisabled=1))))",
220                        p);
221       else if (!only_exact)
222         f = xasprintf ("(pgpUserID=*<%s>*)", p);
223       break;
224
225     case KEYDB_SEARCH_MODE_MAILSUB:
226       if (! only_exact)
227         f = xasprintf ("(pgpUserID=*<*%s*>*)",
228                        (freeme = ldap_escape_filter (desc.u.name)));
229       break;
230
231     case KEYDB_SEARCH_MODE_MAILEND:
232       if (! only_exact)
233         f = xasprintf ("(pgpUserID=*<*%s>*)",
234                        (freeme = ldap_escape_filter (desc.u.name)));
235       break;
236
237     case KEYDB_SEARCH_MODE_SHORT_KID:
238       f = xasprintf ("(pgpKeyID=%08lX)", (ulong) desc.u.kid[1]);
239       break;
240     case KEYDB_SEARCH_MODE_LONG_KID:
241       f = xasprintf ("(pgpCertID=%08lX%08lX)",
242                      (ulong) desc.u.kid[0], (ulong) desc.u.kid[1]);
243       break;
244
245     case KEYDB_SEARCH_MODE_FPR:
246       if ((serverinfo & SERVERINFO_SCHEMAV2))
247         {
248           freeme = bin2hex (desc.u.fpr, desc.fprlen, NULL);
249           if (!freeme)
250             return gpg_error_from_syserror ();
251           f = xasprintf ("(|(gpgFingerprint=%s)(gpgSubFingerprint=%s))",
252                          freeme, freeme);
253           /* FIXME: For an exact search and in case of a match on
254            * gpgSubFingerprint we need to check that there is only one
255            * matching value.  */
256         }
257       break;
258
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:
267     default:
268       break;
269     }
270
271   xfree (freeme);
272
273   if (! f)
274     {
275       log_error ("Unsupported search mode.\n");
276       return gpg_error (GPG_ERR_NOT_SUPPORTED);
277     }
278
279   *filter = f;
280
281   return 0;
282 }
283
284
285 \f
286 /* Connect to an LDAP server and interrogate it.
287
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).
291
292    This function returns:
293
294      - The ldap connection handle in *LDAP_CONNP.
295
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').
299
300      - The attribute to lookup to find the pgp key.  This is either
301        'pgpKey' or 'pgpKeyV2'.
302
303      - Whether this is a real ldap server.  (It's unclear what this
304        exactly means.)
305
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
309    *BASEDNP.
310
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
314    be freed.)
315
316    R_SERVERINFO receives information about the server.
317
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.  */
321 static gpg_error_t
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)
325 {
326   gpg_error_t err = 0;
327   int lerr;
328   ldap_server_t server = NULL;
329   LDAP *ldap_conn = NULL;
330   char *basedn = 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
339   char *tmpstr;
340 #endif
341
342   if (r_basedn)
343     *r_basedn = NULL;
344   if (r_host)
345     *r_host = NULL;
346   if (r_use_tls)
347     *r_use_tls = 0;
348   *r_serverinfo = 0;
349
350   if (uri->opaque)
351     {
352       server = ldapserver_parse_one (uri->path, NULL, 0);
353       if (!server)
354         return gpg_error (GPG_ERR_LDAP_OTHER);
355       host = server->host;
356       port = server->port;
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;
362     }
363   else
364     {
365       host = uri->host;
366       port = uri->port;
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;
372     }
373
374   if (!port)
375     port = use_tls == 2? 636 : 389;
376
377
378   if (host)
379     {
380       host = xtrystrdup (host);
381       if (!host)
382         {
383           err = gpg_error_from_syserror ();
384           goto out;
385         }
386     }
387
388   if (opt.verbose)
389     log_info ("ldap connect to '%s:%d:%s:%s:%s:%s%s'\n",
390               host, port,
391               basedn_arg ? basedn_arg : "",
392               bindname ? bindname : "",
393               password ? "*****" : "",
394               use_tls == 1? "starttls" : use_tls == 2? "ldaptls" : "plain",
395               use_ntds ? ",ntds":"");
396
397
398   /* If the uri specifies a secure connection and we don't support
399      TLS, then fail; don't silently revert to an insecure
400      connection.  */
401   if (use_tls)
402     {
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;
406       goto out;
407 #endif
408     }
409
410
411 #ifdef HAVE_W32_SYSTEM
412   /* Note that host==NULL uses the default domain controller.  */
413   npth_unprotect ();
414   ldap_conn = ldap_sslinit (host, port, (use_tls == 2));
415   npth_protect ();
416   if (!ldap_conn)
417     {
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));
422       goto out;
423     }
424 #else /* Unix */
425   tmpstr = xtryasprintf ("%s://%s:%d",
426                          use_tls == 2? "ldaps" : "ldap",
427                          host, port);
428   if (!tmpstr)
429     {
430       err = gpg_error_from_syserror ();
431       goto out;
432     }
433   npth_unprotect ();
434   lerr = ldap_initialize (&ldap_conn, tmpstr);
435   npth_protect ();
436   if (lerr != LDAP_SUCCESS || !ldap_conn)
437     {
438       err = ldap_err_to_gpg_err (lerr);
439       log_error ("error initializing LDAP '%s': %s\n",
440                  tmpstr, ldap_err2string (lerr));
441       xfree (tmpstr);
442       goto out;
443     }
444   xfree (tmpstr);
445 #endif /* Unix */
446
447 #ifdef HAVE_LDAP_SET_OPTION
448   {
449     int ver = LDAP_VERSION3;
450
451     lerr = ldap_set_option (ldap_conn, LDAP_OPT_PROTOCOL_VERSION, &ver);
452     if (lerr != LDAP_SUCCESS)
453       {
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);
457         goto out;
458       }
459   }
460   if (opt.ldaptimeout)
461     {
462       int ver = opt.ldaptimeout;
463
464       lerr = ldap_set_option (ldap_conn, LDAP_OPT_TIMELIMIT, &ver);
465       if (lerr != LDAP_SUCCESS)
466         {
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);
470           goto out;
471         }
472       if (opt.verbose)
473         log_info ("ldap timeout set to %us\n", opt.ldaptimeout);
474     }
475 #endif
476
477
478 #ifdef HAVE_LDAP_START_TLS_S
479   if (use_tls == 1)
480     {
481 #ifndef HAVE_W32_SYSTEM
482       int check_cert = LDAP_OPT_X_TLS_HARD; /* LDAP_OPT_X_TLS_NEVER */
483
484       lerr = ldap_set_option (ldap_conn,
485                               LDAP_OPT_X_TLS_REQUIRE_CERT, &check_cert);
486       if (lerr)
487         {
488           log_error ("ldap: error setting an TLS option: %s\n",
489                      ldap_err2string (lerr));
490           err = ldap_err_to_gpg_err (lerr);
491           goto out;
492         }
493 #else
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, ..); */
499 #endif
500
501       npth_unprotect ();
502       lerr = ldap_start_tls_s (ldap_conn,
503 #ifdef HAVE_W32_SYSTEM
504                               /* ServerReturnValue, result */
505                               NULL, NULL,
506 #endif
507                               /* ServerControls, ClientControls */
508                               NULL, NULL);
509       npth_protect ();
510       if (lerr)
511         {
512           log_error ("ldap: error switching to STARTTLS mode: %s\n",
513                      ldap_err2string (lerr));
514           err = ldap_err_to_gpg_err (lerr);
515           goto out;
516         }
517     }
518 #endif
519
520   if (use_ntds)
521     {
522 #ifdef HAVE_W32_SYSTEM
523       npth_unprotect ();
524       lerr = ldap_bind_s (ldap_conn, NULL, NULL, LDAP_AUTH_NEGOTIATE);
525       npth_protect ();
526       if (lerr != LDAP_SUCCESS)
527         {
528           log_error ("error binding to LDAP via AD: %s\n",
529                      ldap_err2string (lerr));
530           err = ldap_err_to_gpg_err (lerr);
531           goto out;
532         }
533 #else
534       log_error ("ldap: no Active Directory support but 'ntds' requested\n");
535       err = gpg_error (GPG_ERR_NOT_SUPPORTED);
536       goto out;
537 #endif
538     }
539   else if (bindname)
540     {
541       npth_unprotect ();
542       lerr = ldap_simple_bind_s (ldap_conn, bindname, password);
543       npth_protect ();
544       if (lerr != LDAP_SUCCESS)
545         {
546           log_error ("error binding to LDAP: %s\n", ldap_err2string (lerr));
547           err = ldap_err_to_gpg_err (lerr);
548           goto out;
549         }
550     }
551   else
552     {
553       /* By default we don't bind as there is usually no need to.  */
554     }
555
556   if (basedn_arg && *basedn_arg)
557     {
558       /* User specified base DN.  In this case we know the server is a
559        * real LDAP server.  */
560       basedn = xtrystrdup (basedn_arg);
561       if (!basedn)
562         {
563           err = gpg_error_from_syserror ();
564           goto out;
565         }
566       *r_serverinfo |= SERVERINFO_REALLDAP;
567     }
568   else
569     { /* Look for namingContexts.  */
570       LDAPMessage *res = NULL;
571       char *attr[] = { "namingContexts", NULL };
572
573       npth_unprotect ();
574       lerr = ldap_search_s (ldap_conn, "", LDAP_SCOPE_BASE,
575                            "(objectClass=*)", attr, 0, &res);
576       npth_protect ();
577
578       if (lerr == LDAP_SUCCESS)
579         {
580           char **context;
581
582           npth_unprotect ();
583           context = ldap_get_values (ldap_conn, res, "namingContexts");
584           npth_protect ();
585           if (context)
586             {
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.  */
591               int i;
592               char *attr2[] =
593                 { "pgpBaseKeySpaceDN", "pgpVersion", "pgpSoftware", NULL };
594
595               *r_serverinfo |= SERVERINFO_REALLDAP;
596
597               for (i = 0; context[i] && !basedn; i++)
598                 {
599                   char **vals;
600                   LDAPMessage *si_res;
601                   int is_gnupg = 0;
602
603                   {
604                     char *object = xasprintf ("cn=pgpServerInfo,%s",
605                                               context[i]);
606                     npth_unprotect ();
607                     lerr = ldap_search_s (ldap_conn, object, LDAP_SCOPE_BASE,
608                                          "(objectClass=*)", attr2, 0, &si_res);
609                     npth_protect ();
610                     xfree (object);
611                   }
612
613                   if (lerr == LDAP_SUCCESS)
614                     {
615                       vals = ldap_get_values (ldap_conn, si_res,
616                                               "pgpBaseKeySpaceDN");
617                       if (vals && vals[0])
618                         {
619                           basedn = xtrystrdup (vals[0]);
620                         }
621                       my_ldap_value_free (vals);
622
623                       vals = ldap_get_values (ldap_conn, si_res,
624                                               "pgpSoftware");
625                       if (vals && vals[0])
626                         {
627                           if (opt.debug)
628                             log_debug ("Server: \t%s\n", vals[0]);
629                           if (!ascii_strcasecmp (vals[0], "GnuPG"))
630                             is_gnupg = 1;
631                         }
632                       my_ldap_value_free (vals);
633
634                       vals = ldap_get_values (ldap_conn, si_res,
635                                               "pgpVersion");
636                       if (vals && vals[0])
637                         {
638                           if (opt.debug)
639                             log_debug ("Version:\t%s\n", vals[0]);
640                           if (is_gnupg)
641                             {
642                               const char *fields[2];
643                               int nfields;
644                               nfields = split_fields (vals[0],
645                                                       fields, DIM(fields));
646                               if (nfields > 0 && atoi(fields[0]) > 1)
647                                 *r_serverinfo |= SERVERINFO_SCHEMAV2;
648                               if (nfields > 1
649                                   && !ascii_strcasecmp (fields[1], "ntds"))
650                                 *r_serverinfo |= SERVERINFO_NTDS;
651                             }
652                         }
653                       my_ldap_value_free (vals);
654                     }
655
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);
661                 }
662
663               ldap_value_free (context);
664             }
665         }
666       else /* ldap_search failed.  */
667         {
668           /* We don't have an answer yet, which means the server might
669              be a PGP.com keyserver. */
670           char **vals;
671           LDAPMessage *si_res = NULL;
672
673           char *attr2[] = { "pgpBaseKeySpaceDN", "version", "software", NULL };
674
675           npth_unprotect ();
676           lerr = ldap_search_s (ldap_conn, "cn=pgpServerInfo", LDAP_SCOPE_BASE,
677                                "(objectClass=*)", attr2, 0, &si_res);
678           npth_protect ();
679           if (lerr == LDAP_SUCCESS)
680             {
681               /* For the PGP LDAP keyserver, this is always
682                * "OU=ACTIVE,O=PGP KEYSPACE,C=US", but it might not be
683                * in the future. */
684
685               vals = ldap_get_values (ldap_conn, si_res, "baseKeySpaceDN");
686               if (vals && vals[0])
687                 {
688                   basedn = xtrystrdup (vals[0]);
689                 }
690               my_ldap_value_free (vals);
691
692               vals = ldap_get_values (ldap_conn, si_res, "software");
693               if (vals && vals[0])
694                 {
695                   if (opt.debug)
696                     log_debug ("ks-ldap: PGP Server: \t%s\n", vals[0]);
697                 }
698               my_ldap_value_free (vals);
699
700               vals = ldap_get_values (ldap_conn, si_res, "version");
701               if (vals && vals[0])
702                 {
703                   if (opt.debug)
704                     log_debug ("ks-ldap: PGP Server Version:\t%s\n", vals[0]);
705
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
711                      scheme. */
712                   if (atoi (vals[0]) > 1)
713                     *r_serverinfo |= SERVERINFO_PGPKEYV2;
714
715                 }
716               my_ldap_value_free (vals);
717             }
718
719           ldap_msgfree (si_res);
720         }
721
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.  */
725       ldap_msgfree (res);
726     }
727
728  out:
729   if (!err && opt.debug)
730     {
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");
737     }
738
739   ldapserver_list_free (server);
740
741   if (err)
742     {
743       xfree (basedn);
744       if (ldap_conn)
745         ldap_unbind (ldap_conn);
746     }
747   else
748     {
749       if (r_basedn)
750         *r_basedn = basedn;
751       else
752         xfree (basedn);
753       if (r_host)
754         *r_host = host;
755       else
756         xfree (host);
757
758       *ldap_connp = ldap_conn;
759     }
760
761   return err;
762 }
763
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).  */
767 static void
768 extract_keys (estream_t output,
769               LDAP *ldap_conn, const char *certid, LDAPMessage *message)
770 {
771   char **vals;
772
773   es_fprintf (output, "INFO %s BEGIN\n", certid);
774
775   /* Note: ldap_get_values returns a NULL terminated array of
776      strings.  */
777
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]);
781   else
782     es_fprintf (output, "pub:%s:", certid);
783   my_ldap_value_free (vals);
784
785   vals = ldap_get_values (ldap_conn, message, "pgpkeytype");
786   if (vals && vals[0])
787     {
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");
792     }
793   my_ldap_value_free (vals);
794
795   es_fprintf (output, ":");
796
797   vals = ldap_get_values (ldap_conn, message, "pgpkeysize");
798   if (vals && vals[0])
799     {
800       int v = atoi (vals[0]);
801       if (v > 0)
802         es_fprintf (output, "%d", v);
803     }
804   my_ldap_value_free (vals);
805
806   es_fprintf (output, ":");
807
808   vals = ldap_get_values (ldap_conn, message, "pgpkeycreatetime");
809   if (vals && vals[0])
810     {
811       if (strlen (vals[0]) == 15)
812         es_fprintf (output, "%u", (unsigned int) ldap2epochtime (vals[0]));
813     }
814   my_ldap_value_free (vals);
815
816   es_fprintf (output, ":");
817
818   vals = ldap_get_values (ldap_conn, message, "pgpkeyexpiretime");
819   if (vals && vals[0])
820     {
821       if (strlen (vals[0]) == 15)
822         es_fprintf (output, "%u", (unsigned int) ldap2epochtime (vals[0]));
823     }
824   my_ldap_value_free (vals);
825
826   es_fprintf (output, ":");
827
828   vals = ldap_get_values (ldap_conn, message, "pgprevoked");
829   if (vals && vals[0])
830     {
831       if (atoi (vals[0]) == 1)
832         es_fprintf (output, "r");
833     }
834   my_ldap_value_free (vals);
835
836   es_fprintf (output, "\n");
837
838   vals = ldap_get_values (ldap_conn, message, "pgpuserid");
839   if (vals && vals[0])
840     {
841       int i;
842       for (i = 0; vals[i]; i++)
843         es_fprintf (output, "uid:%s\n", vals[i]);
844     }
845   my_ldap_value_free (vals);
846
847   es_fprintf (output, "INFO %s END\n", certid);
848 }
849
850
851 /* For now we do not support LDAP over Tor.  */
852 static gpg_error_t
853 no_ldap_due_to_tor (ctrl_t ctrl)
854 {
855   gpg_error_t err = gpg_error (GPG_ERR_NOT_SUPPORTED);
856   const char *msg = _("LDAP access not possible due to Tor mode");
857
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);
861 }
862
863
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
866    data.  */
867 gpg_error_t
868 ks_ldap_get (ctrl_t ctrl, parsed_uri_t uri, const char *keyspec,
869              estream_t *r_fp)
870 {
871   gpg_error_t err = 0;
872   int ldap_err;
873   unsigned int serverinfo;
874   char *host = NULL;
875   int use_tls;
876   char *filter = NULL;
877   LDAP *ldap_conn = NULL;
878   char *basedn = NULL;
879   estream_t fp = NULL;
880   LDAPMessage *message = NULL;
881
882   (void) ctrl;
883
884   if (dirmngr_use_tor ())
885     {
886       return no_ldap_due_to_tor (ctrl);
887     }
888
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);
892   if (err || !basedn)
893     {
894       if (!err)
895         err = gpg_error (GPG_ERR_GENERAL);
896       goto out;
897     }
898
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);
902   if (err)
903     goto out;
904
905   if (opt.debug)
906     log_debug ("ks-ldap: using filter: %s\n", filter);
907
908   {
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. */
912     char *attrs[] =
913       {
914         "dummy",
915         "pgpcertid", "pgpuserid", "pgpkeyid", "pgprevoked", "pgpdisabled",
916         "pgpkeycreatetime", "modifytimestamp", "pgpkeysize", "pgpkeytype",
917         "gpgfingerprint",
918         NULL
919       };
920     /* 1 if we want just attribute types; 0 if we want both attribute
921      * types and values.  */
922     int attrsonly = 0;
923     int count;
924
925     /* Replace "dummy".  */
926     attrs[0] = (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2" : "pgpKey";
927
928     npth_unprotect ();
929     ldap_err = ldap_search_s (ldap_conn, basedn, LDAP_SCOPE_SUBTREE,
930                               filter, attrs, attrsonly, &message);
931     npth_protect ();
932     if (ldap_err)
933       {
934         err = ldap_err_to_gpg_err (ldap_err);
935
936         log_error ("ks-ldap: LDAP search error: %s\n",
937                    ldap_err2string (ldap_err));
938         goto out;
939       }
940
941     count = ldap_count_entries (ldap_conn, message);
942     if (count < 1)
943       {
944         log_info ("ks-ldap: key %s not found on keyserver\n", keyspec);
945
946         if (count == -1)
947           err = ldap_to_gpg_err (ldap_conn);
948         else
949           err = gpg_error (GPG_ERR_NO_DATA);
950
951         goto out;
952       }
953
954     {
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
957          id 0xDEADBEEF). */
958
959       /* The set of entries that we've seen.  */
960       strlist_t seen = NULL;
961       LDAPMessage *each;
962       int anykey = 0;
963
964       for (npth_unprotect (),
965              each = ldap_first_entry (ldap_conn, message),
966              npth_protect ();
967            each;
968            npth_unprotect (),
969              each = ldap_next_entry (ldap_conn, each),
970              npth_protect ())
971         {
972           char **vals;
973           char **certid;
974
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 */
984
985           certid = ldap_get_values (ldap_conn, each, "pgpcertid");
986           if (certid && certid[0])
987             {
988               if (! strlist_find (seen, certid[0]))
989                 {
990                   /* It's not a duplicate, add it */
991
992                   add_to_strlist (&seen, certid[0]);
993
994                   if (! fp)
995                     fp = es_fopenmem(0, "rw");
996
997                   extract_keys (fp, ldap_conn, certid[0], each);
998
999                   vals = ldap_get_values (ldap_conn, each, attrs[0]);
1000                   if (! vals)
1001                     {
1002                       err = ldap_to_gpg_err (ldap_conn);
1003                       log_error("ks-ldap: unable to retrieve key %s "
1004                                 "from keyserver\n", certid[0]);
1005                       goto out;
1006                     }
1007                   else
1008                     {
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]);
1013
1014                       ldap_value_free (vals);
1015                       anykey = 1;
1016                     }
1017                 }
1018             }
1019
1020           my_ldap_value_free (certid);
1021         }
1022
1023       free_strlist (seen);
1024
1025       if (! fp)
1026         err = gpg_error (GPG_ERR_NO_DATA);
1027
1028       if (!err && anykey)
1029         err = dirmngr_status_printf (ctrl, "SOURCE", "%s://%s",
1030                                      use_tls? "ldaps" : "ldap",
1031                                      host? host:"");
1032     }
1033   }
1034
1035  out:
1036   if (message)
1037     ldap_msgfree (message);
1038
1039   if (err)
1040     {
1041       if (fp)
1042         es_fclose (fp);
1043     }
1044   else
1045     {
1046       if (fp)
1047         es_fseek (fp, 0, SEEK_SET);
1048
1049       *r_fp = fp;
1050     }
1051
1052   xfree (basedn);
1053   xfree (host);
1054
1055   if (ldap_conn)
1056     ldap_unbind (ldap_conn);
1057
1058   xfree (filter);
1059
1060   return err;
1061 }
1062
1063
1064 /* Search the keyserver identified by URI for keys matching PATTERN.
1065    On success R_FP has an open stream to read the data.  */
1066 gpg_error_t
1067 ks_ldap_search (ctrl_t ctrl, parsed_uri_t uri, const char *pattern,
1068                 estream_t *r_fp)
1069 {
1070   gpg_error_t err;
1071   int ldap_err;
1072   unsigned int serverinfo;
1073   char *filter = NULL;
1074   LDAP *ldap_conn = NULL;
1075   char *basedn = NULL;
1076   estream_t fp = NULL;
1077
1078   (void) ctrl;
1079
1080   if (dirmngr_use_tor ())
1081     {
1082       return no_ldap_due_to_tor (ctrl);
1083     }
1084
1085   /* Make sure we are talking to an OpenPGP LDAP server.  */
1086   err = my_ldap_connect (uri, &ldap_conn, &basedn, NULL, NULL, &serverinfo);
1087   if (err || !basedn)
1088     {
1089       if (!err)
1090         err = GPG_ERR_GENERAL;
1091       goto out;
1092     }
1093
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);
1097   if (err)
1098     {
1099       log_error ("Bad search pattern: '%s'\n", pattern);
1100       goto out;
1101     }
1102
1103   /* Even if we have no results, we want to return a stream.  */
1104   fp = es_fopenmem(0, "rw");
1105   if (!fp)
1106     {
1107       err = gpg_error_from_syserror ();
1108       goto out;
1109     }
1110
1111   {
1112     char **vals;
1113     LDAPMessage *res, *each;
1114     int count = 0;
1115     strlist_t dupelist = NULL;
1116
1117     /* The maximum size of the search, including the optional stuff
1118        and the trailing \0 */
1119     char *attrs[] =
1120       {
1121         "pgpcertid", "pgpuserid", "pgprevoked", "pgpdisabled",
1122         "pgpkeycreatetime", "pgpkeyexpiretime", "modifytimestamp",
1123         "pgpkeysize", "pgpkeytype", "gpgfingerprint",
1124         NULL
1125       };
1126
1127     if (opt.debug)
1128       log_debug ("SEARCH '%s' => '%s' BEGIN\n", pattern, filter);
1129
1130     npth_unprotect ();
1131     ldap_err = ldap_search_s (ldap_conn, basedn,
1132                               LDAP_SCOPE_SUBTREE, filter, attrs, 0, &res);
1133     npth_protect ();
1134
1135     xfree (filter);
1136     filter = NULL;
1137
1138     if (ldap_err != LDAP_SUCCESS && ldap_err != LDAP_SIZELIMIT_EXCEEDED)
1139       {
1140         err = ldap_err_to_gpg_err (ldap_err);
1141
1142         log_error ("SEARCH %s FAILED %d\n", pattern, err);
1143         log_error ("ks-ldap: LDAP search error: %s\n",
1144                    ldap_err2string (err));
1145         goto out;
1146     }
1147
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),
1152            npth_protect ();
1153          each;
1154          npth_unprotect (),
1155            each = ldap_next_entry (ldap_conn, each),
1156            npth_protect ())
1157       {
1158         char **certid = ldap_get_values (ldap_conn, each, "pgpcertid");
1159         if (certid && certid[0] && ! strlist_find (dupelist, certid[0]))
1160           {
1161             add_to_strlist (&dupelist, certid[0]);
1162             count++;
1163           }
1164         my_ldap_value_free (certid);
1165       }
1166
1167     if (ldap_err == LDAP_SIZELIMIT_EXCEEDED)
1168       {
1169         if (count == 1)
1170           log_error ("ks-ldap: search results exceeded server limit."
1171                      "  First 1 result shown.\n");
1172         else
1173           log_error ("ks-ldap: search results exceeded server limit."
1174                      "  First %d results shown.\n", count);
1175       }
1176
1177     free_strlist (dupelist);
1178     dupelist = NULL;
1179
1180     if (count < 1)
1181       es_fputs ("info:1:0\n", fp);
1182     else
1183       {
1184         es_fprintf (fp, "info:1:%d\n", count);
1185
1186         for (each = ldap_first_entry (ldap_conn, res);
1187              each;
1188              each = ldap_next_entry (ldap_conn, each))
1189           {
1190             char **certid;
1191             LDAPMessage *uids;
1192
1193             certid = ldap_get_values (ldap_conn, each, "pgpcertid");
1194             if (!certid || !certid[0])
1195               {
1196                 my_ldap_value_free (certid);
1197                 continue;
1198               }
1199
1200             /* Have we seen this certid before? */
1201             if (! strlist_find (dupelist, certid[0]))
1202               {
1203                 add_to_strlist (&dupelist, certid[0]);
1204
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]);
1208                 else
1209                   es_fprintf (fp, "pub:%s:", certid[0]);
1210                 my_ldap_value_free (vals);
1211
1212                 vals = ldap_get_values (ldap_conn, each, "pgpkeytype");
1213                 if (vals && vals[0])
1214                   {
1215                     /* The LDAP server doesn't exactly handle this
1216                        well. */
1217                     if (strcasecmp (vals[0], "RSA") == 0)
1218                       es_fputs ("1", fp);
1219                     else if (strcasecmp (vals[0], "DSS/DH") == 0)
1220                       es_fputs ("17", fp);
1221                   }
1222                 my_ldap_value_free (vals);
1223
1224                 es_fputc (':', fp);
1225
1226                 vals = ldap_get_values (ldap_conn, each, "pgpkeysize");
1227                 if (vals && vals[0])
1228                   {
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]));
1233                   }
1234                 my_ldap_value_free (vals);
1235
1236                 es_fputc (':', fp);
1237
1238                 /* YYYYMMDDHHmmssZ */
1239
1240                 vals = ldap_get_values (ldap_conn, each, "pgpkeycreatetime");
1241                 if(vals && vals[0] && strlen (vals[0]) == 15)
1242                   {
1243                     es_fprintf (fp, "%u",
1244                                 (unsigned int) ldap2epochtime(vals[0]));
1245                   }
1246                 my_ldap_value_free (vals);
1247
1248                 es_fputc (':', fp);
1249
1250                 vals = ldap_get_values (ldap_conn, each, "pgpkeyexpiretime");
1251                 if (vals && vals[0] && strlen (vals[0]) == 15)
1252                   {
1253                     es_fprintf (fp, "%u",
1254                                 (unsigned int) ldap2epochtime (vals[0]));
1255                   }
1256                 my_ldap_value_free (vals);
1257
1258                 es_fputc (':', fp);
1259
1260                 vals = ldap_get_values (ldap_conn, each, "pgprevoked");
1261                 if (vals && vals[0])
1262                   {
1263                     if (atoi (vals[0]) == 1)
1264                       es_fprintf (fp, "r");
1265                   }
1266                 my_ldap_value_free (vals);
1267
1268                 vals = ldap_get_values (ldap_conn, each, "pgpdisabled");
1269                 if (vals && vals[0])
1270                   {
1271                     if (atoi (vals[0]) ==1)
1272                       es_fprintf (fp, "d");
1273                   }
1274                 my_ldap_value_free (vals);
1275
1276 #if 0
1277                 /* This is not yet specified in the keyserver
1278                    protocol, but may be someday. */
1279                 es_fputc (':', fp);
1280
1281                 vals = ldap_get_values (ldap_conn, each, "modifytimestamp");
1282                 if(vals && vals[0] strlen (vals[0]) == 15)
1283                   {
1284                     es_fprintf (fp, "%u",
1285                                 (unsigned int) ldap2epochtime (vals[0]));
1286                   }
1287                 my_ldap_value_free (vals);
1288 #endif
1289
1290                 es_fprintf (fp, "\n");
1291
1292                 /* Now print all the uids that have this certid */
1293                 for (uids = ldap_first_entry (ldap_conn, res);
1294                      uids;
1295                      uids = ldap_next_entry (ldap_conn, uids))
1296                   {
1297                     vals = ldap_get_values (ldap_conn, uids, "pgpcertid");
1298                     if (!vals || !vals[0])
1299                       {
1300                         my_ldap_value_free (vals);
1301                         continue;
1302                       }
1303
1304                     if (!ascii_strcasecmp (certid[0], vals[0]))
1305                       {
1306                         char **uidvals;
1307
1308                         es_fprintf (fp, "uid:");
1309
1310                         uidvals = ldap_get_values (ldap_conn,
1311                                                    uids, "pgpuserid");
1312                         if (uidvals)
1313                           {
1314                             /* Need to percent escape any colons */
1315                             char *quoted = try_percent_escape (uidvals[0],
1316                                                                NULL);
1317                             if (quoted)
1318                               es_fputs (quoted, fp);
1319                             xfree (quoted);
1320                           }
1321                         my_ldap_value_free (uidvals);
1322
1323                         es_fprintf (fp, "\n");
1324                       }
1325
1326                     ldap_value_free(vals);
1327                   }
1328               }
1329
1330             my_ldap_value_free (certid);
1331           }
1332       }
1333
1334     ldap_msgfree (res);
1335     free_strlist (dupelist);
1336   }
1337
1338   if (opt.debug)
1339     log_debug ("SEARCH %s END\n", pattern);
1340
1341  out:
1342   if (err)
1343     {
1344       es_fclose (fp);
1345     }
1346   else
1347     {
1348       /* Return the read stream.  */
1349       if (fp)
1350         es_fseek (fp, 0, SEEK_SET);
1351
1352       *r_fp = fp;
1353     }
1354
1355   xfree (basedn);
1356
1357   if (ldap_conn)
1358     ldap_unbind (ldap_conn);
1359
1360   xfree (filter);
1361
1362   return err;
1363 }
1364
1365
1366 \f
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.)
1371
1372    A modlist is a NULL terminated array of struct LDAPMod's.
1373
1374    Thus, if we have:
1375
1376      LDAPMod **modlist;
1377
1378    Then:
1379
1380      modlist[i]
1381
1382    Is the ith modification.
1383
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
1390    to NULL.
1391
1392    Thus, if:
1393
1394      modlist[i]->mod_values == NULL
1395
1396    then we remove the attribute.
1397
1398    (Using LDAP_MOD_DELETE doesn't work here as we don't know if the
1399    attribute in question exists or not.)
1400
1401    Note: this function does NOT copy or free ATTR.  It does copy
1402    VALUE.  */
1403 static void
1404 modlist_add (LDAPMod ***modlistp, char *attr, const char *value)
1405 {
1406   LDAPMod **modlist = *modlistp;
1407
1408   LDAPMod **m;
1409   int nummods = 0;
1410
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 ++)
1415     {
1416       /* The attribute is already on the list.  */
1417       char **ptr;
1418       int numvalues = 0;
1419
1420       if (strcasecmp ((*m)->mod_type, attr) != 0)
1421         continue;
1422
1423       /* We have this attribute already, so when the REPLACE happens,
1424          the server attributes will be replaced anyway. */
1425       if (! value)
1426         return;
1427
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++)
1432         {
1433           if (strcmp (*ptr, value) == 0)
1434             /* Duplicate value, we're done.  */
1435             return;
1436           numvalues ++;
1437         }
1438
1439       /* Append the value.  */
1440       ptr = xrealloc ((*m)->mod_values, sizeof (char *) * (numvalues + 2));
1441
1442       (*m)->mod_values = ptr;
1443       ptr[numvalues] = xstrdup (value);
1444
1445       ptr[numvalues + 1] = NULL;
1446
1447       return;
1448     }
1449
1450   /* We didn't find the attr, so make one and add it to the end */
1451
1452   /* Like attribute values, the list of attributes is NULL terminated
1453      array of pointers.  */
1454   modlist = xrealloc (modlist, sizeof (LDAPMod *) * (nummods + 2));
1455
1456   *modlistp = modlist;
1457   modlist[nummods] = xmalloc (sizeof (LDAPMod));
1458
1459   modlist[nummods]->mod_op = LDAP_MOD_REPLACE;
1460   modlist[nummods]->mod_type = attr;
1461   if (value)
1462     {
1463       modlist[nummods]->mod_values = xmalloc (sizeof(char *) * 2);
1464
1465       modlist[nummods]->mod_values[0] = xstrdup (value);
1466       modlist[nummods]->mod_values[1] = NULL;
1467     }
1468   else
1469     modlist[nummods]->mod_values = NULL;
1470
1471   modlist[nummods + 1] = NULL;
1472
1473   return;
1474 }
1475
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.  */
1479 static char **
1480 modlist_lookup (LDAPMod **modlist, const char *attr)
1481 {
1482   LDAPMod **m;
1483   for (m = modlist; m && *m; m++)
1484     {
1485       if (strcasecmp ((*m)->mod_type, attr) != 0)
1486         continue;
1487
1488       return (*m)->mod_values;
1489     }
1490
1491   return NULL;
1492 }
1493
1494 /* Dump a modlist to a file.  This is useful for debugging.  */
1495 static estream_t modlist_dump (LDAPMod **modlist, estream_t output)
1496   GPGRT_ATTR_USED;
1497
1498 static estream_t
1499 modlist_dump (LDAPMod **modlist, estream_t output)
1500 {
1501   LDAPMod **m;
1502
1503   int opened = 0;
1504
1505   if (! output)
1506     {
1507       output = es_fopenmem (0, "rw");
1508       if (!output)
1509         return NULL;
1510       opened = 1;
1511     }
1512
1513   for (m = modlist; m && *m; m++)
1514     {
1515       es_fprintf (output, "  %s:", (*m)->mod_type);
1516
1517       if (! (*m)->mod_values)
1518         es_fprintf(output, " delete.\n");
1519       else
1520         {
1521           char **ptr;
1522           int i;
1523
1524           int multi = 0;
1525           if ((*m)->mod_values[0] && (*m)->mod_values[1])
1526             /* Have at least 2.  */
1527             multi = 1;
1528
1529           if (multi)
1530             es_fprintf (output, "\n");
1531
1532           for ((ptr = (*m)->mod_values), (i = 1); ptr && *ptr; ptr++, i ++)
1533             {
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
1537                  the end.  */
1538               const int max_len = 10 * 70;
1539               size_t value_len = strlen (*ptr);
1540               int elide = value_len > max_len;
1541
1542               if (multi)
1543                 es_fprintf (output, "    %d. ", i);
1544               es_fprintf (output, "`%.*s", max_len, *ptr);
1545               if (elide)
1546                 es_fprintf (output, "...' (%zd bytes elided)",
1547                             value_len - max_len);
1548               else
1549                 es_fprintf (output, "'");
1550               es_fprintf (output, "\n");
1551             }
1552         }
1553     }
1554
1555   if (opened)
1556     es_fseek (output, 0, SEEK_SET);
1557
1558   return output;
1559 }
1560
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.)  */
1564 static void
1565 modlist_free (LDAPMod **modlist)
1566 {
1567   LDAPMod **ml;
1568
1569   if (! modlist)
1570     return;
1571
1572   /* Unwind and free the whole modlist structure */
1573
1574   /* The modlist is a NULL terminated array of pointers.  */
1575   for (ml = modlist; *ml; ml++)
1576     {
1577       LDAPMod *mod = *ml;
1578       char **ptr;
1579
1580       /* The list of values is a NULL termianted array of pointers.
1581          If the list is NULL, there are no values.  */
1582
1583       if (mod->mod_values)
1584         {
1585           for (ptr = mod->mod_values; *ptr; ptr++)
1586             xfree (*ptr);
1587
1588           xfree (mod->mod_values);
1589         }
1590
1591       xfree (mod);
1592     }
1593   xfree (modlist);
1594 }
1595
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!
1598
1599    As long as you don't add anything to ONE, TWO is still valid.
1600    After that all bets are off.  */
1601 static void
1602 modlists_join (LDAPMod ***one, LDAPMod **two)
1603 {
1604   int i, one_count = 0, two_count = 0;
1605   LDAPMod **grow;
1606
1607   if (!*two)
1608     /* two is empty.  Nothing to do.  */
1609     return;
1610
1611   if (!*one)
1612     /* one is empty.  Just set it equal to *two.  */
1613     {
1614       *one = two;
1615       return;
1616     }
1617
1618   for (grow = *one; *grow; grow++)
1619     one_count ++;
1620
1621   for (grow = two; *grow; grow++)
1622     two_count ++;
1623
1624   grow = xrealloc (*one, sizeof(LDAPMod *) * (one_count + two_count + 1));
1625
1626   for (i = 0; i < two_count; i++)
1627     grow[one_count + i] = two[i];
1628
1629   grow[one_count + i] = NULL;
1630
1631   *one = grow;
1632 }
1633
1634 /* Given a string, unescape C escapes.  In particular, \xXX.  This
1635    modifies the string in place.  */
1636 static void
1637 uncescape (char *str)
1638 {
1639   size_t r = 0;
1640   size_t w = 0;
1641
1642   char *first = strchr (str, '\\');
1643   if (! first)
1644     /* No backslashes => no escaping.  We're done.  */
1645     return;
1646
1647   /* Start at the first '\\'.  */
1648   r = w = (uintptr_t) first - (uintptr_t) str;
1649
1650   while (str[r])
1651     {
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))
1659         {
1660           int x = hextobyte (&str[r + 2]);
1661           log_assert (0 <= x && x <= 0xff);
1662
1663           str[w] = x;
1664
1665           /* We consumed 4 characters and wrote 1.  */
1666           r += 4;
1667           w ++;
1668         }
1669       else
1670         str[w ++] = str[r ++];
1671     }
1672
1673   str[w] = '\0';
1674 }
1675
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.  */
1681 static void
1682 extract_attributes (LDAPMod ***modlist, int *extract_state,
1683                     char *line, int schemav2)
1684 {
1685   int field_count;
1686   char **fields;
1687   char *keyid;
1688   int is_pub, is_sub, is_uid, is_sig;
1689
1690   /* Remove trailing whitespace */
1691   trim_trailing_spaces (line);
1692
1693   fields = strsplit (line, ':', '\0', &field_count);
1694   if (field_count == 1)
1695     /* We only have a single field.  There is definitely nothing to
1696        do.  */
1697     goto out;
1698
1699   if (field_count < 7)
1700     goto out;
1701
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]))
1707     {
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)
1713         {
1714           if ((*extract_state & 2))
1715             modlist_add (modlist, "gpgFingerprint", fields[9]);
1716           else
1717             modlist_add (modlist, "gpgSubFingerprint", fields[9]);
1718         }
1719       goto out;
1720     }
1721
1722   *extract_state &= ~(1|2);
1723   if (is_pub)
1724     *extract_state |= (1|2);
1725   else if (is_sub)
1726     *extract_state |= 1;
1727
1728   if (!is_pub && !is_sub && !is_uid && !is_sig)
1729     goto out; /* Not a relevant line.  */
1730
1731   keyid = fields[4];
1732
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.  */
1738   else
1739     {
1740       log_error ("malformed record!\n");
1741       goto out;
1742     }
1743
1744   if (is_pub)
1745     {
1746       int disabled = 0;
1747       int revoked = 0;
1748       char *flags;
1749       for (flags = fields[1]; *flags; flags ++)
1750         switch (*flags)
1751           {
1752           case 'r':
1753           case 'R':
1754             revoked = 1;
1755             break;
1756
1757           case 'd':
1758           case 'D':
1759             disabled = 1;
1760             break;
1761           }
1762
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))"  */
1767
1768       if (is_pub)
1769         {
1770           modlist_add (modlist,"pgpDisabled", disabled ? "1" : "0");
1771           modlist_add (modlist,"pgpRevoked", revoked ? "1" : "0");
1772         }
1773     }
1774
1775   if (is_pub || is_sub)
1776     {
1777       char padded[6];
1778       int val;
1779
1780       val = atoi (fields[2]);
1781       if (val < 99999 && val > 0)
1782         {
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);
1786         }
1787     }
1788
1789   if (is_pub)
1790     {
1791       char *algo = fields[3];
1792       int val = atoi (algo);
1793       switch (val)
1794         {
1795         case 1:
1796           algo = "RSA";
1797           break;
1798
1799         case 17:
1800           algo = "DSS/DH";
1801           break;
1802
1803         default:
1804           algo = NULL;
1805           break;
1806         }
1807
1808       if (algo)
1809         modlist_add (modlist, "pgpKeyType", algo);
1810     }
1811
1812   if (is_pub || is_sub || is_sig)
1813     {
1814       if (is_pub)
1815         {
1816           modlist_add (modlist, "pgpCertID", keyid);    /* Long keyid(!) */
1817           modlist_add (modlist, "pgpKeyID", &keyid[8]); /* Short keyid   */
1818         }
1819
1820       if (is_sub)
1821         modlist_add (modlist, "pgpSubKeyID", keyid);    /* Long keyid(!)  */
1822     }
1823
1824   if (is_pub)
1825     {
1826       char *create_time = fields[5];
1827
1828       if (strlen (create_time) == 0)
1829         create_time = NULL;
1830       else
1831         {
1832           char *create_time_orig = create_time;
1833           struct tm tm;
1834           time_t t;
1835           char *end;
1836
1837           memset (&tm, 0, sizeof (tm));
1838
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
1843              parse_timestamp.  */
1844
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
1848                    && *end == '\0')
1849             {
1850
1851               if (!gnupg_gmtime (&t, &tm))
1852                 create_time = NULL;
1853               else
1854                 create_time = tm2ldaptime (&tm);
1855             }
1856           else
1857             create_time = NULL;
1858
1859           if (! create_time)
1860             /* Failed to parse string.  */
1861             log_error ("Failed to parse creation time ('%s')",
1862                        create_time_orig);
1863         }
1864
1865       if (create_time)
1866         {
1867           modlist_add (modlist, "pgpKeyCreateTime", create_time);
1868           xfree (create_time);
1869         }
1870     }
1871
1872   if (is_pub)
1873     {
1874       char *expire_time = fields[6];
1875
1876       if (strlen (expire_time) == 0)
1877         expire_time = NULL;
1878       else
1879         {
1880           char *expire_time_orig = expire_time;
1881           struct tm tm;
1882           time_t t;
1883           char *end;
1884
1885           memset (&tm, 0, sizeof (tm));
1886
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
1891              parse_timestamp.  */
1892
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
1896                    && *end == '\0')
1897             {
1898               if (!gnupg_gmtime (&t, &tm))
1899                 expire_time = NULL;
1900               else
1901                 expire_time = tm2ldaptime (&tm);
1902             }
1903           else
1904             expire_time = NULL;
1905
1906           if (! expire_time)
1907             /* Failed to parse string.  */
1908             log_error ("Failed to parse creation time ('%s')",
1909                        expire_time_orig);
1910         }
1911
1912       if (expire_time)
1913         {
1914           modlist_add (modlist, "pgpKeyExpireTime", expire_time);
1915           xfree (expire_time);
1916         }
1917     }
1918
1919   if (is_uid && field_count >= 10)
1920     {
1921       char *uid = fields[9];
1922       char *mbox;
1923
1924       uncescape (uid);
1925       modlist_add (modlist, "pgpUserID", uid);
1926       if (schemav2 && (mbox = mailbox_from_userid (uid, 0)))
1927         {
1928           modlist_add (modlist, "gpgMailbox", mbox);
1929           xfree (mbox);
1930         }
1931     }
1932
1933  out:
1934   xfree (fields);
1935 }
1936
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.  */
1940 gpg_error_t
1941 ks_ldap_put (ctrl_t ctrl, parsed_uri_t uri,
1942              void *data, size_t datalen,
1943              void *info, size_t infolen)
1944 {
1945   gpg_error_t err = 0;
1946   int ldap_err;
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;
1953   int extract_state;
1954
1955   /* The last byte of the info block.  */
1956   const char *infoend = (const char *) info + infolen - 1;
1957
1958   /* Enable this code to dump the modlist to /tmp/modlist.txt.  */
1959 #if 0
1960 # warning Disable debug code before checking in.
1961   const int dump_modlist = 1;
1962 #else
1963   const int dump_modlist = 0;
1964 #endif
1965   estream_t dump = NULL;
1966
1967   /* Elide a warning.  */
1968   (void) ctrl;
1969
1970   if (dirmngr_use_tor ())
1971     {
1972       return no_ldap_due_to_tor (ctrl);
1973     }
1974
1975   err = my_ldap_connect (uri, &ldap_conn, &basedn, NULL, NULL, &serverinfo);
1976   if (err || !basedn)
1977     {
1978       if (!err)
1979         err = GPG_ERR_GENERAL;
1980       goto out;
1981     }
1982
1983   if (!(serverinfo & SERVERINFO_REALLDAP))
1984     {
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.  */
1988       LDAPMod mod;
1989       LDAPMod *attrs[2];
1990       char *key[2];
1991       char *dn;
1992
1993       key[0] = data;
1994       key[1] = NULL;
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;
1999       attrs[0] = &mod;
2000       attrs[1] = NULL;
2001
2002       dn = xtryasprintf ("pgpCertid=virtual,%s", basedn);
2003       if (!dn)
2004         {
2005           err = gpg_error_from_syserror ();
2006           goto out;
2007         }
2008       ldap_err = ldap_add_s (ldap_conn, dn, attrs);
2009       xfree (dn);
2010
2011       if (ldap_err != LDAP_SUCCESS)
2012         {
2013           err = ldap_err_to_gpg_err (err);
2014           goto out;
2015         }
2016
2017       goto out;
2018     }
2019
2020   modlist = xtrymalloc (sizeof (LDAPMod *));
2021   if (!modlist)
2022     {
2023       err = gpg_error_from_syserror ();
2024       goto out;
2025     }
2026   *modlist = NULL;
2027
2028   if (dump_modlist)
2029     {
2030       dump = es_fopen("/tmp/modlist.txt", "w");
2031       if (! dump)
2032         log_error ("failed to open /tmp/modlist.txt: %s\n",
2033                    gpg_strerror (gpg_error_from_syserror ()));
2034
2035       if (dump)
2036         {
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");
2041         }
2042     }
2043
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))
2058     {
2059       modlist_add (&modlist, "gpgFingerprint", NULL);
2060       modlist_add (&modlist, "gpgSubFingerprint", NULL);
2061       modlist_add (&modlist, "gpgMailbox", NULL);
2062     }
2063
2064   /* Assemble the INFO stuff into LDAP attributes */
2065   extract_state = 0;
2066   while (infolen > 0)
2067     {
2068       char *temp = NULL;
2069
2070       char *newline = memchr (info, '\n', infolen);
2071       if (! newline)
2072         /* The last line is not \n terminated!  Make a copy so we can
2073            add a NUL terminator.  */
2074         {
2075           temp = xmalloc (infolen + 1);
2076           memcpy (temp, info, infolen);
2077           info = temp;
2078           newline = (char *) info + infolen;
2079         }
2080
2081       *newline = '\0';
2082
2083       extract_attributes (&addlist, &extract_state, info,
2084                           (serverinfo & SERVERINFO_SCHEMAV2));
2085
2086       infolen = infolen - ((uintptr_t) newline - (uintptr_t) info + 1);
2087       info = newline + 1;
2088
2089       /* Sanity check.  */
2090       if (! temp)
2091         log_assert ((char *) info + infolen - 1 == infoend);
2092       else
2093         {
2094           log_assert (infolen == -1);
2095           xfree (temp);
2096         }
2097     }
2098
2099   modlist_add (&addlist, "objectClass", "pgpKeyInfo");
2100
2101   err = armor_data (&data_armored, data, datalen);
2102   if (err)
2103     goto out;
2104
2105   modlist_add (&addlist,
2106                (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey",
2107                data_armored);
2108
2109   /* Now append addlist onto modlist.  */
2110   modlists_join (&modlist, addlist);
2111
2112   if (dump)
2113     {
2114       estream_t input = modlist_dump (modlist, NULL);
2115       if (input)
2116         {
2117           copy_stream (input, dump);
2118           es_fclose (input);
2119         }
2120     }
2121
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. */
2129   {
2130     char **attrval;
2131     char *dn;
2132
2133     if ((serverinfo & SERVERINFO_NTDS))
2134       {
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]))
2142           {
2143             log_error ("ks-ldap: bad gpgFingerprint provided\n");
2144             err = GPG_ERR_GENERAL;
2145             goto out;
2146           }
2147         dn = xtryasprintf ("CN=%s,%s", attrval[0], basedn);
2148       }
2149     else  /* The old style way.  */
2150       {
2151         attrval = modlist_lookup (addlist, "pgpCertID");
2152         /* We should have exactly one value.  */
2153         if (!attrval || !(attrval[0] && !attrval[1]))
2154           {
2155             log_error ("ks-ldap: bad pgpCertID provided\n");
2156             err = GPG_ERR_GENERAL;
2157             goto out;
2158           }
2159         dn = xtryasprintf ("pgpCertID=%s,%s", attrval[0], basedn);
2160       }
2161     if (!dn)
2162       {
2163         err = gpg_error_from_syserror ();
2164         goto out;
2165       }
2166     if (opt.debug)
2167       log_debug ("ks-ldap: using DN: %s\n", dn);
2168
2169     npth_unprotect ();
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);
2173     npth_protect ();
2174
2175     xfree (dn);
2176
2177     if (err != LDAP_SUCCESS)
2178       {
2179         log_error ("ks-ldap: error adding key to keyserver: %s\n",
2180                    ldap_err2string (err));
2181         err = ldap_err_to_gpg_err (err);
2182       }
2183   }
2184
2185  out:
2186   if (dump)
2187     es_fclose (dump);
2188
2189   if (ldap_conn)
2190     ldap_unbind (ldap_conn);
2191
2192   xfree (basedn);
2193
2194   modlist_free (modlist);
2195   xfree (addlist);
2196
2197   xfree (data_armored);
2198
2199   return err;
2200 }