Imported Upstream version 1.7.4
[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         return(-1);
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     return(count);
1255 }
1256
1257 /*
1258  * STUB
1259  */
1260 static int
1261 sudo_ldap_display_bound_defaults(nss, pw, lbuf)
1262     struct sudo_nss *nss;
1263     struct passwd *pw;
1264     struct lbuf *lbuf;
1265 {
1266     return(1);
1267 }
1268
1269 /*
1270  * Print a record in the short form, ala file sudoers.
1271  */
1272 static int
1273 sudo_ldap_display_entry_short(ld, entry, lbuf)
1274     LDAP *ld;
1275     LDAPMessage *entry;
1276     struct lbuf *lbuf;
1277 {
1278     struct berval **bv, **p;
1279     int count = 0;
1280
1281     lbuf_append(lbuf, "    (", NULL);
1282
1283     /* get the RunAsUser Values from the entry */
1284     bv = ldap_get_values_len(ld, entry, "sudoRunAsUser");
1285     if (bv == NULL)
1286         bv = ldap_get_values_len(ld, entry, "sudoRunAs");
1287     if (bv != NULL) {
1288         for (p = bv; *p != NULL; p++) {
1289             if (p != bv)
1290                 lbuf_append(lbuf, ", ", NULL);
1291             lbuf_append(lbuf, (*p)->bv_val, NULL);
1292         }
1293         ldap_value_free_len(bv);
1294     } else
1295         lbuf_append(lbuf, def_runas_default, NULL);
1296
1297     /* get the RunAsGroup Values from the entry */
1298     bv = ldap_get_values_len(ld, entry, "sudoRunAsGroup");
1299     if (bv != NULL) {
1300         lbuf_append(lbuf, " : ", NULL);
1301         for (p = bv; *p != NULL; p++) {
1302             if (p != bv)
1303                 lbuf_append(lbuf, ", ", NULL);
1304             lbuf_append(lbuf, (*p)->bv_val, NULL);
1305         }
1306         ldap_value_free_len(bv);
1307     }
1308     lbuf_append(lbuf, ") ", NULL);
1309
1310     /* get the Option Values from the entry */
1311     bv = ldap_get_values_len(ld, entry, "sudoOption");
1312     if (bv != NULL) {
1313         char *cp, *tag;
1314
1315         for (p = bv; *p != NULL; p++) {
1316             cp = (*p)->bv_val;
1317             if (*cp == '!')
1318                 cp++;
1319             tag = NULL;
1320             if (strcmp(cp, "authenticate") == 0)
1321                 tag = (*p)->bv_val[0] == '!' ?
1322                     "NOPASSWD: " : "PASSWD: ";
1323             else if (strcmp(cp, "noexec") == 0)
1324                 tag = (*p)->bv_val[0] == '!' ?
1325                     "EXEC: " : "NOEXEC: ";
1326             else if (strcmp(cp, "setenv") == 0)
1327                 tag = (*p)->bv_val[0] == '!' ?
1328                     "NOSETENV: " : "SETENV: ";
1329             if (tag != NULL)
1330                 lbuf_append(lbuf, tag, NULL);
1331             /* XXX - ignores other options */
1332         }
1333         ldap_value_free_len(bv);
1334     }
1335
1336     /* get the Command Values from the entry */
1337     bv = ldap_get_values_len(ld, entry, "sudoCommand");
1338     if (bv != NULL) {
1339         for (p = bv; *p != NULL; p++) {
1340             if (p != bv)
1341                 lbuf_append(lbuf, ", ", NULL);
1342             lbuf_append(lbuf, (*p)->bv_val, NULL);
1343             count++;
1344         }
1345         ldap_value_free_len(bv);
1346     }
1347     lbuf_append(lbuf, "\n", NULL);
1348
1349     return(count);
1350 }
1351
1352 /*
1353  * Print a record in the long form.
1354  */
1355 static int
1356 sudo_ldap_display_entry_long(ld, entry, lbuf)
1357     LDAP *ld;
1358     LDAPMessage *entry;
1359     struct lbuf *lbuf;
1360 {
1361     struct berval **bv, **p;
1362     char *rdn;
1363     int count = 0;
1364
1365     /* extract the dn, only show the first rdn */
1366     rdn = sudo_ldap_get_first_rdn(ld, entry);
1367     lbuf_append(lbuf, "\nLDAP Role: ", rdn ? rdn : "UNKNOWN", "\n", NULL);
1368     if (rdn)
1369         ldap_memfree(rdn);
1370
1371     /* get the RunAsUser Values from the entry */
1372     lbuf_append(lbuf, "    RunAsUsers: ", NULL);
1373     bv = ldap_get_values_len(ld, entry, "sudoRunAsUser");
1374     if (bv == NULL)
1375         bv = ldap_get_values_len(ld, entry, "sudoRunAs");
1376     if (bv != NULL) {
1377         for (p = bv; *p != NULL; p++) {
1378             if (p != bv)
1379                 lbuf_append(lbuf, ", ", NULL);
1380             lbuf_append(lbuf, (*p)->bv_val, NULL);
1381         }
1382         ldap_value_free_len(bv);
1383     } else
1384         lbuf_append(lbuf, def_runas_default, NULL);
1385     lbuf_append(lbuf, "\n", NULL);
1386
1387     /* get the RunAsGroup Values from the entry */
1388     bv = ldap_get_values_len(ld, entry, "sudoRunAsGroup");
1389     if (bv != NULL) {
1390         lbuf_append(lbuf, "    RunAsGroups: ", NULL);
1391         for (p = bv; *p != NULL; p++) {
1392             if (p != bv)
1393                 lbuf_append(lbuf, ", ", NULL);
1394             lbuf_append(lbuf, (*p)->bv_val, NULL);
1395         }
1396         ldap_value_free_len(bv);
1397         lbuf_append(lbuf, "\n", NULL);
1398     }
1399
1400     /* get the Option Values from the entry */
1401     bv = ldap_get_values_len(ld, entry, "sudoOption");
1402     if (bv != NULL) {
1403         lbuf_append(lbuf, "    Options: ", NULL);
1404         for (p = bv; *p != NULL; p++) {
1405             if (p != bv)
1406                 lbuf_append(lbuf, ", ", NULL);
1407             lbuf_append(lbuf, (*p)->bv_val, NULL);
1408         }
1409         ldap_value_free_len(bv);
1410         lbuf_append(lbuf, "\n", NULL);
1411     }
1412
1413     /* get the Command Values from the entry */
1414     bv = ldap_get_values_len(ld, entry, "sudoCommand");
1415     if (bv != NULL) {
1416         lbuf_append(lbuf, "    Commands:\n", NULL);
1417         for (p = bv; *p != NULL; p++) {
1418             lbuf_append(lbuf, "\t", (*p)->bv_val, "\n", NULL);
1419             count++;
1420         }
1421         ldap_value_free_len(bv);
1422     }
1423
1424     return(count);
1425 }
1426
1427 /*
1428  * Like sudo_ldap_lookup(), except we just print entries.
1429  */
1430 static int
1431 sudo_ldap_display_privs(nss, pw, lbuf)
1432     struct sudo_nss *nss;
1433     struct passwd *pw;
1434     struct lbuf *lbuf;
1435 {
1436     struct ldap_config_list_str *base;
1437     LDAP *ld = (LDAP *) nss->handle;
1438     LDAPMessage *entry, *result;
1439     char *filt;
1440     int rc, do_netgr, count = 0;
1441
1442     if (ld == NULL)
1443         return(-1);
1444
1445     /*
1446      * Okay - time to search for anything that matches this user
1447      * Lets limit it to only two queries of the LDAP server
1448      *
1449      * The first pass will look by the username, groups, and
1450      * the keyword ALL.  We will then inspect the results that
1451      * came back from the query.  We don't need to inspect the
1452      * sudoUser in this pass since the LDAP server already scanned
1453      * it for us.
1454      *
1455      * The second pass will return all the entries that contain
1456      * user netgroups.  Then we take the netgroups returned and
1457      * try to match them against the username.
1458      */
1459     for (do_netgr = 0; do_netgr < 2; do_netgr++) {
1460         filt = do_netgr ? estrdup("sudoUser=+*") : sudo_ldap_build_pass1(pw);
1461         DPRINTF(("ldap search '%s'", filt), 1);
1462         for (base = ldap_conf.base; base != NULL; base = base->next) {
1463             result = NULL;
1464             rc = ldap_search_ext_s(ld, base->val, LDAP_SCOPE_SUBTREE, filt,
1465                 NULL, 0, NULL, NULL, NULL, 0, &result);
1466             if (rc != LDAP_SUCCESS)
1467                 continue;       /* no entries for this pass */
1468
1469             /* print each matching entry */
1470             LDAP_FOREACH(entry, ld, result) {
1471                 if ((!do_netgr ||
1472                     sudo_ldap_check_user_netgroup(ld, entry, pw->pw_name)) &&
1473                     sudo_ldap_check_host(ld, entry)) {
1474
1475                     if (long_list)
1476                         count += sudo_ldap_display_entry_long(ld, entry, lbuf);
1477                     else
1478                         count += sudo_ldap_display_entry_short(ld, entry, lbuf);
1479                 }
1480             }
1481             ldap_msgfree(result);
1482         }
1483         efree(filt);
1484     }
1485     return(count);
1486 }
1487
1488 static int
1489 sudo_ldap_display_cmnd(nss, pw)
1490     struct sudo_nss *nss;
1491     struct passwd *pw;
1492 {
1493     struct ldap_config_list_str *base;
1494     LDAP *ld = (LDAP *) nss->handle;
1495     LDAPMessage *entry, *result;                /* used for searches */
1496     char *filt;                                 /* used to parse attributes */
1497     int rc, found, do_netgr;                    /* temp/final return values */
1498
1499     if (ld == NULL)
1500         return(1);
1501
1502     /*
1503      * Okay - time to search for anything that matches this user
1504      * Lets limit it to only two queries of the LDAP server
1505      *
1506      * The first pass will look by the username, groups, and
1507      * the keyword ALL.  We will then inspect the results that
1508      * came back from the query.  We don't need to inspect the
1509      * sudoUser in this pass since the LDAP server already scanned
1510      * it for us.
1511      *
1512      * The second pass will return all the entries that contain
1513      * user netgroups.  Then we take the netgroups returned and
1514      * try to match them against the username.
1515      */
1516     for (found = FALSE, do_netgr = 0; !found && do_netgr < 2; do_netgr++) {
1517         filt = do_netgr ? estrdup("sudoUser=+*") : sudo_ldap_build_pass1(pw);
1518         DPRINTF(("ldap search '%s'", filt), 1);
1519         for (base = ldap_conf.base; base != NULL; base = base->next) {
1520             result = NULL;
1521             rc = ldap_search_ext_s(ld, base->val, LDAP_SCOPE_SUBTREE, filt,
1522                 NULL, 0, NULL, NULL, NULL, 0, &result);
1523             if (rc != LDAP_SUCCESS)
1524                 continue;       /* no entries for this pass */
1525
1526             LDAP_FOREACH(entry, ld, result) {
1527                 if ((!do_netgr ||
1528                     sudo_ldap_check_user_netgroup(ld, entry, pw->pw_name)) &&
1529                     sudo_ldap_check_host(ld, entry) &&
1530                     sudo_ldap_check_command(ld, entry, NULL) &&
1531                     sudo_ldap_check_runas(ld, entry)) {
1532
1533                     found = TRUE;
1534                     break;
1535                 }
1536             }
1537             ldap_msgfree(result);
1538         }
1539         efree(filt);
1540     }
1541
1542     if (found)
1543         printf("%s%s%s\n", safe_cmnd ? safe_cmnd : user_cmnd,
1544             user_args ? " " : "", user_args ? user_args : "");
1545    return(!found);
1546 }
1547
1548 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
1549 static int
1550 sudo_ldap_sasl_interact(ld, flags, _auth_id, _interact)
1551     LDAP *ld;
1552     unsigned int flags;
1553     void *_auth_id;
1554     void *_interact;
1555 {
1556     char *auth_id = (char *)_auth_id;
1557     sasl_interact_t *interact = (sasl_interact_t *)_interact;
1558
1559     for (; interact->id != SASL_CB_LIST_END; interact++) {
1560         if (interact->id != SASL_CB_USER)
1561             return(LDAP_PARAM_ERROR);
1562
1563         if (auth_id != NULL)
1564             interact->result = auth_id;
1565         else if (interact->defresult != NULL)
1566             interact->result = interact->defresult;
1567         else
1568             interact->result = "";
1569
1570         interact->len = strlen(interact->result);
1571 #if SASL_VERSION_MAJOR < 2
1572         interact->result = estrdup(interact->result);
1573 #endif /* SASL_VERSION_MAJOR < 2 */
1574     }
1575     return(LDAP_SUCCESS);
1576 }
1577 #endif /* HAVE_LDAP_SASL_INTERACTIVE_BIND_S */
1578
1579 /*
1580  * Set LDAP options based on the config table.
1581  */
1582 static int
1583 sudo_ldap_set_options(ld)
1584     LDAP *ld;
1585 {
1586     struct ldap_config_table *cur;
1587     int rc;
1588
1589     /* Set ber options */
1590 #ifdef LBER_OPT_DEBUG_LEVEL
1591     if (ldap_conf.ldap_debug)
1592         ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &ldap_conf.ldap_debug);
1593 #endif
1594
1595     /* Set simple LDAP options */
1596     for (cur = ldap_conf_table; cur->conf_str != NULL; cur++) {
1597         LDAP *conn;
1598         int ival;
1599         char *sval;
1600
1601         if (cur->opt_val == -1)
1602             continue;
1603
1604         conn = cur->connected ? ld : NULL;
1605         switch (cur->type) {
1606         case CONF_BOOL:
1607         case CONF_INT:
1608             ival = *(int *)(cur->valp);
1609             if (ival >= 0) {
1610                 rc = ldap_set_option(conn, cur->opt_val, &ival);
1611                 if (rc != LDAP_OPT_SUCCESS) {
1612                     warningx("ldap_set_option: %s -> %d: %s",
1613                         cur->conf_str, ival, ldap_err2string(rc));
1614                     return(-1);
1615                 }
1616                 DPRINTF(("ldap_set_option: %s -> %d", cur->conf_str, ival), 1);
1617             }
1618             break;
1619         case CONF_STR:
1620             sval = *(char **)(cur->valp);
1621             if (sval != NULL) {
1622                 rc = ldap_set_option(conn, cur->opt_val, sval);
1623                 if (rc != LDAP_OPT_SUCCESS) {
1624                     warningx("ldap_set_option: %s -> %s: %s",
1625                         cur->conf_str, sval, ldap_err2string(rc));
1626                     return(-1);
1627                 }
1628                 DPRINTF(("ldap_set_option: %s -> %s", cur->conf_str, sval), 1);
1629             }
1630             break;
1631         }
1632     }
1633
1634 #ifdef LDAP_OPT_NETWORK_TIMEOUT
1635     /* Convert bind_timelimit to a timeval */
1636     if (ldap_conf.bind_timelimit > 0) {
1637         struct timeval tv;
1638         tv.tv_sec = ldap_conf.bind_timelimit / 1000;
1639         tv.tv_usec = 0;
1640         rc = ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &tv);
1641         if (rc != LDAP_OPT_SUCCESS) {
1642             warningx("ldap_set_option(NETWORK_TIMEOUT, %ld): %s",
1643                 (long)tv.tv_sec, ldap_err2string(rc));
1644             return(-1);
1645         }
1646         DPRINTF(("ldap_set_option(LDAP_OPT_NETWORK_TIMEOUT, %ld)",
1647             (long)tv.tv_sec), 1);
1648     }
1649 #endif
1650
1651 #if defined(LDAP_OPT_X_TLS) && !defined(HAVE_LDAPSSL_INIT)
1652     if (ldap_conf.ssl_mode == SUDO_LDAP_SSL) {
1653         int val = LDAP_OPT_X_TLS_HARD;
1654         rc = ldap_set_option(ld, LDAP_OPT_X_TLS, &val);
1655         if (rc != LDAP_SUCCESS) {
1656             warningx("ldap_set_option(LDAP_OPT_X_TLS, LDAP_OPT_X_TLS_HARD): %s",
1657                 ldap_err2string(rc));
1658             return(-1);
1659         }
1660         DPRINTF(("ldap_set_option(LDAP_OPT_X_TLS, LDAP_OPT_X_TLS_HARD)"), 1);
1661     }
1662 #endif
1663     return(0);
1664 }
1665
1666 /*
1667  * Connect to the LDAP server specified by ld
1668  */
1669 static int
1670 sudo_ldap_bind_s(ld)
1671     LDAP *ld;
1672 {
1673     int rc;
1674 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
1675     const char *old_ccname = user_ccname;
1676 # ifdef HAVE_GSS_KRB5_CCACHE_NAME
1677     unsigned int status;
1678 # endif
1679 #endif
1680
1681 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
1682     if (ldap_conf.rootuse_sasl == TRUE ||
1683         (ldap_conf.rootuse_sasl != FALSE && ldap_conf.use_sasl == TRUE)) {
1684         void *auth_id = ldap_conf.rootsasl_auth_id ?
1685             ldap_conf.rootsasl_auth_id : ldap_conf.sasl_auth_id;
1686
1687         if (ldap_conf.krb5_ccname != NULL) {
1688 # ifdef HAVE_GSS_KRB5_CCACHE_NAME
1689             if (gss_krb5_ccache_name(&status, ldap_conf.krb5_ccname, &old_ccname)
1690                 != GSS_S_COMPLETE) {
1691                 old_ccname = NULL;
1692                 DPRINTF(("gss_krb5_ccache_name() failed: %d", status), 1);
1693             }
1694 # else
1695             setenv("KRB5CCNAME", ldap_conf.krb5_ccname, TRUE);
1696 # endif
1697         }
1698         rc = ldap_sasl_interactive_bind_s(ld, ldap_conf.binddn, "GSSAPI",
1699             NULL, NULL, LDAP_SASL_QUIET, sudo_ldap_sasl_interact, auth_id);
1700         if (ldap_conf.krb5_ccname != NULL) {
1701 # ifdef HAVE_GSS_KRB5_CCACHE_NAME
1702             if (gss_krb5_ccache_name(&status, old_ccname, NULL) != GSS_S_COMPLETE)
1703                     DPRINTF(("gss_krb5_ccache_name() failed: %d", status), 1);
1704 # else
1705             if (old_ccname != NULL)
1706                 setenv("KRB5CCNAME", old_ccname, TRUE);
1707             else
1708                 unsetenv("KRB5CCNAME");
1709 # endif
1710         }
1711         if (rc != LDAP_SUCCESS) {
1712             warningx("ldap_sasl_interactive_bind_s(): %s", ldap_err2string(rc));
1713             return(-1);
1714         }
1715         DPRINTF(("ldap_sasl_interactive_bind_s() ok"), 1);
1716     } else
1717 #endif /* HAVE_LDAP_SASL_INTERACTIVE_BIND_S */
1718 #ifdef HAVE_LDAP_SASL_BIND_S
1719     {
1720         struct berval bv;
1721
1722         bv.bv_val = ldap_conf.bindpw ? ldap_conf.bindpw : "";
1723         bv.bv_len = strlen(bv.bv_val);
1724
1725         rc = ldap_sasl_bind_s(ld, ldap_conf.binddn, LDAP_SASL_SIMPLE, &bv,
1726             NULL, NULL, NULL);
1727         if (rc != LDAP_SUCCESS) {
1728             warningx("ldap_sasl_bind_s(): %s", ldap_err2string(rc));
1729             return(-1);
1730         }
1731         DPRINTF(("ldap_sasl_bind_s() ok"), 1);
1732     }
1733 #else
1734     {
1735         rc = ldap_simple_bind_s(ld, ldap_conf.binddn, ldap_conf.bindpw);
1736         if (rc != LDAP_SUCCESS) {
1737             warningx("ldap_simple_bind_s(): %s", ldap_err2string(rc));
1738             return(-1);
1739         }
1740         DPRINTF(("ldap_simple_bind_s() ok"), 1);
1741     }
1742 #endif
1743     return(0);
1744 }
1745
1746 /*
1747  * Open a connection to the LDAP server.
1748  * Returns 0 on success and non-zero on failure.
1749  */
1750 static int
1751 sudo_ldap_open(nss)
1752     struct sudo_nss *nss;
1753 {
1754     LDAP *ld;
1755     int rc, ldapnoinit = FALSE;
1756
1757     if (!sudo_ldap_read_config())
1758         return(-1);
1759
1760     /* Prevent reading of user ldaprc and system defaults. */
1761     if (getenv("LDAPNOINIT") == NULL) {
1762         ldapnoinit = TRUE;
1763         setenv("LDAPNOINIT", "1", TRUE);
1764     }
1765
1766     /* Connect to LDAP server */
1767 #ifdef HAVE_LDAP_INITIALIZE
1768     if (ldap_conf.uri != NULL) {
1769         char *buf = sudo_ldap_join_uri(ldap_conf.uri);
1770         DPRINTF(("ldap_initialize(ld, %s)", buf), 2);
1771         rc = ldap_initialize(&ld, buf);
1772         efree(buf);
1773     } else
1774 #endif
1775         rc = sudo_ldap_init(&ld, ldap_conf.host, ldap_conf.port);
1776     if (rc != LDAP_SUCCESS) {
1777         warningx("unable to initialize LDAP: %s", ldap_err2string(rc));
1778         return(-1);
1779     }
1780
1781     if (ldapnoinit)
1782         unsetenv("LDAPNOINIT");
1783
1784     /* Set LDAP options */
1785     if (sudo_ldap_set_options(ld) < 0)
1786         return(-1);
1787
1788     if (ldap_conf.ssl_mode == SUDO_LDAP_STARTTLS) {
1789 #if defined(HAVE_LDAP_START_TLS_S)
1790         rc = ldap_start_tls_s(ld, NULL, NULL);
1791         if (rc != LDAP_SUCCESS) {
1792             warningx("ldap_start_tls_s(): %s", ldap_err2string(rc));
1793             return(-1);
1794         }
1795         DPRINTF(("ldap_start_tls_s() ok"), 1);
1796 #elif defined(HAVE_LDAP_SSL_CLIENT_INIT) && defined(HAVE_LDAP_START_TLS_S_NP)
1797         if (ldap_ssl_client_init(NULL, NULL, 0, &rc) != LDAP_SUCCESS) {
1798             warningx("ldap_ssl_client_init(): %s", ldap_err2string(rc));
1799             return(-1);
1800         }
1801         rc = ldap_start_tls_s_np(ld, NULL);
1802         if (rc != LDAP_SUCCESS) {
1803             warningx("ldap_start_tls_s_np(): %s", ldap_err2string(rc));
1804             return(-1);
1805         }
1806         DPRINTF(("ldap_start_tls_s_np() ok"), 1);
1807 #else
1808         warningx("start_tls specified but LDAP libs do not support ldap_start_tls_s() or ldap_start_tls_s_np()");
1809 #endif /* !HAVE_LDAP_START_TLS_S && !HAVE_LDAP_START_TLS_S_NP */
1810     }
1811
1812     /* Actually connect */
1813     if (sudo_ldap_bind_s(ld) != 0)
1814         return(-1);
1815
1816     nss->handle = ld;
1817     return(0);
1818 }
1819
1820 static int
1821 sudo_ldap_setdefs(nss)
1822     struct sudo_nss *nss;
1823 {
1824     struct ldap_config_list_str *base;
1825     LDAP *ld = (LDAP *) nss->handle;
1826     LDAPMessage *entry, *result;                 /* used for searches */
1827     int rc;                                      /* temp return value */
1828
1829     if (ld == NULL)
1830         return(-1);
1831
1832     for (base = ldap_conf.base; base != NULL; base = base->next) {
1833         result = NULL;
1834         rc = ldap_search_ext_s(ld, base->val, LDAP_SCOPE_SUBTREE,
1835             "cn=defaults", NULL, 0, NULL, NULL, NULL, 0, &result);
1836         if (rc == LDAP_SUCCESS && (entry = ldap_first_entry(ld, result))) {
1837             DPRINTF(("found:%s", ldap_get_dn(ld, entry)), 1);
1838             sudo_ldap_parse_options(ld, entry);
1839         } else
1840             DPRINTF(("no default options found in %s", base->val), 1);
1841
1842         if (result)
1843             ldap_msgfree(result);
1844     }
1845
1846     return(0);
1847 }
1848
1849 /*
1850  * like sudoers_lookup() - only LDAP style
1851  */
1852 static int
1853 sudo_ldap_lookup(nss, ret, pwflag)
1854     struct sudo_nss *nss;
1855     int ret;
1856     int pwflag;
1857 {
1858     struct ldap_config_list_str *base;
1859     LDAP *ld = (LDAP *) nss->handle;
1860     LDAPMessage *entry, *result;
1861     char *filt;
1862     int do_netgr, rc, matched;
1863     int setenv_implied;
1864     int ldap_user_matches = FALSE, ldap_host_matches = FALSE;
1865     struct passwd *pw = list_pw ? list_pw : sudo_user.pw;
1866
1867     if (ld == NULL)
1868         return(ret);
1869
1870     if (pwflag) {
1871         int doauth = UNSPEC;
1872         enum def_tupple pwcheck = 
1873             (pwflag == -1) ? never : sudo_defs_table[pwflag].sd_un.tuple;
1874
1875         for (matched = 0, do_netgr = 0; !matched && do_netgr < 2; do_netgr++) {
1876             filt = do_netgr ? estrdup("sudoUser=+*") : sudo_ldap_build_pass1(pw);
1877             for (base = ldap_conf.base; base != NULL; base = base->next) {
1878                 result = NULL;
1879                 rc = ldap_search_ext_s(ld, base->val, LDAP_SCOPE_SUBTREE, filt,
1880                     NULL, 0, NULL, NULL, NULL, 0, &result);
1881                 if (rc != LDAP_SUCCESS)
1882                     continue;
1883
1884                 LDAP_FOREACH(entry, ld, result) {
1885                     /* only verify netgroup matches in pass 2 */
1886                     if (do_netgr && !sudo_ldap_check_user_netgroup(ld, entry, pw->pw_name))
1887                         continue;
1888
1889                     ldap_user_matches = TRUE;
1890                     if (sudo_ldap_check_host(ld, entry)) {
1891                         ldap_host_matches = TRUE;
1892                         if ((pwcheck == any && doauth != FALSE) ||
1893                             (pwcheck == all && doauth == FALSE))
1894                             doauth = sudo_ldap_check_bool(ld, entry, "authenticate");
1895                         /* Only check the command when listing another user. */
1896                         if (user_uid == 0 || list_pw == NULL ||
1897                             user_uid == list_pw->pw_uid ||
1898                             sudo_ldap_check_command(ld, entry, NULL)) {
1899                             matched = 1;
1900                             break;      /* end foreach */
1901                         }
1902                     }
1903                 }
1904                 ldap_msgfree(result);
1905             }
1906             efree(filt);
1907         }
1908         if (matched || user_uid == 0) {
1909             SET(ret, VALIDATE_OK);
1910             CLR(ret, VALIDATE_NOT_OK);
1911             if (def_authenticate) {
1912                 switch (pwcheck) {
1913                     case always:
1914                         SET(ret, FLAG_CHECK_USER);
1915                         break;
1916                     case all:
1917                     case any:
1918                         if (doauth == FALSE)
1919                             def_authenticate = FALSE;
1920                         break;
1921                     case never:
1922                         def_authenticate = FALSE;
1923                         break;
1924                     default:
1925                         break;
1926                 }
1927             }
1928         }
1929         goto done;
1930     }
1931
1932     /*
1933      * Okay - time to search for anything that matches this user
1934      * Lets limit it to only two queries of the LDAP server
1935      *
1936      * The first pass will look by the username, groups, and
1937      * the keyword ALL.  We will then inspect the results that
1938      * came back from the query.  We don't need to inspect the
1939      * sudoUser in this pass since the LDAP server already scanned
1940      * it for us.
1941      *
1942      * The second pass will return all the entries that contain
1943      * user netgroups.  Then we take the netgroups returned and
1944      * try to match them against the username.
1945      */
1946     setenv_implied = FALSE;
1947     for (matched = 0, do_netgr = 0; !matched && do_netgr < 2; do_netgr++) {
1948         filt = do_netgr ? estrdup("sudoUser=+*") : sudo_ldap_build_pass1(pw);
1949         DPRINTF(("ldap search '%s'", filt), 1);
1950         for (base = ldap_conf.base; base != NULL; base = base->next) {
1951             result = NULL;
1952             rc = ldap_search_ext_s(ld, base->val, LDAP_SCOPE_SUBTREE, filt,
1953                 NULL, 0, NULL, NULL, NULL, 0, &result);
1954             if (rc != LDAP_SUCCESS) {
1955                 DPRINTF(("nothing found for '%s'", filt), 1);
1956                 continue;
1957             }
1958
1959             /* parse each entry returned from this most recent search */
1960             LDAP_FOREACH(entry, ld, result) {
1961                 DPRINTF(("found:%s", ldap_get_dn(ld, entry)), 1);
1962                 if (
1963                 /* first verify user netgroup matches - only if in pass 2 */
1964                     (!do_netgr || sudo_ldap_check_user_netgroup(ld, entry, pw->pw_name)) &&
1965                 /* remember that user matched */
1966                     (ldap_user_matches = TRUE) &&
1967                 /* verify host match */
1968                     sudo_ldap_check_host(ld, entry) &&
1969                 /* remember that host matched */
1970                     (ldap_host_matches = TRUE) &&
1971                 /* verify runas match */
1972                     sudo_ldap_check_runas(ld, entry) &&
1973                 /* verify command match */
1974                     (rc = sudo_ldap_check_command(ld, entry, &setenv_implied)) != UNSPEC
1975                     ) {
1976                     /* We have a match! */
1977                     DPRINTF(("Command %sallowed", rc == TRUE ? "" : "NOT "), 1);
1978                     matched = TRUE;
1979                     if (rc == TRUE) {
1980                         /* pick up any options */
1981                         if (setenv_implied)
1982                             def_setenv = TRUE;
1983                         sudo_ldap_parse_options(ld, entry);
1984 #ifdef HAVE_SELINUX
1985                         /* Set role and type if not specified on command line. */
1986                         if (user_role == NULL)
1987                             user_role = def_role;
1988                         if (user_type == NULL)
1989                             user_type = def_type;
1990 #endif /* HAVE_SELINUX */
1991                         /* make sure we don't reenter loop */
1992                         SET(ret, VALIDATE_OK);
1993                         CLR(ret, VALIDATE_NOT_OK);
1994                     } else {
1995                         SET(ret, VALIDATE_NOT_OK);
1996                         CLR(ret, VALIDATE_OK);
1997                     }
1998                     /* break from inside for loop */
1999                     break;
2000                 }
2001             }
2002             ldap_msgfree(result);
2003         }
2004         efree(filt);
2005     }
2006
2007 done:
2008     DPRINTF(("user_matches=%d", ldap_user_matches), 1);
2009     DPRINTF(("host_matches=%d", ldap_host_matches), 1);
2010
2011     if (!ISSET(ret, VALIDATE_OK)) {
2012         /* we do not have a match */
2013         if (pwflag && list_pw == NULL)
2014             SET(ret, FLAG_NO_CHECK);
2015     }
2016     if (ldap_user_matches)
2017         CLR(ret, FLAG_NO_USER);
2018     if (ldap_host_matches)
2019         CLR(ret, FLAG_NO_HOST);
2020     DPRINTF(("sudo_ldap_lookup(%d)=0x%02x", pwflag, ret), 1);
2021
2022     return(ret);
2023 }
2024
2025 /*
2026  * shut down LDAP connection
2027  */
2028 static int
2029 sudo_ldap_close(nss)
2030     struct sudo_nss *nss;
2031 {
2032     if (nss->handle != NULL) {
2033         ldap_unbind_ext_s((LDAP *) nss->handle, NULL, NULL);
2034         nss->handle = NULL;
2035     }
2036     return(0);
2037 }
2038
2039 /*
2040  * STUB
2041  */
2042 static int
2043 sudo_ldap_parse(nss)
2044     struct sudo_nss *nss;
2045 {
2046     return(0);
2047 }