1 /* dirmngr-ldap.c - The LDAP helper for dirmngr.
2 * Copyright (C) 2004, 2021 g10 Code GmbH
3 * Copyright (C) 2010 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <https://www.gnu.org/licenses/>.
19 * SPDX-License-Identifier: GPL-3.0-or-later
37 #ifdef HAVE_W32_SYSTEM
38 # include <winsock2.h>
42 # include "ldap-url.h"
44 /* For OpenLDAP, to enable the API that we're using. */
45 # define LDAP_DEPRECATED 1
50 #include <gpg-error.h>
51 #include "../common/logging.h"
52 #include "../common/stringhelp.h"
53 #include "../common/mischelp.h"
54 #include "../common/strlist.h"
55 #include "../common/util.h"
56 #include "../common/init.h"
57 #include "ldap-misc.h"
60 /* There is no need for the npth_unprotect and leave functions here;
61 * thus we redefine them to nops. We keep them in the code just for
62 * the case we ever want to reuse parts of the code in npth programs. */
63 static void npth_unprotect (void) { }
64 static void npth_protect (void) { }
67 #ifdef HAVE_W32_SYSTEM
68 typedef LDAP_TIMEVAL my_ldap_timeval_t;
70 typedef struct timeval my_ldap_timeval_t;
73 #define DEFAULT_LDAP_TIMEOUT 15 /* Arbitrary long timeout. */
76 /* Constants for the options. */
101 /* The list of options as used by the argparse.c code. */
102 static gpgrt_opt_t opts[] = {
103 { oVerbose, "verbose", 0, "verbose" },
104 { oQuiet, "quiet", 0, "be somewhat more quiet" },
105 { oTimeout, "timeout", 1, "|N|set LDAP timeout to N seconds"},
106 { oMulti, "multi", 0, "return all values in"
107 " a record oriented format"},
108 { oProxy, "proxy", 2,
109 "|NAME|ignore host part and connect through NAME"},
110 { oStartTLS, "starttls", 0, "use STARTLS for the conenction"},
111 { oLdapTLS, "ldaptls", 0, "use a TLS for the connection"},
112 { oNtds, "ntds", 0, "authenticate using AD"},
113 { oARecOnly, "areconly", 0, "do only an A record lookup"},
114 { oHost, "host", 2, "|NAME|connect to host NAME"},
115 { oPort, "port", 1, "|N|connect to port N"},
116 { oUser, "user", 2, "|NAME|use NAME for authentication"},
117 { oPass, "pass", 2, "|PASS|use password PASS"
118 " for authentication"},
119 { oEnvPass, "env-pass", 0, "take password from $DIRMNGR_LDAP_PASS"},
120 { oBase, "base", 2, "|DN|Start query at DN"},
121 { oAttr, "attr", 2, "|STRING|return the attribute STRING"},
122 { oOnlySearchTimeout, "only-search-timeout", 0, "@"},
123 { oLogWithPID,"log-with-pid", 0, "@"},
128 /* A structure with module options. */
133 my_ldap_timeval_t timeout;/* Timeout for the LDAP search functions. */
134 unsigned int alarm_timeout; /* And for the alarm based timeout. */
141 estream_t outstream; /* Send output to this stream. */
143 /* Note that we can't use const for the strings because ldap_* are
144 not defined that way. */
145 char *proxy; /* Host and Port override. */
146 char *user; /* Authentication user. */
147 char *pass; /* Authentication password. */
148 char *host; /* Override host. */
149 int port; /* Override port. */
150 char *base; /* Override DN. */
151 char *attr; /* Override attribute. */
156 #ifndef HAVE_W32_SYSTEM
157 static void catch_alarm (int dummy);
159 static gpg_error_t connect_ldap (LDAP **r_ld);
160 static gpg_error_t process_filter (LDAP *ld, const char *string);
164 /* Function called by argparse.c to display information. */
166 my_strusage (int level)
172 case 9: p = "GPL-3.0-or-later"; break;
173 case 11: p = "dirmngr_ldap (@GNUPG@)";
175 case 13: p = VERSION; break;
176 case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break;
177 case 17: p = PRINTABLE_OS_NAME; break;
178 case 19: p = "Please report bugs to <@EMAIL@>.\n"; break;
179 case 49: p = PACKAGE_BUGREPORT; break;
182 "Usage: dirmngr_ldap [options] filters (-h for help)\n";
185 ("Syntax: dirmngr_ldap [options] filters\n"
186 "Internal LDAP helper for Dirmngr\n"
187 "Interface and options may change without notice\n");
197 main (int argc, char **argv)
199 gpgrt_argparse_t pargs;
202 int only_search_timeout = 0;
203 char *malloced_buffer1 = NULL;
206 early_system_init ();
208 gpgrt_set_strusage (my_strusage);
209 log_set_prefix ("dirmngr_ldap", GPGRT_LOG_WITH_PREFIX);
211 init_common_subsystems (&argc, &argv);
213 es_set_binary (es_stdout);
214 opt.outstream = es_stdout;
217 opt.timeout.tv_sec = DEFAULT_LDAP_TIMEOUT;
218 opt.timeout.tv_usec = 0;
219 opt.alarm_timeout = 0;
221 /* Parse the command line. */
224 pargs.flags= ARGPARSE_FLAG_KEEP;
225 while (gpgrt_argparse (NULL, &pargs, opts))
229 case oVerbose: opt.verbose++; break;
230 case oQuiet: opt.quiet++; break;
232 opt.timeout.tv_sec = pargs.r.ret_int;
233 opt.timeout.tv_usec = 0;
234 opt.alarm_timeout = pargs.r.ret_int;
236 case oOnlySearchTimeout: only_search_timeout = 1; break;
237 case oStartTLS: opt.starttls = 1; opt.ldaptls = 0; break;
238 case oLdapTLS: opt.starttls = 0; opt.ldaptls = 1; break;
239 case oNtds: opt.ntds = 1; break;
240 case oARecOnly: opt.areconly = 1; break;
241 case oMulti: opt.multi = 1; break;
242 case oUser: opt.user = pargs.r.ret_str; break;
243 case oPass: opt.pass = pargs.r.ret_str; break;
245 opt.pass = getenv ("DIRMNGR_LDAP_PASS");
247 case oProxy: opt.proxy = pargs.r.ret_str; break;
248 case oHost: opt.host = pargs.r.ret_str; break;
249 case oPort: opt.port = pargs.r.ret_int; break;
250 case oBase: opt.base = pargs.r.ret_str; break;
251 case oAttr: opt.attr = pargs.r.ret_str; break;
254 unsigned int oldflags;
255 log_get_prefix (&oldflags);
256 log_set_prefix (NULL, oldflags | GPGRT_LOG_WITH_PID);
261 pargs.err = ARGPARSE_PRINT_ERROR;
265 gpgrt_argparse (NULL, &pargs, NULL);
267 if (only_search_timeout)
268 opt.alarm_timeout = 0;
272 malloced_buffer1 = xtrystrdup (opt.proxy);
273 if (!malloced_buffer1)
275 log_error ("error copying string: %s\n", strerror (errno));
278 opt.host = malloced_buffer1;
279 p = strchr (opt.host, ':');
286 opt.port = 389; /* make sure ports gets overridden. */
289 if (opt.port < 0 || opt.port > 65535)
290 log_error ("invalid port number %d\n", opt.port);
293 opt.port = opt.ldaptls? 636 : 389;
295 #ifndef HAVE_W32_SYSTEM
297 opt.host = "localhost";
301 if (log_get_errorcount (0))
304 if (opt.alarm_timeout)
306 #ifndef HAVE_W32_SYSTEM
307 # if defined(HAVE_SIGACTION) && defined(HAVE_STRUCT_SIGACTION)
308 struct sigaction act;
310 act.sa_handler = catch_alarm;
311 sigemptyset (&act.sa_mask);
313 if (sigaction (SIGALRM,&act,NULL))
315 if (signal (SIGALRM, catch_alarm) == SIG_ERR)
317 log_fatal ("unable to register timeout handler\n");
321 if (connect_ldap (&ld))
327 if (process_filter (ld, "(objectClass=*)"))
332 for (; argc; argc--, argv++)
333 if (process_filter (ld, *argv))
339 xfree (malloced_buffer1);
343 #ifndef HAVE_W32_SYSTEM
345 catch_alarm (int dummy)
353 #ifdef HAVE_W32_SYSTEM
354 static DWORD CALLBACK
355 alarm_thread (void *arg)
359 WaitForSingleObject (timer, INFINITE);
370 if (opt.alarm_timeout)
372 #ifdef HAVE_W32_SYSTEM
374 LARGE_INTEGER due_time;
376 /* A negative value is a relative time. */
377 due_time.QuadPart = (unsigned long long)-10000000 * opt.alarm_timeout;
381 SECURITY_ATTRIBUTES sec_attr;
384 memset (&sec_attr, 0, sizeof sec_attr);
385 sec_attr.nLength = sizeof sec_attr;
386 sec_attr.bInheritHandle = FALSE;
388 /* Create a manual resettable timer. */
389 timer = CreateWaitableTimer (NULL, TRUE, NULL);
390 /* Initially set the timer. */
391 SetWaitableTimer (timer, &due_time, 0, NULL, NULL, 0);
393 if (CreateThread (&sec_attr, 0, alarm_thread, timer, 0, &tid))
394 log_error ("failed to create alarm thread\n");
396 else /* Retrigger the timer. */
397 SetWaitableTimer (timer, &due_time, 0, NULL, NULL, 0);
399 alarm (opt.alarm_timeout);
406 /* Connect to the ldap server. On success the connection handle is
409 connect_ldap (LDAP **r_ld)
414 #ifndef HAVE_W32_SYSTEM
420 if (opt.starttls || opt.ldaptls)
422 #ifndef HAVE_LDAP_START_TLS_S
423 log_error ("ldap: can't connect to the server: no TLS support.");
424 err = GPG_ERR_LDAP_NOT_SUPPORTED;
431 #ifdef HAVE_W32_SYSTEM
433 ld = ldap_sslinit (opt.host, opt.port, opt.ldaptls);
437 lerr = LdapGetLastError ();
438 err = ldap_err_to_gpg_err (lerr);
439 log_error ("error initializing LDAP '%s:%d': %s\n",
440 opt.host, opt.port, ldap_err2string (lerr));
445 lerr = ldap_set_option (ld, LDAP_OPT_AREC_EXCLUSIVE, LDAP_OPT_ON);
446 if (lerr != LDAP_SUCCESS)
448 log_error ("ldap: unable to set AREC_EXLUSIVE: %s\n",
449 ldap_err2string (lerr));
450 err = ldap_err_to_gpg_err (lerr);
455 tmpstr = xtryasprintf ("%s://%s:%d",
456 opt.ldaptls? "ldaps" : "ldap",
460 err = gpg_error_from_syserror ();
464 lerr = ldap_initialize (&ld, tmpstr);
468 err = ldap_err_to_gpg_err (lerr);
469 log_error ("error initializing LDAP '%s': %s\n",
470 tmpstr, ldap_err2string (lerr));
478 log_info ("LDAP connected to '%s:%d'%s\n",
480 opt.starttls? " using STARTTLS" :
481 opt.ldaptls? " using LDAP-over-TLS" : "");
484 #ifdef HAVE_LDAP_SET_OPTION
486 int ver = LDAP_VERSION3;
488 lerr = ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &ver);
489 if (lerr != LDAP_SUCCESS)
491 log_error ("unable to go to LDAP 3: %s\n", ldap_err2string (lerr));
492 err = ldap_err_to_gpg_err (lerr);
499 #ifdef HAVE_LDAP_START_TLS_S
502 #ifndef HAVE_W32_SYSTEM
503 int check_cert = LDAP_OPT_X_TLS_HARD; /* LDAP_OPT_X_TLS_NEVER */
505 lerr = ldap_set_option (ld, LDAP_OPT_X_TLS_REQUIRE_CERT, &check_cert);
508 log_error ("ldap: error setting an TLS option: %s\n",
509 ldap_err2string (lerr));
510 err = ldap_err_to_gpg_err (lerr);
514 /* On Windows, the certificates are checked by default. If the
515 option to disable checking mentioned above is ever
516 implemented, the way to do that on Windows is to install a
517 callback routine using ldap_set_option (..,
518 LDAP_OPT_SERVER_CERTIFICATE, ..); */
522 lerr = ldap_start_tls_s (ld,
523 #ifdef HAVE_W32_SYSTEM
524 /* ServerReturnValue, result */
527 /* ServerControls, ClientControls */
532 log_error ("ldap: error switching to STARTTLS mode: %s\n",
533 ldap_err2string (lerr));
534 err = ldap_err_to_gpg_err (lerr);
543 log_info ("binding to current user via AD\n");
544 #ifdef HAVE_W32_SYSTEM
546 lerr = ldap_bind_s (ld, NULL, NULL, LDAP_AUTH_NEGOTIATE);
548 if (lerr != LDAP_SUCCESS)
550 log_error ("error binding to LDAP via AD: %s\n",
551 ldap_err2string (lerr));
552 err = ldap_err_to_gpg_err (lerr);
556 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
563 log_info ("LDAP bind to '%s', password '%s'\n",
564 opt.user, opt.pass ? ">not_shown<" : ">none<");
567 lerr = ldap_simple_bind_s (ld, opt.user, opt.pass);
569 if (lerr != LDAP_SUCCESS)
571 log_error ("error binding to LDAP: %s\n", ldap_err2string (lerr));
572 err = ldap_err_to_gpg_err (lerr);
578 /* By default we don't bind as there is usually no need to. */
593 /* Helper for fetch_ldap(). */
595 print_ldap_entries (LDAP *ld, LDAPMessage *msg, char *want_attr)
600 for (npth_unprotect (), item = ldap_first_entry (ld, msg), npth_protect ();
602 npth_unprotect (), item = ldap_next_entry (ld, item), npth_protect ())
608 log_info ("scanning result for attribute '%s'\n",
609 want_attr? want_attr : "[all]");
612 { /* Write item marker. */
613 if (es_fwrite ("I\0\0\0\0", 5, 1, opt.outstream) != 1)
615 log_error ("error writing to stdout: %s\n",
622 for (npth_unprotect (), attr = ldap_first_attribute (ld, item, &berctx),
625 npth_unprotect (), attr = ldap_next_attribute (ld, item, berctx),
628 struct berval **values;
632 log_info (" available attribute '%s'\n", attr);
636 /* I case we want only one attribute we do a case
637 insensitive compare without the optional extension
638 (i.e. ";binary"). Case insensitive is not really correct
639 but the best we can do. */
645 cp1 = strchr (want_attr, ';');
648 cp2 = strchr (attr, ';');
651 cmpres = ascii_strcasecmp (want_attr, attr);
659 continue; /* Not found: Try next attribute. */
664 values = ldap_get_values_len (ld, item, attr);
670 log_info ("attribute '%s' not found\n", attr);
677 log_info ("found attribute '%s'\n", attr);
679 for (idx=0; values[idx]; idx++)
680 log_info (" length[%d]=%d\n",
681 idx, (int)values[0]->bv_len);
686 { /* Write attribute marker. */
687 unsigned char tmp[5];
688 size_t n = strlen (attr);
695 if (es_fwrite (tmp, 5, 1, opt.outstream) != 1
696 || es_fwrite (attr, n, 1, opt.outstream) != 1)
698 log_error ("error writing to stdout: %s\n",
700 ldap_value_free_len (values);
702 ber_free (berctx, 0);
707 for (idx=0; values[idx]; idx++)
710 { /* Write value marker. */
711 unsigned char tmp[5];
712 size_t n = values[0]->bv_len;
720 if (es_fwrite (tmp, 5, 1, opt.outstream) != 1)
722 log_error ("error writing to stdout: %s\n",
724 ldap_value_free_len (values);
726 ber_free (berctx, 0);
731 if (es_fwrite (values[0]->bv_val, values[0]->bv_len,
732 1, opt.outstream) != 1)
734 log_error ("error writing to stdout: %s\n",
736 ldap_value_free_len (values);
738 ber_free (berctx, 0);
744 break; /* Print only the first value. */
746 ldap_value_free_len (values);
748 if (want_attr || !opt.multi)
749 break; /* We only want to return the first attribute. */
751 ber_free (berctx, 0);
754 if (opt.verbose > 1 && any)
755 log_info ("result has been printed\n");
762 /* Fetch data from the server at LD using FILTER. */
764 fetch_ldap (LDAP *ld, const char *base, int scope, const char *filter)
771 if (filter && !*filter)
776 log_info ("fetching using");
778 log_printf (" base '%s'", base);
780 log_printf (" filter '%s'", filter);
789 lerr = ldap_search_st (ld, base, scope, filter,
794 if (lerr == LDAP_SIZELIMIT_EXCEEDED && opt.multi)
796 if (es_fwrite ("E\0\0\0\x09truncated", 14, 1, opt.outstream) != 1)
798 log_error ("error writing to stdout: %s\n", strerror (errno));
804 log_error ("searching '%s' failed: %s\n",
805 filter, ldap_err2string (lerr));
806 if (lerr != LDAP_NO_SUCH_OBJECT)
808 /* FIXME: Need deinit (ld)? */
809 /* Hmmm: Do we need to released MSG in case of an error? */
814 err = print_ldap_entries (ld, msg, opt.multi? NULL:opt.attr);
823 /* Main processing. Take the filter and run the LDAP query. The
824 * result is printed to stdout, errors are logged to the log stream.
825 * To allow searching with a different base it is possible to extend
826 * the filter. For example:
828 * ^CN=foo, OU=My Users&(objectClasses=*)
830 * Uses "CN=foo, OU=My Users" as base DN and "(objectClasses=*)" as
831 * filter. If the base prefix includes an ampersand, it needs to be
832 * doubled. The usual escaping rules for DNs (for the base) and
833 * filters apply. If no scope is given (see ldap_parse_extfilter for
834 * the syntax) subtree scope is used.
837 process_filter (LDAP *ld, const char *string)
843 err = ldap_parse_extfilter (string, 0, &base, &scope, &filter);
845 err = fetch_ldap (ld,
846 base? base : opt.base,
847 scope == -1? LDAP_SCOPE_SUBTREE : scope,