go back to using explicit install calls in rules due to renaming required
[debian/sudo] / ldap.c
1 /*
2  * Copyright (c) 2003-2010 Todd C. Miller <Todd.Miller@courtesan.com>
3  *
4  * This code is derived from software contributed by Aaron Spangler.
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18
19 #include <config.h>
20
21 #include <sys/types.h>
22 #include <sys/time.h>
23 #include <sys/param.h>
24 #include <sys/stat.h>
25 #include <stdio.h>
26 #ifdef STDC_HEADERS
27 # include <stdlib.h>
28 # include <stddef.h>
29 #else
30 # ifdef HAVE_STDLIB_H
31 #  include <stdlib.h>
32 # endif
33 #endif /* STDC_HEADERS */
34 #ifdef HAVE_STRING_H
35 # include <string.h>
36 #endif /* HAVE_STRING_H */
37 #ifdef HAVE_STRINGS_H
38 # include <strings.h>
39 #endif /* HAVE_STRINGS_H */
40 #if defined(HAVE_MALLOC_H) && !defined(STDC_HEADERS)
41 # include <malloc.h>
42 #endif /* HAVE_MALLOC_H && !STDC_HEADERS */
43 #ifdef HAVE_UNISTD_H
44 # include <unistd.h>
45 #endif /* HAVE_UNISTD_H */
46 #include <ctype.h>
47 #include <pwd.h>
48 #include <grp.h>
49 #include <netinet/in.h>
50 #include <arpa/inet.h>
51 #include <netdb.h>
52 #ifdef HAVE_LBER_H
53 # include <lber.h>
54 #endif
55 #include <ldap.h>
56 #if defined(HAVE_LDAP_SSL_H)
57 # include <ldap_ssl.h>
58 #elif defined(HAVE_MPS_LDAP_SSL_H)
59 # include <mps/ldap_ssl.h>
60 #endif
61 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
62 # ifdef HAVE_SASL_SASL_H
63 #  include <sasl/sasl.h>
64 # else
65 #  include <sasl.h>
66 # endif
67 # if HAVE_GSS_KRB5_CCACHE_NAME
68 #  if defined(HAVE_GSSAPI_GSSAPI_KRB5_H)
69 #   include <gssapi/gssapi.h>
70 #   include <gssapi/gssapi_krb5.h>
71 #  elif defined(HAVE_GSSAPI_GSSAPI_H)
72 #   include <gssapi/gssapi.h>
73 #  else
74 #   include <gssapi.h>
75 #  endif
76 # endif
77 #endif
78
79 #include "sudo.h"
80 #include "parse.h"
81 #include "lbuf.h"
82
83 #ifndef LDAP_OPT_SUCCESS
84 # define LDAP_OPT_SUCCESS LDAP_SUCCESS
85 #endif
86
87 #ifndef LDAPS_PORT
88 # define LDAPS_PORT 636
89 #endif
90
91 #if defined(HAVE_LDAP_SASL_INTERACTIVE_BIND_S) && !defined(LDAP_SASL_QUIET)
92 # define LDAP_SASL_QUIET        0
93 #endif
94
95 #ifndef HAVE_LDAP_UNBIND_EXT_S
96 #define ldap_unbind_ext_s(a, b, c)      ldap_unbind_s(a)
97 #endif
98
99 #ifndef HAVE_LDAP_SEARCH_EXT_S
100 #define ldap_search_ext_s(a, b, c, d, e, f, g, h, i, j, k)              \
101         ldap_search_s(a, b, c, d, e, f, k)
102 #endif
103
104 #define LDAP_FOREACH(var, ld, res)                                      \
105     for ((var) = ldap_first_entry((ld), (res));                         \
106         (var) != NULL;                                                  \
107         (var) = ldap_next_entry((ld), (var)))
108
109 #define DPRINTF(args, level)    if (ldap_conf.debug >= level) warningx args
110
111 #define CONF_BOOL       0
112 #define CONF_INT        1
113 #define CONF_STR        2
114 #define CONF_LIST_STR   4
115
116 #define SUDO_LDAP_SSL           1
117 #define SUDO_LDAP_STARTTLS      2
118
119 struct ldap_config_table {
120     const char *conf_str;       /* config file string */
121     short type;                 /* CONF_BOOL, CONF_INT, CONF_STR */
122     short connected;            /* connection-specific value? */
123     int opt_val;                /* LDAP_OPT_* (or -1 for sudo internal) */
124     void *valp;                 /* pointer into ldap_conf */
125 };
126
127 struct ldap_config_list_str {
128     struct ldap_config_list_str *next;
129     char val[1];
130 };
131
132 /* ldap configuration structure */
133 static struct ldap_config {
134     int port;
135     int version;
136     int debug;
137     int ldap_debug;
138     int tls_checkpeer;
139     int timelimit;
140     int bind_timelimit;
141     int use_sasl;
142     int rootuse_sasl;
143     int ssl_mode;
144     char *host;
145     struct ldap_config_list_str *uri;
146     char *binddn;
147     char *bindpw;
148     char *rootbinddn;
149     struct ldap_config_list_str *base;
150     char *ssl;
151     char *tls_cacertfile;
152     char *tls_cacertdir;
153     char *tls_random_file;
154     char *tls_cipher_suite;
155     char *tls_certfile;
156     char *tls_keyfile;
157     char *sasl_auth_id;
158     char *rootsasl_auth_id;
159     char *sasl_secprops;
160     char *krb5_ccname;
161 } ldap_conf;
162
163 static struct ldap_config_table ldap_conf_table[] = {
164     { "sudoers_debug", CONF_INT, FALSE, -1, &ldap_conf.debug },
165     { "host", CONF_STR, FALSE, -1, &ldap_conf.host },
166     { "port", CONF_INT, FALSE, -1, &ldap_conf.port },
167     { "ssl", CONF_STR, FALSE, -1, &ldap_conf.ssl },
168     { "sslpath", CONF_STR, FALSE, -1, &ldap_conf.tls_certfile },
169     { "uri", CONF_LIST_STR, FALSE, -1, &ldap_conf.uri },
170 #ifdef LDAP_OPT_DEBUG_LEVEL
171     { "debug", CONF_INT, FALSE, LDAP_OPT_DEBUG_LEVEL, &ldap_conf.ldap_debug },
172 #endif
173 #ifdef LDAP_OPT_PROTOCOL_VERSION
174     { "ldap_version", CONF_INT, TRUE, LDAP_OPT_PROTOCOL_VERSION,
175         &ldap_conf.version },
176 #endif
177 #ifdef LDAP_OPT_X_TLS_REQUIRE_CERT
178     { "tls_checkpeer", CONF_BOOL, FALSE, LDAP_OPT_X_TLS_REQUIRE_CERT,
179         &ldap_conf.tls_checkpeer },
180 #else
181     { "tls_checkpeer", CONF_BOOL, FALSE, -1, &ldap_conf.tls_checkpeer },
182 #endif
183 #ifdef LDAP_OPT_X_TLS_CACERTFILE
184     { "tls_cacertfile", CONF_STR, FALSE, LDAP_OPT_X_TLS_CACERTFILE,
185         &ldap_conf.tls_cacertfile },
186     { "tls_cacert", CONF_STR, FALSE, LDAP_OPT_X_TLS_CACERTFILE,
187         &ldap_conf.tls_cacertfile },
188 #endif
189 #ifdef LDAP_OPT_X_TLS_CACERTDIR
190     { "tls_cacertdir", CONF_STR, FALSE, LDAP_OPT_X_TLS_CACERTDIR,
191         &ldap_conf.tls_cacertdir },
192 #endif
193 #ifdef LDAP_OPT_X_TLS_RANDOM_FILE
194     { "tls_randfile", CONF_STR, FALSE, LDAP_OPT_X_TLS_RANDOM_FILE,
195         &ldap_conf.tls_random_file },
196 #endif
197 #ifdef LDAP_OPT_X_TLS_CIPHER_SUITE
198     { "tls_ciphers", CONF_STR, FALSE, LDAP_OPT_X_TLS_CIPHER_SUITE,
199         &ldap_conf.tls_cipher_suite },
200 #endif
201 #ifdef LDAP_OPT_X_TLS_CERTFILE
202     { "tls_cert", CONF_STR, FALSE, LDAP_OPT_X_TLS_CERTFILE,
203         &ldap_conf.tls_certfile },
204 #else
205     { "tls_cert", CONF_STR, FALSE, -1, &ldap_conf.tls_certfile },
206 #endif
207 #ifdef LDAP_OPT_X_TLS_KEYFILE
208     { "tls_key", CONF_STR, FALSE, LDAP_OPT_X_TLS_KEYFILE,
209         &ldap_conf.tls_keyfile },
210 #else
211     { "tls_key", CONF_STR, FALSE, -1, &ldap_conf.tls_keyfile },
212 #endif
213 #ifdef LDAP_OPT_NETWORK_TIMEOUT
214     { "bind_timelimit", CONF_INT, TRUE, -1 /* needs timeval, set manually */,
215         &ldap_conf.bind_timelimit },
216 #elif defined(LDAP_X_OPT_CONNECT_TIMEOUT)
217     { "bind_timelimit", CONF_INT, TRUE, LDAP_X_OPT_CONNECT_TIMEOUT,
218         &ldap_conf.bind_timelimit },
219 #endif
220     { "timelimit", CONF_INT, TRUE, LDAP_OPT_TIMELIMIT, &ldap_conf.timelimit },
221     { "binddn", CONF_STR, FALSE, -1, &ldap_conf.binddn },
222     { "bindpw", CONF_STR, FALSE, -1, &ldap_conf.bindpw },
223     { "rootbinddn", CONF_STR, FALSE, -1, &ldap_conf.rootbinddn },
224     { "sudoers_base", CONF_LIST_STR, FALSE, -1, &ldap_conf.base },
225 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
226     { "use_sasl", CONF_BOOL, FALSE, -1, &ldap_conf.use_sasl },
227     { "sasl_auth_id", CONF_STR, FALSE, -1, &ldap_conf.sasl_auth_id },
228     { "rootuse_sasl", CONF_BOOL, FALSE, -1, &ldap_conf.rootuse_sasl },
229     { "rootsasl_auth_id", CONF_STR, FALSE, -1, &ldap_conf.rootsasl_auth_id },
230 # ifdef LDAP_OPT_X_SASL_SECPROPS
231     { "sasl_secprops", CONF_STR, TRUE, LDAP_OPT_X_SASL_SECPROPS,
232         &ldap_conf.sasl_secprops },
233 # endif
234     { "krb5_ccname", CONF_STR, FALSE, -1, &ldap_conf.krb5_ccname },
235 #endif /* HAVE_LDAP_SASL_INTERACTIVE_BIND_S */
236     { NULL }
237 };
238
239 /* sudo_nss implementation */
240 static int sudo_ldap_open __P((struct sudo_nss *nss));
241 static int sudo_ldap_close __P((struct sudo_nss *nss));
242 static int sudo_ldap_parse __P((struct sudo_nss *nss));
243 static int sudo_ldap_setdefs __P((struct sudo_nss *nss));
244 static int sudo_ldap_lookup __P((struct sudo_nss *nss, int ret, int pwflag));
245 static int sudo_ldap_display_cmnd __P((struct sudo_nss *nss,
246     struct passwd *pw));
247 static int sudo_ldap_display_defaults __P((struct sudo_nss *nss,
248     struct passwd *pw, struct lbuf *lbuf));
249 static int sudo_ldap_display_bound_defaults __P((struct sudo_nss *nss,
250     struct passwd *pw, struct lbuf *lbuf));
251 static int sudo_ldap_display_privs __P((struct sudo_nss *nss,
252     struct passwd *pw, struct lbuf *lbuf));
253
254 struct sudo_nss sudo_nss_ldap = {
255     &sudo_nss_ldap,
256     NULL,
257     sudo_ldap_open,
258     sudo_ldap_close,
259     sudo_ldap_parse,
260     sudo_ldap_setdefs,
261     sudo_ldap_lookup,
262     sudo_ldap_display_cmnd,
263     sudo_ldap_display_defaults,
264     sudo_ldap_display_bound_defaults,
265     sudo_ldap_display_privs
266 };
267
268 #ifdef HAVE_LDAP_CREATE
269 /*
270  * Rebuild the hosts list and include a specific port for each host.
271  * ldap_create() does not take a default port parameter so we must
272  * append one if we want something other than LDAP_PORT.
273  */
274 static void
275 sudo_ldap_conf_add_ports()
276 {
277
278     char *host, *port, defport[13];
279     char hostbuf[LINE_MAX * 2];
280
281     hostbuf[0] = '\0';
282     if (snprintf(defport, sizeof(defport), ":%d", ldap_conf.port) >= sizeof(defport))
283         errorx(1, "sudo_ldap_conf_add_ports: port too large");
284
285     for ((host = strtok(ldap_conf.host, " \t")); host; (host = strtok(NULL, " \t"))) {
286         if (hostbuf[0] != '\0') {
287             if (strlcat(hostbuf, " ", sizeof(hostbuf)) >= sizeof(hostbuf))
288                 goto toobig;
289         }
290
291         if (strlcat(hostbuf, host, sizeof(hostbuf)) >= sizeof(hostbuf))
292             goto toobig;
293         /* Append port if there is not one already. */
294         if ((port = strrchr(host, ':')) == NULL ||
295             !isdigit((unsigned char)port[1])) {
296             if (strlcat(hostbuf, defport, sizeof(hostbuf)) >= sizeof(hostbuf))
297                 goto toobig;
298         }
299     }
300
301     free(ldap_conf.host);
302     ldap_conf.host = estrdup(hostbuf);
303     return;
304
305 toobig:
306     errorx(1, "sudo_ldap_conf_add_ports: out of space expanding hostbuf");
307 }
308 #endif
309
310 #ifndef HAVE_LDAP_INITIALIZE
311 /*
312  * For each uri, convert to host:port pairs.  For ldaps:// enable SSL
313  * Accepts: uris of the form ldap:/// or ldap://hostname:portnum/
314  * where the trailing slash is optional.
315  */
316 static int
317 sudo_ldap_parse_uri(uri_list)
318     const struct ldap_config_list_str *uri_list;
319 {
320     char *buf, *uri, *host, *cp, *port;
321     char hostbuf[LINE_MAX];
322     int nldap = 0, nldaps = 0;
323     int rc = -1;
324
325     do {
326         buf = estrdup(uri_list->val);
327         hostbuf[0] = '\0';
328         for ((uri = strtok(buf, " \t")); uri != NULL; (uri = strtok(NULL, " \t"))) {
329             if (strncasecmp(uri, "ldap://", 7) == 0) {
330                 nldap++;
331                 host = uri + 7;
332             } else if (strncasecmp(uri, "ldaps://", 8) == 0) {
333                 nldaps++;
334                 host = uri + 8;
335             } else {
336                 warningx("unsupported LDAP uri type: %s", uri);
337                 goto done;
338             }
339
340             /* trim optional trailing slash */
341             if ((cp = strrchr(host, '/')) != NULL && cp[1] == '\0') {
342                 *cp = '\0';
343             }
344
345             if (hostbuf[0] != '\0') {
346                 if (strlcat(hostbuf, " ", sizeof(hostbuf)) >= sizeof(hostbuf))
347                     goto toobig;
348             }
349
350             if (*host == '\0')
351                 host = "localhost";             /* no host specified, use localhost */
352
353             if (strlcat(hostbuf, host, sizeof(hostbuf)) >= sizeof(hostbuf))
354                 goto toobig;
355
356             /* If using SSL and no port specified, add port 636 */
357             if (nldaps) {
358                 if ((port = strrchr(host, ':')) == NULL ||
359                     !isdigit((unsigned char)port[1]))
360                     if (strlcat(hostbuf, ":636", sizeof(hostbuf)) >= sizeof(hostbuf))
361                         goto toobig;
362             }
363         }
364         if (hostbuf[0] == '\0') {
365             warningx("invalid uri: %s", uri_list);
366             goto done;
367         }
368
369         if (nldaps != 0) {
370             if (nldap != 0) {
371                 warningx("cannot mix ldap and ldaps URIs");
372                 goto done;
373             }
374             if (ldap_conf.ssl_mode == SUDO_LDAP_STARTTLS) {
375                 warningx("cannot mix ldaps and starttls");
376                 goto done;
377             }
378             ldap_conf.ssl_mode = SUDO_LDAP_SSL;
379         }
380
381         free(ldap_conf.host);
382         ldap_conf.host = estrdup(hostbuf);
383         efree(buf);
384     } while ((uri_list = uri_list->next));
385
386     buf = NULL;
387     rc = 0;
388
389 done:
390     efree(buf);
391     return(rc);
392
393 toobig:
394     errorx(1, "sudo_ldap_parse_uri: out of space building hostbuf");
395 }
396 #else
397 static char *
398 sudo_ldap_join_uri(uri_list)
399     struct ldap_config_list_str *uri_list;
400 {
401     struct ldap_config_list_str *uri;
402     size_t len = 0;
403     char *buf, *cp;
404
405     /* Usually just a single entry. */
406     if (uri_list->next == NULL)
407         return(estrdup(uri_list->val));
408
409     for (uri = uri_list; uri != NULL; uri = uri->next) {
410         len += strlen(uri->val) + 1;
411     }
412     buf = cp = emalloc(len);
413     buf[0] = '\0';
414     for (uri = uri_list; uri != NULL; uri = uri->next) {
415         cp += strlcpy(cp, uri->val, len - (cp - buf));
416         *cp++ = ' ';
417     }
418     cp[-1] = '\0';
419     return(buf);
420 }
421 #endif /* HAVE_LDAP_INITIALIZE */
422
423 static int
424 sudo_ldap_init(ldp, host, port)
425     LDAP **ldp;
426     const char *host;
427     int port;
428 {
429     LDAP *ld = NULL;
430     int rc = LDAP_CONNECT_ERROR;
431
432 #ifdef HAVE_LDAPSSL_INIT
433     if (ldap_conf.ssl_mode == SUDO_LDAP_SSL) {
434         DPRINTF(("ldapssl_clientauth_init(%s, %s)",
435             ldap_conf.tls_certfile ? ldap_conf.tls_certfile : "NULL",
436             ldap_conf.tls_keyfile ? ldap_conf.tls_keyfile : "NULL"), 2);
437         rc = ldapssl_clientauth_init(ldap_conf.tls_certfile, NULL,
438             ldap_conf.tls_keyfile != NULL, ldap_conf.tls_keyfile, NULL);
439         /*
440          * Mozilla-derived SDKs have a bug starting with version 5.0
441          * where the path can no longer be a file name and must be a dir.
442          */
443         if (rc != LDAP_SUCCESS) {
444             char *cp;
445             if (ldap_conf.tls_certfile) {
446                 cp = strrchr(ldap_conf.tls_certfile, '/');
447                 if (cp != NULL && strncmp(cp + 1, "cert", 4) == 0)
448                     *cp = '\0';
449             }
450             if (ldap_conf.tls_keyfile) {
451                 cp = strrchr(ldap_conf.tls_keyfile, '/');
452                 if (cp != NULL && strncmp(cp + 1, "key", 3) == 0)
453                     *cp = '\0';
454             }
455             DPRINTF(("ldapssl_clientauth_init(%s, %s)",
456                 ldap_conf.tls_certfile ? ldap_conf.tls_certfile : "NULL",
457                 ldap_conf.tls_keyfile ? ldap_conf.tls_keyfile : "NULL"), 2);
458             rc = ldapssl_clientauth_init(ldap_conf.tls_certfile, NULL,
459                 ldap_conf.tls_keyfile != NULL, ldap_conf.tls_keyfile, NULL);
460             if (rc != LDAP_SUCCESS) {
461                 warningx("unable to initialize SSL cert and key db: %s",
462                     ldapssl_err2string(rc));
463                 goto done;
464             }
465         }
466
467         DPRINTF(("ldapssl_init(%s, %d, 1)", host, port), 2);
468         if ((ld = ldapssl_init(host, port, 1)) != NULL)
469             rc = LDAP_SUCCESS;
470     } else
471 #endif
472     {
473 #ifdef HAVE_LDAP_CREATE
474         DPRINTF(("ldap_create()"), 2);
475         if ((rc = ldap_create(&ld)) != LDAP_SUCCESS)
476             goto done;
477         DPRINTF(("ldap_set_option(LDAP_OPT_HOST_NAME, %s)", host), 2);
478         rc = ldap_set_option(ld, LDAP_OPT_HOST_NAME, host);
479 #else
480         DPRINTF(("ldap_init(%s, %d)", host, port), 2);
481         if ((ld = ldap_init(host, port)) != NULL)
482             rc = LDAP_SUCCESS;
483 #endif
484     }
485
486 done:
487     *ldp = ld;
488     return(rc);
489 }
490
491 /*
492  * Walk through search results and return TRUE if we have a matching
493  * netgroup, else FALSE.
494  */
495 static int
496 sudo_ldap_check_user_netgroup(ld, entry, user)
497     LDAP *ld;
498     LDAPMessage *entry;
499     char *user;
500 {
501     struct berval **bv, **p;
502     char *val;
503     int ret = FALSE;
504
505     if (!entry)
506         return(ret);
507
508     /* get the values from the entry */
509     bv = ldap_get_values_len(ld, entry, "sudoUser");
510     if (bv == NULL)
511         return(ret);
512
513     /* walk through values */
514     for (p = bv; *p != NULL && !ret; p++) {
515         val = (*p)->bv_val;
516         /* match any */
517         if (netgr_matches(val, NULL, NULL, user))
518             ret = TRUE;
519         DPRINTF(("ldap sudoUser netgroup '%s' ... %s", val,
520             ret ? "MATCH!" : "not"), 2);
521     }
522
523     ldap_value_free_len(bv);    /* cleanup */
524
525     return(ret);
526 }
527
528 /*
529  * Walk through search results and return TRUE if we have a
530  * host match, else FALSE.
531  */
532 static int
533 sudo_ldap_check_host(ld, entry)
534     LDAP *ld;
535     LDAPMessage *entry;
536 {
537     struct berval **bv, **p;
538     char *val;
539     int ret = FALSE;
540
541     if (!entry)
542         return(ret);
543
544     /* get the values from the entry */
545     bv = ldap_get_values_len(ld, entry, "sudoHost");
546     if (bv == NULL)
547         return(ret);
548
549     /* walk through values */
550     for (p = bv; *p != NULL && !ret; p++) {
551         val = (*p)->bv_val;
552         /* match any or address or netgroup or hostname */
553         if (!strcmp(val, "ALL") || addr_matches(val) ||
554             netgr_matches(val, user_host, user_shost, NULL) ||
555             hostname_matches(user_shost, user_host, val))
556             ret = TRUE;
557         DPRINTF(("ldap sudoHost '%s' ... %s", val,
558             ret ? "MATCH!" : "not"), 2);
559     }
560
561     ldap_value_free_len(bv);    /* cleanup */
562
563     return(ret);
564 }
565
566 static int
567 sudo_ldap_check_runas_user(ld, entry)
568     LDAP *ld;
569     LDAPMessage *entry;
570 {
571     struct berval **bv, **p;
572     char *val;
573     int ret = FALSE;
574
575     if (!runas_pw)
576         return(UNSPEC);
577
578     /* get the runas user from the entry */
579     bv = ldap_get_values_len(ld, entry, "sudoRunAsUser");
580     if (bv == NULL)
581         bv = ldap_get_values_len(ld, entry, "sudoRunAs"); /* old style */
582
583     /*
584      * BUG:
585      * 
586      * if runas is not specified on the command line, the only information
587      * as to which user to run as is in the runas_default option.  We should
588      * check to see if we have the local option present.  Unfortunately we
589      * don't parse these options until after this routine says yes or no.
590      * The query has already returned, so we could peek at the attribute
591      * values here though.
592      * 
593      * For now just require users to always use -u option unless its set
594      * in the global defaults. This behaviour is no different than the global
595      * /etc/sudoers.
596      * 
597      * Sigh - maybe add this feature later
598      */
599
600     /*
601      * If there are no runas entries, match runas_default against
602      * what the user specified on the command line.
603      */
604     if (bv == NULL)
605         return(!strcasecmp(runas_pw->pw_name, def_runas_default));
606
607     /* walk through values returned, looking for a match */
608     for (p = bv; *p != NULL && !ret; p++) {
609         val = (*p)->bv_val;
610         switch (val[0]) {
611         case '+':
612             if (netgr_matches(val, NULL, NULL, runas_pw->pw_name))
613                 ret = TRUE;
614             break;
615         case '%':
616             if (usergr_matches(val, runas_pw->pw_name, runas_pw))
617                 ret = TRUE;
618             break;
619         case 'A':
620             if (strcmp(val, "ALL") == 0) {
621                 ret = TRUE;
622                 break;
623             }
624             /* FALLTHROUGH */
625         default:
626             if (strcasecmp(val, runas_pw->pw_name) == 0)
627                 ret = TRUE;
628             break;
629         }
630         DPRINTF(("ldap sudoRunAsUser '%s' ... %s", val,
631             ret ? "MATCH!" : "not"), 2);
632     }
633
634     ldap_value_free_len(bv);    /* cleanup */
635
636     return(ret);
637 }
638
639 static int
640 sudo_ldap_check_runas_group(ld, entry)
641     LDAP *ld;
642     LDAPMessage *entry;
643 {
644     struct berval **bv, **p;
645     char *val;
646     int ret = FALSE;
647
648     /* runas_gr is only set if the user specified the -g flag */
649     if (!runas_gr)
650         return(UNSPEC);
651
652     /* get the values from the entry */
653     bv = ldap_get_values_len(ld, entry, "sudoRunAsGroup");
654     if (bv == NULL)
655         return(ret);
656
657     /* walk through values returned, looking for a match */
658     for (p = bv; *p != NULL && !ret; p++) {
659         val = (*p)->bv_val;
660         if (strcmp(val, "ALL") == 0 || group_matches(val, runas_gr))
661             ret = TRUE;
662         DPRINTF(("ldap sudoRunAsGroup '%s' ... %s", val,
663             ret ? "MATCH!" : "not"), 2);
664     }
665
666     ldap_value_free_len(bv);    /* cleanup */
667
668     return(ret);
669 }
670
671 /*
672  * Walk through search results and return TRUE if we have a runas match,
673  * else FALSE.  RunAs info is optional.
674  */
675 static int
676 sudo_ldap_check_runas(ld, entry)
677     LDAP *ld;
678     LDAPMessage *entry;
679 {
680     int ret;
681
682     if (!entry)
683         return(FALSE);
684
685     ret = sudo_ldap_check_runas_user(ld, entry) != FALSE &&
686         sudo_ldap_check_runas_group(ld, entry) != FALSE;
687
688     return(ret);
689 }
690
691 /*
692  * Walk through search results and return TRUE if we have a command match,
693  * FALSE if disallowed and UNSPEC if not matched.
694  */
695 static int
696 sudo_ldap_check_command(ld, entry, setenv_implied)
697     LDAP *ld;
698     LDAPMessage *entry;
699     int *setenv_implied;
700 {
701     struct berval **bv, **p;
702     char *allowed_cmnd, *allowed_args, *val;
703     int foundbang, ret = UNSPEC;
704
705     if (!entry)
706         return(ret);
707
708     bv = ldap_get_values_len(ld, entry, "sudoCommand");
709     if (bv == NULL)
710         return(ret);
711
712     for (p = bv; *p != NULL && ret != FALSE; p++) {
713         val = (*p)->bv_val;
714         /* Match against ALL ? */
715         if (!strcmp(val, "ALL")) {
716             ret = TRUE;
717             if (setenv_implied != NULL)
718                 *setenv_implied = TRUE;
719             DPRINTF(("ldap sudoCommand '%s' ... MATCH!", val), 2);
720             continue;
721         }
722
723         /* check for !command */
724         if (*val == '!') {
725             foundbang = TRUE;
726             allowed_cmnd = estrdup(1 + val);    /* !command */
727         } else {
728             foundbang = FALSE;
729             allowed_cmnd = estrdup(val);        /* command */
730         }
731
732         /* split optional args away from command */
733         allowed_args = strchr(allowed_cmnd, ' ');
734         if (allowed_args)
735             *allowed_args++ = '\0';
736
737         /* check the command like normal */
738         if (command_matches(allowed_cmnd, allowed_args)) {
739             /*
740              * If allowed (no bang) set ret but keep on checking.
741              * If disallowed (bang), exit loop.
742              */
743             ret = foundbang ? FALSE : TRUE;
744         }
745         DPRINTF(("ldap sudoCommand '%s' ... %s", val,
746             ret == TRUE ? "MATCH!" : "not"), 2);
747
748         efree(allowed_cmnd);    /* cleanup */
749     }
750
751     ldap_value_free_len(bv);    /* more cleanup */
752
753     return(ret);
754 }
755
756 /*
757  * Search for boolean "option" in sudoOption.
758  * Returns TRUE if found and allowed, FALSE if negated, else UNSPEC.
759  */
760 static int
761 sudo_ldap_check_bool(ld, entry, option)
762     LDAP *ld;
763     LDAPMessage *entry;
764     char *option;
765 {
766     struct berval **bv, **p;
767     char ch, *var;
768     int ret = UNSPEC;
769
770     if (entry == NULL)
771         return(UNSPEC);
772
773     bv = ldap_get_values_len(ld, entry, "sudoOption");
774     if (bv == NULL)
775         return(ret);
776
777     /* walk through options */
778     for (p = bv; *p != NULL; p++) {
779         var = (*p)->bv_val;;
780         DPRINTF(("ldap sudoOption: '%s'", var), 2);
781
782         if ((ch = *var) == '!')
783             var++;
784         if (strcmp(var, option) == 0)
785             ret = (ch != '!');
786     }
787
788     ldap_value_free_len(bv);
789
790     return(ret);
791 }
792
793 /*
794  * Read sudoOption and modify the defaults as we go.  This is used once
795  * from the cn=defaults entry and also once when a final sudoRole is matched.
796  */
797 static void
798 sudo_ldap_parse_options(ld, entry)
799     LDAP *ld;
800     LDAPMessage *entry;
801 {
802     struct berval **bv, **p;
803     char op, *var, *val;
804
805     if (entry == NULL)
806         return;
807
808     bv = ldap_get_values_len(ld, entry, "sudoOption");
809     if (bv == NULL)
810         return;
811
812     /* walk through options */
813     for (p = bv; *p != NULL; p++) {
814         var = estrdup((*p)->bv_val);
815         DPRINTF(("ldap sudoOption: '%s'", var), 2);
816
817         /* check for equals sign past first char */
818         val = strchr(var, '=');
819         if (val > var) {
820             *val++ = '\0';      /* split on = and truncate var */
821             op = *(val - 2);    /* peek for += or -= cases */
822             if (op == '+' || op == '-') {
823                 *(val - 2) = '\0';      /* found, remove extra char */
824                 /* case var+=val or var-=val */
825                 set_default(var, val, (int) op);
826             } else {
827                 /* case var=val */
828                 set_default(var, val, TRUE);
829             }
830         } else if (*var == '!') {
831             /* case !var Boolean False */
832             set_default(var + 1, NULL, FALSE);
833         } else {
834             /* case var Boolean True */
835             set_default(var, NULL, TRUE);
836         }
837         efree(var);
838     }
839
840     ldap_value_free_len(bv);
841 }
842
843 /*
844  * builds together a filter to check against ldap
845  */
846 static char *
847 sudo_ldap_build_pass1(pw)
848     struct passwd *pw;
849 {
850     struct group *grp;
851     size_t sz;
852     char *buf;
853     int i;
854
855     /* Start with (|(sudoUser=USERNAME)(sudoUser=ALL)) + NUL */
856     sz = 29 + strlen(pw->pw_name);
857
858     /* Add space for groups */
859     if ((grp = sudo_getgrgid(pw->pw_gid)) != NULL)
860         sz += 12 + strlen(grp->gr_name);        /* primary group */
861     for (i = 0; i < user_ngroups; i++) {
862         if (user_groups[i] == pw->pw_gid)
863             continue;
864         if ((grp = sudo_getgrgid(user_groups[i])) != NULL)
865             sz += 12 + strlen(grp->gr_name);    /* supplementary group */
866     }
867     buf = emalloc(sz);
868
869     /* Global OR + sudoUser=user_name filter */
870     (void) strlcpy(buf, "(|(sudoUser=", sz);
871     (void) strlcat(buf, pw->pw_name, sz);
872     (void) strlcat(buf, ")", sz);
873
874     /* Append primary group */
875     if ((grp = sudo_getgrgid(pw->pw_gid)) != NULL) {
876         (void) strlcat(buf, "(sudoUser=%", sz);
877         (void) strlcat(buf, grp->gr_name, sz);
878         (void) strlcat(buf, ")", sz);
879     }
880
881     /* Append supplementary groups */
882     for (i = 0; i < user_ngroups; i++) {
883         if (user_groups[i] == pw->pw_gid)
884             continue;
885         if ((grp = sudo_getgrgid(user_groups[i])) != NULL) {
886             (void) strlcat(buf, "(sudoUser=%", sz);
887             (void) strlcat(buf, grp->gr_name, sz);
888             (void) strlcat(buf, ")", sz);
889         }
890     }
891
892     /* Add ALL to list and end the global OR */
893     if (strlcat(buf, "(sudoUser=ALL))", sz) >= sz)
894         errorx(1, "sudo_ldap_build_pass1 allocation mismatch");
895
896     return(buf);
897 }
898
899 /*
900  * Map yes/true/on to TRUE, no/false/off to FALSE, else -1
901  */
902 static int
903 _atobool(s)
904     const char *s;
905 {
906     switch (*s) {
907         case 'y':
908         case 'Y':
909             if (strcasecmp(s, "yes") == 0)
910                 return(TRUE);
911             break;
912         case 't':
913         case 'T':
914             if (strcasecmp(s, "true") == 0)
915                 return(TRUE);
916             break;
917         case 'o':
918         case 'O':
919             if (strcasecmp(s, "on") == 0)
920                 return(TRUE);
921             if (strcasecmp(s, "off") == 0)
922                 return(FALSE);
923             break;
924         case 'n':
925         case 'N':
926             if (strcasecmp(s, "no") == 0)
927                 return(FALSE);
928             break;
929         case 'f':
930         case 'F':
931             if (strcasecmp(s, "false") == 0)
932                 return(FALSE);
933             break;
934     }
935     return(-1);
936 }
937
938 static void
939 sudo_ldap_read_secret(path)
940     const char *path;
941 {
942     FILE *fp;
943     char buf[LINE_MAX], *cp;
944
945     if ((fp = fopen(_PATH_LDAP_SECRET, "r")) != NULL) {
946         if (fgets(buf, sizeof(buf), fp) != NULL) {
947             if ((cp = strchr(buf, '\n')) != NULL)
948                 *cp = '\0';
949             /* copy to bindpw and binddn */
950             efree(ldap_conf.bindpw);
951             ldap_conf.bindpw = estrdup(buf);
952             efree(ldap_conf.binddn);
953             ldap_conf.binddn = ldap_conf.rootbinddn;
954             ldap_conf.rootbinddn = NULL;
955         }
956         fclose(fp);
957     }
958 }
959
960 static int
961 sudo_ldap_read_config()
962 {
963     FILE *fp;
964     char *cp, *keyword, *value;
965     struct ldap_config_table *cur;
966
967     /* defaults */
968     ldap_conf.version = 3;
969     ldap_conf.port = -1;
970     ldap_conf.tls_checkpeer = -1;
971     ldap_conf.timelimit = -1;
972     ldap_conf.bind_timelimit = -1;
973     ldap_conf.use_sasl = -1;
974     ldap_conf.rootuse_sasl = -1;
975
976     if ((fp = fopen(_PATH_LDAP_CONF, "r")) == NULL)
977         return(FALSE);
978
979     while ((cp = sudo_parseln(fp)) != NULL) {
980         if (*cp == '\0')
981             continue;           /* skip empty line */
982
983         /* split into keyword and value */
984         keyword = cp;
985         while (*cp && !isblank((unsigned char) *cp))
986             cp++;
987         if (*cp)
988             *cp++ = '\0';       /* terminate keyword */
989
990         /* skip whitespace before value */
991         while (isblank((unsigned char) *cp))
992             cp++;
993         value = cp;
994
995         /* Look up keyword in config table. */
996         for (cur = ldap_conf_table; cur->conf_str != NULL; cur++) {
997             if (strcasecmp(keyword, cur->conf_str) == 0) {
998                 switch (cur->type) {
999                 case CONF_BOOL:
1000                     *(int *)(cur->valp) = _atobool(value);
1001                     break;
1002                 case CONF_INT:
1003                     *(int *)(cur->valp) = atoi(value);
1004                     break;
1005                 case CONF_STR:
1006                     efree(*(char **)(cur->valp));
1007                     *(char **)(cur->valp) = estrdup(value);
1008                     break;
1009                 case CONF_LIST_STR:
1010                     {
1011                         struct ldap_config_list_str **p;
1012                         size_t len = strlen(value);
1013
1014                         if (len > 0) {
1015                             p = (struct ldap_config_list_str **)cur->valp;
1016                             while (*p != NULL)
1017                                 p = &(*p)->next;
1018                             *p = emalloc(sizeof(struct ldap_config_list_str) + len);
1019                             memcpy((*p)->val, value, len + 1);
1020                             (*p)->next = NULL;
1021                         }
1022                     }
1023                     break;
1024                 }
1025                 break;
1026             }
1027         }
1028     }
1029     fclose(fp);
1030
1031     if (!ldap_conf.host)
1032         ldap_conf.host = estrdup("localhost");
1033
1034     if (ldap_conf.bind_timelimit > 0)
1035         ldap_conf.bind_timelimit *= 1000;       /* convert to ms */
1036
1037     if (ldap_conf.debug > 1) {
1038         fprintf(stderr, "LDAP Config Summary\n");
1039         fprintf(stderr, "===================\n");
1040         if (ldap_conf.uri) {
1041             struct ldap_config_list_str *uri = ldap_conf.uri;
1042
1043             do {
1044                 fprintf(stderr, "uri              %s\n", uri->val);
1045             } while ((uri = uri->next) != NULL);
1046         } else {
1047             fprintf(stderr, "host             %s\n", ldap_conf.host ?
1048                 ldap_conf.host : "(NONE)");
1049             fprintf(stderr, "port             %d\n", ldap_conf.port);
1050         }
1051         fprintf(stderr, "ldap_version     %d\n", ldap_conf.version);
1052         if (ldap_conf.base) {
1053             struct ldap_config_list_str *base = ldap_conf.base;
1054
1055             do {
1056                 fprintf(stderr, "sudoers_base     %s\n", base->val);
1057             } while ((base = base->next) != NULL);
1058         } else {
1059             fprintf(stderr, "sudoers_base     %s\n",
1060                 "(NONE) <---Sudo will ignore ldap)");
1061         }
1062         fprintf(stderr, "binddn           %s\n", ldap_conf.binddn ?
1063             ldap_conf.binddn : "(anonymous)");
1064         fprintf(stderr, "bindpw           %s\n", ldap_conf.bindpw ?
1065             ldap_conf.bindpw : "(anonymous)");
1066         if (ldap_conf.bind_timelimit > 0)
1067             fprintf(stderr, "bind_timelimit   %d\n", ldap_conf.bind_timelimit);
1068         if (ldap_conf.timelimit > 0)
1069             fprintf(stderr, "timelimit        %d\n", ldap_conf.timelimit);
1070         fprintf(stderr, "ssl              %s\n", ldap_conf.ssl ?
1071             ldap_conf.ssl : "(no)");
1072         if (ldap_conf.tls_checkpeer != -1)
1073             fprintf(stderr, "tls_checkpeer    %s\n", ldap_conf.tls_checkpeer ?
1074                 "(yes)" : "(no)");
1075         if (ldap_conf.tls_cacertfile != NULL)
1076             fprintf(stderr, "tls_cacertfile   %s\n", ldap_conf.tls_cacertfile);
1077         if (ldap_conf.tls_cacertdir != NULL)
1078             fprintf(stderr, "tls_cacertdir    %s\n", ldap_conf.tls_cacertdir);
1079         if (ldap_conf.tls_random_file != NULL)
1080             fprintf(stderr, "tls_random_file  %s\n", ldap_conf.tls_random_file);
1081         if (ldap_conf.tls_cipher_suite != NULL)
1082             fprintf(stderr, "tls_cipher_suite %s\n", ldap_conf.tls_cipher_suite);
1083         if (ldap_conf.tls_certfile != NULL)
1084             fprintf(stderr, "tls_certfile     %s\n", ldap_conf.tls_certfile);
1085         if (ldap_conf.tls_keyfile != NULL)
1086             fprintf(stderr, "tls_keyfile      %s\n", ldap_conf.tls_keyfile);
1087 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
1088         if (ldap_conf.use_sasl != -1) {
1089             fprintf(stderr, "use_sasl         %s\n",
1090                 ldap_conf.use_sasl ? "yes" : "no");
1091             fprintf(stderr, "sasl_auth_id     %s\n", ldap_conf.sasl_auth_id ?
1092                 ldap_conf.sasl_auth_id : "(NONE)");
1093             fprintf(stderr, "rootuse_sasl     %d\n", ldap_conf.rootuse_sasl);
1094             fprintf(stderr, "rootsasl_auth_id %s\n", ldap_conf.rootsasl_auth_id ?
1095                 ldap_conf.rootsasl_auth_id : "(NONE)");
1096             fprintf(stderr, "sasl_secprops    %s\n", ldap_conf.sasl_secprops ?
1097                 ldap_conf.sasl_secprops : "(NONE)");
1098             fprintf(stderr, "krb5_ccname      %s\n", ldap_conf.krb5_ccname ?
1099                 ldap_conf.krb5_ccname : "(NONE)");
1100         }
1101 #endif
1102         fprintf(stderr, "===================\n");
1103     }
1104     if (!ldap_conf.base)
1105         return(FALSE);          /* if no base is defined, ignore LDAP */
1106
1107     /*
1108      * Interpret SSL option
1109      */
1110     if (ldap_conf.ssl != NULL) {
1111         if (strcasecmp(ldap_conf.ssl, "start_tls") == 0)
1112             ldap_conf.ssl_mode = SUDO_LDAP_STARTTLS;
1113         else if (_atobool(ldap_conf.ssl))
1114             ldap_conf.ssl_mode = SUDO_LDAP_SSL;
1115     }
1116
1117 #if defined(HAVE_LDAPSSL_SET_STRENGTH) && !defined(LDAP_OPT_X_TLS_REQUIRE_CERT)
1118     if (ldap_conf.tls_checkpeer != -1) {
1119         ldapssl_set_strength(NULL,
1120             ldap_conf.tls_checkpeer ? LDAPSSL_AUTH_CERT : LDAPSSL_AUTH_WEAK);
1121     }
1122 #endif
1123
1124 #ifndef HAVE_LDAP_INITIALIZE
1125     /* Convert uri list to host list if no ldap_initialize(). */
1126     if (ldap_conf.uri) {
1127         struct ldap_config_list_str *uri = ldap_conf.uri;
1128         if (sudo_ldap_parse_uri(uri) != 0)
1129             return(FALSE);
1130         do {
1131             ldap_conf.uri = uri->next;
1132             efree(uri);
1133         } while ((uri = ldap_conf.uri));
1134         ldap_conf.port = LDAP_PORT;
1135     }
1136 #endif
1137
1138     if (!ldap_conf.uri) {
1139         /* Use port 389 for plaintext LDAP and port 636 for SSL LDAP */
1140         if (ldap_conf.port < 0)
1141             ldap_conf.port =
1142                 ldap_conf.ssl_mode == SUDO_LDAP_SSL ? LDAPS_PORT : LDAP_PORT;
1143
1144 #ifdef HAVE_LDAP_CREATE
1145         /*
1146          * Cannot specify port directly to ldap_create(), each host must
1147          * include :port to override the default.
1148          */
1149         if (ldap_conf.port != LDAP_PORT)
1150             sudo_ldap_conf_add_ports();
1151 #endif
1152     }
1153
1154     /* If rootbinddn set, read in /etc/ldap.secret if it exists. */
1155     if (ldap_conf.rootbinddn)
1156         sudo_ldap_read_secret(_PATH_LDAP_SECRET);
1157
1158 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
1159     /*
1160      * Make sure we can open the file specified by krb5_ccname.
1161      */
1162     if (ldap_conf.krb5_ccname != NULL) {
1163         if (strncasecmp(ldap_conf.krb5_ccname, "FILE:", 5) == 0 ||
1164             strncasecmp(ldap_conf.krb5_ccname, "WRFILE:", 7) == 0) {
1165             value = ldap_conf.krb5_ccname +
1166                 (ldap_conf.krb5_ccname[4] == ':' ? 5 : 7);
1167             if ((fp = fopen(value, "r")) != NULL) {
1168                 DPRINTF(("using krb5 credential cache: %s", value), 1);
1169                 fclose(fp);
1170             } else {
1171                 /* Can't open it, just ignore the entry. */
1172                 DPRINTF(("unable to open krb5 credential cache: %s", value), 1);
1173                 efree(ldap_conf.krb5_ccname);
1174                 ldap_conf.krb5_ccname = NULL;
1175             }
1176         }
1177     }
1178 #endif
1179     return(TRUE);
1180 }
1181
1182 /*
1183  * Extract the dn from an entry and return the first rdn from it.
1184  */
1185 static char *
1186 sudo_ldap_get_first_rdn(ld, entry)
1187     LDAP *ld;
1188     LDAPMessage *entry;
1189 {
1190 #ifdef HAVE_LDAP_STR2DN
1191     char *dn, *rdn = NULL;
1192     LDAPDN tmpDN;
1193
1194     if ((dn = ldap_get_dn(ld, entry)) == NULL)
1195         return(NULL);
1196     if (ldap_str2dn(dn, &tmpDN, LDAP_DN_FORMAT_LDAP) == LDAP_SUCCESS) {
1197         ldap_rdn2str(tmpDN[0], &rdn, LDAP_DN_FORMAT_UFN);
1198         ldap_dnfree(tmpDN);
1199     }
1200     ldap_memfree(dn);
1201     return(rdn);
1202 #else
1203     char *dn, **edn;
1204
1205     if ((dn = ldap_get_dn(ld, entry)) == NULL)
1206         return(NULL);
1207     edn = ldap_explode_dn(dn, 1);
1208     ldap_memfree(dn);
1209     return(edn ? edn[0] : NULL);
1210 #endif
1211 }
1212
1213 /*
1214  * Fetch and display the global Options.
1215  */
1216 static int
1217 sudo_ldap_display_defaults(nss, pw, lbuf)
1218     struct sudo_nss *nss;
1219     struct passwd *pw;
1220     struct lbuf *lbuf;
1221 {
1222     struct berval **bv, **p;
1223     struct ldap_config_list_str *base;
1224     LDAP *ld = (LDAP *) nss->handle;
1225     LDAPMessage *entry, *result;
1226     char *prefix;
1227     int rc, count = 0;
1228
1229     if (ld == NULL)
1230         goto done;
1231
1232     for (base = ldap_conf.base; base != NULL; base = base->next) {
1233         result = NULL;
1234         rc = ldap_search_ext_s(ld, base->val, LDAP_SCOPE_SUBTREE,
1235             "cn=defaults", NULL, 0, NULL, NULL, NULL, 0, &result);
1236         if (rc == LDAP_SUCCESS && (entry = ldap_first_entry(ld, result))) {
1237             bv = ldap_get_values_len(ld, entry, "sudoOption");
1238             if (bv != NULL) {
1239                 if (lbuf->len == 0 || isspace((unsigned char)lbuf->buf[lbuf->len - 1]))
1240                     prefix = "    ";
1241                 else
1242                     prefix = ", ";
1243                 for (p = bv; *p != NULL; p++) {
1244                     lbuf_append(lbuf, prefix, (*p)->bv_val, NULL);
1245                     prefix = ", ";
1246                     count++;
1247                 }
1248                 ldap_value_free_len(bv);
1249             }
1250         }
1251         if (result)
1252             ldap_msgfree(result);
1253     }
1254 done:
1255     return(count);
1256 }
1257
1258 /*
1259  * STUB
1260  */
1261 static int
1262 sudo_ldap_display_bound_defaults(nss, pw, lbuf)
1263     struct sudo_nss *nss;
1264     struct passwd *pw;
1265     struct lbuf *lbuf;
1266 {
1267     return(0);
1268 }
1269
1270 /*
1271  * Print a record in the short form, ala file sudoers.
1272  */
1273 static int
1274 sudo_ldap_display_entry_short(ld, entry, lbuf)
1275     LDAP *ld;
1276     LDAPMessage *entry;
1277     struct lbuf *lbuf;
1278 {
1279     struct berval **bv, **p;
1280     int count = 0;
1281
1282     lbuf_append(lbuf, "    (", NULL);
1283
1284     /* get the RunAsUser Values from the entry */
1285     bv = ldap_get_values_len(ld, entry, "sudoRunAsUser");
1286     if (bv == NULL)
1287         bv = ldap_get_values_len(ld, entry, "sudoRunAs");
1288     if (bv != NULL) {
1289         for (p = bv; *p != NULL; p++) {
1290             if (p != bv)
1291                 lbuf_append(lbuf, ", ", NULL);
1292             lbuf_append(lbuf, (*p)->bv_val, NULL);
1293         }
1294         ldap_value_free_len(bv);
1295     } else
1296         lbuf_append(lbuf, def_runas_default, NULL);
1297
1298     /* get the RunAsGroup Values from the entry */
1299     bv = ldap_get_values_len(ld, entry, "sudoRunAsGroup");
1300     if (bv != NULL) {
1301         lbuf_append(lbuf, " : ", NULL);
1302         for (p = bv; *p != NULL; p++) {
1303             if (p != bv)
1304                 lbuf_append(lbuf, ", ", NULL);
1305             lbuf_append(lbuf, (*p)->bv_val, NULL);
1306         }
1307         ldap_value_free_len(bv);
1308     }
1309     lbuf_append(lbuf, ") ", NULL);
1310
1311     /* get the Option Values from the entry */
1312     bv = ldap_get_values_len(ld, entry, "sudoOption");
1313     if (bv != NULL) {
1314         char *cp, *tag;
1315
1316         for (p = bv; *p != NULL; p++) {
1317             cp = (*p)->bv_val;
1318             if (*cp == '!')
1319                 cp++;
1320             tag = NULL;
1321             if (strcmp(cp, "authenticate") == 0)
1322                 tag = (*p)->bv_val[0] == '!' ?
1323                     "NOPASSWD: " : "PASSWD: ";
1324             else if (strcmp(cp, "noexec") == 0)
1325                 tag = (*p)->bv_val[0] == '!' ?
1326                     "EXEC: " : "NOEXEC: ";
1327             else if (strcmp(cp, "setenv") == 0)
1328                 tag = (*p)->bv_val[0] == '!' ?
1329                     "NOSETENV: " : "SETENV: ";
1330             if (tag != NULL)
1331                 lbuf_append(lbuf, tag, NULL);
1332             /* XXX - ignores other options */
1333         }
1334         ldap_value_free_len(bv);
1335     }
1336
1337     /* get the Command Values from the entry */
1338     bv = ldap_get_values_len(ld, entry, "sudoCommand");
1339     if (bv != NULL) {
1340         for (p = bv; *p != NULL; p++) {
1341             if (p != bv)
1342                 lbuf_append(lbuf, ", ", NULL);
1343             lbuf_append(lbuf, (*p)->bv_val, NULL);
1344             count++;
1345         }
1346         ldap_value_free_len(bv);
1347     }
1348     lbuf_append(lbuf, "\n", NULL);
1349
1350     return(count);
1351 }
1352
1353 /*
1354  * Print a record in the long form.
1355  */
1356 static int
1357 sudo_ldap_display_entry_long(ld, entry, lbuf)
1358     LDAP *ld;
1359     LDAPMessage *entry;
1360     struct lbuf *lbuf;
1361 {
1362     struct berval **bv, **p;
1363     char *rdn;
1364     int count = 0;
1365
1366     /* extract the dn, only show the first rdn */
1367     rdn = sudo_ldap_get_first_rdn(ld, entry);
1368     lbuf_append(lbuf, "\nLDAP Role: ", rdn ? rdn : "UNKNOWN", "\n", NULL);
1369     if (rdn)
1370         ldap_memfree(rdn);
1371
1372     /* get the RunAsUser Values from the entry */
1373     lbuf_append(lbuf, "    RunAsUsers: ", NULL);
1374     bv = ldap_get_values_len(ld, entry, "sudoRunAsUser");
1375     if (bv == NULL)
1376         bv = ldap_get_values_len(ld, entry, "sudoRunAs");
1377     if (bv != NULL) {
1378         for (p = bv; *p != NULL; p++) {
1379             if (p != bv)
1380                 lbuf_append(lbuf, ", ", NULL);
1381             lbuf_append(lbuf, (*p)->bv_val, NULL);
1382         }
1383         ldap_value_free_len(bv);
1384     } else
1385         lbuf_append(lbuf, def_runas_default, NULL);
1386     lbuf_append(lbuf, "\n", NULL);
1387
1388     /* get the RunAsGroup Values from the entry */
1389     bv = ldap_get_values_len(ld, entry, "sudoRunAsGroup");
1390     if (bv != NULL) {
1391         lbuf_append(lbuf, "    RunAsGroups: ", NULL);
1392         for (p = bv; *p != NULL; p++) {
1393             if (p != bv)
1394                 lbuf_append(lbuf, ", ", NULL);
1395             lbuf_append(lbuf, (*p)->bv_val, NULL);
1396         }
1397         ldap_value_free_len(bv);
1398         lbuf_append(lbuf, "\n", NULL);
1399     }
1400
1401     /* get the Option Values from the entry */
1402     bv = ldap_get_values_len(ld, entry, "sudoOption");
1403     if (bv != NULL) {
1404         lbuf_append(lbuf, "    Options: ", NULL);
1405         for (p = bv; *p != NULL; p++) {
1406             if (p != bv)
1407                 lbuf_append(lbuf, ", ", NULL);
1408             lbuf_append(lbuf, (*p)->bv_val, NULL);
1409         }
1410         ldap_value_free_len(bv);
1411         lbuf_append(lbuf, "\n", NULL);
1412     }
1413
1414     /* get the Command Values from the entry */
1415     bv = ldap_get_values_len(ld, entry, "sudoCommand");
1416     if (bv != NULL) {
1417         lbuf_append(lbuf, "    Commands:\n", NULL);
1418         for (p = bv; *p != NULL; p++) {
1419             lbuf_append(lbuf, "\t", (*p)->bv_val, "\n", NULL);
1420             count++;
1421         }
1422         ldap_value_free_len(bv);
1423     }
1424
1425     return(count);
1426 }
1427
1428 /*
1429  * Like sudo_ldap_lookup(), except we just print entries.
1430  */
1431 static int
1432 sudo_ldap_display_privs(nss, pw, lbuf)
1433     struct sudo_nss *nss;
1434     struct passwd *pw;
1435     struct lbuf *lbuf;
1436 {
1437     struct ldap_config_list_str *base;
1438     LDAP *ld = (LDAP *) nss->handle;
1439     LDAPMessage *entry, *result;
1440     char *filt;
1441     int rc, do_netgr, count = 0;
1442
1443     if (ld == NULL)
1444         goto done;
1445
1446     /*
1447      * Okay - time to search for anything that matches this user
1448      * Lets limit it to only two queries of the LDAP server
1449      *
1450      * The first pass will look by the username, groups, and
1451      * the keyword ALL.  We will then inspect the results that
1452      * came back from the query.  We don't need to inspect the
1453      * sudoUser in this pass since the LDAP server already scanned
1454      * it for us.
1455      *
1456      * The second pass will return all the entries that contain
1457      * user netgroups.  Then we take the netgroups returned and
1458      * try to match them against the username.
1459      */
1460     for (do_netgr = 0; do_netgr < 2; do_netgr++) {
1461         filt = do_netgr ? estrdup("sudoUser=+*") : sudo_ldap_build_pass1(pw);
1462         DPRINTF(("ldap search '%s'", filt), 1);
1463         for (base = ldap_conf.base; base != NULL; base = base->next) {
1464             result = NULL;
1465             rc = ldap_search_ext_s(ld, base->val, LDAP_SCOPE_SUBTREE, filt,
1466                 NULL, 0, NULL, NULL, NULL, 0, &result);
1467             if (rc != LDAP_SUCCESS)
1468                 continue;       /* no entries for this pass */
1469
1470             /* print each matching entry */
1471             LDAP_FOREACH(entry, ld, result) {
1472                 if ((!do_netgr ||
1473                     sudo_ldap_check_user_netgroup(ld, entry, pw->pw_name)) &&
1474                     sudo_ldap_check_host(ld, entry)) {
1475
1476                     if (long_list)
1477                         count += sudo_ldap_display_entry_long(ld, entry, lbuf);
1478                     else
1479                         count += sudo_ldap_display_entry_short(ld, entry, lbuf);
1480                 }
1481             }
1482             ldap_msgfree(result);
1483         }
1484         efree(filt);
1485     }
1486 done:
1487     return(count);
1488 }
1489
1490 static int
1491 sudo_ldap_display_cmnd(nss, pw)
1492     struct sudo_nss *nss;
1493     struct passwd *pw;
1494 {
1495     struct ldap_config_list_str *base;
1496     LDAP *ld = (LDAP *) nss->handle;
1497     LDAPMessage *entry, *result;                /* used for searches */
1498     char *filt;                                 /* used to parse attributes */
1499     int rc, found, do_netgr;                    /* temp/final return values */
1500
1501     if (ld == NULL)
1502         return(1);
1503
1504     /*
1505      * Okay - time to search for anything that matches this user
1506      * Lets limit it to only two queries of the LDAP server
1507      *
1508      * The first pass will look by the username, groups, and
1509      * the keyword ALL.  We will then inspect the results that
1510      * came back from the query.  We don't need to inspect the
1511      * sudoUser in this pass since the LDAP server already scanned
1512      * it for us.
1513      *
1514      * The second pass will return all the entries that contain
1515      * user netgroups.  Then we take the netgroups returned and
1516      * try to match them against the username.
1517      */
1518     for (found = FALSE, do_netgr = 0; !found && do_netgr < 2; do_netgr++) {
1519         filt = do_netgr ? estrdup("sudoUser=+*") : sudo_ldap_build_pass1(pw);
1520         DPRINTF(("ldap search '%s'", filt), 1);
1521         for (base = ldap_conf.base; base != NULL; base = base->next) {
1522             result = NULL;
1523             rc = ldap_search_ext_s(ld, base->val, LDAP_SCOPE_SUBTREE, filt,
1524                 NULL, 0, NULL, NULL, NULL, 0, &result);
1525             if (rc != LDAP_SUCCESS)
1526                 continue;       /* no entries for this pass */
1527
1528             LDAP_FOREACH(entry, ld, result) {
1529                 if ((!do_netgr ||
1530                     sudo_ldap_check_user_netgroup(ld, entry, pw->pw_name)) &&
1531                     sudo_ldap_check_host(ld, entry) &&
1532                     sudo_ldap_check_command(ld, entry, NULL) &&
1533                     sudo_ldap_check_runas(ld, entry)) {
1534
1535                     found = TRUE;
1536                     break;
1537                 }
1538             }
1539             ldap_msgfree(result);
1540         }
1541         efree(filt);
1542     }
1543
1544     if (found)
1545         printf("%s%s%s\n", safe_cmnd ? safe_cmnd : user_cmnd,
1546             user_args ? " " : "", user_args ? user_args : "");
1547    return(!found);
1548 }
1549
1550 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
1551 static int
1552 sudo_ldap_sasl_interact(ld, flags, _auth_id, _interact)
1553     LDAP *ld;
1554     unsigned int flags;
1555     void *_auth_id;
1556     void *_interact;
1557 {
1558     char *auth_id = (char *)_auth_id;
1559     sasl_interact_t *interact = (sasl_interact_t *)_interact;
1560
1561     for (; interact->id != SASL_CB_LIST_END; interact++) {
1562         if (interact->id != SASL_CB_USER)
1563             return(LDAP_PARAM_ERROR);
1564
1565         if (auth_id != NULL)
1566             interact->result = auth_id;
1567         else if (interact->defresult != NULL)
1568             interact->result = interact->defresult;
1569         else
1570             interact->result = "";
1571
1572         interact->len = strlen(interact->result);
1573 #if SASL_VERSION_MAJOR < 2
1574         interact->result = estrdup(interact->result);
1575 #endif /* SASL_VERSION_MAJOR < 2 */
1576     }
1577     return(LDAP_SUCCESS);
1578 }
1579 #endif /* HAVE_LDAP_SASL_INTERACTIVE_BIND_S */
1580
1581 /*
1582  * Set LDAP options based on the config table.
1583  */
1584 static int
1585 sudo_ldap_set_options(ld)
1586     LDAP *ld;
1587 {
1588     struct ldap_config_table *cur;
1589     int rc;
1590
1591     /* Set ber options */
1592 #ifdef LBER_OPT_DEBUG_LEVEL
1593     if (ldap_conf.ldap_debug)
1594         ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &ldap_conf.ldap_debug);
1595 #endif
1596
1597     /* Set simple LDAP options */
1598     for (cur = ldap_conf_table; cur->conf_str != NULL; cur++) {
1599         LDAP *conn;
1600         int ival;
1601         char *sval;
1602
1603         if (cur->opt_val == -1)
1604             continue;
1605
1606         conn = cur->connected ? ld : NULL;
1607         switch (cur->type) {
1608         case CONF_BOOL:
1609         case CONF_INT:
1610             ival = *(int *)(cur->valp);
1611             if (ival >= 0) {
1612                 rc = ldap_set_option(conn, cur->opt_val, &ival);
1613                 if (rc != LDAP_OPT_SUCCESS) {
1614                     warningx("ldap_set_option: %s -> %d: %s",
1615                         cur->conf_str, ival, ldap_err2string(rc));
1616                     return(-1);
1617                 }
1618                 DPRINTF(("ldap_set_option: %s -> %d", cur->conf_str, ival), 1);
1619             }
1620             break;
1621         case CONF_STR:
1622             sval = *(char **)(cur->valp);
1623             if (sval != NULL) {
1624                 rc = ldap_set_option(conn, cur->opt_val, sval);
1625                 if (rc != LDAP_OPT_SUCCESS) {
1626                     warningx("ldap_set_option: %s -> %s: %s",
1627                         cur->conf_str, sval, ldap_err2string(rc));
1628                     return(-1);
1629                 }
1630                 DPRINTF(("ldap_set_option: %s -> %s", cur->conf_str, sval), 1);
1631             }
1632             break;
1633         }
1634     }
1635
1636 #ifdef LDAP_OPT_NETWORK_TIMEOUT
1637     /* Convert bind_timelimit to a timeval */
1638     if (ldap_conf.bind_timelimit > 0) {
1639         struct timeval tv;
1640         tv.tv_sec = ldap_conf.bind_timelimit / 1000;
1641         tv.tv_usec = 0;
1642         rc = ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &tv);
1643         if (rc != LDAP_OPT_SUCCESS) {
1644             warningx("ldap_set_option(NETWORK_TIMEOUT, %ld): %s",
1645                 (long)tv.tv_sec, ldap_err2string(rc));
1646             return(-1);
1647         }
1648         DPRINTF(("ldap_set_option(LDAP_OPT_NETWORK_TIMEOUT, %ld)",
1649             (long)tv.tv_sec), 1);
1650     }
1651 #endif
1652
1653 #if defined(LDAP_OPT_X_TLS) && !defined(HAVE_LDAPSSL_INIT)
1654     if (ldap_conf.ssl_mode == SUDO_LDAP_SSL) {
1655         int val = LDAP_OPT_X_TLS_HARD;
1656         rc = ldap_set_option(ld, LDAP_OPT_X_TLS, &val);
1657         if (rc != LDAP_SUCCESS) {
1658             warningx("ldap_set_option(LDAP_OPT_X_TLS, LDAP_OPT_X_TLS_HARD): %s",
1659                 ldap_err2string(rc));
1660             return(-1);
1661         }
1662         DPRINTF(("ldap_set_option(LDAP_OPT_X_TLS, LDAP_OPT_X_TLS_HARD)"), 1);
1663     }
1664 #endif
1665     return(0);
1666 }
1667
1668 /*
1669  * Connect to the LDAP server specified by ld
1670  */
1671 static int
1672 sudo_ldap_bind_s(ld)
1673     LDAP *ld;
1674 {
1675     int rc;
1676 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
1677     const char *old_ccname = user_ccname;
1678 # ifdef HAVE_GSS_KRB5_CCACHE_NAME
1679     unsigned int status;
1680 # endif
1681 #endif
1682
1683 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
1684     if (ldap_conf.rootuse_sasl == TRUE ||
1685         (ldap_conf.rootuse_sasl != FALSE && ldap_conf.use_sasl == TRUE)) {
1686         void *auth_id = ldap_conf.rootsasl_auth_id ?
1687             ldap_conf.rootsasl_auth_id : ldap_conf.sasl_auth_id;
1688
1689         if (ldap_conf.krb5_ccname != NULL) {
1690 # ifdef HAVE_GSS_KRB5_CCACHE_NAME
1691             if (gss_krb5_ccache_name(&status, ldap_conf.krb5_ccname, &old_ccname)
1692                 != GSS_S_COMPLETE) {
1693                 old_ccname = NULL;
1694                 DPRINTF(("gss_krb5_ccache_name() failed: %d", status), 1);
1695             }
1696 # else
1697             setenv("KRB5CCNAME", ldap_conf.krb5_ccname, TRUE);
1698 # endif
1699         }
1700         rc = ldap_sasl_interactive_bind_s(ld, ldap_conf.binddn, "GSSAPI",
1701             NULL, NULL, LDAP_SASL_QUIET, sudo_ldap_sasl_interact, auth_id);
1702         if (ldap_conf.krb5_ccname != NULL) {
1703 # ifdef HAVE_GSS_KRB5_CCACHE_NAME
1704             if (gss_krb5_ccache_name(&status, old_ccname, NULL) != GSS_S_COMPLETE)
1705                     DPRINTF(("gss_krb5_ccache_name() failed: %d", status), 1);
1706 # else
1707             if (old_ccname != NULL)
1708                 setenv("KRB5CCNAME", old_ccname, TRUE);
1709             else
1710                 unsetenv("KRB5CCNAME");
1711 # endif
1712         }
1713         if (rc != LDAP_SUCCESS) {
1714             warningx("ldap_sasl_interactive_bind_s(): %s", ldap_err2string(rc));
1715             return(-1);
1716         }
1717         DPRINTF(("ldap_sasl_interactive_bind_s() ok"), 1);
1718     } else
1719 #endif /* HAVE_LDAP_SASL_INTERACTIVE_BIND_S */
1720 #ifdef HAVE_LDAP_SASL_BIND_S
1721     {
1722         struct berval bv;
1723
1724         bv.bv_val = ldap_conf.bindpw ? ldap_conf.bindpw : "";
1725         bv.bv_len = strlen(bv.bv_val);
1726
1727         rc = ldap_sasl_bind_s(ld, ldap_conf.binddn, LDAP_SASL_SIMPLE, &bv,
1728             NULL, NULL, NULL);
1729         if (rc != LDAP_SUCCESS) {
1730             warningx("ldap_sasl_bind_s(): %s", ldap_err2string(rc));
1731             return(-1);
1732         }
1733         DPRINTF(("ldap_sasl_bind_s() ok"), 1);
1734     }
1735 #else
1736     {
1737         rc = ldap_simple_bind_s(ld, ldap_conf.binddn, ldap_conf.bindpw);
1738         if (rc != LDAP_SUCCESS) {
1739             warningx("ldap_simple_bind_s(): %s", ldap_err2string(rc));
1740             return(-1);
1741         }
1742         DPRINTF(("ldap_simple_bind_s() ok"), 1);
1743     }
1744 #endif
1745     return(0);
1746 }
1747
1748 /*
1749  * Open a connection to the LDAP server.
1750  * Returns 0 on success and non-zero on failure.
1751  */
1752 static int
1753 sudo_ldap_open(nss)
1754     struct sudo_nss *nss;
1755 {
1756     LDAP *ld;
1757     int rc, ldapnoinit = FALSE;
1758
1759     if (!sudo_ldap_read_config())
1760         return(-1);
1761
1762     /* Prevent reading of user ldaprc and system defaults. */
1763     if (getenv("LDAPNOINIT") == NULL) {
1764         ldapnoinit = TRUE;
1765         setenv("LDAPNOINIT", "1", TRUE);
1766     }
1767
1768     /* Connect to LDAP server */
1769 #ifdef HAVE_LDAP_INITIALIZE
1770     if (ldap_conf.uri != NULL) {
1771         char *buf = sudo_ldap_join_uri(ldap_conf.uri);
1772         DPRINTF(("ldap_initialize(ld, %s)", buf), 2);
1773         rc = ldap_initialize(&ld, buf);
1774         efree(buf);
1775     } else
1776 #endif
1777         rc = sudo_ldap_init(&ld, ldap_conf.host, ldap_conf.port);
1778     if (rc != LDAP_SUCCESS) {
1779         warningx("unable to initialize LDAP: %s", ldap_err2string(rc));
1780         return(-1);
1781     }
1782
1783     if (ldapnoinit)
1784         unsetenv("LDAPNOINIT");
1785
1786     /* Set LDAP options */
1787     if (sudo_ldap_set_options(ld) < 0)
1788         return(-1);
1789
1790     if (ldap_conf.ssl_mode == SUDO_LDAP_STARTTLS) {
1791 #if defined(HAVE_LDAP_START_TLS_S)
1792         rc = ldap_start_tls_s(ld, NULL, NULL);
1793         if (rc != LDAP_SUCCESS) {
1794             warningx("ldap_start_tls_s(): %s", ldap_err2string(rc));
1795             return(-1);
1796         }
1797         DPRINTF(("ldap_start_tls_s() ok"), 1);
1798 #elif defined(HAVE_LDAP_SSL_CLIENT_INIT) && defined(HAVE_LDAP_START_TLS_S_NP)
1799         if (ldap_ssl_client_init(NULL, NULL, 0, &rc) != LDAP_SUCCESS) {
1800             warningx("ldap_ssl_client_init(): %s", ldap_err2string(rc));
1801             return(-1);
1802         }
1803         rc = ldap_start_tls_s_np(ld, NULL);
1804         if (rc != LDAP_SUCCESS) {
1805             warningx("ldap_start_tls_s_np(): %s", ldap_err2string(rc));
1806             return(-1);
1807         }
1808         DPRINTF(("ldap_start_tls_s_np() ok"), 1);
1809 #else
1810         warningx("start_tls specified but LDAP libs do not support ldap_start_tls_s() or ldap_start_tls_s_np()");
1811 #endif /* !HAVE_LDAP_START_TLS_S && !HAVE_LDAP_START_TLS_S_NP */
1812     }
1813
1814     /* Actually connect */
1815     if (sudo_ldap_bind_s(ld) != 0)
1816         return(-1);
1817
1818     nss->handle = ld;
1819     return(0);
1820 }
1821
1822 static int
1823 sudo_ldap_setdefs(nss)
1824     struct sudo_nss *nss;
1825 {
1826     struct ldap_config_list_str *base;
1827     LDAP *ld = (LDAP *) nss->handle;
1828     LDAPMessage *entry, *result;                 /* used for searches */
1829     int rc;                                      /* temp return value */
1830
1831     if (ld == NULL)
1832         return(-1);
1833
1834     for (base = ldap_conf.base; base != NULL; base = base->next) {
1835         result = NULL;
1836         rc = ldap_search_ext_s(ld, base->val, LDAP_SCOPE_SUBTREE,
1837             "cn=defaults", NULL, 0, NULL, NULL, NULL, 0, &result);
1838         if (rc == LDAP_SUCCESS && (entry = ldap_first_entry(ld, result))) {
1839             DPRINTF(("found:%s", ldap_get_dn(ld, entry)), 1);
1840             sudo_ldap_parse_options(ld, entry);
1841         } else
1842             DPRINTF(("no default options found in %s", base->val), 1);
1843
1844         if (result)
1845             ldap_msgfree(result);
1846     }
1847
1848     return(0);
1849 }
1850
1851 /*
1852  * like sudoers_lookup() - only LDAP style
1853  */
1854 static int
1855 sudo_ldap_lookup(nss, ret, pwflag)
1856     struct sudo_nss *nss;
1857     int ret;
1858     int pwflag;
1859 {
1860     struct ldap_config_list_str *base;
1861     LDAP *ld = (LDAP *) nss->handle;
1862     LDAPMessage *entry, *result;
1863     char *filt;
1864     int do_netgr, rc, matched;
1865     int setenv_implied;
1866     int ldap_user_matches = FALSE, ldap_host_matches = FALSE;
1867     struct passwd *pw = list_pw ? list_pw : sudo_user.pw;
1868
1869     if (ld == NULL)
1870         return(ret);
1871
1872     if (pwflag) {
1873         int doauth = UNSPEC;
1874         enum def_tupple pwcheck = 
1875             (pwflag == -1) ? never : sudo_defs_table[pwflag].sd_un.tuple;
1876
1877         for (matched = 0, do_netgr = 0; !matched && do_netgr < 2; do_netgr++) {
1878             filt = do_netgr ? estrdup("sudoUser=+*") : sudo_ldap_build_pass1(pw);
1879             for (base = ldap_conf.base; base != NULL; base = base->next) {
1880                 result = NULL;
1881                 rc = ldap_search_ext_s(ld, base->val, LDAP_SCOPE_SUBTREE, filt,
1882                     NULL, 0, NULL, NULL, NULL, 0, &result);
1883                 if (rc != LDAP_SUCCESS)
1884                     continue;
1885
1886                 LDAP_FOREACH(entry, ld, result) {
1887                     /* only verify netgroup matches in pass 2 */
1888                     if (do_netgr && !sudo_ldap_check_user_netgroup(ld, entry, pw->pw_name))
1889                         continue;
1890
1891                     ldap_user_matches = TRUE;
1892                     if (sudo_ldap_check_host(ld, entry)) {
1893                         ldap_host_matches = TRUE;
1894                         if ((pwcheck == any && doauth != FALSE) ||
1895                             (pwcheck == all && doauth == FALSE))
1896                             doauth = sudo_ldap_check_bool(ld, entry, "authenticate");
1897                         /* Only check the command when listing another user. */
1898                         if (user_uid == 0 || list_pw == NULL ||
1899                             user_uid == list_pw->pw_uid ||
1900                             sudo_ldap_check_command(ld, entry, NULL)) {
1901                             matched = 1;
1902                             break;      /* end foreach */
1903                         }
1904                     }
1905                 }
1906                 ldap_msgfree(result);
1907             }
1908             efree(filt);
1909         }
1910         if (matched || user_uid == 0) {
1911             SET(ret, VALIDATE_OK);
1912             CLR(ret, VALIDATE_NOT_OK);
1913             if (def_authenticate) {
1914                 switch (pwcheck) {
1915                     case always:
1916                         SET(ret, FLAG_CHECK_USER);
1917                         break;
1918                     case all:
1919                     case any:
1920                         if (doauth == FALSE)
1921                             def_authenticate = FALSE;
1922                         break;
1923                     case never:
1924                         def_authenticate = FALSE;
1925                         break;
1926                     default:
1927                         break;
1928                 }
1929             }
1930         }
1931         goto done;
1932     }
1933
1934     /*
1935      * Okay - time to search for anything that matches this user
1936      * Lets limit it to only two queries of the LDAP server
1937      *
1938      * The first pass will look by the username, groups, and
1939      * the keyword ALL.  We will then inspect the results that
1940      * came back from the query.  We don't need to inspect the
1941      * sudoUser in this pass since the LDAP server already scanned
1942      * it for us.
1943      *
1944      * The second pass will return all the entries that contain
1945      * user netgroups.  Then we take the netgroups returned and
1946      * try to match them against the username.
1947      */
1948     setenv_implied = FALSE;
1949     for (matched = 0, do_netgr = 0; !matched && do_netgr < 2; do_netgr++) {
1950         filt = do_netgr ? estrdup("sudoUser=+*") : sudo_ldap_build_pass1(pw);
1951         DPRINTF(("ldap search '%s'", filt), 1);
1952         for (base = ldap_conf.base; base != NULL; base = base->next) {
1953             result = NULL;
1954             rc = ldap_search_ext_s(ld, base->val, LDAP_SCOPE_SUBTREE, filt,
1955                 NULL, 0, NULL, NULL, NULL, 0, &result);
1956             if (rc != LDAP_SUCCESS) {
1957                 DPRINTF(("nothing found for '%s'", filt), 1);
1958                 continue;
1959             }
1960
1961             /* parse each entry returned from this most recent search */
1962             LDAP_FOREACH(entry, ld, result) {
1963                 DPRINTF(("found:%s", ldap_get_dn(ld, entry)), 1);
1964                 if (
1965                 /* first verify user netgroup matches - only if in pass 2 */
1966                     (!do_netgr || sudo_ldap_check_user_netgroup(ld, entry, pw->pw_name)) &&
1967                 /* remember that user matched */
1968                     (ldap_user_matches = TRUE) &&
1969                 /* verify host match */
1970                     sudo_ldap_check_host(ld, entry) &&
1971                 /* remember that host matched */
1972                     (ldap_host_matches = TRUE) &&
1973                 /* verify runas match */
1974                     sudo_ldap_check_runas(ld, entry) &&
1975                 /* verify command match */
1976                     (rc = sudo_ldap_check_command(ld, entry, &setenv_implied)) != UNSPEC
1977                     ) {
1978                     /* We have a match! */
1979                     DPRINTF(("Command %sallowed", rc == TRUE ? "" : "NOT "), 1);
1980                     matched = TRUE;
1981                     if (rc == TRUE) {
1982                         /* pick up any options */
1983                         if (setenv_implied)
1984                             def_setenv = TRUE;
1985                         sudo_ldap_parse_options(ld, entry);
1986 #ifdef HAVE_SELINUX
1987                         /* Set role and type if not specified on command line. */
1988                         if (user_role == NULL)
1989                             user_role = def_role;
1990                         if (user_type == NULL)
1991                             user_type = def_type;
1992 #endif /* HAVE_SELINUX */
1993                         /* make sure we don't reenter loop */
1994                         SET(ret, VALIDATE_OK);
1995                         CLR(ret, VALIDATE_NOT_OK);
1996                     } else {
1997                         SET(ret, VALIDATE_NOT_OK);
1998                         CLR(ret, VALIDATE_OK);
1999                     }
2000                     /* break from inside for loop */
2001                     break;
2002                 }
2003             }
2004             ldap_msgfree(result);
2005         }
2006         efree(filt);
2007     }
2008
2009 done:
2010     DPRINTF(("user_matches=%d", ldap_user_matches), 1);
2011     DPRINTF(("host_matches=%d", ldap_host_matches), 1);
2012
2013     if (!ISSET(ret, VALIDATE_OK)) {
2014         /* we do not have a match */
2015         if (pwflag && list_pw == NULL)
2016             SET(ret, FLAG_NO_CHECK);
2017     }
2018     if (ldap_user_matches)
2019         CLR(ret, FLAG_NO_USER);
2020     if (ldap_host_matches)
2021         CLR(ret, FLAG_NO_HOST);
2022     DPRINTF(("sudo_ldap_lookup(%d)=0x%02x", pwflag, ret), 1);
2023
2024     return(ret);
2025 }
2026
2027 /*
2028  * shut down LDAP connection
2029  */
2030 static int
2031 sudo_ldap_close(nss)
2032     struct sudo_nss *nss;
2033 {
2034     if (nss->handle != NULL) {
2035         ldap_unbind_ext_s((LDAP *) nss->handle, NULL, NULL);
2036         nss->handle = NULL;
2037     }
2038     return(0);
2039 }
2040
2041 /*
2042  * STUB
2043  */
2044 static int
2045 sudo_ldap_parse(nss)
2046     struct sudo_nss *nss;
2047 {
2048     return(0);
2049 }