2 * Copyright (c) 2003-2013 Todd C. Miller <Todd.Miller@courtesan.com>
4 * This code is derived from software contributed by Aaron Spangler.
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.
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.
21 #include <sys/types.h>
32 #endif /* STDC_HEADERS */
35 #endif /* HAVE_STRING_H */
38 #endif /* HAVE_STRINGS_H */
41 #endif /* HAVE_UNISTD_H */
42 #if TIME_WITH_SYS_TIME
48 #include <netinet/in.h>
49 #include <arpa/inet.h>
54 #if defined(HAVE_LDAP_SSL_H)
55 # include <ldap_ssl.h>
56 #elif defined(HAVE_MPS_LDAP_SSL_H)
57 # include <mps/ldap_ssl.h>
59 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
60 # ifdef HAVE_SASL_SASL_H
61 # include <sasl/sasl.h>
65 # if HAVE_GSS_KRB5_CCACHE_NAME
66 # if defined(HAVE_GSSAPI_GSSAPI_KRB5_H)
67 # include <gssapi/gssapi.h>
68 # include <gssapi/gssapi_krb5.h>
69 # elif defined(HAVE_GSSAPI_GSSAPI_H)
70 # include <gssapi/gssapi.h>
81 /* Older Netscape LDAP SDKs don't prototype ldapssl_set_strength() */
82 #if defined(HAVE_LDAPSSL_SET_STRENGTH) && !defined(HAVE_LDAP_SSL_H) && !defined(HAVE_MPS_LDAP_SSL_H)
83 extern int ldapssl_set_strength(LDAP *ldap, int strength);
86 #if !defined(LDAP_OPT_NETWORK_TIMEOUT) && defined(LDAP_OPT_CONNECT_TIMEOUT)
87 # define LDAP_OPT_NETWORK_TIMEOUT LDAP_OPT_CONNECT_TIMEOUT
90 #ifndef LDAP_OPT_SUCCESS
91 # define LDAP_OPT_SUCCESS LDAP_SUCCESS
95 # define LDAPS_PORT 636
98 #if defined(HAVE_LDAP_SASL_INTERACTIVE_BIND_S) && !defined(LDAP_SASL_QUIET)
99 # define LDAP_SASL_QUIET 0
102 #ifndef HAVE_LDAP_UNBIND_EXT_S
103 #define ldap_unbind_ext_s(a, b, c) ldap_unbind_s(a)
106 #ifndef HAVE_LDAP_SEARCH_EXT_S
107 # ifdef HAVE_LDAP_SEARCH_ST
108 # define ldap_search_ext_s(a, b, c, d, e, f, g, h, i, j, k) \
109 ldap_search_st(a, b, c, d, e, f, i, k)
111 # define ldap_search_ext_s(a, b, c, d, e, f, g, h, i, j, k) \
112 ldap_search_s(a, b, c, d, e, f, k)
116 #define LDAP_FOREACH(var, ld, res) \
117 for ((var) = ldap_first_entry((ld), (res)); \
119 (var) = ldap_next_entry((ld), (var)))
121 #if defined(__GNUC__) && __GNUC__ == 2
122 # define DPRINTF1(fmt...) do { \
123 if (ldap_conf.debug >= 1) \
124 warningx(__VA_ARGS__); \
125 sudo_debug_printf(SUDO_DEBUG_DIAG, fmt); \
127 # define DPRINTF2(fmt...) do { \
128 if (ldap_conf.debug >= 2) \
129 warningx(__VA_ARGS__); \
130 sudo_debug_printf(SUDO_DEBUG_INFO, fmt); \
133 # define DPRINTF1(...) do { \
134 if (ldap_conf.debug >= 1) \
135 warningx(__VA_ARGS__); \
136 sudo_debug_printf(SUDO_DEBUG_DIAG, __VA_ARGS__); \
138 # define DPRINTF2(...) do { \
139 if (ldap_conf.debug >= 2) \
140 warningx(__VA_ARGS__); \
141 sudo_debug_printf(SUDO_DEBUG_INFO, __VA_ARGS__); \
148 #define CONF_LIST_STR 4
149 #define CONF_DEREF_VAL 5
151 #define SUDO_LDAP_CLEAR 0
152 #define SUDO_LDAP_SSL 1
153 #define SUDO_LDAP_STARTTLS 2
155 /* The TIMEFILTER_LENGTH is the length of the filter when timed entries
156 are used. The length is computed as follows:
157 81 for the filter itself
158 + 2 * 17 for the now timestamp
160 #define TIMEFILTER_LENGTH 115
163 * The ldap_search structure implements a linked list of ldap and
164 * search result pointers, which allows us to remove them after
165 * all search results have been combined in memory.
166 * XXX - should probably be a tailq since we do appends
168 struct ldap_search_list {
170 LDAPMessage *searchresult;
171 struct ldap_search_list *next;
175 * The ldap_entry_wrapper structure is used to implement sorted result entries.
176 * A double is used for the order to allow for insertion of new entries
177 * without having to renumber everything.
178 * Note: there is no standard floating point type in LDAP.
179 * As a result, some LDAP servers will only allow an integer.
181 struct ldap_entry_wrapper {
187 * The ldap_result structure contains the list of matching searches as
188 * well as an array of all result entries sorted by the sudoOrder attribute.
191 struct ldap_search_list *searches;
192 struct ldap_entry_wrapper *entries;
193 int allocated_entries;
198 #define ALLOCATION_INCREMENT 100
200 struct ldap_config_table {
201 const char *conf_str; /* config file string */
202 int type; /* CONF_BOOL, CONF_INT, CONF_STR */
203 int opt_val; /* LDAP_OPT_* (or -1 for sudo internal) */
204 void *valp; /* pointer into ldap_conf */
207 struct ldap_config_list_str {
208 struct ldap_config_list_str *next;
212 /* LDAP configuration structure */
213 static struct ldap_config {
228 struct ldap_config_list_str *uri;
232 struct ldap_config_list_str *base;
235 char *tls_cacertfile;
237 char *tls_random_file;
238 char *tls_cipher_suite;
243 char *rootsasl_auth_id;
248 static struct ldap_config_table ldap_conf_global[] = {
249 { "sudoers_debug", CONF_INT, -1, &ldap_conf.debug },
250 { "host", CONF_STR, -1, &ldap_conf.host },
251 { "port", CONF_INT, -1, &ldap_conf.port },
252 { "ssl", CONF_STR, -1, &ldap_conf.ssl },
253 { "sslpath", CONF_STR, -1, &ldap_conf.tls_certfile },
254 { "uri", CONF_LIST_STR, -1, &ldap_conf.uri },
255 #ifdef LDAP_OPT_DEBUG_LEVEL
256 { "debug", CONF_INT, LDAP_OPT_DEBUG_LEVEL, &ldap_conf.ldap_debug },
258 #ifdef LDAP_OPT_X_TLS_REQUIRE_CERT
259 { "tls_checkpeer", CONF_BOOL, LDAP_OPT_X_TLS_REQUIRE_CERT,
260 &ldap_conf.tls_checkpeer },
262 { "tls_checkpeer", CONF_BOOL, -1, &ldap_conf.tls_checkpeer },
264 #ifdef LDAP_OPT_X_TLS_CACERTFILE
265 { "tls_cacertfile", CONF_STR, LDAP_OPT_X_TLS_CACERTFILE,
266 &ldap_conf.tls_cacertfile },
267 { "tls_cacert", CONF_STR, LDAP_OPT_X_TLS_CACERTFILE,
268 &ldap_conf.tls_cacertfile },
270 #ifdef LDAP_OPT_X_TLS_CACERTDIR
271 { "tls_cacertdir", CONF_STR, LDAP_OPT_X_TLS_CACERTDIR,
272 &ldap_conf.tls_cacertdir },
274 #ifdef LDAP_OPT_X_TLS_RANDOM_FILE
275 { "tls_randfile", CONF_STR, LDAP_OPT_X_TLS_RANDOM_FILE,
276 &ldap_conf.tls_random_file },
278 #ifdef LDAP_OPT_X_TLS_CIPHER_SUITE
279 { "tls_ciphers", CONF_STR, LDAP_OPT_X_TLS_CIPHER_SUITE,
280 &ldap_conf.tls_cipher_suite },
281 #elif defined(LDAP_OPT_SSL_CIPHER)
282 { "tls_ciphers", CONF_STR, LDAP_OPT_SSL_CIPHER,
283 &ldap_conf.tls_cipher_suite },
285 #ifdef LDAP_OPT_X_TLS_CERTFILE
286 { "tls_cert", CONF_STR, LDAP_OPT_X_TLS_CERTFILE,
287 &ldap_conf.tls_certfile },
289 { "tls_cert", CONF_STR, -1, &ldap_conf.tls_certfile },
291 #ifdef LDAP_OPT_X_TLS_KEYFILE
292 { "tls_key", CONF_STR, LDAP_OPT_X_TLS_KEYFILE,
293 &ldap_conf.tls_keyfile },
295 { "tls_key", CONF_STR, -1, &ldap_conf.tls_keyfile },
297 #ifdef HAVE_LDAP_SSL_CLIENT_INIT
298 { "tls_keypw", CONF_STR, -1, &ldap_conf.tls_keypw },
300 { "binddn", CONF_STR, -1, &ldap_conf.binddn },
301 { "bindpw", CONF_STR, -1, &ldap_conf.bindpw },
302 { "rootbinddn", CONF_STR, -1, &ldap_conf.rootbinddn },
303 { "sudoers_base", CONF_LIST_STR, -1, &ldap_conf.base },
304 { "sudoers_timed", CONF_BOOL, -1, &ldap_conf.timed },
305 { "sudoers_search_filter", CONF_STR, -1, &ldap_conf.search_filter },
306 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
307 { "use_sasl", CONF_BOOL, -1, &ldap_conf.use_sasl },
308 { "sasl_auth_id", CONF_STR, -1, &ldap_conf.sasl_auth_id },
309 { "rootuse_sasl", CONF_BOOL, -1, &ldap_conf.rootuse_sasl },
310 { "rootsasl_auth_id", CONF_STR, -1, &ldap_conf.rootsasl_auth_id },
311 { "krb5_ccname", CONF_STR, -1, &ldap_conf.krb5_ccname },
312 #endif /* HAVE_LDAP_SASL_INTERACTIVE_BIND_S */
316 static struct ldap_config_table ldap_conf_conn[] = {
317 #ifdef LDAP_OPT_PROTOCOL_VERSION
318 { "ldap_version", CONF_INT, LDAP_OPT_PROTOCOL_VERSION,
319 &ldap_conf.version },
321 #ifdef LDAP_OPT_NETWORK_TIMEOUT
322 { "bind_timelimit", CONF_INT, -1 /* needs timeval, set manually */,
323 &ldap_conf.bind_timelimit },
324 { "network_timeout", CONF_INT, -1 /* needs timeval, set manually */,
325 &ldap_conf.bind_timelimit },
326 #elif defined(LDAP_X_OPT_CONNECT_TIMEOUT)
327 { "bind_timelimit", CONF_INT, LDAP_X_OPT_CONNECT_TIMEOUT,
328 &ldap_conf.bind_timelimit },
329 { "network_timeout", CONF_INT, LDAP_X_OPT_CONNECT_TIMEOUT,
330 &ldap_conf.bind_timelimit },
332 { "timelimit", CONF_INT, LDAP_OPT_TIMELIMIT, &ldap_conf.timelimit },
333 #ifdef LDAP_OPT_TIMEOUT
334 { "timeout", CONF_INT, -1 /* needs timeval, set manually */,
335 &ldap_conf.timeout },
337 #ifdef LDAP_OPT_DEREF
338 { "deref", CONF_DEREF_VAL, LDAP_OPT_DEREF, &ldap_conf.deref },
340 #ifdef LDAP_OPT_X_SASL_SECPROPS
341 { "sasl_secprops", CONF_STR, LDAP_OPT_X_SASL_SECPROPS,
342 &ldap_conf.sasl_secprops },
347 /* sudo_nss implementation */
348 static int sudo_ldap_open(struct sudo_nss *nss);
349 static int sudo_ldap_close(struct sudo_nss *nss);
350 static int sudo_ldap_parse(struct sudo_nss *nss);
351 static int sudo_ldap_setdefs(struct sudo_nss *nss);
352 static int sudo_ldap_lookup(struct sudo_nss *nss, int ret, int pwflag);
353 static int sudo_ldap_display_cmnd(struct sudo_nss *nss, struct passwd *pw);
354 static int sudo_ldap_display_defaults(struct sudo_nss *nss, struct passwd *pw,
356 static int sudo_ldap_display_bound_defaults(struct sudo_nss *nss,
357 struct passwd *pw, struct lbuf *lbuf);
358 static int sudo_ldap_display_privs(struct sudo_nss *nss, struct passwd *pw,
360 static struct ldap_result *sudo_ldap_result_get(struct sudo_nss *nss,
364 * LDAP sudo_nss handle.
365 * We store the connection to the LDAP server, the cached ldap_result object
366 * (if any), and the name of the user the query was performed for.
367 * If a new query is launched with sudo_ldap_result_get() that specifies a
368 * different user, the old cached result is freed before the new query is run.
370 struct sudo_ldap_handle {
372 struct ldap_result *result;
374 struct group_list *grlist;
377 struct sudo_nss sudo_nss_ldap = {
385 sudo_ldap_display_cmnd,
386 sudo_ldap_display_defaults,
387 sudo_ldap_display_bound_defaults,
388 sudo_ldap_display_privs
391 #ifdef HAVE_LDAP_CREATE
393 * Rebuild the hosts list and include a specific port for each host.
394 * ldap_create() does not take a default port parameter so we must
395 * append one if we want something other than LDAP_PORT.
398 sudo_ldap_conf_add_ports(void)
401 char *host, *port, defport[13];
402 char hostbuf[LINE_MAX * 2];
403 debug_decl(sudo_ldap_conf_add_ports, SUDO_DEBUG_LDAP)
406 if (snprintf(defport, sizeof(defport), ":%d", ldap_conf.port) >= sizeof(defport))
407 fatalx(_("sudo_ldap_conf_add_ports: port too large"));
409 for ((host = strtok(ldap_conf.host, " \t")); host; (host = strtok(NULL, " \t"))) {
410 if (hostbuf[0] != '\0') {
411 if (strlcat(hostbuf, " ", sizeof(hostbuf)) >= sizeof(hostbuf))
415 if (strlcat(hostbuf, host, sizeof(hostbuf)) >= sizeof(hostbuf))
417 /* Append port if there is not one already. */
418 if ((port = strrchr(host, ':')) == NULL ||
419 !isdigit((unsigned char)port[1])) {
420 if (strlcat(hostbuf, defport, sizeof(hostbuf)) >= sizeof(hostbuf))
425 efree(ldap_conf.host);
426 ldap_conf.host = estrdup(hostbuf);
430 fatalx(_("sudo_ldap_conf_add_ports: out of space expanding hostbuf"));
434 #ifndef HAVE_LDAP_INITIALIZE
436 * For each uri, convert to host:port pairs. For ldaps:// enable SSL
437 * Accepts: uris of the form ldap:/// or ldap://hostname:portnum/
438 * where the trailing slash is optional.
441 sudo_ldap_parse_uri(const struct ldap_config_list_str *uri_list)
443 char *buf, *uri, *host, *cp, *port;
444 char hostbuf[LINE_MAX];
445 int nldap = 0, nldaps = 0;
447 debug_decl(sudo_ldap_parse_uri, SUDO_DEBUG_LDAP)
450 buf = estrdup(uri_list->val);
452 for ((uri = strtok(buf, " \t")); uri != NULL; (uri = strtok(NULL, " \t"))) {
453 if (strncasecmp(uri, "ldap://", 7) == 0) {
456 } else if (strncasecmp(uri, "ldaps://", 8) == 0) {
460 warningx(_("unsupported LDAP uri type: %s"), uri);
464 /* trim optional trailing slash */
465 if ((cp = strrchr(host, '/')) != NULL && cp[1] == '\0') {
469 if (hostbuf[0] != '\0') {
470 if (strlcat(hostbuf, " ", sizeof(hostbuf)) >= sizeof(hostbuf))
475 host = "localhost"; /* no host specified, use localhost */
477 if (strlcat(hostbuf, host, sizeof(hostbuf)) >= sizeof(hostbuf))
480 /* If using SSL and no port specified, add port 636 */
482 if ((port = strrchr(host, ':')) == NULL ||
483 !isdigit((unsigned char)port[1]))
484 if (strlcat(hostbuf, ":636", sizeof(hostbuf)) >= sizeof(hostbuf))
488 if (hostbuf[0] == '\0') {
489 warningx(_("invalid uri: %s"), uri_list->val);
495 warningx(_("unable to mix ldap and ldaps URIs"));
498 if (ldap_conf.ssl_mode == SUDO_LDAP_STARTTLS) {
499 warningx(_("unable to mix ldaps and starttls"));
502 ldap_conf.ssl_mode = SUDO_LDAP_SSL;
505 efree(ldap_conf.host);
506 ldap_conf.host = estrdup(hostbuf);
508 } while ((uri_list = uri_list->next));
515 debug_return_int(rc);
518 fatalx(_("sudo_ldap_parse_uri: out of space building hostbuf"));
522 sudo_ldap_join_uri(struct ldap_config_list_str *uri_list)
524 struct ldap_config_list_str *uri;
527 debug_decl(sudo_ldap_join_uri, SUDO_DEBUG_LDAP)
529 /* Usually just a single entry. */
530 if (uri_list->next == NULL)
531 debug_return_str(estrdup(uri_list->val));
533 for (uri = uri_list; uri != NULL; uri = uri->next) {
534 len += strlen(uri->val) + 1;
536 buf = cp = emalloc(len);
538 for (uri = uri_list; uri != NULL; uri = uri->next) {
539 cp += strlcpy(cp, uri->val, len - (cp - buf));
543 debug_return_str(buf);
545 #endif /* HAVE_LDAP_INITIALIZE */
548 sudo_ldap_init(LDAP **ldp, const char *host, int port)
551 int rc = LDAP_CONNECT_ERROR;
552 debug_decl(sudo_ldap_init, SUDO_DEBUG_LDAP)
554 #ifdef HAVE_LDAPSSL_INIT
555 if (ldap_conf.ssl_mode != SUDO_LDAP_CLEAR) {
556 const int defsecure = ldap_conf.ssl_mode == SUDO_LDAP_SSL;
557 DPRINTF2("ldapssl_clientauth_init(%s, %s)",
558 ldap_conf.tls_certfile ? ldap_conf.tls_certfile : "NULL",
559 ldap_conf.tls_keyfile ? ldap_conf.tls_keyfile : "NULL");
560 rc = ldapssl_clientauth_init(ldap_conf.tls_certfile, NULL,
561 ldap_conf.tls_keyfile != NULL, ldap_conf.tls_keyfile, NULL);
563 * Starting with version 5.0, Mozilla-derived LDAP SDKs require
564 * the cert and key paths to be a directory, not a file.
565 * If the user specified a file and it fails, try the parent dir.
567 if (rc != LDAP_SUCCESS) {
569 if (ldap_conf.tls_certfile != NULL) {
570 char *cp = strrchr(ldap_conf.tls_certfile, '/');
571 if (cp != NULL && strncmp(cp + 1, "cert", 4) == 0) {
576 if (ldap_conf.tls_keyfile != NULL) {
577 char *cp = strrchr(ldap_conf.tls_keyfile, '/');
578 if (cp != NULL && strncmp(cp + 1, "key", 3) == 0) {
584 DPRINTF2("ldapssl_clientauth_init(%s, %s)",
585 ldap_conf.tls_certfile ? ldap_conf.tls_certfile : "NULL",
586 ldap_conf.tls_keyfile ? ldap_conf.tls_keyfile : "NULL");
587 rc = ldapssl_clientauth_init(ldap_conf.tls_certfile, NULL,
588 ldap_conf.tls_keyfile != NULL, ldap_conf.tls_keyfile, NULL);
591 if (rc != LDAP_SUCCESS) {
592 warningx(_("unable to initialize SSL cert and key db: %s"),
593 ldapssl_err2string(rc));
594 if (ldap_conf.tls_certfile == NULL)
595 warningx(_("you must set TLS_CERT in %s to use SSL"),
600 DPRINTF2("ldapssl_init(%s, %d, %d)", host, port, defsecure);
601 if ((ld = ldapssl_init(host, port, defsecure)) != NULL)
604 #elif defined(HAVE_LDAP_SSL_INIT) && defined(HAVE_LDAP_SSL_CLIENT_INIT)
605 if (ldap_conf.ssl_mode == SUDO_LDAP_SSL) {
606 if (ldap_ssl_client_init(ldap_conf.tls_keyfile, ldap_conf.tls_keypw, 0, &rc) != LDAP_SUCCESS) {
607 warningx("ldap_ssl_client_init(): %s", ldap_err2string(rc));
608 debug_return_int(-1);
610 DPRINTF2("ldap_ssl_init(%s, %d, NULL)", host, port);
611 if ((ld = ldap_ssl_init((char *)host, port, NULL)) != NULL)
616 #ifdef HAVE_LDAP_CREATE
617 DPRINTF2("ldap_create()");
618 if ((rc = ldap_create(&ld)) != LDAP_SUCCESS)
620 DPRINTF2("ldap_set_option(LDAP_OPT_HOST_NAME, %s)", host);
621 rc = ldap_set_option(ld, LDAP_OPT_HOST_NAME, host);
623 DPRINTF2("ldap_init(%s, %d)", host, port);
624 if ((ld = ldap_init((char *)host, port)) != NULL)
631 debug_return_int(rc);
635 * Walk through search results and return true if we have a matching
636 * non-Unix group (including netgroups), else false.
639 sudo_ldap_check_non_unix_group(LDAP *ld, LDAPMessage *entry, struct passwd *pw)
641 struct berval **bv, **p;
644 debug_decl(sudo_ldap_check_non_unix_group, SUDO_DEBUG_LDAP)
647 debug_return_bool(ret);
649 /* get the values from the entry */
650 bv = ldap_get_values_len(ld, entry, "sudoUser");
652 debug_return_bool(ret);
654 /* walk through values */
655 for (p = bv; *p != NULL && !ret; p++) {
658 if (netgr_matches(val, NULL, NULL, pw->pw_name))
660 DPRINTF2("ldap sudoUser netgroup '%s' ... %s", val,
661 ret ? "MATCH!" : "not");
663 if (group_plugin_query(pw->pw_name, val + 2, pw))
665 DPRINTF2("ldap sudoUser non-Unix group '%s' ... %s", val,
666 ret ? "MATCH!" : "not");
670 ldap_value_free_len(bv); /* cleanup */
672 debug_return_bool(ret);
676 * Walk through search results and return true if we have a
677 * host match, else false.
680 sudo_ldap_check_host(LDAP *ld, LDAPMessage *entry)
682 struct berval **bv, **p;
685 debug_decl(sudo_ldap_check_host, SUDO_DEBUG_LDAP)
688 debug_return_bool(ret);
690 /* get the values from the entry */
691 bv = ldap_get_values_len(ld, entry, "sudoHost");
693 debug_return_bool(ret);
695 /* walk through values */
696 for (p = bv; *p != NULL && !ret; p++) {
698 /* match any or address or netgroup or hostname */
699 if (!strcmp(val, "ALL") || addr_matches(val) ||
700 netgr_matches(val, user_host, user_shost, NULL) ||
701 hostname_matches(user_shost, user_host, val))
703 DPRINTF2("ldap sudoHost '%s' ... %s", val, ret ? "MATCH!" : "not");
706 ldap_value_free_len(bv); /* cleanup */
708 debug_return_bool(ret);
712 sudo_ldap_check_runas_user(LDAP *ld, LDAPMessage *entry)
714 struct berval **bv, **p;
717 debug_decl(sudo_ldap_check_runas_user, SUDO_DEBUG_LDAP)
720 debug_return_bool(UNSPEC);
722 /* get the runas user from the entry */
723 bv = ldap_get_values_len(ld, entry, "sudoRunAsUser");
725 bv = ldap_get_values_len(ld, entry, "sudoRunAs"); /* old style */
730 * if runas is not specified on the command line, the only information
731 * as to which user to run as is in the runas_default option. We should
732 * check to see if we have the local option present. Unfortunately we
733 * don't parse these options until after this routine says yes or no.
734 * The query has already returned, so we could peek at the attribute
735 * values here though.
737 * For now just require users to always use -u option unless its set
738 * in the global defaults. This behaviour is no different than the global
741 * Sigh - maybe add this feature later
745 * If there are no runas entries, match runas_default against
746 * what the user specified on the command line.
749 debug_return_bool(!strcasecmp(runas_pw->pw_name, def_runas_default));
751 /* walk through values returned, looking for a match */
752 for (p = bv; *p != NULL && !ret; p++) {
756 if (netgr_matches(val, NULL, NULL, runas_pw->pw_name))
760 if (usergr_matches(val, runas_pw->pw_name, runas_pw))
764 if (strcmp(val, "ALL") == 0) {
770 if (userpw_matches(val, runas_pw->pw_name, runas_pw))
774 DPRINTF2("ldap sudoRunAsUser '%s' ... %s", val, ret ? "MATCH!" : "not");
777 ldap_value_free_len(bv); /* cleanup */
779 debug_return_bool(ret);
783 sudo_ldap_check_runas_group(LDAP *ld, LDAPMessage *entry)
785 struct berval **bv, **p;
788 debug_decl(sudo_ldap_check_runas_group, SUDO_DEBUG_LDAP)
790 /* runas_gr is only set if the user specified the -g flag */
792 debug_return_bool(UNSPEC);
794 /* get the values from the entry */
795 bv = ldap_get_values_len(ld, entry, "sudoRunAsGroup");
797 debug_return_bool(ret);
799 /* walk through values returned, looking for a match */
800 for (p = bv; *p != NULL && !ret; p++) {
802 if (strcmp(val, "ALL") == 0 || group_matches(val, runas_gr))
804 DPRINTF2("ldap sudoRunAsGroup '%s' ... %s",
805 val, ret ? "MATCH!" : "not");
808 ldap_value_free_len(bv); /* cleanup */
810 debug_return_bool(ret);
814 * Walk through search results and return true if we have a runas match,
815 * else false. RunAs info is optional.
818 sudo_ldap_check_runas(LDAP *ld, LDAPMessage *entry)
821 debug_decl(sudo_ldap_check_runas, SUDO_DEBUG_LDAP)
824 debug_return_bool(false);
826 ret = sudo_ldap_check_runas_user(ld, entry) != false &&
827 sudo_ldap_check_runas_group(ld, entry) != false;
829 debug_return_bool(ret);
832 static struct sudo_digest *
833 sudo_ldap_extract_digest(char **cmnd, struct sudo_digest *digest)
835 char *ep, *cp = *cmnd;
836 int digest_type = SUDO_DIGEST_INVALID;
837 debug_decl(sudo_ldap_check_command, SUDO_DEBUG_LDAP)
840 * Check for and extract a digest prefix, e.g.
841 * sha224:d06a2617c98d377c250edd470fd5e576327748d82915d6e33b5f8db1 /bin/ls
843 if (cp[0] == 's' && cp[1] == 'h' && cp[2] == 'a') {
846 if (cp[4] == '2' && cp[5] == '4')
847 digest_type = SUDO_DIGEST_SHA224;
848 else if (cp[4] == '5' && cp[5] == '6')
849 digest_type = SUDO_DIGEST_SHA256;
852 if (cp[4] == '8' && cp[5] == '4')
853 digest_type = SUDO_DIGEST_SHA384;
856 if (cp[4] == '1' && cp[5] == '2')
857 digest_type = SUDO_DIGEST_SHA512;
860 if (digest_type != SUDO_DIGEST_INVALID) {
862 while (isblank((unsigned char)*cp))
866 while (isblank((unsigned char)*cp))
869 while (*ep != '\0' && !isblank((unsigned char)*ep))
872 digest->digest_type = digest_type;
873 digest->digest_str = estrndup(cp, (size_t)(ep - cp));
875 while (isblank((unsigned char)*cp))
878 DPRINTF1("%s digest %s for %s",
879 digest_type == SUDO_DIGEST_SHA224 ? "sha224" :
880 digest_type == SUDO_DIGEST_SHA256 ? "sha256" :
881 digest_type == SUDO_DIGEST_SHA384 ? "sha384" :
882 "sha512", digest->digest_str, cp);
883 debug_return_ptr(digest);
888 debug_return_ptr(NULL);
892 * Walk through search results and return true if we have a command match,
893 * false if disallowed and UNSPEC if not matched.
896 sudo_ldap_check_command(LDAP *ld, LDAPMessage *entry, int *setenv_implied)
898 struct sudo_digest digest, *allowed_digest = NULL;
899 struct berval **bv, **p;
900 char *allowed_cmnd, *allowed_args, *val;
903 debug_decl(sudo_ldap_check_command, SUDO_DEBUG_LDAP)
906 debug_return_bool(ret);
908 bv = ldap_get_values_len(ld, entry, "sudoCommand");
910 debug_return_bool(ret);
912 for (p = bv; *p != NULL && ret != false; p++) {
914 /* Match against ALL ? */
915 if (!strcmp(val, "ALL")) {
917 if (setenv_implied != NULL)
918 *setenv_implied = true;
919 DPRINTF2("ldap sudoCommand '%s' ... MATCH!", val);
923 /* check for sha-2 digest */
924 allowed_digest = sudo_ldap_extract_digest(&val, &digest);
926 /* check for !command */
929 allowed_cmnd = estrdup(1 + val); /* !command */
932 allowed_cmnd = estrdup(val); /* command */
935 /* split optional args away from command */
936 allowed_args = strchr(allowed_cmnd, ' ');
938 *allowed_args++ = '\0';
940 /* check the command like normal */
941 if (command_matches(allowed_cmnd, allowed_args, allowed_digest)) {
943 * If allowed (no bang) set ret but keep on checking.
944 * If disallowed (bang), exit loop.
946 ret = foundbang ? false : true;
948 DPRINTF2("ldap sudoCommand '%s' ... %s",
949 val, ret == true ? "MATCH!" : "not");
951 efree(allowed_cmnd); /* cleanup */
952 if (allowed_digest != NULL)
953 efree(allowed_digest->digest_str);
956 ldap_value_free_len(bv); /* more cleanup */
958 debug_return_bool(ret);
962 * Search for boolean "option" in sudoOption.
963 * Returns true if found and allowed, false if negated, else UNSPEC.
966 sudo_ldap_check_bool(LDAP *ld, LDAPMessage *entry, char *option)
968 struct berval **bv, **p;
971 debug_decl(sudo_ldap_check_bool, SUDO_DEBUG_LDAP)
974 debug_return_bool(ret);
976 bv = ldap_get_values_len(ld, entry, "sudoOption");
978 debug_return_bool(ret);
980 /* walk through options */
981 for (p = bv; *p != NULL; p++) {
983 DPRINTF2("ldap sudoOption: '%s'", var);
985 if ((ch = *var) == '!')
987 if (strcmp(var, option) == 0)
991 ldap_value_free_len(bv);
993 debug_return_bool(ret);
997 * Read sudoOption and modify the defaults as we go. This is used once
998 * from the cn=defaults entry and also once when a final sudoRole is matched.
1001 sudo_ldap_parse_options(LDAP *ld, LDAPMessage *entry)
1003 struct berval **bv, **p;
1004 char op, *var, *val;
1005 debug_decl(sudo_ldap_parse_options, SUDO_DEBUG_LDAP)
1010 bv = ldap_get_values_len(ld, entry, "sudoOption");
1014 /* walk through options */
1015 for (p = bv; *p != NULL; p++) {
1016 var = estrdup((*p)->bv_val);
1017 DPRINTF2("ldap sudoOption: '%s'", var);
1019 /* check for equals sign past first char */
1020 val = strchr(var, '=');
1022 *val++ = '\0'; /* split on = and truncate var */
1023 op = *(val - 2); /* peek for += or -= cases */
1024 if (op == '+' || op == '-') {
1025 *(val - 2) = '\0'; /* found, remove extra char */
1026 /* case var+=val or var-=val */
1027 set_default(var, val, (int) op);
1030 set_default(var, val, true);
1032 } else if (*var == '!') {
1033 /* case !var Boolean False */
1034 set_default(var + 1, NULL, false);
1036 /* case var Boolean True */
1037 set_default(var, NULL, true);
1042 ldap_value_free_len(bv);
1048 * Build an LDAP timefilter.
1050 * Stores a filter in the buffer that makes sure only entries
1051 * are selected that have a sudoNotBefore in the past and a
1052 * sudoNotAfter in the future, i.e. a filter of the following
1053 * structure (spaced out a little more for better readability:
1057 * (!(sudoNotAfter=*))
1058 * (sudoNotAfter>__now__)
1061 * (!(sudoNotBefore=*))
1062 * (sudoNotBefore<__now__)
1066 * If either the sudoNotAfter or sudoNotBefore attributes are missing,
1067 * no time restriction shall be imposed.
1070 sudo_ldap_timefilter(char *buffer, size_t buffersize)
1074 char timebuffer[sizeof("20120727121554.0Z")];
1076 debug_decl(sudo_ldap_timefilter, SUDO_DEBUG_LDAP)
1078 /* Make sure we have a formatted timestamp for __now__. */
1080 if ((tp = gmtime(&now)) == NULL) {
1081 warning(_("unable to get GMT time"));
1085 /* Format the timestamp according to the RFC. */
1086 if (strftime(timebuffer, sizeof(timebuffer), "%Y%m%d%H%M%S.0Z", tp) == 0) {
1087 warningx(_("unable to format timestamp"));
1092 bytes = snprintf(buffer, buffersize, "(&(|(!(sudoNotAfter=*))(sudoNotAfter>=%s))(|(!(sudoNotBefore=*))(sudoNotBefore<=%s)))",
1093 timebuffer, timebuffer);
1094 if (bytes < 0 || bytes >= buffersize) {
1095 warning(_("unable to build time filter"));
1100 debug_return_int(bytes);
1104 * Builds up a filter to search for default settings
1107 sudo_ldap_build_default_filter(void)
1110 debug_decl(sudo_ldap_build_default_filter, SUDO_DEBUG_LDAP)
1112 if (ldap_conf.search_filter)
1113 easprintf(&filt, "(&%s(cn=defaults))", ldap_conf.search_filter);
1115 filt = estrdup("cn=defaults");
1116 debug_return_str(filt);
1120 * Determine length of query value after escaping characters
1124 sudo_ldap_value_len(const char *value)
1129 for (s = value; *s != '\0'; s++) {
1139 len += (size_t)(s - value);
1144 * Like strlcat() but escapes characters as per RFC 4515.
1147 sudo_ldap_value_cat(char *dst, const char *src, size_t size)
1150 const char *s = src;
1154 /* Find the end of dst and adjust bytes left but don't go past end */
1155 while (n-- != 0 && *d != '\0')
1161 return dlen + strlen(s);
1162 while (*s != '\0') {
1209 return dlen + (s - src); /* count does not include NUL */
1213 * Builds up a filter to check against LDAP.
1216 sudo_ldap_build_pass1(struct passwd *pw)
1219 char *buf, timebuffer[TIMEFILTER_LENGTH + 1], gidbuf[MAX_UID_T_LEN + 1];
1220 struct group_list *grlist;
1223 debug_decl(sudo_ldap_build_pass1, SUDO_DEBUG_LDAP)
1225 /* If there is a filter, allocate space for the global AND. */
1226 if (ldap_conf.timed || ldap_conf.search_filter)
1229 /* Add LDAP search filter if present. */
1230 if (ldap_conf.search_filter)
1231 sz += strlen(ldap_conf.search_filter);
1233 /* Then add (|(sudoUser=USERNAME)(sudoUser=ALL)) + NUL */
1234 sz += 29 + sudo_ldap_value_len(pw->pw_name);
1236 /* Add space for primary and supplementary groups and gids */
1237 if ((grp = sudo_getgrgid(pw->pw_gid)) != NULL) {
1238 sz += 12 + sudo_ldap_value_len(grp->gr_name);
1240 sz += 13 + MAX_UID_T_LEN;
1241 if ((grlist = sudo_get_grlist(pw)) != NULL) {
1242 for (i = 0; i < grlist->ngroups; i++) {
1243 if (grp != NULL && strcasecmp(grlist->groups[i], grp->gr_name) == 0)
1245 sz += 12 + sudo_ldap_value_len(grlist->groups[i]);
1247 for (i = 0; i < grlist->ngids; i++) {
1248 if (pw->pw_gid == grlist->gids[i])
1250 sz += 13 + MAX_UID_T_LEN;
1254 /* If timed, add space for time limits. */
1255 if (ldap_conf.timed)
1256 sz += TIMEFILTER_LENGTH;
1261 * If timed or using a search filter, start a global AND clause to
1262 * contain the search filter, search criteria, and time restriction.
1264 if (ldap_conf.timed || ldap_conf.search_filter)
1265 (void) strlcpy(buf, "(&", sz);
1267 if (ldap_conf.search_filter)
1268 (void) strlcat(buf, ldap_conf.search_filter, sz);
1270 /* Global OR + sudoUser=user_name filter */
1271 (void) strlcat(buf, "(|(sudoUser=", sz);
1272 (void) sudo_ldap_value_cat(buf, pw->pw_name, sz);
1273 (void) strlcat(buf, ")", sz);
1275 /* Append primary group and gid */
1277 (void) strlcat(buf, "(sudoUser=%", sz);
1278 (void) sudo_ldap_value_cat(buf, grp->gr_name, sz);
1279 (void) strlcat(buf, ")", sz);
1281 (void) snprintf(gidbuf, sizeof(gidbuf), "%u", (unsigned int)pw->pw_gid);
1282 (void) strlcat(buf, "(sudoUser=%#", sz);
1283 (void) strlcat(buf, gidbuf, sz);
1284 (void) strlcat(buf, ")", sz);
1286 /* Append supplementary groups and gids */
1287 if (grlist != NULL) {
1288 for (i = 0; i < grlist->ngroups; i++) {
1289 if (grp != NULL && strcasecmp(grlist->groups[i], grp->gr_name) == 0)
1291 (void) strlcat(buf, "(sudoUser=%", sz);
1292 (void) sudo_ldap_value_cat(buf, grlist->groups[i], sz);
1293 (void) strlcat(buf, ")", sz);
1295 for (i = 0; i < grlist->ngids; i++) {
1296 if (pw->pw_gid == grlist->gids[i])
1298 (void) snprintf(gidbuf, sizeof(gidbuf), "%u",
1299 (unsigned int)grlist->gids[i]);
1300 (void) strlcat(buf, "(sudoUser=%#", sz);
1301 (void) strlcat(buf, gidbuf, sz);
1302 (void) strlcat(buf, ")", sz);
1306 /* Done with groups. */
1308 sudo_grlist_delref(grlist);
1310 sudo_gr_delref(grp);
1312 /* Add ALL to list and end the global OR */
1313 if (strlcat(buf, "(sudoUser=ALL)", sz) >= sz)
1314 fatalx(_("sudo_ldap_build_pass1 allocation mismatch"));
1316 /* Add the time restriction, or simply end the global OR. */
1317 if (ldap_conf.timed) {
1318 strlcat(buf, ")", sz); /* closes the global OR */
1319 sudo_ldap_timefilter(timebuffer, sizeof(timebuffer));
1320 strlcat(buf, timebuffer, sz);
1321 } else if (ldap_conf.search_filter) {
1322 strlcat(buf, ")", sz); /* closes the global OR */
1324 strlcat(buf, ")", sz); /* closes the global OR or the global AND */
1326 debug_return_str(buf);
1330 * Builds up a filter to check against non-Unix group
1331 * entries in LDAP, including netgroups.
1334 sudo_ldap_build_pass2(void)
1336 char *filt, timebuffer[TIMEFILTER_LENGTH + 1];
1337 debug_decl(sudo_ldap_build_pass2, SUDO_DEBUG_LDAP)
1339 if (ldap_conf.timed)
1340 sudo_ldap_timefilter(timebuffer, sizeof(timebuffer));
1343 * Match all sudoUsers beginning with '+' or '%:'.
1344 * If a search filter or time restriction is specified,
1345 * those get ANDed in to the expression.
1347 if (def_group_plugin) {
1348 easprintf(&filt, "%s%s(|(sudoUser=+*)(sudoUser=%%:*))%s%s",
1349 (ldap_conf.timed || ldap_conf.search_filter) ? "(&" : "",
1350 ldap_conf.search_filter ? ldap_conf.search_filter : "",
1351 ldap_conf.timed ? timebuffer : "",
1352 (ldap_conf.timed || ldap_conf.search_filter) ? ")" : "");
1354 easprintf(&filt, "%s%s(sudoUser=+*)%s%s",
1355 (ldap_conf.timed || ldap_conf.search_filter) ? "(&" : "",
1356 ldap_conf.search_filter ? ldap_conf.search_filter : "",
1357 ldap_conf.timed ? timebuffer : "",
1358 (ldap_conf.timed || ldap_conf.search_filter) ? ")" : "");
1361 debug_return_str(filt);
1365 sudo_ldap_read_secret(const char *path)
1368 char buf[LINE_MAX], *cp;
1369 debug_decl(sudo_ldap_read_secret, SUDO_DEBUG_LDAP)
1371 if ((fp = fopen(path_ldap_secret, "r")) != NULL) {
1372 if (fgets(buf, sizeof(buf), fp) != NULL) {
1373 if ((cp = strchr(buf, '\n')) != NULL)
1375 /* copy to bindpw and binddn */
1376 efree(ldap_conf.bindpw);
1377 ldap_conf.bindpw = estrdup(buf);
1378 efree(ldap_conf.binddn);
1379 ldap_conf.binddn = ldap_conf.rootbinddn;
1380 ldap_conf.rootbinddn = NULL;
1388 * Look up keyword in config tables.
1389 * Returns true if found, else false.
1392 sudo_ldap_parse_keyword(const char *keyword, const char *value,
1393 struct ldap_config_table *table)
1395 struct ldap_config_table *cur;
1396 debug_decl(sudo_ldap_parse_keyword, SUDO_DEBUG_LDAP)
1398 /* Look up keyword in config tables */
1399 for (cur = table; cur->conf_str != NULL; cur++) {
1400 if (strcasecmp(keyword, cur->conf_str) == 0) {
1401 switch (cur->type) {
1402 case CONF_DEREF_VAL:
1403 if (strcasecmp(value, "searching") == 0)
1404 *(int *)(cur->valp) = LDAP_DEREF_SEARCHING;
1405 else if (strcasecmp(value, "finding") == 0)
1406 *(int *)(cur->valp) = LDAP_DEREF_FINDING;
1407 else if (strcasecmp(value, "always") == 0)
1408 *(int *)(cur->valp) = LDAP_DEREF_ALWAYS;
1410 *(int *)(cur->valp) = LDAP_DEREF_NEVER;
1413 *(int *)(cur->valp) = atobool(value) == true;
1416 *(int *)(cur->valp) = atoi(value);
1419 efree(*(char **)(cur->valp));
1420 *(char **)(cur->valp) = estrdup(value);
1424 struct ldap_config_list_str **p;
1425 size_t len = strlen(value);
1428 p = (struct ldap_config_list_str **)cur->valp;
1431 *p = emalloc(sizeof(struct ldap_config_list_str) + len);
1432 memcpy((*p)->val, value, len + 1);
1438 debug_return_bool(true);
1441 debug_return_bool(false);
1445 sudo_ldap_read_config(void)
1448 char *cp, *keyword, *value, *line = NULL;
1449 size_t linesize = 0;
1450 debug_decl(sudo_ldap_read_config, SUDO_DEBUG_LDAP)
1453 ldap_conf.version = 3;
1454 ldap_conf.port = -1;
1455 ldap_conf.tls_checkpeer = -1;
1456 ldap_conf.timelimit = -1;
1457 ldap_conf.timeout = -1;
1458 ldap_conf.bind_timelimit = -1;
1459 ldap_conf.use_sasl = -1;
1460 ldap_conf.rootuse_sasl = -1;
1461 ldap_conf.deref = -1;
1463 if ((fp = fopen(path_ldap_conf, "r")) == NULL)
1464 debug_return_bool(false);
1466 while (sudo_parseln(&line, &linesize, NULL, fp) != -1) {
1468 continue; /* skip empty line */
1470 /* split into keyword and value */
1471 keyword = cp = line;
1472 while (*cp && !isblank((unsigned char) *cp))
1475 *cp++ = '\0'; /* terminate keyword */
1477 /* skip whitespace before value */
1478 while (isblank((unsigned char) *cp))
1482 /* Look up keyword in config tables */
1483 if (!sudo_ldap_parse_keyword(keyword, value, ldap_conf_global))
1484 sudo_ldap_parse_keyword(keyword, value, ldap_conf_conn);
1489 if (!ldap_conf.host)
1490 ldap_conf.host = estrdup("localhost");
1492 DPRINTF1("LDAP Config Summary");
1493 DPRINTF1("===================");
1494 if (ldap_conf.uri) {
1495 struct ldap_config_list_str *uri = ldap_conf.uri;
1498 DPRINTF1("uri %s", uri->val);
1499 } while ((uri = uri->next) != NULL);
1502 ldap_conf.host ? ldap_conf.host : "(NONE)");
1503 DPRINTF1("port %d", ldap_conf.port);
1505 DPRINTF1("ldap_version %d", ldap_conf.version);
1507 if (ldap_conf.base) {
1508 struct ldap_config_list_str *base = ldap_conf.base;
1510 DPRINTF1("sudoers_base %s", base->val);
1511 } while ((base = base->next) != NULL);
1513 DPRINTF1("sudoers_base %s", "(NONE: LDAP disabled)");
1515 if (ldap_conf.search_filter) {
1516 DPRINTF1("search_filter %s", ldap_conf.search_filter);
1518 DPRINTF1("binddn %s",
1519 ldap_conf.binddn ? ldap_conf.binddn : "(anonymous)");
1520 DPRINTF1("bindpw %s",
1521 ldap_conf.bindpw ? ldap_conf.bindpw : "(anonymous)");
1522 if (ldap_conf.bind_timelimit > 0) {
1523 DPRINTF1("bind_timelimit %d", ldap_conf.bind_timelimit);
1525 if (ldap_conf.timelimit > 0) {
1526 DPRINTF1("timelimit %d", ldap_conf.timelimit);
1528 if (ldap_conf.deref != -1) {
1529 DPRINTF1("deref %d", ldap_conf.deref);
1531 DPRINTF1("ssl %s", ldap_conf.ssl ? ldap_conf.ssl : "(no)");
1532 if (ldap_conf.tls_checkpeer != -1) {
1533 DPRINTF1("tls_checkpeer %s",
1534 ldap_conf.tls_checkpeer ? "(yes)" : "(no)");
1536 if (ldap_conf.tls_cacertfile != NULL) {
1537 DPRINTF1("tls_cacertfile %s", ldap_conf.tls_cacertfile);
1539 if (ldap_conf.tls_cacertdir != NULL) {
1540 DPRINTF1("tls_cacertdir %s", ldap_conf.tls_cacertdir);
1542 if (ldap_conf.tls_random_file != NULL) {
1543 DPRINTF1("tls_random_file %s", ldap_conf.tls_random_file);
1545 if (ldap_conf.tls_cipher_suite != NULL) {
1546 DPRINTF1("tls_cipher_suite %s", ldap_conf.tls_cipher_suite);
1548 if (ldap_conf.tls_certfile != NULL) {
1549 DPRINTF1("tls_certfile %s", ldap_conf.tls_certfile);
1551 if (ldap_conf.tls_keyfile != NULL) {
1552 DPRINTF1("tls_keyfile %s", ldap_conf.tls_keyfile);
1554 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
1555 if (ldap_conf.use_sasl != -1) {
1556 DPRINTF1("use_sasl %s", ldap_conf.use_sasl ? "yes" : "no");
1557 DPRINTF1("sasl_auth_id %s",
1558 ldap_conf.sasl_auth_id ? ldap_conf.sasl_auth_id : "(NONE)");
1559 DPRINTF1("rootuse_sasl %d",
1560 ldap_conf.rootuse_sasl);
1561 DPRINTF1("rootsasl_auth_id %s",
1562 ldap_conf.rootsasl_auth_id ? ldap_conf.rootsasl_auth_id : "(NONE)");
1563 DPRINTF1("sasl_secprops %s",
1564 ldap_conf.sasl_secprops ? ldap_conf.sasl_secprops : "(NONE)");
1565 DPRINTF1("krb5_ccname %s",
1566 ldap_conf.krb5_ccname ? ldap_conf.krb5_ccname : "(NONE)");
1569 DPRINTF1("===================");
1571 if (!ldap_conf.base)
1572 debug_return_bool(false); /* if no base is defined, ignore LDAP */
1574 if (ldap_conf.bind_timelimit > 0)
1575 ldap_conf.bind_timelimit *= 1000; /* convert to ms */
1578 * Interpret SSL option
1580 if (ldap_conf.ssl != NULL) {
1581 if (strcasecmp(ldap_conf.ssl, "start_tls") == 0)
1582 ldap_conf.ssl_mode = SUDO_LDAP_STARTTLS;
1583 else if (atobool(ldap_conf.ssl) == true)
1584 ldap_conf.ssl_mode = SUDO_LDAP_SSL;
1587 #if defined(HAVE_LDAPSSL_SET_STRENGTH) && !defined(LDAP_OPT_X_TLS_REQUIRE_CERT)
1588 if (ldap_conf.tls_checkpeer != -1) {
1589 ldapssl_set_strength(NULL,
1590 ldap_conf.tls_checkpeer ? LDAPSSL_AUTH_CERT : LDAPSSL_AUTH_WEAK);
1594 #ifndef HAVE_LDAP_INITIALIZE
1595 /* Convert uri list to host list if no ldap_initialize(). */
1596 if (ldap_conf.uri) {
1597 struct ldap_config_list_str *uri = ldap_conf.uri;
1598 if (sudo_ldap_parse_uri(uri) != 0)
1599 debug_return_bool(false);
1601 ldap_conf.uri = uri->next;
1603 } while ((uri = ldap_conf.uri));
1604 ldap_conf.port = LDAP_PORT;
1608 if (!ldap_conf.uri) {
1609 /* Use port 389 for plaintext LDAP and port 636 for SSL LDAP */
1610 if (ldap_conf.port < 0)
1612 ldap_conf.ssl_mode == SUDO_LDAP_SSL ? LDAPS_PORT : LDAP_PORT;
1614 #ifdef HAVE_LDAP_CREATE
1616 * Cannot specify port directly to ldap_create(), each host must
1617 * include :port to override the default.
1619 if (ldap_conf.port != LDAP_PORT)
1620 sudo_ldap_conf_add_ports();
1624 /* If search filter is not parenthesized, make it so. */
1625 if (ldap_conf.search_filter && ldap_conf.search_filter[0] != '(') {
1626 size_t len = strlen(ldap_conf.search_filter);
1627 cp = ldap_conf.search_filter;
1628 ldap_conf.search_filter = emalloc(len + 3);
1629 ldap_conf.search_filter[0] = '(';
1630 memcpy(ldap_conf.search_filter + 1, cp, len);
1631 ldap_conf.search_filter[len + 1] = ')';
1632 ldap_conf.search_filter[len + 2] = '\0';
1636 /* If rootbinddn set, read in /etc/ldap.secret if it exists. */
1637 if (ldap_conf.rootbinddn)
1638 sudo_ldap_read_secret(path_ldap_secret);
1640 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
1642 * Make sure we can open the file specified by krb5_ccname.
1644 if (ldap_conf.krb5_ccname != NULL) {
1645 if (strncasecmp(ldap_conf.krb5_ccname, "FILE:", 5) == 0 ||
1646 strncasecmp(ldap_conf.krb5_ccname, "WRFILE:", 7) == 0) {
1647 value = ldap_conf.krb5_ccname +
1648 (ldap_conf.krb5_ccname[4] == ':' ? 5 : 7);
1649 if ((fp = fopen(value, "r")) != NULL) {
1650 sudo_debug_printf(SUDO_DEBUG_INFO,
1651 "using krb5 credential cache: %s", value);
1654 /* Can't open it, just ignore the entry. */
1655 sudo_debug_printf(SUDO_DEBUG_WARN|SUDO_DEBUG_LINENO,
1656 "unable to open krb5 credential cache: %s", value);
1657 efree(ldap_conf.krb5_ccname);
1658 ldap_conf.krb5_ccname = NULL;
1663 debug_return_bool(true);
1667 * Extract the dn from an entry and return the first rdn from it.
1670 sudo_ldap_get_first_rdn(LDAP *ld, LDAPMessage *entry)
1672 #ifdef HAVE_LDAP_STR2DN
1673 char *dn, *rdn = NULL;
1675 debug_decl(sudo_ldap_get_first_rdn, SUDO_DEBUG_LDAP)
1677 if ((dn = ldap_get_dn(ld, entry)) == NULL)
1678 debug_return_str(NULL);
1679 if (ldap_str2dn(dn, &tmpDN, LDAP_DN_FORMAT_LDAP) == LDAP_SUCCESS) {
1680 ldap_rdn2str(tmpDN[0], &rdn, LDAP_DN_FORMAT_UFN);
1684 debug_return_str(rdn);
1687 debug_decl(sudo_ldap_get_first_rdn, SUDO_DEBUG_LDAP)
1689 if ((dn = ldap_get_dn(ld, entry)) == NULL)
1691 edn = ldap_explode_dn(dn, 1);
1693 debug_return_str(edn ? edn[0] : NULL);
1698 * Fetch and display the global Options.
1701 sudo_ldap_display_defaults(struct sudo_nss *nss, struct passwd *pw,
1704 struct berval **bv, **p;
1705 struct timeval tv, *tvp = NULL;
1706 struct ldap_config_list_str *base;
1707 struct sudo_ldap_handle *handle = nss->handle;
1709 LDAPMessage *entry, *result;
1710 char *prefix, *filt;
1712 debug_decl(sudo_ldap_display_defaults, SUDO_DEBUG_LDAP)
1714 if (handle == NULL || handle->ld == NULL)
1718 filt = sudo_ldap_build_default_filter();
1719 for (base = ldap_conf.base; base != NULL; base = base->next) {
1720 if (ldap_conf.timeout > 0) {
1721 tv.tv_sec = ldap_conf.timeout;
1726 rc = ldap_search_ext_s(ld, base->val, LDAP_SCOPE_SUBTREE,
1727 filt, NULL, 0, NULL, NULL, tvp, 0, &result);
1728 if (rc == LDAP_SUCCESS && (entry = ldap_first_entry(ld, result))) {
1729 bv = ldap_get_values_len(ld, entry, "sudoOption");
1731 if (lbuf->len == 0 || isspace((unsigned char)lbuf->buf[lbuf->len - 1]))
1735 for (p = bv; *p != NULL; p++) {
1736 lbuf_append(lbuf, "%s%s", prefix, (*p)->bv_val);
1740 ldap_value_free_len(bv);
1744 ldap_msgfree(result);
1748 debug_return_int(count);
1755 sudo_ldap_display_bound_defaults(struct sudo_nss *nss, struct passwd *pw,
1758 debug_decl(sudo_ldap_display_bound_defaults, SUDO_DEBUG_LDAP)
1759 debug_return_int(0);
1763 * Print a record in the short form, ala file sudoers.
1766 sudo_ldap_display_entry_short(LDAP *ld, LDAPMessage *entry, struct lbuf *lbuf)
1768 struct berval **bv, **p;
1770 debug_decl(sudo_ldap_display_entry_short, SUDO_DEBUG_LDAP)
1772 lbuf_append(lbuf, " (");
1774 /* get the RunAsUser Values from the entry */
1775 bv = ldap_get_values_len(ld, entry, "sudoRunAsUser");
1777 bv = ldap_get_values_len(ld, entry, "sudoRunAs");
1779 for (p = bv; *p != NULL; p++) {
1780 lbuf_append(lbuf, "%s%s", p != bv ? ", " : "", (*p)->bv_val);
1782 ldap_value_free_len(bv);
1784 lbuf_append(lbuf, "%s", def_runas_default);
1786 /* get the RunAsGroup Values from the entry */
1787 bv = ldap_get_values_len(ld, entry, "sudoRunAsGroup");
1789 lbuf_append(lbuf, " : ");
1790 for (p = bv; *p != NULL; p++) {
1791 lbuf_append(lbuf, "%s%s", p != bv ? ", " : "", (*p)->bv_val);
1793 ldap_value_free_len(bv);
1795 lbuf_append(lbuf, ") ");
1797 /* get the Option Values from the entry */
1798 bv = ldap_get_values_len(ld, entry, "sudoOption");
1800 for (p = bv; *p != NULL; p++) {
1801 char *cp = (*p)->bv_val;
1804 if (strcmp(cp, "authenticate") == 0)
1805 lbuf_append(lbuf, (*p)->bv_val[0] == '!' ?
1806 "NOPASSWD: " : "PASSWD: ");
1807 else if (strcmp(cp, "noexec") == 0)
1808 lbuf_append(lbuf, (*p)->bv_val[0] == '!' ?
1809 "EXEC: " : "NOEXEC: ");
1810 else if (strcmp(cp, "setenv") == 0)
1811 lbuf_append(lbuf, (*p)->bv_val[0] == '!' ?
1812 "NOSETENV: " : "SETENV: ");
1814 ldap_value_free_len(bv);
1817 /* get the Command Values from the entry */
1818 bv = ldap_get_values_len(ld, entry, "sudoCommand");
1820 for (p = bv; *p != NULL; p++) {
1821 lbuf_append(lbuf, "%s%s", p != bv ? ", " : "", (*p)->bv_val);
1824 ldap_value_free_len(bv);
1826 lbuf_append(lbuf, "\n");
1828 debug_return_int(count);
1832 * Print a record in the long form.
1835 sudo_ldap_display_entry_long(LDAP *ld, LDAPMessage *entry, struct lbuf *lbuf)
1837 struct berval **bv, **p;
1840 debug_decl(sudo_ldap_display_entry_long, SUDO_DEBUG_LDAP)
1842 /* extract the dn, only show the first rdn */
1843 rdn = sudo_ldap_get_first_rdn(ld, entry);
1845 lbuf_append(lbuf, _("\nLDAP Role: %s\n"), rdn);
1847 lbuf_append(lbuf, _("\nLDAP Role: UNKNOWN\n"));
1851 /* get the RunAsUser Values from the entry */
1852 lbuf_append(lbuf, " RunAsUsers: ");
1853 bv = ldap_get_values_len(ld, entry, "sudoRunAsUser");
1855 bv = ldap_get_values_len(ld, entry, "sudoRunAs");
1857 for (p = bv; *p != NULL; p++) {
1858 lbuf_append(lbuf, "%s%s", p != bv ? ", " : "", (*p)->bv_val);
1860 ldap_value_free_len(bv);
1862 lbuf_append(lbuf, "%s", def_runas_default);
1863 lbuf_append(lbuf, "\n");
1865 /* get the RunAsGroup Values from the entry */
1866 bv = ldap_get_values_len(ld, entry, "sudoRunAsGroup");
1868 lbuf_append(lbuf, " RunAsGroups: ");
1869 for (p = bv; *p != NULL; p++) {
1870 lbuf_append(lbuf, "%s%s", p != bv ? ", " : "", (*p)->bv_val);
1872 ldap_value_free_len(bv);
1873 lbuf_append(lbuf, "\n");
1876 /* get the Option Values from the entry */
1877 bv = ldap_get_values_len(ld, entry, "sudoOption");
1879 lbuf_append(lbuf, " Options: ");
1880 for (p = bv; *p != NULL; p++) {
1881 lbuf_append(lbuf, "%s%s", p != bv ? ", " : "", (*p)->bv_val);
1883 ldap_value_free_len(bv);
1884 lbuf_append(lbuf, "\n");
1888 * Display order attribute if present. This attribute is single valued,
1889 * so there is no need for a loop.
1891 bv = ldap_get_values_len(ld, entry, "sudoOrder");
1894 lbuf_append(lbuf, _(" Order: %s\n"), (*bv)->bv_val);
1896 ldap_value_free_len(bv);
1899 /* Get the command values from the entry. */
1900 bv = ldap_get_values_len(ld, entry, "sudoCommand");
1902 lbuf_append(lbuf, _(" Commands:\n"));
1903 for (p = bv; *p != NULL; p++) {
1904 lbuf_append(lbuf, "\t%s\n", (*p)->bv_val);
1907 ldap_value_free_len(bv);
1910 debug_return_int(count);
1914 * Like sudo_ldap_lookup(), except we just print entries.
1917 sudo_ldap_display_privs(struct sudo_nss *nss, struct passwd *pw,
1920 struct sudo_ldap_handle *handle = nss->handle;
1922 struct ldap_result *lres;
1925 debug_decl(sudo_ldap_display_privs, SUDO_DEBUG_LDAP)
1927 if (handle == NULL || handle->ld == NULL)
1931 DPRINTF1("ldap search for command list");
1932 lres = sudo_ldap_result_get(nss, pw);
1934 /* Display all matching entries. */
1935 for (i = 0; i < lres->nentries; i++) {
1936 entry = lres->entries[i].entry;
1938 count += sudo_ldap_display_entry_long(ld, entry, lbuf);
1940 count += sudo_ldap_display_entry_short(ld, entry, lbuf);
1944 debug_return_int(count);
1948 sudo_ldap_display_cmnd(struct sudo_nss *nss, struct passwd *pw)
1950 struct sudo_ldap_handle *handle = nss->handle;
1952 struct ldap_result *lres;
1956 debug_decl(sudo_ldap_display_cmnd, SUDO_DEBUG_LDAP)
1958 if (handle == NULL || handle->ld == NULL)
1963 * The sudo_ldap_result_get() function returns all nodes that match
1964 * the user and the host.
1966 DPRINTF1("ldap search for command list");
1967 lres = sudo_ldap_result_get(nss, pw);
1968 for (i = 0; i < lres->nentries; i++) {
1969 entry = lres->entries[i].entry;
1970 if (sudo_ldap_check_command(ld, entry, NULL) &&
1971 sudo_ldap_check_runas(ld, entry)) {
1979 printf("%s%s%s\n", safe_cmnd ? safe_cmnd : user_cmnd,
1980 user_args ? " " : "", user_args ? user_args : "");
1981 debug_return_bool(!found);
1984 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
1986 sudo_ldap_sasl_interact(LDAP *ld, unsigned int flags, void *_auth_id,
1989 char *auth_id = (char *)_auth_id;
1990 sasl_interact_t *interact = (sasl_interact_t *)_interact;
1991 debug_decl(sudo_ldap_sasl_interact, SUDO_DEBUG_LDAP)
1993 for (; interact->id != SASL_CB_LIST_END; interact++) {
1994 if (interact->id != SASL_CB_USER)
1995 debug_return_int(LDAP_PARAM_ERROR);
1997 if (auth_id != NULL)
1998 interact->result = auth_id;
1999 else if (interact->defresult != NULL)
2000 interact->result = interact->defresult;
2002 interact->result = "";
2004 interact->len = strlen(interact->result);
2005 #if SASL_VERSION_MAJOR < 2
2006 interact->result = estrdup(interact->result);
2007 #endif /* SASL_VERSION_MAJOR < 2 */
2009 debug_return_int(LDAP_SUCCESS);
2011 #endif /* HAVE_LDAP_SASL_INTERACTIVE_BIND_S */
2015 * Set LDAP options from the specified options table
2018 sudo_ldap_set_options_table(LDAP *ld, struct ldap_config_table *table)
2020 struct ldap_config_table *cur;
2021 int ival, rc, errors = 0;
2023 debug_decl(sudo_ldap_set_options_table, SUDO_DEBUG_LDAP)
2025 for (cur = table; cur->conf_str != NULL; cur++) {
2026 if (cur->opt_val == -1)
2029 switch (cur->type) {
2032 ival = *(int *)(cur->valp);
2034 DPRINTF1("ldap_set_option: %s -> %d", cur->conf_str, ival);
2035 rc = ldap_set_option(ld, cur->opt_val, &ival);
2036 if (rc != LDAP_OPT_SUCCESS) {
2037 warningx("ldap_set_option: %s -> %d: %s",
2038 cur->conf_str, ival, ldap_err2string(rc));
2044 sval = *(char **)(cur->valp);
2046 DPRINTF1("ldap_set_option: %s -> %s", cur->conf_str, sval);
2047 rc = ldap_set_option(ld, cur->opt_val, sval);
2048 if (rc != LDAP_OPT_SUCCESS) {
2049 warningx("ldap_set_option: %s -> %s: %s",
2050 cur->conf_str, sval, ldap_err2string(rc));
2057 debug_return_int(errors ? -1 : 0);
2061 * Set LDAP options based on the global config table.
2064 sudo_ldap_set_options_global(void)
2067 debug_decl(sudo_ldap_set_options_global, SUDO_DEBUG_LDAP)
2069 /* Set ber options */
2070 #ifdef LBER_OPT_DEBUG_LEVEL
2071 if (ldap_conf.ldap_debug)
2072 ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &ldap_conf.ldap_debug);
2075 /* Parse global LDAP options table. */
2076 rc = sudo_ldap_set_options_table(NULL, ldap_conf_global);
2078 debug_return_int(-1);
2079 debug_return_int(0);
2083 * Set LDAP options based on the per-connection config table.
2086 sudo_ldap_set_options_conn(LDAP *ld)
2089 debug_decl(sudo_ldap_set_options_conn, SUDO_DEBUG_LDAP)
2091 /* Parse per-connection LDAP options table. */
2092 rc = sudo_ldap_set_options_table(ld, ldap_conf_conn);
2094 debug_return_int(-1);
2096 #ifdef LDAP_OPT_TIMEOUT
2097 /* Convert timeout to a timeval */
2098 if (ldap_conf.timeout > 0) {
2100 tv.tv_sec = ldap_conf.timeout;
2102 DPRINTF1("ldap_set_option(LDAP_OPT_TIMEOUT, %d)", ldap_conf.timeout);
2103 rc = ldap_set_option(ld, LDAP_OPT_TIMEOUT, &tv);
2104 if (rc != LDAP_OPT_SUCCESS) {
2105 warningx("ldap_set_option(TIMEOUT, %d): %s",
2106 ldap_conf.timeout, ldap_err2string(rc));
2110 #ifdef LDAP_OPT_NETWORK_TIMEOUT
2111 /* Convert bind_timelimit to a timeval */
2112 if (ldap_conf.bind_timelimit > 0) {
2114 tv.tv_sec = ldap_conf.bind_timelimit / 1000;
2116 DPRINTF1("ldap_set_option(LDAP_OPT_NETWORK_TIMEOUT, %d)",
2117 ldap_conf.bind_timelimit / 1000);
2118 rc = ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &tv);
2119 # if !defined(LDAP_OPT_CONNECT_TIMEOUT) || LDAP_VENDOR_VERSION != 510
2120 /* Tivoli Directory Server 6.3 libs always return a (bogus) error. */
2121 if (rc != LDAP_OPT_SUCCESS) {
2122 warningx("ldap_set_option(NETWORK_TIMEOUT, %d): %s",
2123 ldap_conf.bind_timelimit / 1000, ldap_err2string(rc));
2129 #if defined(LDAP_OPT_X_TLS) && !defined(HAVE_LDAPSSL_INIT)
2130 if (ldap_conf.ssl_mode == SUDO_LDAP_SSL) {
2131 int val = LDAP_OPT_X_TLS_HARD;
2132 DPRINTF1("ldap_set_option(LDAP_OPT_X_TLS, LDAP_OPT_X_TLS_HARD)");
2133 rc = ldap_set_option(ld, LDAP_OPT_X_TLS, &val);
2134 if (rc != LDAP_SUCCESS) {
2135 warningx("ldap_set_option(LDAP_OPT_X_TLS, LDAP_OPT_X_TLS_HARD): %s",
2136 ldap_err2string(rc));
2137 debug_return_int(-1);
2141 debug_return_int(0);
2145 * Create a new sudo_ldap_result structure.
2147 static struct ldap_result *
2148 sudo_ldap_result_alloc(void)
2150 struct ldap_result *result;
2151 debug_decl(sudo_ldap_result_alloc, SUDO_DEBUG_LDAP)
2153 debug_return_ptr(ecalloc(1, sizeof(*result)));
2157 * Free the ldap result structure
2160 sudo_ldap_result_free(struct ldap_result *lres)
2162 struct ldap_search_list *s;
2163 debug_decl(sudo_ldap_result_free, SUDO_DEBUG_LDAP)
2166 if (lres->nentries) {
2167 efree(lres->entries);
2168 lres->entries = NULL;
2170 if (lres->searches) {
2171 while ((s = lres->searches) != NULL) {
2172 ldap_msgfree(s->searchresult);
2173 lres->searches = s->next;
2183 * Add a search result to the ldap_result structure.
2185 static struct ldap_search_list *
2186 sudo_ldap_result_add_search(struct ldap_result *lres, LDAP *ldap,
2187 LDAPMessage *searchresult)
2189 struct ldap_search_list *s, *news;
2190 debug_decl(sudo_ldap_result_add_search, SUDO_DEBUG_LDAP)
2192 news = ecalloc(1, sizeof(struct ldap_search_list));
2194 news->searchresult = searchresult;
2195 /* news->next = NULL; */
2197 /* Add entry to the end of the chain (XXX - tailq instead?). */
2198 if (lres->searches) {
2199 for (s = lres->searches; s->next != NULL; s = s->next)
2203 lres->searches = news;
2205 debug_return_ptr(news);
2209 * Connect to the LDAP server specified by ld
2212 sudo_ldap_bind_s(LDAP *ld)
2215 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
2216 const char *old_ccname = user_ccname;
2217 # ifdef HAVE_GSS_KRB5_CCACHE_NAME
2218 unsigned int status;
2221 debug_decl(sudo_ldap_bind_s, SUDO_DEBUG_LDAP)
2223 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
2224 if (ldap_conf.rootuse_sasl == true ||
2225 (ldap_conf.rootuse_sasl != false && ldap_conf.use_sasl == true)) {
2226 void *auth_id = ldap_conf.rootsasl_auth_id ?
2227 ldap_conf.rootsasl_auth_id : ldap_conf.sasl_auth_id;
2229 if (ldap_conf.krb5_ccname != NULL) {
2230 # ifdef HAVE_GSS_KRB5_CCACHE_NAME
2231 if (gss_krb5_ccache_name(&status, ldap_conf.krb5_ccname, &old_ccname)
2232 != GSS_S_COMPLETE) {
2234 sudo_debug_printf(SUDO_DEBUG_WARN|SUDO_DEBUG_LINENO,
2235 "gss_krb5_ccache_name() failed: %d", status);
2238 sudo_setenv("KRB5CCNAME", ldap_conf.krb5_ccname, true);
2241 rc = ldap_sasl_interactive_bind_s(ld, ldap_conf.binddn, "GSSAPI",
2242 NULL, NULL, LDAP_SASL_QUIET, sudo_ldap_sasl_interact, auth_id);
2243 if (ldap_conf.krb5_ccname != NULL) {
2244 # ifdef HAVE_GSS_KRB5_CCACHE_NAME
2245 if (gss_krb5_ccache_name(&status, old_ccname, NULL) != GSS_S_COMPLETE)
2246 sudo_debug_printf(SUDO_DEBUG_WARN|SUDO_DEBUG_LINENO,
2247 "gss_krb5_ccache_name() failed: %d", status);
2249 if (old_ccname != NULL)
2250 sudo_setenv("KRB5CCNAME", old_ccname, true);
2252 sudo_unsetenv("KRB5CCNAME");
2255 if (rc != LDAP_SUCCESS) {
2256 warningx("ldap_sasl_interactive_bind_s(): %s",
2257 ldap_err2string(rc));
2258 debug_return_int(-1);
2260 DPRINTF1("ldap_sasl_interactive_bind_s() ok");
2262 #endif /* HAVE_LDAP_SASL_INTERACTIVE_BIND_S */
2263 #ifdef HAVE_LDAP_SASL_BIND_S
2267 bv.bv_val = ldap_conf.bindpw ? ldap_conf.bindpw : "";
2268 bv.bv_len = strlen(bv.bv_val);
2270 rc = ldap_sasl_bind_s(ld, ldap_conf.binddn, LDAP_SASL_SIMPLE, &bv,
2272 if (rc != LDAP_SUCCESS) {
2273 warningx("ldap_sasl_bind_s(): %s", ldap_err2string(rc));
2274 debug_return_int(-1);
2276 DPRINTF1("ldap_sasl_bind_s() ok");
2280 rc = ldap_simple_bind_s(ld, ldap_conf.binddn, ldap_conf.bindpw);
2281 if (rc != LDAP_SUCCESS) {
2282 warningx("ldap_simple_bind_s(): %s", ldap_err2string(rc));
2283 debug_return_int(-1);
2285 DPRINTF1("ldap_simple_bind_s() ok");
2288 debug_return_int(0);
2292 * Open a connection to the LDAP server.
2293 * Returns 0 on success and non-zero on failure.
2296 sudo_ldap_open(struct sudo_nss *nss)
2300 bool ldapnoinit = false;
2301 struct sudo_ldap_handle *handle;
2302 debug_decl(sudo_ldap_open, SUDO_DEBUG_LDAP)
2304 if (!sudo_ldap_read_config())
2305 debug_return_int(-1);
2307 /* Prevent reading of user ldaprc and system defaults. */
2308 if (sudo_getenv("LDAPNOINIT") == NULL) {
2310 sudo_setenv("LDAPNOINIT", "1", true);
2313 /* Set global LDAP options */
2314 if (sudo_ldap_set_options_global() < 0)
2315 debug_return_int(-1);
2317 /* Connect to LDAP server */
2318 #ifdef HAVE_LDAP_INITIALIZE
2319 if (ldap_conf.uri != NULL) {
2320 char *buf = sudo_ldap_join_uri(ldap_conf.uri);
2321 DPRINTF2("ldap_initialize(ld, %s)", buf);
2322 rc = ldap_initialize(&ld, buf);
2324 if (rc != LDAP_SUCCESS)
2325 warningx(_("unable to initialize LDAP: %s"), ldap_err2string(rc));
2328 rc = sudo_ldap_init(&ld, ldap_conf.host, ldap_conf.port);
2329 if (rc != LDAP_SUCCESS)
2330 debug_return_int(-1);
2332 /* Set LDAP per-connection options */
2333 if (sudo_ldap_set_options_conn(ld) < 0)
2334 debug_return_int(-1);
2337 sudo_unsetenv("LDAPNOINIT");
2339 if (ldap_conf.ssl_mode == SUDO_LDAP_STARTTLS) {
2340 #if defined(HAVE_LDAP_START_TLS_S)
2341 rc = ldap_start_tls_s(ld, NULL, NULL);
2342 if (rc != LDAP_SUCCESS) {
2343 warningx("ldap_start_tls_s(): %s", ldap_err2string(rc));
2344 debug_return_int(-1);
2346 DPRINTF1("ldap_start_tls_s() ok");
2347 #elif defined(HAVE_LDAP_SSL_CLIENT_INIT) && defined(HAVE_LDAP_START_TLS_S_NP)
2348 if (ldap_ssl_client_init(ldap_conf.tls_keyfile, ldap_conf.tls_keypw, 0, &rc) != LDAP_SUCCESS) {
2349 warningx("ldap_ssl_client_init(): %s", ldap_err2string(rc));
2350 debug_return_int(-1);
2352 rc = ldap_start_tls_s_np(ld, NULL);
2353 if (rc != LDAP_SUCCESS) {
2354 warningx("ldap_start_tls_s_np(): %s", ldap_err2string(rc));
2355 debug_return_int(-1);
2357 DPRINTF1("ldap_start_tls_s_np() ok");
2359 warningx(_("start_tls specified but LDAP libs do not support ldap_start_tls_s() or ldap_start_tls_s_np()"));
2360 #endif /* !HAVE_LDAP_START_TLS_S && !HAVE_LDAP_START_TLS_S_NP */
2363 /* Actually connect */
2364 if (sudo_ldap_bind_s(ld) != 0)
2365 debug_return_int(-1);
2367 /* Create a handle container. */
2368 handle = ecalloc(1, sizeof(struct sudo_ldap_handle));
2370 /* handle->result = NULL; */
2371 /* handle->username = NULL; */
2372 /* handle->grlist = NULL; */
2373 nss->handle = handle;
2375 debug_return_int(0);
2379 sudo_ldap_setdefs(struct sudo_nss *nss)
2381 struct ldap_config_list_str *base;
2382 struct sudo_ldap_handle *handle = nss->handle;
2383 struct timeval tv, *tvp = NULL;
2385 LDAPMessage *entry, *result;
2388 debug_decl(sudo_ldap_setdefs, SUDO_DEBUG_LDAP)
2390 if (handle == NULL || handle->ld == NULL)
2391 debug_return_int(-1);
2394 filt = sudo_ldap_build_default_filter();
2395 DPRINTF1("Looking for cn=defaults: %s", filt);
2397 for (base = ldap_conf.base; base != NULL; base = base->next) {
2398 if (ldap_conf.timeout > 0) {
2399 tv.tv_sec = ldap_conf.timeout;
2404 rc = ldap_search_ext_s(ld, base->val, LDAP_SCOPE_SUBTREE,
2405 filt, NULL, 0, NULL, NULL, tvp, 0, &result);
2406 if (rc == LDAP_SUCCESS && (entry = ldap_first_entry(ld, result))) {
2407 DPRINTF1("found:%s", ldap_get_dn(ld, entry));
2408 sudo_ldap_parse_options(ld, entry);
2410 DPRINTF1("no default options found in %s", base->val);
2413 ldap_msgfree(result);
2417 debug_return_int(0);
2421 * like sudoers_lookup() - only LDAP style
2424 sudo_ldap_lookup(struct sudo_nss *nss, int ret, int pwflag)
2426 struct sudo_ldap_handle *handle = nss->handle;
2429 int i, rc, setenv_implied;
2430 struct ldap_result *lres = NULL;
2431 debug_decl(sudo_ldap_lookup, SUDO_DEBUG_LDAP)
2433 if (handle == NULL || handle->ld == NULL)
2434 debug_return_int(ret);
2437 /* Fetch list of sudoRole entries that match user and host. */
2438 lres = sudo_ldap_result_get(nss, sudo_user.pw);
2441 * The following queries are only determine whether or not a
2442 * password is required, so the order of the entries doesn't matter.
2445 int doauth = UNSPEC;
2446 int matched = UNSPEC;
2447 enum def_tuple pwcheck =
2448 (pwflag == -1) ? never : sudo_defs_table[pwflag].sd_un.tuple;
2450 DPRINTF1("perform search for pwflag %d", pwflag);
2451 for (i = 0; i < lres->nentries; i++) {
2452 entry = lres->entries[i].entry;
2453 if ((pwcheck == any && doauth != false) ||
2454 (pwcheck == all && doauth == false)) {
2455 doauth = sudo_ldap_check_bool(ld, entry, "authenticate");
2457 /* Only check the command when listing another user. */
2458 if (user_uid == 0 || list_pw == NULL ||
2459 user_uid == list_pw->pw_uid ||
2460 sudo_ldap_check_command(ld, entry, NULL)) {
2465 if (matched || user_uid == 0) {
2466 SET(ret, VALIDATE_OK);
2467 CLR(ret, VALIDATE_NOT_OK);
2468 if (def_authenticate) {
2471 SET(ret, FLAG_CHECK_USER);
2475 if (doauth == false)
2476 def_authenticate = false;
2479 def_authenticate = false;
2489 DPRINTF1("searching LDAP for sudoers entries");
2491 setenv_implied = false;
2492 for (i = 0; i < lres->nentries; i++) {
2493 entry = lres->entries[i].entry;
2494 if (!sudo_ldap_check_runas(ld, entry))
2496 rc = sudo_ldap_check_command(ld, entry, &setenv_implied);
2498 /* We have a match. */
2499 DPRINTF1("Command %sallowed", rc == true ? "" : "NOT ");
2501 DPRINTF1("LDAP entry: %p", entry);
2502 /* Apply entry-specific options. */
2505 sudo_ldap_parse_options(ld, entry);
2507 /* Set role and type if not specified on command line. */
2508 if (user_role == NULL)
2509 user_role = def_role;
2510 if (user_type == NULL)
2511 user_type = def_type;
2512 #endif /* HAVE_SELINUX */
2513 SET(ret, VALIDATE_OK);
2514 CLR(ret, VALIDATE_NOT_OK);
2516 SET(ret, VALIDATE_NOT_OK);
2517 CLR(ret, VALIDATE_OK);
2524 DPRINTF1("done with LDAP searches");
2525 DPRINTF1("user_matches=%d", lres->user_matches);
2526 DPRINTF1("host_matches=%d", lres->host_matches);
2528 if (!ISSET(ret, VALIDATE_OK)) {
2529 /* No matching entries. */
2530 if (pwflag && list_pw == NULL)
2531 SET(ret, FLAG_NO_CHECK);
2533 if (lres->user_matches)
2534 CLR(ret, FLAG_NO_USER);
2535 if (lres->host_matches)
2536 CLR(ret, FLAG_NO_HOST);
2537 DPRINTF1("sudo_ldap_lookup(%d)=0x%02x", pwflag, ret);
2539 debug_return_int(ret);
2543 * Comparison function for ldap_entry_wrapper structures, descending order.
2546 ldap_entry_compare(const void *a, const void *b)
2548 const struct ldap_entry_wrapper *aw = a;
2549 const struct ldap_entry_wrapper *bw = b;
2550 debug_decl(ldap_entry_compare, SUDO_DEBUG_LDAP)
2552 debug_return_int(bw->order < aw->order ? -1 :
2553 (bw->order > aw->order ? 1 : 0));
2557 * Find the last entry in the list of searches, usually the
2558 * one currently being used to add entries.
2559 * XXX - use a tailq instead?
2561 static struct ldap_search_list *
2562 sudo_ldap_result_last_search(struct ldap_result *lres)
2564 struct ldap_search_list *result = lres->searches;
2565 debug_decl(sudo_ldap_result_last_search, SUDO_DEBUG_LDAP)
2568 while (result->next)
2569 result = result->next;
2571 debug_return_ptr(result);
2575 * Add an entry to the result structure.
2577 static struct ldap_entry_wrapper *
2578 sudo_ldap_result_add_entry(struct ldap_result *lres, LDAPMessage *entry)
2580 struct ldap_search_list *last;
2584 debug_decl(sudo_ldap_result_add_entry, SUDO_DEBUG_LDAP)
2586 /* Determine whether the entry has the sudoOrder attribute. */
2587 last = sudo_ldap_result_last_search(lres);
2588 bv = ldap_get_values_len(last->ldap, entry, "sudoOrder");
2590 if (ldap_count_values_len(bv) > 0) {
2591 /* Get the value of this attribute, 0 if not present. */
2592 DPRINTF2("order attribute raw: %s", (*bv)->bv_val);
2593 order = strtod((*bv)->bv_val, &ep);
2594 if (ep == (*bv)->bv_val || *ep != '\0') {
2595 warningx(_("invalid sudoOrder attribute: %s"), (*bv)->bv_val);
2598 DPRINTF2("order attribute: %f", order);
2600 ldap_value_free_len(bv);
2604 * Enlarge the array of entry wrappers as needed, preallocating blocks
2605 * of 100 entries to save on allocation time.
2607 if (++lres->nentries > lres->allocated_entries) {
2608 lres->allocated_entries += ALLOCATION_INCREMENT;
2609 lres->entries = erealloc3(lres->entries, lres->allocated_entries,
2610 sizeof(lres->entries[0]));
2613 /* Fill in the new entry and return it. */
2614 lres->entries[lres->nentries - 1].entry = entry;
2615 lres->entries[lres->nentries - 1].order = order;
2617 debug_return_ptr(&lres->entries[lres->nentries - 1]);
2621 * Free the ldap result structure in the sudo_nss handle.
2624 sudo_ldap_result_free_nss(struct sudo_nss *nss)
2626 struct sudo_ldap_handle *handle = nss->handle;
2627 debug_decl(sudo_ldap_result_free_nss, SUDO_DEBUG_LDAP)
2629 if (handle->result != NULL) {
2630 DPRINTF1("removing reusable search result");
2631 sudo_ldap_result_free(handle->result);
2632 if (handle->username) {
2633 efree(handle->username);
2634 handle->username = NULL;
2636 handle->grlist = NULL;
2637 handle->result = NULL;
2643 * Perform the LDAP query for the user or return a cached query if
2644 * there is one for this user.
2646 static struct ldap_result *
2647 sudo_ldap_result_get(struct sudo_nss *nss, struct passwd *pw)
2649 struct sudo_ldap_handle *handle = nss->handle;
2650 struct ldap_config_list_str *base;
2651 struct ldap_result *lres;
2652 struct timeval tv, *tvp = NULL;
2653 LDAPMessage *entry, *result;
2654 LDAP *ld = handle->ld;
2657 debug_decl(sudo_ldap_result_get, SUDO_DEBUG_LDAP)
2660 * If we already have a cached result, return it so we don't have to
2661 * have to contact the LDAP server again.
2663 if (handle->result) {
2664 if (handle->grlist == user_group_list &&
2665 strcmp(pw->pw_name, handle->username) == 0) {
2666 DPRINTF1("reusing previous result (user %s) with %d entries",
2667 handle->username, handle->result->nentries);
2668 debug_return_ptr(handle->result);
2670 /* User mismatch, cached result cannot be used. */
2671 DPRINTF1("removing result (user %s), new search (user %s)",
2672 handle->username, pw->pw_name);
2673 sudo_ldap_result_free_nss(nss);
2677 * Okay - time to search for anything that matches this user
2678 * Lets limit it to only two queries of the LDAP server
2680 * The first pass will look by the username, groups, and
2681 * the keyword ALL. We will then inspect the results that
2682 * came back from the query. We don't need to inspect the
2683 * sudoUser in this pass since the LDAP server already scanned
2686 * The second pass will return all the entries that contain non-
2687 * Unix groups, including netgroups. Then we take the non-Unix
2688 * groups returned and try to match them against the username.
2690 * Since we have to sort the possible entries before we make a
2691 * decision, we perform the queries and store all of the results in
2692 * an ldap_result object. The results are then sorted by sudoOrder.
2694 lres = sudo_ldap_result_alloc();
2695 for (pass = 0; pass < 2; pass++) {
2696 filt = pass ? sudo_ldap_build_pass2() : sudo_ldap_build_pass1(pw);
2697 DPRINTF1("ldap search '%s'", filt);
2698 for (base = ldap_conf.base; base != NULL; base = base->next) {
2699 DPRINTF1("searching from base '%s'",
2701 if (ldap_conf.timeout > 0) {
2702 tv.tv_sec = ldap_conf.timeout;
2707 rc = ldap_search_ext_s(ld, base->val, LDAP_SCOPE_SUBTREE, filt,
2708 NULL, 0, NULL, NULL, tvp, 0, &result);
2709 if (rc != LDAP_SUCCESS) {
2710 DPRINTF1("nothing found for '%s'", filt);
2713 lres->user_matches = true;
2715 /* Add the seach result to list of search results. */
2716 DPRINTF1("adding search result");
2717 sudo_ldap_result_add_search(lres, ld, result);
2718 LDAP_FOREACH(entry, ld, result) {
2720 sudo_ldap_check_non_unix_group(ld, entry, pw)) &&
2721 sudo_ldap_check_host(ld, entry)) {
2722 lres->host_matches = true;
2723 sudo_ldap_result_add_entry(lres, entry);
2726 DPRINTF1("result now has %d entries", lres->nentries);
2731 /* Sort the entries by the sudoOrder attribute. */
2732 DPRINTF1("sorting remaining %d entries", lres->nentries);
2733 qsort(lres->entries, lres->nentries, sizeof(lres->entries[0]),
2734 ldap_entry_compare);
2736 /* Store everything in the sudo_nss handle. */
2737 handle->result = lres;
2738 handle->username = estrdup(pw->pw_name);
2739 handle->grlist = user_group_list;
2741 debug_return_ptr(lres);
2745 * Shut down the LDAP connection.
2748 sudo_ldap_close(struct sudo_nss *nss)
2750 struct sudo_ldap_handle *handle = nss->handle;
2751 debug_decl(sudo_ldap_close, SUDO_DEBUG_LDAP)
2753 if (handle != NULL) {
2754 /* Free the result before unbinding; it may use the LDAP connection. */
2755 sudo_ldap_result_free_nss(nss);
2757 /* Unbind and close the LDAP connection. */
2758 if (handle->ld != NULL) {
2759 ldap_unbind_ext_s(handle->ld, NULL, NULL);
2763 /* Free the handle container. */
2767 debug_return_int(0);
2774 sudo_ldap_parse(struct sudo_nss *nss)
2781 * Create an ldap_result from an LDAP search result.
2783 * This function is currently not used anywhere, it is left here as
2784 * an example of how to use the cached searches.
2786 static struct ldap_result *
2787 sudo_ldap_result_from_search(LDAP *ldap, LDAPMessage *searchresult)
2790 * An ldap_result is built from several search results, which are
2791 * organized in a list. The head of the list is maintained in the
2792 * ldap_result structure, together with the wrappers that point
2793 * to individual entries, this has to be initialized first.
2795 struct ldap_result *result = sudo_ldap_result_alloc();
2798 * Build a new list node for the search result, this creates the
2801 struct ldap_search_list *last = sudo_ldap_result_add_search(result,
2802 ldap, searchresult);
2805 * Now add each entry in the search result to the array of of entries
2806 * in the ldap_result object.
2809 LDAP_FOREACH(entry, last->ldap, last->searchresult) {
2810 sudo_ldap_result_add_entry(result, entry);
2812 DPRINTF1("sudo_ldap_result_from_search: %d entries found", result->nentries);