Diff for /embedaddon/sudo/plugins/sudoers/ldap.c between versions 1.1.1.2 and 1.1.1.6

version 1.1.1.2, 2012/05/29 12:26:49 version 1.1.1.6, 2014/06/15 16:12:54
Line 1 Line 1
 /*  /*
 * Copyright (c) 2003-2011 Todd C. Miller <Todd.Miller@courtesan.com> * Copyright (c) 2003-2014 Todd C. Miller <Todd.Miller@courtesan.com>
  *   *
  * This code is derived from software contributed by Aaron Spangler.   * This code is derived from software contributed by Aaron Spangler.
  *   *
Line 20 Line 20
   
 #include <sys/types.h>  #include <sys/types.h>
 #include <sys/time.h>  #include <sys/time.h>
 #include <sys/param.h>  
 #include <sys/stat.h>  #include <sys/stat.h>
 #include <stdio.h>  #include <stdio.h>
 #ifdef STDC_HEADERS  #ifdef STDC_HEADERS
Line 40 Line 39
 #ifdef HAVE_UNISTD_H  #ifdef HAVE_UNISTD_H
 # include <unistd.h>  # include <unistd.h>
 #endif /* HAVE_UNISTD_H */  #endif /* HAVE_UNISTD_H */
#if TIME_WITH_SYS_TIME#ifdef TIME_WITH_SYS_TIME
 # include <time.h>  # include <time.h>
 #endif  #endif
 #include <ctype.h>  #include <ctype.h>
   #include <fcntl.h>
 #include <pwd.h>  #include <pwd.h>
 #include <grp.h>  #include <grp.h>
   #include <signal.h>
 #include <netinet/in.h>  #include <netinet/in.h>
 #include <arpa/inet.h>  #include <arpa/inet.h>
 #include <netdb.h>  
 #ifdef HAVE_LBER_H  #ifdef HAVE_LBER_H
 # include <lber.h>  # include <lber.h>
 #endif  #endif
Line 64 Line 64
 # else  # else
 #  include <sasl.h>  #  include <sasl.h>
 # endif  # endif
# if HAVE_GSS_KRB5_CCACHE_NAME#endif /* HAVE_LDAP_SASL_INTERACTIVE_BIND_S */
#  if defined(HAVE_GSSAPI_GSSAPI_KRB5_H) 
#   include <gssapi/gssapi.h> 
#   include <gssapi/gssapi_krb5.h> 
#  elif defined(HAVE_GSSAPI_GSSAPI_H) 
#   include <gssapi/gssapi.h> 
#  else 
#   include <gssapi.h> 
#  endif 
# endif 
#endif 
   
 #include "sudoers.h"  #include "sudoers.h"
 #include "parse.h"  #include "parse.h"
 #include "lbuf.h"  #include "lbuf.h"
   #include "sudo_dso.h"
   
 /* Older Netscape LDAP SDKs don't prototype ldapssl_set_strength() */  /* Older Netscape LDAP SDKs don't prototype ldapssl_set_strength() */
 #if defined(HAVE_LDAPSSL_SET_STRENGTH) && !defined(HAVE_LDAP_SSL_H) && !defined(HAVE_MPS_LDAP_SSL_H)  #if defined(HAVE_LDAPSSL_SET_STRENGTH) && !defined(HAVE_LDAP_SSL_H) && !defined(HAVE_MPS_LDAP_SSL_H)
 extern int ldapssl_set_strength(LDAP *ldap, int strength);  extern int ldapssl_set_strength(LDAP *ldap, int strength);
 #endif  #endif
   
   #if !defined(LDAP_OPT_NETWORK_TIMEOUT) && defined(LDAP_OPT_CONNECT_TIMEOUT)
   # define LDAP_OPT_NETWORK_TIMEOUT LDAP_OPT_CONNECT_TIMEOUT
   #endif
   
 #ifndef LDAP_OPT_SUCCESS  #ifndef LDAP_OPT_SUCCESS
 # define LDAP_OPT_SUCCESS LDAP_SUCCESS  # define LDAP_OPT_SUCCESS LDAP_SUCCESS
 #endif  #endif
Line 116  extern int ldapssl_set_strength(LDAP *ldap, int streng Line 111  extern int ldapssl_set_strength(LDAP *ldap, int streng
         (var) != NULL;                                                  \          (var) != NULL;                                                  \
         (var) = ldap_next_entry((ld), (var)))          (var) = ldap_next_entry((ld), (var)))
   
#define  DPRINTF(args, level)        if (ldap_conf.debug >= level) warningx args#if defined(__GNUC__) && __GNUC__ == 2
 # define DPRINTF1(fmt...) do {                                          \
     if (ldap_conf.debug >= 1)                                              \
         warningx(__VA_ARGS__);                                          \
     sudo_debug_printf(SUDO_DEBUG_DIAG, fmt);                            \
 } while (0)
 # define DPRINTF2(fmt...) do {                                          \
     if (ldap_conf.debug >= 2)                                           \
         warningx(__VA_ARGS__);                                          \
     sudo_debug_printf(SUDO_DEBUG_INFO, fmt);                            \
 } while (0)
 #else
 # define DPRINTF1(...) do {                                             \
     if (ldap_conf.debug >= 1)                                           \
         warningx(__VA_ARGS__);                                          \
     sudo_debug_printf(SUDO_DEBUG_DIAG, __VA_ARGS__);                    \
 } while (0)
 # define DPRINTF2(...) do {                                             \
     if (ldap_conf.debug >= 2)                                           \
         warningx(__VA_ARGS__);                                          \
     sudo_debug_printf(SUDO_DEBUG_INFO, __VA_ARGS__);                    \
 } while (0)
 #endif
   
 #define CONF_BOOL       0  #define CONF_BOOL       0
 #define CONF_INT        1  #define CONF_INT        1
Line 128  extern int ldapssl_set_strength(LDAP *ldap, int streng Line 145  extern int ldapssl_set_strength(LDAP *ldap, int streng
 #define SUDO_LDAP_SSL           1  #define SUDO_LDAP_SSL           1
 #define SUDO_LDAP_STARTTLS      2  #define SUDO_LDAP_STARTTLS      2
   
/* The TIMEFILTER_LENGTH includes the filter itself plus the global AND/* Default search filter. */
   wrapped around the user filter and the time filter when timed entries#define DEFAULT_SEARCH_FILTER   "(objectClass=sudoRole)"
 
 /* The TIMEFILTER_LENGTH is the length of the filter when timed entries
    are used. The length is computed as follows:     are used. The length is computed as follows:
       85       for the filter       81       for the filter itself
       + 2 * 13 for the now timestamp       + 2 * 17 for the now timestamp
       +      3 for the global AND 
 */  */
#define TIMEFILTER_LENGTH       114    #define TIMEFILTER_LENGTH       115
   
 /*  /*
  * The ldap_search structure implements a linked list of ldap and   * The ldap_search structure implements a linked list of ldap and
  * search result pointers, which allows us to remove them after   * search result pointers, which allows us to remove them after
  * all search results have been combined in memory.   * all search results have been combined in memory.
  * XXX - should probably be a tailq since we do appends  
  */   */
struct ldap_search_list {struct ldap_search_result {
     STAILQ_ENTRY(ldap_search_result) entries;
     LDAP *ldap;      LDAP *ldap;
     LDAPMessage *searchresult;      LDAPMessage *searchresult;
     struct ldap_search_list *next;  
 };  };
   STAILQ_HEAD(ldap_search_list, ldap_search_result);
   
 /*  /*
  * The ldap_entry_wrapper structure is used to implement sorted result entries.   * The ldap_entry_wrapper structure is used to implement sorted result entries.
Line 166  struct ldap_entry_wrapper { Line 184  struct ldap_entry_wrapper {
  * well as an array of all result entries sorted by the sudoOrder attribute.   * well as an array of all result entries sorted by the sudoOrder attribute.
  */   */
 struct ldap_result {  struct ldap_result {
    struct ldap_search_list *searches;    struct ldap_search_list searches;
     struct ldap_entry_wrapper *entries;      struct ldap_entry_wrapper *entries;
     int allocated_entries;      int allocated_entries;
     int nentries;      int nentries;
Line 182  struct ldap_config_table { Line 200  struct ldap_config_table {
     void *valp;                 /* pointer into ldap_conf */      void *valp;                 /* pointer into ldap_conf */
 };  };
   
struct ldap_config_list_str {struct ldap_config_str {
    struct ldap_config_list_str *next;    STAILQ_ENTRY(ldap_config_str) entries;
     char val[1];      char val[1];
 };  };
   
   STAILQ_HEAD(ldap_config_str_list, ldap_config_str);
   
 /* LDAP configuration structure */  /* LDAP configuration structure */
 static struct ldap_config {  static struct ldap_config {
     int port;      int port;
Line 203  static struct ldap_config { Line 223  static struct ldap_config {
     int timed;      int timed;
     int deref;      int deref;
     char *host;      char *host;
    struct ldap_config_list_str *uri;    struct ldap_config_str_list uri;
     char *binddn;      char *binddn;
     char *bindpw;      char *bindpw;
     char *rootbinddn;      char *rootbinddn;
    struct ldap_config_list_str *base;    struct ldap_config_str_list base;
     char *search_filter;      char *search_filter;
     char *ssl;      char *ssl;
     char *tls_cacertfile;      char *tls_cacertfile;
Line 216  static struct ldap_config { Line 236  static struct ldap_config {
     char *tls_cipher_suite;      char *tls_cipher_suite;
     char *tls_certfile;      char *tls_certfile;
     char *tls_keyfile;      char *tls_keyfile;
       char *tls_keypw;
     char *sasl_auth_id;      char *sasl_auth_id;
     char *rootsasl_auth_id;      char *rootsasl_auth_id;
     char *sasl_secprops;      char *sasl_secprops;
Line 255  static struct ldap_config_table ldap_conf_global[] = { Line 276  static struct ldap_config_table ldap_conf_global[] = {
 #ifdef LDAP_OPT_X_TLS_CIPHER_SUITE  #ifdef LDAP_OPT_X_TLS_CIPHER_SUITE
     { "tls_ciphers", CONF_STR, LDAP_OPT_X_TLS_CIPHER_SUITE,      { "tls_ciphers", CONF_STR, LDAP_OPT_X_TLS_CIPHER_SUITE,
         &ldap_conf.tls_cipher_suite },          &ldap_conf.tls_cipher_suite },
   #elif defined(LDAP_OPT_SSL_CIPHER)
       { "tls_ciphers", CONF_STR, LDAP_OPT_SSL_CIPHER,
           &ldap_conf.tls_cipher_suite },
 #endif  #endif
 #ifdef LDAP_OPT_X_TLS_CERTFILE  #ifdef LDAP_OPT_X_TLS_CERTFILE
     { "tls_cert", CONF_STR, LDAP_OPT_X_TLS_CERTFILE,      { "tls_cert", CONF_STR, LDAP_OPT_X_TLS_CERTFILE,
Line 268  static struct ldap_config_table ldap_conf_global[] = { Line 292  static struct ldap_config_table ldap_conf_global[] = {
 #else  #else
     { "tls_key", CONF_STR, -1, &ldap_conf.tls_keyfile },      { "tls_key", CONF_STR, -1, &ldap_conf.tls_keyfile },
 #endif  #endif
   #ifdef HAVE_LDAP_SSL_CLIENT_INIT
       { "tls_keypw", CONF_STR, -1, &ldap_conf.tls_keypw },
   #endif
     { "binddn", CONF_STR, -1, &ldap_conf.binddn },      { "binddn", CONF_STR, -1, &ldap_conf.binddn },
     { "bindpw", CONF_STR, -1, &ldap_conf.bindpw },      { "bindpw", CONF_STR, -1, &ldap_conf.bindpw },
     { "rootbinddn", CONF_STR, -1, &ldap_conf.rootbinddn },      { "rootbinddn", CONF_STR, -1, &ldap_conf.rootbinddn },
Line 346  struct sudo_ldap_handle { Line 373  struct sudo_ldap_handle {
 };  };
   
 struct sudo_nss sudo_nss_ldap = {  struct sudo_nss sudo_nss_ldap = {
    &sudo_nss_ldap,    { NULL, NULL },
    NULL, 
     sudo_ldap_open,      sudo_ldap_open,
     sudo_ldap_close,      sudo_ldap_close,
     sudo_ldap_parse,      sudo_ldap_parse,
Line 371  sudo_ldap_conf_add_ports(void) Line 397  sudo_ldap_conf_add_ports(void)
   
     char *host, *port, defport[13];      char *host, *port, defport[13];
     char hostbuf[LINE_MAX * 2];      char hostbuf[LINE_MAX * 2];
       int len;
     debug_decl(sudo_ldap_conf_add_ports, SUDO_DEBUG_LDAP)      debug_decl(sudo_ldap_conf_add_ports, SUDO_DEBUG_LDAP)
   
     hostbuf[0] = '\0';      hostbuf[0] = '\0';
    if (snprintf(defport, sizeof(defport), ":%d", ldap_conf.port) >= sizeof(defport))    len = snprintf(defport, sizeof(defport), ":%d", ldap_conf.port);
        errorx(1, _("sudo_ldap_conf_add_ports: port too large"));    if (len <= 0 || (size_t)len >= sizeof(defport))
         fatalx(U_("sudo_ldap_conf_add_ports: port too large"));
   
     for ((host = strtok(ldap_conf.host, " \t")); host; (host = strtok(NULL, " \t"))) {      for ((host = strtok(ldap_conf.host, " \t")); host; (host = strtok(NULL, " \t"))) {
         if (hostbuf[0] != '\0') {          if (hostbuf[0] != '\0') {
Line 398  sudo_ldap_conf_add_ports(void) Line 426  sudo_ldap_conf_add_ports(void)
     debug_return;      debug_return;
   
 toobig:  toobig:
    errorx(1, _("sudo_ldap_conf_add_ports: out of space expanding hostbuf"));    fatalx(U_("sudo_ldap_conf_add_ports: out of space expanding hostbuf"));
 }  }
 #endif  #endif
   
Line 407  toobig: Line 435  toobig:
  * For each uri, convert to host:port pairs.  For ldaps:// enable SSL   * For each uri, convert to host:port pairs.  For ldaps:// enable SSL
  * Accepts: uris of the form ldap:/// or ldap://hostname:portnum/   * Accepts: uris of the form ldap:/// or ldap://hostname:portnum/
  * where the trailing slash is optional.   * where the trailing slash is optional.
    * Returns LDAP_SUCCESS on success, else non-zero.
  */   */
 static int  static int
sudo_ldap_parse_uri(const struct ldap_config_list_str *uri_list)sudo_ldap_parse_uri(const struct ldap_config_str_list *uri_list)
 {  {
       const struct ldap_config_str *entry;
     char *buf, *uri, *host, *cp, *port;      char *buf, *uri, *host, *cp, *port;
     char hostbuf[LINE_MAX];      char hostbuf[LINE_MAX];
     int nldap = 0, nldaps = 0;      int nldap = 0, nldaps = 0;
     int rc = -1;      int rc = -1;
     debug_decl(sudo_ldap_parse_uri, SUDO_DEBUG_LDAP)      debug_decl(sudo_ldap_parse_uri, SUDO_DEBUG_LDAP)
   
    do {    hostbuf[0] = '\0';
        buf = estrdup(uri_list->val);    STAILQ_FOREACH(entry, uri_list, entries) {
        hostbuf[0] = '\0';        buf = estrdup(entry->val);
         for ((uri = strtok(buf, " \t")); uri != NULL; (uri = strtok(NULL, " \t"))) {          for ((uri = strtok(buf, " \t")); uri != NULL; (uri = strtok(NULL, " \t"))) {
             if (strncasecmp(uri, "ldap://", 7) == 0) {              if (strncasecmp(uri, "ldap://", 7) == 0) {
                 nldap++;                  nldap++;
Line 428  sudo_ldap_parse_uri(const struct ldap_config_list_str  Line 458  sudo_ldap_parse_uri(const struct ldap_config_list_str 
                 nldaps++;                  nldaps++;
                 host = uri + 8;                  host = uri + 8;
             } else {              } else {
                warningx(_("unsupported LDAP uri type: %s"), uri);                warningx(U_("unsupported LDAP uri type: %s"), uri);
                 goto done;                  goto done;
             }              }
   
Line 456  sudo_ldap_parse_uri(const struct ldap_config_list_str  Line 486  sudo_ldap_parse_uri(const struct ldap_config_list_str 
                         goto toobig;                          goto toobig;
             }              }
         }          }
         if (hostbuf[0] == '\0') {  
             warningx(_("invalid uri: %s"), uri_list->val);  
             goto done;  
         }  
   
         if (nldaps != 0) {          if (nldaps != 0) {
             if (nldap != 0) {              if (nldap != 0) {
                warningx(_("unable to mix ldap and ldaps URIs"));                warningx(U_("unable to mix ldap and ldaps URIs"));
                 goto done;                  goto done;
             }              }
            if (ldap_conf.ssl_mode == SUDO_LDAP_STARTTLS) {            if (ldap_conf.ssl_mode == SUDO_LDAP_STARTTLS)
                warningx(_("unable to mix ldaps and starttls"));                warningx(U_("starttls not supported when using ldaps"));
                goto done; 
            } 
             ldap_conf.ssl_mode = SUDO_LDAP_SSL;              ldap_conf.ssl_mode = SUDO_LDAP_SSL;
         }          }
   
         efree(ldap_conf.host);  
         ldap_conf.host = estrdup(hostbuf);  
         efree(buf);          efree(buf);
    } while ((uri_list = uri_list->next));    }
 
     buf = NULL;      buf = NULL;
     rc = 0;  
   
       /* Store parsed URI(s) in host for ldap_create() or ldap_init(). */
       efree(ldap_conf.host);
       ldap_conf.host = estrdup(hostbuf);
   
       rc = LDAP_SUCCESS;
   
 done:  done:
     efree(buf);      efree(buf);
     debug_return_int(rc);      debug_return_int(rc);
   
 toobig:  toobig:
    errorx(1, _("sudo_ldap_parse_uri: out of space building hostbuf"));    fatalx(U_("sudo_ldap_parse_uri: out of space building hostbuf"));
 }  }
 #else  #else
 static char *  static char *
sudo_ldap_join_uri(struct ldap_config_list_str *uri_list)sudo_ldap_join_uri(struct ldap_config_str_list *uri_list)
 {  {
    struct ldap_config_list_str *uri;    struct ldap_config_str *uri;
     size_t len = 0;      size_t len = 0;
     char *buf, *cp;      char *buf, *cp;
     debug_decl(sudo_ldap_join_uri, SUDO_DEBUG_LDAP)      debug_decl(sudo_ldap_join_uri, SUDO_DEBUG_LDAP)
   
    /* Usually just a single entry. */    STAILQ_FOREACH(uri, uri_list, entries) {
    if (uri_list->next == NULL)        if (ldap_conf.ssl_mode == SUDO_LDAP_STARTTLS) {
        debug_return_str(estrdup(uri_list->val));            if (strncasecmp(uri->val, "ldaps://", 8) == 0) {
                warningx(U_("starttls not supported when using ldaps"));
    for (uri = uri_list; uri != NULL; uri = uri->next) {                ldap_conf.ssl_mode = SUDO_LDAP_SSL;
             }
         }
         len += strlen(uri->val) + 1;          len += strlen(uri->val) + 1;
     }      }
     buf = cp = emalloc(len);      buf = cp = emalloc(len);
     buf[0] = '\0';      buf[0] = '\0';
    for (uri = uri_list; uri != NULL; uri = uri->next) {    STAILQ_FOREACH(uri, uri_list, entries) {
         cp += strlcpy(cp, uri->val, len - (cp - buf));          cp += strlcpy(cp, uri->val, len - (cp - buf));
         *cp++ = ' ';          *cp++ = ' ';
     }      }
Line 515  sudo_ldap_join_uri(struct ldap_config_list_str *uri_li Line 542  sudo_ldap_join_uri(struct ldap_config_list_str *uri_li
 }  }
 #endif /* HAVE_LDAP_INITIALIZE */  #endif /* HAVE_LDAP_INITIALIZE */
   
   /*
    * Wrapper for ldap_create() or ldap_init() that handles
    * SSL/TLS initialization as well.
    * Returns LDAP_SUCCESS on success, else non-zero.
    */
 static int  static int
 sudo_ldap_init(LDAP **ldp, const char *host, int port)  sudo_ldap_init(LDAP **ldp, const char *host, int port)
 {  {
    LDAP *ld = NULL;    LDAP *ld;
     int rc = LDAP_CONNECT_ERROR;      int rc = LDAP_CONNECT_ERROR;
     debug_decl(sudo_ldap_init, SUDO_DEBUG_LDAP)      debug_decl(sudo_ldap_init, SUDO_DEBUG_LDAP)
   
 #ifdef HAVE_LDAPSSL_INIT  #ifdef HAVE_LDAPSSL_INIT
     if (ldap_conf.ssl_mode != SUDO_LDAP_CLEAR) {      if (ldap_conf.ssl_mode != SUDO_LDAP_CLEAR) {
         const int defsecure = ldap_conf.ssl_mode == SUDO_LDAP_SSL;          const int defsecure = ldap_conf.ssl_mode == SUDO_LDAP_SSL;
        DPRINTF(("ldapssl_clientauth_init(%s, %s)",        DPRINTF2("ldapssl_clientauth_init(%s, %s)",
             ldap_conf.tls_certfile ? ldap_conf.tls_certfile : "NULL",              ldap_conf.tls_certfile ? ldap_conf.tls_certfile : "NULL",
            ldap_conf.tls_keyfile ? ldap_conf.tls_keyfile : "NULL"), 2);            ldap_conf.tls_keyfile ? ldap_conf.tls_keyfile : "NULL");
         rc = ldapssl_clientauth_init(ldap_conf.tls_certfile, NULL,          rc = ldapssl_clientauth_init(ldap_conf.tls_certfile, NULL,
             ldap_conf.tls_keyfile != NULL, ldap_conf.tls_keyfile, NULL);              ldap_conf.tls_keyfile != NULL, ldap_conf.tls_keyfile, NULL);
         /*          /*
Line 552  sudo_ldap_init(LDAP **ldp, const char *host, int port) Line 584  sudo_ldap_init(LDAP **ldp, const char *host, int port)
                 }                  }
             }              }
             if (retry) {              if (retry) {
                DPRINTF(("ldapssl_clientauth_init(%s, %s)",                DPRINTF2("ldapssl_clientauth_init(%s, %s)",
                     ldap_conf.tls_certfile ? ldap_conf.tls_certfile : "NULL",                      ldap_conf.tls_certfile ? ldap_conf.tls_certfile : "NULL",
                    ldap_conf.tls_keyfile ? ldap_conf.tls_keyfile : "NULL"), 2);                    ldap_conf.tls_keyfile ? ldap_conf.tls_keyfile : "NULL");
                 rc = ldapssl_clientauth_init(ldap_conf.tls_certfile, NULL,                  rc = ldapssl_clientauth_init(ldap_conf.tls_certfile, NULL,
                     ldap_conf.tls_keyfile != NULL, ldap_conf.tls_keyfile, NULL);                      ldap_conf.tls_keyfile != NULL, ldap_conf.tls_keyfile, NULL);
             }              }
         }          }
         if (rc != LDAP_SUCCESS) {          if (rc != LDAP_SUCCESS) {
            warningx(_("unable to initialize SSL cert and key db: %s"),            warningx(U_("unable to initialize SSL cert and key db: %s"),
                 ldapssl_err2string(rc));                  ldapssl_err2string(rc));
             if (ldap_conf.tls_certfile == NULL)              if (ldap_conf.tls_certfile == NULL)
                warningx(_("you must set TLS_CERT in %s to use SSL"),                warningx(U_("you must set TLS_CERT in %s to use SSL"),
                    _PATH_LDAP_CONF);                    path_ldap_conf);
             goto done;              goto done;
         }          }
   
        DPRINTF(("ldapssl_init(%s, %d, %d)", host, port, defsecure), 2);        DPRINTF2("ldapssl_init(%s, %d, %d)", host, port, defsecure);
         if ((ld = ldapssl_init(host, port, defsecure)) != NULL)          if ((ld = ldapssl_init(host, port, defsecure)) != NULL)
             rc = LDAP_SUCCESS;              rc = LDAP_SUCCESS;
     } else      } else
   #elif defined(HAVE_LDAP_SSL_INIT) && defined(HAVE_LDAP_SSL_CLIENT_INIT)
       if (ldap_conf.ssl_mode == SUDO_LDAP_SSL) {
           int sslrc;
           rc = ldap_ssl_client_init(ldap_conf.tls_keyfile, ldap_conf.tls_keypw,
               0, &sslrc);
           if (rc != LDAP_SUCCESS) {
               warningx("ldap_ssl_client_init(): %s (SSL reason code %d)",
                   ldap_err2string(rc), sslrc);
               goto done;
           }
           DPRINTF2("ldap_ssl_init(%s, %d, NULL)", host, port);
           if ((ld = ldap_ssl_init((char *)host, port, NULL)) != NULL)
               rc = LDAP_SUCCESS;
       } else
 #endif  #endif
     {      {
 #ifdef HAVE_LDAP_CREATE  #ifdef HAVE_LDAP_CREATE
        DPRINTF(("ldap_create()"), 2);        DPRINTF2("ldap_create()");
         if ((rc = ldap_create(&ld)) != LDAP_SUCCESS)          if ((rc = ldap_create(&ld)) != LDAP_SUCCESS)
             goto done;              goto done;
        DPRINTF(("ldap_set_option(LDAP_OPT_HOST_NAME, %s)", host), 2);        DPRINTF2("ldap_set_option(LDAP_OPT_HOST_NAME, %s)", host);
         rc = ldap_set_option(ld, LDAP_OPT_HOST_NAME, host);          rc = ldap_set_option(ld, LDAP_OPT_HOST_NAME, host);
 #else  #else
        DPRINTF(("ldap_init(%s, %d)", host, port), 2);        DPRINTF2("ldap_init(%s, %d)", host, port);
        if ((ld = ldap_init(host, port)) != NULL)        if ((ld = ldap_init((char *)host, port)) == NULL)
            rc = LDAP_SUCCESS;            goto done;
         rc = LDAP_SUCCESS;
 #endif  #endif
     }      }
   
 done:  
     *ldp = ld;      *ldp = ld;
   done:
     debug_return_int(rc);      debug_return_int(rc);
 }  }
   
 /*  /*
  * Walk through search results and return true if we have a matching   * Walk through search results and return true if we have a matching
 * netgroup, else false. * non-Unix group (including netgroups), else false.
  */   */
 static bool  static bool
sudo_ldap_check_user_netgroup(LDAP *ld, LDAPMessage *entry, char *user)sudo_ldap_check_non_unix_group(LDAP *ld, LDAPMessage *entry, struct passwd *pw)
 {  {
     struct berval **bv, **p;      struct berval **bv, **p;
     char *val;      char *val;
     int ret = false;      int ret = false;
    debug_decl(sudo_ldap_check_user_netgroup, SUDO_DEBUG_LDAP)    debug_decl(sudo_ldap_check_non_unix_group, SUDO_DEBUG_LDAP)
   
     if (!entry)      if (!entry)
         debug_return_bool(ret);          debug_return_bool(ret);
Line 615  sudo_ldap_check_user_netgroup(LDAP *ld, LDAPMessage *e Line 662  sudo_ldap_check_user_netgroup(LDAP *ld, LDAPMessage *e
     /* walk through values */      /* walk through values */
     for (p = bv; *p != NULL && !ret; p++) {      for (p = bv; *p != NULL && !ret; p++) {
         val = (*p)->bv_val;          val = (*p)->bv_val;
        /* match any */        if (*val == '+') {
        if (netgr_matches(val, NULL, NULL, user))            if (netgr_matches(val, NULL, NULL, pw->pw_name))
            ret = true;                ret = true;
        DPRINTF(("ldap sudoUser netgroup '%s' ... %s", val,            DPRINTF2("ldap sudoUser netgroup '%s' ... %s", val,
            ret ? "MATCH!" : "not"), 2 + ((ret) ? 0 : 1));                ret ? "MATCH!" : "not");
         } else {
             if (group_plugin_query(pw->pw_name, val + 2, pw))
                 ret = true;
             DPRINTF2("ldap sudoUser non-Unix group '%s' ... %s", val,
                 ret ? "MATCH!" : "not");
         }
     }      }
   
     ldap_value_free_len(bv);    /* cleanup */      ldap_value_free_len(bv);    /* cleanup */
Line 655  sudo_ldap_check_host(LDAP *ld, LDAPMessage *entry) Line 708  sudo_ldap_check_host(LDAP *ld, LDAPMessage *entry)
             netgr_matches(val, user_host, user_shost, NULL) ||              netgr_matches(val, user_host, user_shost, NULL) ||
             hostname_matches(user_shost, user_host, val))              hostname_matches(user_shost, user_host, val))
             ret = true;              ret = true;
        DPRINTF(("ldap sudoHost '%s' ... %s", val,        DPRINTF2("ldap sudoHost '%s' ... %s", val, ret ? "MATCH!" : "not");
            ret ? "MATCH!" : "not"), 2); 
     }      }
   
     ldap_value_free_len(bv);    /* cleanup */      ldap_value_free_len(bv);    /* cleanup */
Line 723  sudo_ldap_check_runas_user(LDAP *ld, LDAPMessage *entr Line 775  sudo_ldap_check_runas_user(LDAP *ld, LDAPMessage *entr
             }              }
             /* FALLTHROUGH */              /* FALLTHROUGH */
         default:          default:
            if (strcasecmp(val, runas_pw->pw_name) == 0)            if (userpw_matches(val, runas_pw->pw_name, runas_pw))
                 ret = true;                  ret = true;
             break;              break;
         }          }
        DPRINTF(("ldap sudoRunAsUser '%s' ... %s", val,        DPRINTF2("ldap sudoRunAsUser '%s' ... %s", val, ret ? "MATCH!" : "not");
            ret ? "MATCH!" : "not"), 2); 
     }      }
   
     ldap_value_free_len(bv);    /* cleanup */      ldap_value_free_len(bv);    /* cleanup */
Line 758  sudo_ldap_check_runas_group(LDAP *ld, LDAPMessage *ent Line 809  sudo_ldap_check_runas_group(LDAP *ld, LDAPMessage *ent
         val = (*p)->bv_val;          val = (*p)->bv_val;
         if (strcmp(val, "ALL") == 0 || group_matches(val, runas_gr))          if (strcmp(val, "ALL") == 0 || group_matches(val, runas_gr))
             ret = true;              ret = true;
        DPRINTF(("ldap sudoRunAsGroup '%s' ... %s", val,        DPRINTF2("ldap sudoRunAsGroup '%s' ... %s",
            ret ? "MATCH!" : "not"), 2);            val, ret ? "MATCH!" : "not");
     }      }
   
     ldap_value_free_len(bv);    /* cleanup */      ldap_value_free_len(bv);    /* cleanup */
Line 786  sudo_ldap_check_runas(LDAP *ld, LDAPMessage *entry) Line 837  sudo_ldap_check_runas(LDAP *ld, LDAPMessage *entry)
     debug_return_bool(ret);      debug_return_bool(ret);
 }  }
   
   static struct sudo_digest *
   sudo_ldap_extract_digest(char **cmnd, struct sudo_digest *digest)
   {
       char *ep, *cp = *cmnd;
       int digest_type = SUDO_DIGEST_INVALID;
       debug_decl(sudo_ldap_check_command, SUDO_DEBUG_LDAP)
   
       /*
        * Check for and extract a digest prefix, e.g.
        * sha224:d06a2617c98d377c250edd470fd5e576327748d82915d6e33b5f8db1 /bin/ls
        */
       if (cp[0] == 's' && cp[1] == 'h' && cp[2] == 'a') {
           switch (cp[3]) {
           case '2':
               if (cp[4] == '2' && cp[5] == '4')
                   digest_type = SUDO_DIGEST_SHA224;
               else if (cp[4] == '5' && cp[5] == '6')
                   digest_type = SUDO_DIGEST_SHA256;
               break;
           case '3':
               if (cp[4] == '8' && cp[5] == '4')
                   digest_type = SUDO_DIGEST_SHA384;
               break;
           case '5':
               if (cp[4] == '1' && cp[5] == '2')
                   digest_type = SUDO_DIGEST_SHA512;
               break;
           }
           if (digest_type != SUDO_DIGEST_INVALID) {
               cp += 6;
               while (isblank((unsigned char)*cp))
                   cp++;
               if (*cp == ':') {
                   cp++;
                   while (isblank((unsigned char)*cp))
                       cp++;
                   ep = cp;
                   while (*ep != '\0' && !isblank((unsigned char)*ep))
                       ep++;
                   if (*ep != '\0') {
                       digest->digest_type = digest_type;
                       digest->digest_str = estrndup(cp, (size_t)(ep - cp));
                       cp = ep + 1;
                       while (isblank((unsigned char)*cp))
                           cp++;
                       *cmnd = cp;
                       DPRINTF1("%s digest %s for %s",
                           digest_type == SUDO_DIGEST_SHA224 ? "sha224" :
                           digest_type == SUDO_DIGEST_SHA256 ? "sha256" :
                           digest_type == SUDO_DIGEST_SHA384 ? "sha384" :
                           "sha512", digest->digest_str, cp);
                       debug_return_ptr(digest);
                   }
               }
           }
       }
       debug_return_ptr(NULL);
   }
   
 /*  /*
  * Walk through search results and return true if we have a command match,   * Walk through search results and return true if we have a command match,
  * false if disallowed and UNSPEC if not matched.   * false if disallowed and UNSPEC if not matched.
Line 793  sudo_ldap_check_runas(LDAP *ld, LDAPMessage *entry) Line 903  sudo_ldap_check_runas(LDAP *ld, LDAPMessage *entry)
 static int  static int
 sudo_ldap_check_command(LDAP *ld, LDAPMessage *entry, int *setenv_implied)  sudo_ldap_check_command(LDAP *ld, LDAPMessage *entry, int *setenv_implied)
 {  {
       struct sudo_digest digest, *allowed_digest = NULL;
     struct berval **bv, **p;      struct berval **bv, **p;
     char *allowed_cmnd, *allowed_args, *val;      char *allowed_cmnd, *allowed_args, *val;
     bool foundbang;      bool foundbang;
Line 813  sudo_ldap_check_command(LDAP *ld, LDAPMessage *entry,  Line 924  sudo_ldap_check_command(LDAP *ld, LDAPMessage *entry, 
             ret = true;              ret = true;
             if (setenv_implied != NULL)              if (setenv_implied != NULL)
                 *setenv_implied = true;                  *setenv_implied = true;
            DPRINTF(("ldap sudoCommand '%s' ... MATCH!", val), 2);            DPRINTF2("ldap sudoCommand '%s' ... MATCH!", val);
             continue;              continue;
         }          }
   
           /* check for sha-2 digest */
           allowed_digest = sudo_ldap_extract_digest(&val, &digest);
   
         /* check for !command */          /* check for !command */
         if (*val == '!') {          if (*val == '!') {
             foundbang = true;              foundbang = true;
Line 832  sudo_ldap_check_command(LDAP *ld, LDAPMessage *entry,  Line 946  sudo_ldap_check_command(LDAP *ld, LDAPMessage *entry, 
             *allowed_args++ = '\0';              *allowed_args++ = '\0';
   
         /* check the command like normal */          /* check the command like normal */
        if (command_matches(allowed_cmnd, allowed_args)) {        if (command_matches(allowed_cmnd, allowed_args, allowed_digest)) {
             /*              /*
              * If allowed (no bang) set ret but keep on checking.               * If allowed (no bang) set ret but keep on checking.
              * If disallowed (bang), exit loop.               * If disallowed (bang), exit loop.
              */               */
             ret = foundbang ? false : true;              ret = foundbang ? false : true;
         }          }
        DPRINTF(("ldap sudoCommand '%s' ... %s", val,        DPRINTF2("ldap sudoCommand '%s' ... %s",
            ret == true ? "MATCH!" : "not"), 2);            val, ret == true ? "MATCH!" : "not");
   
         efree(allowed_cmnd);    /* cleanup */          efree(allowed_cmnd);    /* cleanup */
           if (allowed_digest != NULL)
               efree(allowed_digest->digest_str);
     }      }
   
     ldap_value_free_len(bv);    /* more cleanup */      ldap_value_free_len(bv);    /* more cleanup */
Line 872  sudo_ldap_check_bool(LDAP *ld, LDAPMessage *entry, cha Line 988  sudo_ldap_check_bool(LDAP *ld, LDAPMessage *entry, cha
     /* walk through options */      /* walk through options */
     for (p = bv; *p != NULL; p++) {      for (p = bv; *p != NULL; p++) {
         var = (*p)->bv_val;;          var = (*p)->bv_val;;
        DPRINTF(("ldap sudoOption: '%s'", var), 2);        DPRINTF2("ldap sudoOption: '%s'", var);
   
         if ((ch = *var) == '!')          if ((ch = *var) == '!')
             var++;              var++;
Line 906  sudo_ldap_parse_options(LDAP *ld, LDAPMessage *entry) Line 1022  sudo_ldap_parse_options(LDAP *ld, LDAPMessage *entry)
     /* walk through options */      /* walk through options */
     for (p = bv; *p != NULL; p++) {      for (p = bv; *p != NULL; p++) {
         var = estrdup((*p)->bv_val);          var = estrdup((*p)->bv_val);
        DPRINTF(("ldap sudoOption: '%s'", var), 2);        DPRINTF2("ldap sudoOption: '%s'", var);
   
         /* check for equals sign past first char */          /* check for equals sign past first char */
         val = strchr(var, '=');          val = strchr(var, '=');
Line 963  sudo_ldap_timefilter(char *buffer, size_t buffersize) Line 1079  sudo_ldap_timefilter(char *buffer, size_t buffersize)
 {  {
     struct tm *tp;      struct tm *tp;
     time_t now;      time_t now;
    char timebuffer[16];    char timebuffer[sizeof("20120727121554.0Z")];
     int bytes = 0;      int bytes = 0;
     debug_decl(sudo_ldap_timefilter, SUDO_DEBUG_LDAP)      debug_decl(sudo_ldap_timefilter, SUDO_DEBUG_LDAP)
   
     /* Make sure we have a formatted timestamp for __now__. */      /* Make sure we have a formatted timestamp for __now__. */
     time(&now);      time(&now);
     if ((tp = gmtime(&now)) == NULL) {      if ((tp = gmtime(&now)) == NULL) {
        warning(_("unable to get GMT time"));        warning(U_("unable to get GMT time"));
         goto done;          goto done;
     }      }
   
     /* Format the timestamp according to the RFC. */      /* Format the timestamp according to the RFC. */
    if (strftime(timebuffer, sizeof(timebuffer), "%Y%m%d%H%M%SZ", tp) == 0) {    if (strftime(timebuffer, sizeof(timebuffer), "%Y%m%d%H%M%S.0Z", tp) == 0) {
        warning(_("unable to format timestamp"));        warningx(U_("unable to format timestamp"));
         goto done;          goto done;
     }      }
   
     /* Build filter. */      /* Build filter. */
     bytes = snprintf(buffer, buffersize, "(&(|(!(sudoNotAfter=*))(sudoNotAfter>=%s))(|(!(sudoNotBefore=*))(sudoNotBefore<=%s)))",      bytes = snprintf(buffer, buffersize, "(&(|(!(sudoNotAfter=*))(sudoNotAfter>=%s))(|(!(sudoNotBefore=*))(sudoNotBefore<=%s)))",
         timebuffer, timebuffer);          timebuffer, timebuffer);
    if (bytes < 0 || bytes >= buffersize) {    if (bytes <= 0 || (size_t)bytes >= buffersize) {
        warning(_("unable to build time filter"));        warning(U_("unable to build time filter"));
         bytes = 0;          bytes = 0;
     }      }
   
Line 1108  static char * Line 1224  static char *
 sudo_ldap_build_pass1(struct passwd *pw)  sudo_ldap_build_pass1(struct passwd *pw)
 {  {
     struct group *grp;      struct group *grp;
    char *buf, timebuffer[TIMEFILTER_LENGTH], gidbuf[MAX_UID_T_LEN];    char *buf, timebuffer[TIMEFILTER_LENGTH + 1], gidbuf[MAX_UID_T_LEN + 1];
     struct group_list *grlist;      struct group_list *grlist;
     size_t sz = 0;      size_t sz = 0;
     int i;      int i;
     debug_decl(sudo_ldap_build_pass1, SUDO_DEBUG_LDAP)      debug_decl(sudo_ldap_build_pass1, SUDO_DEBUG_LDAP)
   
    /* Start with LDAP search filter length + 3 */    /* If there is a filter, allocate space for the global AND. */
     if (ldap_conf.timed || ldap_conf.search_filter)
         sz += 3;
 
     /* Add LDAP search filter if present. */
     if (ldap_conf.search_filter)      if (ldap_conf.search_filter)
        sz += strlen(ldap_conf.search_filter) + 3;        sz += strlen(ldap_conf.search_filter);
   
     /* Then add (|(sudoUser=USERNAME)(sudoUser=ALL)) + NUL */      /* Then add (|(sudoUser=USERNAME)(sudoUser=ALL)) + NUL */
     sz += 29 + sudo_ldap_value_len(pw->pw_name);      sz += 29 + sudo_ldap_value_len(pw->pw_name);
Line 1126  sudo_ldap_build_pass1(struct passwd *pw) Line 1246  sudo_ldap_build_pass1(struct passwd *pw)
         sz += 12 + sudo_ldap_value_len(grp->gr_name);          sz += 12 + sudo_ldap_value_len(grp->gr_name);
     }      }
     sz += 13 + MAX_UID_T_LEN;      sz += 13 + MAX_UID_T_LEN;
    if ((grlist = get_group_list(pw)) != NULL) {    if ((grlist = sudo_get_grlist(pw)) != NULL) {
         for (i = 0; i < grlist->ngroups; i++) {          for (i = 0; i < grlist->ngroups; i++) {
             if (grp != NULL && strcasecmp(grlist->groups[i], grp->gr_name) == 0)              if (grp != NULL && strcasecmp(grlist->groups[i], grp->gr_name) == 0)
                 continue;                  continue;
Line 1193  sudo_ldap_build_pass1(struct passwd *pw) Line 1313  sudo_ldap_build_pass1(struct passwd *pw)
   
     /* Done with groups. */      /* Done with groups. */
     if (grlist != NULL)      if (grlist != NULL)
        grlist_delref(grlist);        sudo_grlist_delref(grlist);
     if (grp != NULL)      if (grp != NULL)
        gr_delref(grp);        sudo_gr_delref(grp);
   
     /* Add ALL to list and end the global OR */      /* Add ALL to list and end the global OR */
     if (strlcat(buf, "(sudoUser=ALL)", sz) >= sz)      if (strlcat(buf, "(sudoUser=ALL)", sz) >= sz)
        errorx(1, _("sudo_ldap_build_pass1 allocation mismatch"));        fatalx(U_("sudo_ldap_build_pass1 allocation mismatch"));
   
     /* Add the time restriction, or simply end the global OR. */      /* Add the time restriction, or simply end the global OR. */
     if (ldap_conf.timed) {      if (ldap_conf.timed) {
Line 1215  sudo_ldap_build_pass1(struct passwd *pw) Line 1335  sudo_ldap_build_pass1(struct passwd *pw)
 }  }
   
 /*  /*
 * Builds up a filter to check against netgroup entries in LDAP. * Builds up a filter to check against non-Unix group
  * entries in LDAP, including netgroups.
  */   */
 static char *  static char *
 sudo_ldap_build_pass2(void)  sudo_ldap_build_pass2(void)
 {  {
    char *filt, timebuffer[TIMEFILTER_LENGTH];    char *filt, timebuffer[TIMEFILTER_LENGTH + 1];
     debug_decl(sudo_ldap_build_pass2, SUDO_DEBUG_LDAP)      debug_decl(sudo_ldap_build_pass2, SUDO_DEBUG_LDAP)
   
       /* Short circuit if no non-Unix group support. */
       if (!def_use_netgroups && !def_group_plugin) {
           debug_return_str(NULL);
       }
   
     if (ldap_conf.timed)      if (ldap_conf.timed)
         sudo_ldap_timefilter(timebuffer, sizeof(timebuffer));          sudo_ldap_timefilter(timebuffer, sizeof(timebuffer));
   
     /*      /*
     * Match all sudoUsers beginning with a '+'.     * Match all sudoUsers beginning with '+' or '%:'.
      * If a search filter or time restriction is specified,        * If a search filter or time restriction is specified, 
      * those get ANDed in to the expression.       * those get ANDed in to the expression.
      */       */
    easprintf(&filt, "%s%s(sudoUser=+*)%s%s",    if (def_group_plugin) {
        (ldap_conf.timed || ldap_conf.search_filter) ? "(&" : "",        easprintf(&filt, "%s%s(|(sudoUser=%s*)(sudoUser=%%:*))%s%s",
        ldap_conf.search_filter ? ldap_conf.search_filter : "",            (ldap_conf.timed || ldap_conf.search_filter) ? "(&" : "",
        ldap_conf.timed ? timebuffer : "",            ldap_conf.search_filter ? ldap_conf.search_filter : "",
        (ldap_conf.timed || ldap_conf.search_filter) ? ")" : "");            def_use_netgroups ? "+" : "",
             ldap_conf.timed ? timebuffer : "",
             (ldap_conf.timed || ldap_conf.search_filter) ? ")" : "");
     } else {
         easprintf(&filt, "%s%s(sudoUser=*)(sudoUser=+*)%s%s",
             (ldap_conf.timed || ldap_conf.search_filter) ? "(&" : "",
             ldap_conf.search_filter ? ldap_conf.search_filter : "",
             ldap_conf.timed ? timebuffer : "",
             (ldap_conf.timed || ldap_conf.search_filter) ? ")" : "");
     }
   
     debug_return_str(filt);      debug_return_str(filt);
 }  }
Line 1247  sudo_ldap_read_secret(const char *path) Line 1382  sudo_ldap_read_secret(const char *path)
     char buf[LINE_MAX], *cp;      char buf[LINE_MAX], *cp;
     debug_decl(sudo_ldap_read_secret, SUDO_DEBUG_LDAP)      debug_decl(sudo_ldap_read_secret, SUDO_DEBUG_LDAP)
   
    if ((fp = fopen(_PATH_LDAP_SECRET, "r")) != NULL) {    if ((fp = fopen(path_ldap_secret, "r")) != NULL) {
         if (fgets(buf, sizeof(buf), fp) != NULL) {          if (fgets(buf, sizeof(buf), fp) != NULL) {
             if ((cp = strchr(buf, '\n')) != NULL)              if ((cp = strchr(buf, '\n')) != NULL)
                 *cp = '\0';                  *cp = '\0';
Line 1272  sudo_ldap_parse_keyword(const char *keyword, const cha Line 1407  sudo_ldap_parse_keyword(const char *keyword, const cha
     struct ldap_config_table *table)      struct ldap_config_table *table)
 {  {
     struct ldap_config_table *cur;      struct ldap_config_table *cur;
       const char *errstr;
     debug_decl(sudo_ldap_parse_keyword, SUDO_DEBUG_LDAP)      debug_decl(sudo_ldap_parse_keyword, SUDO_DEBUG_LDAP)
   
     /* Look up keyword in config tables */      /* Look up keyword in config tables */
Line 1292  sudo_ldap_parse_keyword(const char *keyword, const cha Line 1428  sudo_ldap_parse_keyword(const char *keyword, const cha
                 *(int *)(cur->valp) = atobool(value) == true;                  *(int *)(cur->valp) = atobool(value) == true;
                 break;                  break;
             case CONF_INT:              case CONF_INT:
                *(int *)(cur->valp) = atoi(value);                *(int *)(cur->valp) = strtonum(value, INT_MIN, INT_MAX, &errstr);
                 if (errstr != NULL) {
                     warningx(U_("%s: %s: %s: %s"),
                         path_ldap_conf, keyword, value, U_(errstr));
                 }
                 break;                  break;
             case CONF_STR:              case CONF_STR:
                 efree(*(char **)(cur->valp));                  efree(*(char **)(cur->valp));
                *(char **)(cur->valp) = estrdup(value);                *(char **)(cur->valp) = *value ? estrdup(value) : NULL;
                 break;                  break;
             case CONF_LIST_STR:              case CONF_LIST_STR:
                 {                  {
                    struct ldap_config_list_str **p;                    struct ldap_config_str_list *head;
                     struct ldap_config_str *str;
                     size_t len = strlen(value);                      size_t len = strlen(value);
   
                     if (len > 0) {                      if (len > 0) {
                        p = (struct ldap_config_list_str **)cur->valp;                        head = (struct ldap_config_str_list *)cur->valp;
                        while (*p != NULL)                        str = emalloc(sizeof(*str) + len);
                            p = &(*p)->next;                        memcpy(str->val, value, len + 1);
                        *p = emalloc(sizeof(struct ldap_config_list_str) + len);                        STAILQ_INSERT_TAIL(head, str, entries);
                        memcpy((*p)->val, value, len + 1); 
                        (*p)->next = NULL; 
                     }                      }
                 }                  }
                 break;                  break;
Line 1320  sudo_ldap_parse_keyword(const char *keyword, const cha Line 1459  sudo_ldap_parse_keyword(const char *keyword, const cha
     debug_return_bool(false);      debug_return_bool(false);
 }  }
   
   #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
   static const char *
   sudo_krb5_ccname_path(const char *old_ccname)
   {
       const char *ccname = old_ccname;
       debug_decl(sudo_krb5_ccname_path, SUDO_DEBUG_LDAP)
   
       /* Strip off leading FILE: or WRFILE: prefix. */
       switch (ccname[0]) {
           case 'F':
           case 'f':
               if (strncasecmp(ccname, "FILE:", 5) == 0)
                   ccname += 5;
               break;
           case 'W':
           case 'w':
               if (strncasecmp(ccname, "WRFILE:", 7) == 0)
                   ccname += 7;
               break;
       }
       sudo_debug_printf(SUDO_DEBUG_INFO|SUDO_DEBUG_LINENO,
           "ccache %s -> %s", old_ccname, ccname);
   
       /* Credential cache must be a fully-qualified path name. */
       debug_return_const_str(*ccname == '/' ? ccname : NULL);
   }
   
 static bool  static bool
   sudo_check_krb5_ccname(const char *ccname)
   {
       int fd = -1;
       const char *ccname_path;
       debug_decl(sudo_check_krb5_ccname, SUDO_DEBUG_LDAP)
   
       /* Strip off prefix to get path name. */
       ccname_path = sudo_krb5_ccname_path(ccname);
       if (ccname_path == NULL) {
           sudo_debug_printf(SUDO_DEBUG_WARN|SUDO_DEBUG_LINENO,
               "unsupported krb5 credential cache path: %s", ccname);
           debug_return_bool(false);
       }
       /* Make sure credential cache is fully-qualified and exists. */
       fd = open(ccname_path, O_RDONLY|O_NONBLOCK, 0);
       if (fd == -1) {
           sudo_debug_printf(SUDO_DEBUG_WARN|SUDO_DEBUG_LINENO,
               "unable to open krb5 credential cache: %s", ccname_path);
           debug_return_bool(false);
       }
       close(fd);
       sudo_debug_printf(SUDO_DEBUG_INFO,
           "using krb5 credential cache: %s", ccname_path);
       debug_return_bool(true);
   }
   #endif /* HAVE_LDAP_SASL_INTERACTIVE_BIND_S */
   
   static bool
 sudo_ldap_read_config(void)  sudo_ldap_read_config(void)
 {  {
     FILE *fp;      FILE *fp;
    char *cp, *keyword, *value;    char *cp, *keyword, *value, *line = NULL;
     size_t linesize = 0;
     debug_decl(sudo_ldap_read_config, SUDO_DEBUG_LDAP)      debug_decl(sudo_ldap_read_config, SUDO_DEBUG_LDAP)
   
     /* defaults */      /* defaults */
Line 1337  sudo_ldap_read_config(void) Line 1532  sudo_ldap_read_config(void)
     ldap_conf.use_sasl = -1;      ldap_conf.use_sasl = -1;
     ldap_conf.rootuse_sasl = -1;      ldap_conf.rootuse_sasl = -1;
     ldap_conf.deref = -1;      ldap_conf.deref = -1;
       ldap_conf.search_filter = estrdup(DEFAULT_SEARCH_FILTER);
       STAILQ_INIT(&ldap_conf.uri);
       STAILQ_INIT(&ldap_conf.base);
   
    if ((fp = fopen(_PATH_LDAP_CONF, "r")) == NULL)    if ((fp = fopen(path_ldap_conf, "r")) == NULL)
         debug_return_bool(false);          debug_return_bool(false);
   
    while ((cp = sudo_parseln(fp)) != NULL) {    while (sudo_parseln(&line, &linesize, NULL, fp) != -1) {
        if (*cp == '\0')        if (*line == '\0')
             continue;           /* skip empty line */              continue;           /* skip empty line */
   
         /* split into keyword and value */          /* split into keyword and value */
        keyword = cp;        keyword = cp = line;
         while (*cp && !isblank((unsigned char) *cp))          while (*cp && !isblank((unsigned char) *cp))
             cp++;              cp++;
         if (*cp)          if (*cp)
Line 1361  sudo_ldap_read_config(void) Line 1559  sudo_ldap_read_config(void)
         if (!sudo_ldap_parse_keyword(keyword, value, ldap_conf_global))          if (!sudo_ldap_parse_keyword(keyword, value, ldap_conf_global))
             sudo_ldap_parse_keyword(keyword, value, ldap_conf_conn);              sudo_ldap_parse_keyword(keyword, value, ldap_conf_conn);
     }      }
       free(line);
     fclose(fp);      fclose(fp);
   
     if (!ldap_conf.host)      if (!ldap_conf.host)
         ldap_conf.host = estrdup("localhost");          ldap_conf.host = estrdup("localhost");
   
    if (ldap_conf.debug > 1) {    DPRINTF1("LDAP Config Summary");
        sudo_printf(SUDO_CONV_ERROR_MSG, "LDAP Config Summary\n");    DPRINTF1("===================");
        sudo_printf(SUDO_CONV_ERROR_MSG, "===================\n");    if (!STAILQ_EMPTY(&ldap_conf.uri)) {
        if (ldap_conf.uri) {        struct ldap_config_str *uri;
            struct ldap_config_list_str *uri = ldap_conf.uri; 
   
            do {        STAILQ_FOREACH(uri, &ldap_conf.uri, entries) {
                sudo_printf(SUDO_CONV_ERROR_MSG, "uri              %s\n",            DPRINTF1("uri              %s", uri->val);
                    uri->val); 
            } while ((uri = uri->next) != NULL); 
        } else { 
            sudo_printf(SUDO_CONV_ERROR_MSG, "host             %s\n", 
                ldap_conf.host ?  ldap_conf.host : "(NONE)"); 
            sudo_printf(SUDO_CONV_ERROR_MSG, "port             %d\n", 
                ldap_conf.port); 
         }          }
        sudo_printf(SUDO_CONV_ERROR_MSG, "ldap_version     %d\n",    } else {
            ldap_conf.version);        DPRINTF1("host             %s",
             ldap_conf.host ? ldap_conf.host : "(NONE)");
         DPRINTF1("port             %d", ldap_conf.port);
     }
     DPRINTF1("ldap_version     %d", ldap_conf.version);
   
        if (ldap_conf.base) {    if (!STAILQ_EMPTY(&ldap_conf.base)) {
            struct ldap_config_list_str *base = ldap_conf.base;        struct ldap_config_str *base;
            do {        STAILQ_FOREACH(base, &ldap_conf.base, entries) {
                sudo_printf(SUDO_CONV_ERROR_MSG, "sudoers_base     %s\n",            DPRINTF1("sudoers_base     %s", base->val);
                    base->val); 
            } while ((base = base->next) != NULL); 
        } else { 
            sudo_printf(SUDO_CONV_ERROR_MSG, "sudoers_base     %s\n", 
                "(NONE: LDAP disabled)"); 
         }          }
        if (ldap_conf.search_filter) {    } else {
            sudo_printf(SUDO_CONV_ERROR_MSG, "search_filter    %s\n",        DPRINTF1("sudoers_base     %s", "(NONE: LDAP disabled)");
                ldap_conf.search_filter);    }
        }    if (ldap_conf.search_filter) {
        sudo_printf(SUDO_CONV_ERROR_MSG, "binddn           %s\n",        DPRINTF1("search_filter    %s", ldap_conf.search_filter);
            ldap_conf.binddn ?  ldap_conf.binddn : "(anonymous)");    }
        sudo_printf(SUDO_CONV_ERROR_MSG, "bindpw           %s\n",    DPRINTF1("binddn           %s",
            ldap_conf.bindpw ?  ldap_conf.bindpw : "(anonymous)");        ldap_conf.binddn ? ldap_conf.binddn : "(anonymous)");
        if (ldap_conf.bind_timelimit > 0) {    DPRINTF1("bindpw           %s",
            sudo_printf(SUDO_CONV_ERROR_MSG, "bind_timelimit   %d\n",        ldap_conf.bindpw ? ldap_conf.bindpw : "(anonymous)");
                ldap_conf.bind_timelimit);    if (ldap_conf.bind_timelimit > 0) {
        }        DPRINTF1("bind_timelimit   %d", ldap_conf.bind_timelimit);
        if (ldap_conf.timelimit > 0) {    }
            sudo_printf(SUDO_CONV_ERROR_MSG, "timelimit        %d\n",    if (ldap_conf.timelimit > 0) {
                ldap_conf.timelimit);        DPRINTF1("timelimit        %d", ldap_conf.timelimit);
        }    }
        if (ldap_conf.deref != -1) {    if (ldap_conf.deref != -1) {
            sudo_printf(SUDO_CONV_ERROR_MSG, "deref            %d\n",        DPRINTF1("deref            %d", ldap_conf.deref);
                ldap_conf.deref);    }
        }    DPRINTF1("ssl              %s", ldap_conf.ssl ? ldap_conf.ssl : "(no)");
        sudo_printf(SUDO_CONV_ERROR_MSG, "ssl              %s\n",    if (ldap_conf.tls_checkpeer != -1) {
            ldap_conf.ssl ?  ldap_conf.ssl : "(no)");        DPRINTF1("tls_checkpeer    %s",
        if (ldap_conf.tls_checkpeer != -1) {            ldap_conf.tls_checkpeer ? "(yes)" : "(no)");
            sudo_printf(SUDO_CONV_ERROR_MSG, "tls_checkpeer    %s\n",    }
                ldap_conf.tls_checkpeer ?  "(yes)" : "(no)");    if (ldap_conf.tls_cacertfile != NULL) {
        }        DPRINTF1("tls_cacertfile   %s", ldap_conf.tls_cacertfile);
        if (ldap_conf.tls_cacertfile != NULL) {    }
            sudo_printf(SUDO_CONV_ERROR_MSG, "tls_cacertfile   %s\n",    if (ldap_conf.tls_cacertdir != NULL) {
                ldap_conf.tls_cacertfile);        DPRINTF1("tls_cacertdir    %s", ldap_conf.tls_cacertdir);
        }    }
        if (ldap_conf.tls_cacertdir != NULL) {    if (ldap_conf.tls_random_file != NULL) {
            sudo_printf(SUDO_CONV_ERROR_MSG, "tls_cacertdir    %s\n",        DPRINTF1("tls_random_file  %s", ldap_conf.tls_random_file);
                ldap_conf.tls_cacertdir);    }
        }    if (ldap_conf.tls_cipher_suite != NULL) {
        if (ldap_conf.tls_random_file != NULL) {        DPRINTF1("tls_cipher_suite %s", ldap_conf.tls_cipher_suite);
            sudo_printf(SUDO_CONV_ERROR_MSG, "tls_random_file  %s\n",    }
                ldap_conf.tls_random_file);    if (ldap_conf.tls_certfile != NULL) {
        }        DPRINTF1("tls_certfile     %s", ldap_conf.tls_certfile);
        if (ldap_conf.tls_cipher_suite != NULL) {    }
            sudo_printf(SUDO_CONV_ERROR_MSG, "tls_cipher_suite %s\n",    if (ldap_conf.tls_keyfile != NULL) {
                ldap_conf.tls_cipher_suite);        DPRINTF1("tls_keyfile      %s", ldap_conf.tls_keyfile);
        }    }
        if (ldap_conf.tls_certfile != NULL) { 
            sudo_printf(SUDO_CONV_ERROR_MSG, "tls_certfile     %s\n", 
                ldap_conf.tls_certfile); 
        } 
        if (ldap_conf.tls_keyfile != NULL) { 
            sudo_printf(SUDO_CONV_ERROR_MSG, "tls_keyfile      %s\n", 
                ldap_conf.tls_keyfile); 
        } 
 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S  #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
        if (ldap_conf.use_sasl != -1) {    if (ldap_conf.use_sasl != -1) {
            sudo_printf(SUDO_CONV_ERROR_MSG, "use_sasl         %s\n",        DPRINTF1("use_sasl         %s", ldap_conf.use_sasl ? "yes" : "no");
                ldap_conf.use_sasl ? "yes" : "no");        DPRINTF1("sasl_auth_id     %s",
            sudo_printf(SUDO_CONV_ERROR_MSG, "sasl_auth_id     %s\n",            ldap_conf.sasl_auth_id ? ldap_conf.sasl_auth_id : "(NONE)");
                ldap_conf.sasl_auth_id ?  ldap_conf.sasl_auth_id : "(NONE)");        DPRINTF1("rootuse_sasl     %d",
            sudo_printf(SUDO_CONV_ERROR_MSG, "rootuse_sasl     %d\n",            ldap_conf.rootuse_sasl);
                ldap_conf.rootuse_sasl);        DPRINTF1("rootsasl_auth_id %s",
            sudo_printf(SUDO_CONV_ERROR_MSG, "rootsasl_auth_id %s\n",            ldap_conf.rootsasl_auth_id ? ldap_conf.rootsasl_auth_id : "(NONE)");
                ldap_conf.rootsasl_auth_id ?  ldap_conf.rootsasl_auth_id : "(NONE)");        DPRINTF1("sasl_secprops    %s",
            sudo_printf(SUDO_CONV_ERROR_MSG, "sasl_secprops    %s\n",            ldap_conf.sasl_secprops ? ldap_conf.sasl_secprops : "(NONE)");
                ldap_conf.sasl_secprops ?  ldap_conf.sasl_secprops : "(NONE)");        DPRINTF1("krb5_ccname      %s",
            sudo_printf(SUDO_CONV_ERROR_MSG, "krb5_ccname      %s\n",            ldap_conf.krb5_ccname ? ldap_conf.krb5_ccname : "(NONE)");
                ldap_conf.krb5_ccname ?  ldap_conf.krb5_ccname : "(NONE)"); 
        } 
#endif 
        sudo_printf(SUDO_CONV_ERROR_MSG, "===================\n"); 
     }      }
    if (!ldap_conf.base)#endif
     DPRINTF1("===================");
 
     if (STAILQ_EMPTY(&ldap_conf.base))
         debug_return_bool(false);       /* if no base is defined, ignore LDAP */          debug_return_bool(false);       /* if no base is defined, ignore LDAP */
   
     if (ldap_conf.bind_timelimit > 0)      if (ldap_conf.bind_timelimit > 0)
Line 1488  sudo_ldap_read_config(void) Line 1669  sudo_ldap_read_config(void)
   
 #ifndef HAVE_LDAP_INITIALIZE  #ifndef HAVE_LDAP_INITIALIZE
     /* Convert uri list to host list if no ldap_initialize(). */      /* Convert uri list to host list if no ldap_initialize(). */
    if (ldap_conf.uri) {    if (!STAILQ_EMPTY(&ldap_conf.uri)) {
        struct ldap_config_list_str *uri = ldap_conf.uri;        struct ldap_config_str *uri;
        if (sudo_ldap_parse_uri(uri) != 0)
         if (sudo_ldap_parse_uri(&ldap_conf.uri) != LDAP_SUCCESS)
             debug_return_bool(false);              debug_return_bool(false);
        do {        while ((uri = STAILQ_FIRST(&ldap_conf.uri)) != NULL) {
            ldap_conf.uri = uri->next;            STAILQ_REMOVE_HEAD(&ldap_conf.uri, entries);
             efree(uri);              efree(uri);
        } while ((uri = ldap_conf.uri));        }
         ldap_conf.port = LDAP_PORT;          ldap_conf.port = LDAP_PORT;
     }      }
 #endif  #endif
   
    if (!ldap_conf.uri) {    if (STAILQ_EMPTY(&ldap_conf.uri)) {
         /* Use port 389 for plaintext LDAP and port 636 for SSL LDAP */          /* Use port 389 for plaintext LDAP and port 636 for SSL LDAP */
         if (ldap_conf.port < 0)          if (ldap_conf.port < 0)
             ldap_conf.port =              ldap_conf.port =
Line 1530  sudo_ldap_read_config(void) Line 1712  sudo_ldap_read_config(void)
   
     /* If rootbinddn set, read in /etc/ldap.secret if it exists. */      /* If rootbinddn set, read in /etc/ldap.secret if it exists. */
     if (ldap_conf.rootbinddn)      if (ldap_conf.rootbinddn)
        sudo_ldap_read_secret(_PATH_LDAP_SECRET);        sudo_ldap_read_secret(path_ldap_secret);
   
 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S  #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
     /*      /*
      * Make sure we can open the file specified by krb5_ccname.       * Make sure we can open the file specified by krb5_ccname.
      */       */
     if (ldap_conf.krb5_ccname != NULL) {      if (ldap_conf.krb5_ccname != NULL) {
        if (strncasecmp(ldap_conf.krb5_ccname, "FILE:", 5) == 0 ||        if (!sudo_check_krb5_ccname(ldap_conf.krb5_ccname))
            strncasecmp(ldap_conf.krb5_ccname, "WRFILE:", 7) == 0) {            ldap_conf.krb5_ccname = NULL;
            value = ldap_conf.krb5_ccname + 
                (ldap_conf.krb5_ccname[4] == ':' ? 5 : 7); 
            if ((fp = fopen(value, "r")) != NULL) { 
                DPRINTF(("using krb5 credential cache: %s", value), 1); 
                fclose(fp); 
            } else { 
                /* Can't open it, just ignore the entry. */ 
                DPRINTF(("unable to open krb5 credential cache: %s", value), 1); 
                efree(ldap_conf.krb5_ccname); 
                ldap_conf.krb5_ccname = NULL; 
            } 
        } 
     }      }
 #endif  #endif
   
     debug_return_bool(true);      debug_return_bool(true);
 }  }
   
Line 1596  sudo_ldap_display_defaults(struct sudo_nss *nss, struc Line 1767  sudo_ldap_display_defaults(struct sudo_nss *nss, struc
 {  {
     struct berval **bv, **p;      struct berval **bv, **p;
     struct timeval tv, *tvp = NULL;      struct timeval tv, *tvp = NULL;
    struct ldap_config_list_str *base;    struct ldap_config_str *base;
     struct sudo_ldap_handle *handle = nss->handle;      struct sudo_ldap_handle *handle = nss->handle;
     LDAP *ld;      LDAP *ld;
     LDAPMessage *entry, *result;      LDAPMessage *entry, *result;
Line 1609  sudo_ldap_display_defaults(struct sudo_nss *nss, struc Line 1780  sudo_ldap_display_defaults(struct sudo_nss *nss, struc
     ld = handle->ld;      ld = handle->ld;
   
     filt = sudo_ldap_build_default_filter();      filt = sudo_ldap_build_default_filter();
    for (base = ldap_conf.base; base != NULL; base = base->next) {    STAILQ_FOREACH(base, &ldap_conf.base, entries) {
         if (ldap_conf.timeout > 0) {          if (ldap_conf.timeout > 0) {
             tv.tv_sec = ldap_conf.timeout;              tv.tv_sec = ldap_conf.timeout;
             tv.tv_usec = 0;              tv.tv_usec = 0;
Line 1821  sudo_ldap_display_privs(struct sudo_nss *nss, struct p Line 1992  sudo_ldap_display_privs(struct sudo_nss *nss, struct p
         goto done;          goto done;
     ld = handle->ld;      ld = handle->ld;
   
    DPRINTF(("ldap search for command list"), 1);    DPRINTF1("ldap search for command list");
     lres = sudo_ldap_result_get(nss, pw);      lres = sudo_ldap_result_get(nss, pw);
   
     /* Display all matching entries. */      /* Display all matching entries. */
Line 1856  sudo_ldap_display_cmnd(struct sudo_nss *nss, struct pa Line 2027  sudo_ldap_display_cmnd(struct sudo_nss *nss, struct pa
      * The sudo_ldap_result_get() function returns all nodes that match       * The sudo_ldap_result_get() function returns all nodes that match
      * the user and the host.       * the user and the host.
      */       */
    DPRINTF(("ldap search for command list"), 1);    DPRINTF1("ldap search for command list");
     lres = sudo_ldap_result_get(nss, pw);      lres = sudo_ldap_result_get(nss, pw);
     for (i = 0; i < lres->nentries; i++) {      for (i = 0; i < lres->nentries; i++) {
         entry = lres->entries[i].entry;          entry = lres->entries[i].entry;
Line 1875  done: Line 2046  done:
 }  }
   
 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S  #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
   static unsigned int (*sudo_gss_krb5_ccache_name)(unsigned int *minor_status, const char *name, const char **old_name);
   
 static int  static int
   sudo_set_krb5_ccache_name(const char *name, const char **old_name)
   {
       int rc = 0;
       unsigned int junk;
       static bool initialized;
       debug_decl(sudo_set_krb5_ccache_name, SUDO_DEBUG_LDAP)
   
       if (!initialized) {
           sudo_gss_krb5_ccache_name =
               sudo_dso_findsym(SUDO_DSO_DEFAULT, "gss_krb5_ccache_name");
           initialized = true;
       }
   
       /*
        * Try to use gss_krb5_ccache_name() if possible.
        * We also need to set KRB5CCNAME since some LDAP libs may not use
        * gss_krb5_ccache_name().
        */
       if (sudo_gss_krb5_ccache_name != NULL) {
           rc = sudo_gss_krb5_ccache_name(&junk, name, old_name);
       } else {
           /* No gss_krb5_ccache_name(), fall back on KRB5CCNAME. */
           if (old_name != NULL)
               *old_name = sudo_getenv("KRB5CCNAME");
       }
       if (name != NULL && *name != '\0')
           sudo_setenv("KRB5CCNAME", name, true);
       else
           sudo_unsetenv("KRB5CCNAME");
   
       debug_return_int(rc);
   }
   
   /*
    * Make a copy of the credential cache file specified by KRB5CCNAME
    * which must be readable by the user.  The resulting cache file
    * is root-owned and will be removed after authenticating via SASL.
    */
   static char *
   sudo_krb5_copy_cc_file(const char *old_ccname)
   {
       int ofd, nfd;
       ssize_t nread, nwritten = -1;
       static char new_ccname[sizeof(_PATH_TMP) + sizeof("sudocc_XXXXXXXX") - 1];
       char buf[10240], *ret = NULL;
       debug_decl(sudo_krb5_copy_cc_file, SUDO_DEBUG_LDAP)
   
       old_ccname = sudo_krb5_ccname_path(old_ccname);
       if (old_ccname != NULL) {
           /* Open credential cache as user to prevent stolen creds. */
           set_perms(PERM_USER);
           ofd = open(old_ccname, O_RDONLY|O_NONBLOCK);
           restore_perms();
   
           if (ofd != -1) {
               (void) fcntl(ofd, F_SETFL, 0);
               if (lock_file(ofd, SUDO_LOCK)) {
                   snprintf(new_ccname, sizeof(new_ccname), "%s%s",
                       _PATH_TMP, "sudocc_XXXXXXXX");
                   nfd = mkstemp(new_ccname);
                   if (nfd != -1) {
                       sudo_debug_printf(SUDO_DEBUG_INFO|SUDO_DEBUG_LINENO,
                           "copy ccache %s -> %s", old_ccname, new_ccname);
                       while ((nread = read(ofd, buf, sizeof(buf))) > 0) {
                           ssize_t off = 0;
                           do {
                               nwritten = write(nfd, buf + off, nread - off);
                               if (nwritten == -1) {
                                   warning("error writing to %s", new_ccname);
                                   goto write_error;
                               }
                               off += nwritten;
                           } while (off < nread);
                       }
                       if (nread == -1)
                           warning("unable to read %s", new_ccname);
   write_error:
                       close(nfd);
                       if (nread != -1 && nwritten != -1) {
                           ret = new_ccname;       /* success! */
                       } else {
                           unlink(new_ccname);     /* failed */
                       }
                   } else {
                       warning("unable to create temp file %s", new_ccname);
                   }
               }
               close(ofd);
           } else {
               sudo_debug_printf(SUDO_DEBUG_WARN|SUDO_DEBUG_LINENO|SUDO_DEBUG_ERRNO,
                   "unable to open %s", old_ccname);
           }
       }
       debug_return_str(ret);
   }
   
   static int
 sudo_ldap_sasl_interact(LDAP *ld, unsigned int flags, void *_auth_id,  sudo_ldap_sasl_interact(LDAP *ld, unsigned int flags, void *_auth_id,
     void *_interact)      void *_interact)
 {  {
     char *auth_id = (char *)_auth_id;      char *auth_id = (char *)_auth_id;
     sasl_interact_t *interact = (sasl_interact_t *)_interact;      sasl_interact_t *interact = (sasl_interact_t *)_interact;
       int rc = LDAP_SUCCESS;
     debug_decl(sudo_ldap_sasl_interact, SUDO_DEBUG_LDAP)      debug_decl(sudo_ldap_sasl_interact, SUDO_DEBUG_LDAP)
   
     for (; interact->id != SASL_CB_LIST_END; interact++) {      for (; interact->id != SASL_CB_LIST_END; interact++) {
        if (interact->id != SASL_CB_USER)        if (interact->id != SASL_CB_USER) {
            debug_return_int(LDAP_PARAM_ERROR);            warningx("sudo_ldap_sasl_interact: unexpected interact id %lu",
                 interact->id);
             rc = LDAP_PARAM_ERROR;
             break;
         }
   
         if (auth_id != NULL)          if (auth_id != NULL)
             interact->result = auth_id;              interact->result = auth_id;
Line 1896  sudo_ldap_sasl_interact(LDAP *ld, unsigned int flags,  Line 2171  sudo_ldap_sasl_interact(LDAP *ld, unsigned int flags, 
   
         interact->len = strlen(interact->result);          interact->len = strlen(interact->result);
 #if SASL_VERSION_MAJOR < 2  #if SASL_VERSION_MAJOR < 2
        interact->result = estrdup(interact->result);        interact->result = strdup(interact->result);
         if (interact->result == NULL) {
             rc = LDAP_NO_MEMORY;
             break;
         }
 #endif /* SASL_VERSION_MAJOR < 2 */  #endif /* SASL_VERSION_MAJOR < 2 */
           DPRINTF2("sudo_ldap_sasl_interact: SASL_CB_USER %s",
               (const char *)interact->result);
     }      }
    debug_return_int(LDAP_SUCCESS);    debug_return_int(rc);
 }  }
 #endif /* HAVE_LDAP_SASL_INTERACTIVE_BIND_S */  #endif /* HAVE_LDAP_SASL_INTERACTIVE_BIND_S */
   
   
 /*  /*
  * Set LDAP options from the specified options table   * Set LDAP options from the specified options table
    * Returns LDAP_SUCCESS on success, else non-zero.
  */   */
 static int  static int
 sudo_ldap_set_options_table(LDAP *ld, struct ldap_config_table *table)  sudo_ldap_set_options_table(LDAP *ld, struct ldap_config_table *table)
 {  {
     struct ldap_config_table *cur;      struct ldap_config_table *cur;
    int ival, rc;    int ival, rc, errors = 0;
     char *sval;      char *sval;
     debug_decl(sudo_ldap_set_options_table, SUDO_DEBUG_LDAP)      debug_decl(sudo_ldap_set_options_table, SUDO_DEBUG_LDAP)
   
Line 1924  sudo_ldap_set_options_table(LDAP *ld, struct ldap_conf Line 2205  sudo_ldap_set_options_table(LDAP *ld, struct ldap_conf
         case CONF_INT:          case CONF_INT:
             ival = *(int *)(cur->valp);              ival = *(int *)(cur->valp);
             if (ival >= 0) {              if (ival >= 0) {
                   DPRINTF1("ldap_set_option: %s -> %d", cur->conf_str, ival);
                 rc = ldap_set_option(ld, cur->opt_val, &ival);                  rc = ldap_set_option(ld, cur->opt_val, &ival);
                 if (rc != LDAP_OPT_SUCCESS) {                  if (rc != LDAP_OPT_SUCCESS) {
                     warningx("ldap_set_option: %s -> %d: %s",                      warningx("ldap_set_option: %s -> %d: %s",
                         cur->conf_str, ival, ldap_err2string(rc));                          cur->conf_str, ival, ldap_err2string(rc));
                    debug_return_int(-1);                    errors++;
                 }                  }
                 DPRINTF(("ldap_set_option: %s -> %d", cur->conf_str, ival), 1);  
             }              }
             break;              break;
         case CONF_STR:          case CONF_STR:
             sval = *(char **)(cur->valp);              sval = *(char **)(cur->valp);
             if (sval != NULL) {              if (sval != NULL) {
                   DPRINTF1("ldap_set_option: %s -> %s", cur->conf_str, sval);
                 rc = ldap_set_option(ld, cur->opt_val, sval);                  rc = ldap_set_option(ld, cur->opt_val, sval);
                 if (rc != LDAP_OPT_SUCCESS) {                  if (rc != LDAP_OPT_SUCCESS) {
                     warningx("ldap_set_option: %s -> %s: %s",                      warningx("ldap_set_option: %s -> %s: %s",
                         cur->conf_str, sval, ldap_err2string(rc));                          cur->conf_str, sval, ldap_err2string(rc));
                    debug_return_int(-1);                    errors++;
                 }                  }
                 DPRINTF(("ldap_set_option: %s -> %s", cur->conf_str, sval), 1);  
             }              }
             break;              break;
         }          }
     }      }
    debug_return_int(0);    debug_return_int(errors ? -1 : LDAP_SUCCESS);
 }  }
   
 /*  /*
  * Set LDAP options based on the global config table.   * Set LDAP options based on the global config table.
    * Returns LDAP_SUCCESS on success, else non-zero.
  */   */
 static int  static int
 sudo_ldap_set_options_global(void)  sudo_ldap_set_options_global(void)
Line 1967  sudo_ldap_set_options_global(void) Line 2249  sudo_ldap_set_options_global(void)
   
     /* Parse global LDAP options table. */      /* Parse global LDAP options table. */
     rc = sudo_ldap_set_options_table(NULL, ldap_conf_global);      rc = sudo_ldap_set_options_table(NULL, ldap_conf_global);
    if (rc == -1)    debug_return_int(rc);
        debug_return_int(-1); 
    debug_return_int(0); 
 }  }
   
 /*  /*
  * Set LDAP options based on the per-connection config table.   * Set LDAP options based on the per-connection config table.
    * Returns LDAP_SUCCESS on success, else non-zero.
  */   */
 static int  static int
 sudo_ldap_set_options_conn(LDAP *ld)  sudo_ldap_set_options_conn(LDAP *ld)
Line 1992  sudo_ldap_set_options_conn(LDAP *ld) Line 2273  sudo_ldap_set_options_conn(LDAP *ld)
         struct timeval tv;          struct timeval tv;
         tv.tv_sec = ldap_conf.timeout;          tv.tv_sec = ldap_conf.timeout;
         tv.tv_usec = 0;          tv.tv_usec = 0;
           DPRINTF1("ldap_set_option(LDAP_OPT_TIMEOUT, %d)", ldap_conf.timeout);
         rc = ldap_set_option(ld, LDAP_OPT_TIMEOUT, &tv);          rc = ldap_set_option(ld, LDAP_OPT_TIMEOUT, &tv);
         if (rc != LDAP_OPT_SUCCESS) {          if (rc != LDAP_OPT_SUCCESS) {
            warningx("ldap_set_option(TIMEOUT, %ld): %s",            warningx("ldap_set_option(TIMEOUT, %d): %s",
                (long)tv.tv_sec, ldap_err2string(rc));                ldap_conf.timeout, ldap_err2string(rc));
            debug_return_int(-1); 
         }          }
         DPRINTF(("ldap_set_option(LDAP_OPT_TIMEOUT, %ld)",  
             (long)tv.tv_sec), 1);  
     }      }
 #endif  #endif
 #ifdef LDAP_OPT_NETWORK_TIMEOUT  #ifdef LDAP_OPT_NETWORK_TIMEOUT
Line 2008  sudo_ldap_set_options_conn(LDAP *ld) Line 2287  sudo_ldap_set_options_conn(LDAP *ld)
         struct timeval tv;          struct timeval tv;
         tv.tv_sec = ldap_conf.bind_timelimit / 1000;          tv.tv_sec = ldap_conf.bind_timelimit / 1000;
         tv.tv_usec = 0;          tv.tv_usec = 0;
           DPRINTF1("ldap_set_option(LDAP_OPT_NETWORK_TIMEOUT, %d)",
               ldap_conf.bind_timelimit / 1000);
         rc = ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &tv);          rc = ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &tv);
   # if !defined(LDAP_OPT_CONNECT_TIMEOUT) || LDAP_VENDOR_VERSION != 510
           /* Tivoli Directory Server 6.3 libs always return a (bogus) error. */
         if (rc != LDAP_OPT_SUCCESS) {          if (rc != LDAP_OPT_SUCCESS) {
            warningx("ldap_set_option(NETWORK_TIMEOUT, %ld): %s",            warningx("ldap_set_option(NETWORK_TIMEOUT, %d): %s",
                (long)tv.tv_sec, ldap_err2string(rc));                ldap_conf.bind_timelimit / 1000, ldap_err2string(rc));
            debug_return_int(-1); 
         }          }
        DPRINTF(("ldap_set_option(LDAP_OPT_NETWORK_TIMEOUT, %ld)",# endif
            (long)tv.tv_sec), 1); 
     }      }
 #endif  #endif
   
 #if defined(LDAP_OPT_X_TLS) && !defined(HAVE_LDAPSSL_INIT)  #if defined(LDAP_OPT_X_TLS) && !defined(HAVE_LDAPSSL_INIT)
     if (ldap_conf.ssl_mode == SUDO_LDAP_SSL) {      if (ldap_conf.ssl_mode == SUDO_LDAP_SSL) {
         int val = LDAP_OPT_X_TLS_HARD;          int val = LDAP_OPT_X_TLS_HARD;
           DPRINTF1("ldap_set_option(LDAP_OPT_X_TLS, LDAP_OPT_X_TLS_HARD)");
         rc = ldap_set_option(ld, LDAP_OPT_X_TLS, &val);          rc = ldap_set_option(ld, LDAP_OPT_X_TLS, &val);
         if (rc != LDAP_SUCCESS) {          if (rc != LDAP_SUCCESS) {
             warningx("ldap_set_option(LDAP_OPT_X_TLS, LDAP_OPT_X_TLS_HARD): %s",              warningx("ldap_set_option(LDAP_OPT_X_TLS, LDAP_OPT_X_TLS_HARD): %s",
                 ldap_err2string(rc));                  ldap_err2string(rc));
             debug_return_int(-1);              debug_return_int(-1);
         }          }
         DPRINTF(("ldap_set_option(LDAP_OPT_X_TLS, LDAP_OPT_X_TLS_HARD)"), 1);  
     }      }
 #endif  #endif
    debug_return_int(0);    debug_return_int(LDAP_SUCCESS);
 }  }
   
 /*  /*
Line 2043  sudo_ldap_result_alloc(void) Line 2324  sudo_ldap_result_alloc(void)
     struct ldap_result *result;      struct ldap_result *result;
     debug_decl(sudo_ldap_result_alloc, SUDO_DEBUG_LDAP)      debug_decl(sudo_ldap_result_alloc, SUDO_DEBUG_LDAP)
   
    debug_return_ptr(ecalloc(1, sizeof(*result)));    result = ecalloc(1, sizeof(*result));
     STAILQ_INIT(&result->searches);
 
     debug_return_ptr(result);
 }  }
   
 /*  /*
Line 2052  sudo_ldap_result_alloc(void) Line 2336  sudo_ldap_result_alloc(void)
 static void  static void
 sudo_ldap_result_free(struct ldap_result *lres)  sudo_ldap_result_free(struct ldap_result *lres)
 {  {
    struct ldap_search_list *s;    struct ldap_search_result *s;
     debug_decl(sudo_ldap_result_free, SUDO_DEBUG_LDAP)      debug_decl(sudo_ldap_result_free, SUDO_DEBUG_LDAP)
   
     if (lres != NULL) {      if (lres != NULL) {
Line 2060  sudo_ldap_result_free(struct ldap_result *lres) Line 2344  sudo_ldap_result_free(struct ldap_result *lres)
             efree(lres->entries);              efree(lres->entries);
             lres->entries = NULL;              lres->entries = NULL;
         }          }
        if (lres->searches) {        while ((s = STAILQ_FIRST(&lres->searches)) != NULL) {
            while ((s = lres->searches) != NULL) {            STAILQ_REMOVE_HEAD(&lres->searches, entries);
                ldap_msgfree(s->searchresult);            ldap_msgfree(s->searchresult);
                lres->searches = s->next;            efree(s);
                efree(s); 
            } 
         }          }
         efree(lres);          efree(lres);
     }      }
Line 2075  sudo_ldap_result_free(struct ldap_result *lres) Line 2357  sudo_ldap_result_free(struct ldap_result *lres)
 /*  /*
  * Add a search result to the ldap_result structure.   * Add a search result to the ldap_result structure.
  */   */
static struct ldap_search_list *static struct ldap_search_result *
 sudo_ldap_result_add_search(struct ldap_result *lres, LDAP *ldap,  sudo_ldap_result_add_search(struct ldap_result *lres, LDAP *ldap,
     LDAPMessage *searchresult)      LDAPMessage *searchresult)
 {  {
    struct ldap_search_list *s, *news;    struct ldap_search_result *news;
     debug_decl(sudo_ldap_result_add_search, SUDO_DEBUG_LDAP)      debug_decl(sudo_ldap_result_add_search, SUDO_DEBUG_LDAP)
   
    news = ecalloc(1, sizeof(struct ldap_search_list));    /* Create new entry and add it to the end of the chain. */
     news = ecalloc(1, sizeof(*news));
     news->ldap = ldap;      news->ldap = ldap;
     news->searchresult = searchresult;      news->searchresult = searchresult;
    /* news->next = NULL; */    STAILQ_INSERT_TAIL(&lres->searches, news, entries);
   
     /* Add entry to the end of the chain (XXX - tailq instead?). */  
     if (lres->searches) {  
         for (s = lres->searches; s->next != NULL; s = s->next)  
             continue;  
         s->next = news;  
     } else {  
         lres->searches = news;  
     }  
     debug_return_ptr(news);      debug_return_ptr(news);
 }  }
   
 /*  /*
 * Connect to the LDAP server specified by ld * Connect to the LDAP server specified by ld.
  * Returns LDAP_SUCCESS on success, else non-zero.
  */   */
 static int  static int
 sudo_ldap_bind_s(LDAP *ld)  sudo_ldap_bind_s(LDAP *ld)
 {  {
     int rc;      int rc;
 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S  
     const char *old_ccname = user_ccname;  
 # ifdef HAVE_GSS_KRB5_CCACHE_NAME  
     unsigned int status;  
 # endif  
 #endif  
     debug_decl(sudo_ldap_bind_s, SUDO_DEBUG_LDAP)      debug_decl(sudo_ldap_bind_s, SUDO_DEBUG_LDAP)
   
 #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S  #ifdef HAVE_LDAP_SASL_INTERACTIVE_BIND_S
     if (ldap_conf.rootuse_sasl == true ||      if (ldap_conf.rootuse_sasl == true ||
         (ldap_conf.rootuse_sasl != false && ldap_conf.use_sasl == true)) {          (ldap_conf.rootuse_sasl != false && ldap_conf.use_sasl == true)) {
           const char *old_ccname = NULL;
           const char *new_ccname = ldap_conf.krb5_ccname;
           const char *tmp_ccname = NULL;
         void *auth_id = ldap_conf.rootsasl_auth_id ?          void *auth_id = ldap_conf.rootsasl_auth_id ?
             ldap_conf.rootsasl_auth_id : ldap_conf.sasl_auth_id;              ldap_conf.rootsasl_auth_id : ldap_conf.sasl_auth_id;
   
        if (ldap_conf.krb5_ccname != NULL) {        /* Make temp copy of the user's credential cache as needed. */
# ifdef HAVE_GSS_KRB5_CCACHE_NAME        if (ldap_conf.krb5_ccname == NULL && user_ccname != NULL) {
            if (gss_krb5_ccache_name(&status, ldap_conf.krb5_ccname, &old_ccname)            new_ccname = tmp_ccname = sudo_krb5_copy_cc_file(user_ccname);
                != GSS_S_COMPLETE) {            if (tmp_ccname == NULL) {
                old_ccname = NULL;                sudo_debug_printf(SUDO_DEBUG_INFO|SUDO_DEBUG_LINENO,
                DPRINTF(("gss_krb5_ccache_name() failed: %d", status), 1);                    "unable to copy user ccache %s", user_ccname);
             }              }
 # else  
             sudo_setenv("KRB5CCNAME", ldap_conf.krb5_ccname, true);  
 # endif  
         }          }
   
           if (new_ccname != NULL) {
               rc = sudo_set_krb5_ccache_name(new_ccname, &old_ccname);
               if (rc == 0) {
                   sudo_debug_printf(SUDO_DEBUG_INFO|SUDO_DEBUG_LINENO,
                       "set ccache name %s -> %s",
                       old_ccname ? old_ccname : "(none)", new_ccname);
               } else {
                   sudo_debug_printf(SUDO_DEBUG_WARN|SUDO_DEBUG_LINENO,
                       "gss_krb5_ccache_name() failed: %d", rc);
               }
           }
         rc = ldap_sasl_interactive_bind_s(ld, ldap_conf.binddn, "GSSAPI",          rc = ldap_sasl_interactive_bind_s(ld, ldap_conf.binddn, "GSSAPI",
             NULL, NULL, LDAP_SASL_QUIET, sudo_ldap_sasl_interact, auth_id);              NULL, NULL, LDAP_SASL_QUIET, sudo_ldap_sasl_interact, auth_id);
        if (ldap_conf.krb5_ccname != NULL) {        if (new_ccname != NULL) {
# ifdef HAVE_GSS_KRB5_CCACHE_NAME            rc = sudo_set_krb5_ccache_name(old_ccname, NULL);
            if (gss_krb5_ccache_name(&status, old_ccname, NULL) != GSS_S_COMPLETE)            if (rc == 0) {
                    DPRINTF(("gss_krb5_ccache_name() failed: %d", status), 1);                sudo_debug_printf(SUDO_DEBUG_INFO|SUDO_DEBUG_LINENO,
# else                    "restore ccache name %s -> %s", new_ccname, old_ccname);
            if (old_ccname != NULL)            } else {
                sudo_setenv("KRB5CCNAME", old_ccname, true);                sudo_debug_printf(SUDO_DEBUG_WARN|SUDO_DEBUG_LINENO,
            else                    "gss_krb5_ccache_name() failed: %d", rc);
                sudo_unsetenv("KRB5CCNAME");            }
# endif            /* Remove temporary copy of user's credential cache. */
             if (tmp_ccname != NULL)
                 unlink(tmp_ccname);
         }          }
         if (rc != LDAP_SUCCESS) {          if (rc != LDAP_SUCCESS) {
             warningx("ldap_sasl_interactive_bind_s(): %s",              warningx("ldap_sasl_interactive_bind_s(): %s",
                 ldap_err2string(rc));                  ldap_err2string(rc));
            debug_return_int(-1);            goto done;
         }          }
        DPRINTF(("ldap_sasl_interactive_bind_s() ok"), 1);        DPRINTF1("ldap_sasl_interactive_bind_s() ok");
     } else      } else
 #endif /* HAVE_LDAP_SASL_INTERACTIVE_BIND_S */  #endif /* HAVE_LDAP_SASL_INTERACTIVE_BIND_S */
 #ifdef HAVE_LDAP_SASL_BIND_S  #ifdef HAVE_LDAP_SASL_BIND_S
Line 2162  sudo_ldap_bind_s(LDAP *ld) Line 2446  sudo_ldap_bind_s(LDAP *ld)
             NULL, NULL, NULL);              NULL, NULL, NULL);
         if (rc != LDAP_SUCCESS) {          if (rc != LDAP_SUCCESS) {
             warningx("ldap_sasl_bind_s(): %s", ldap_err2string(rc));              warningx("ldap_sasl_bind_s(): %s", ldap_err2string(rc));
            debug_return_int(-1);            goto done;
         }          }
        DPRINTF(("ldap_sasl_bind_s() ok"), 1);        DPRINTF1("ldap_sasl_bind_s() ok");
     }      }
 #else  #else
     {      {
         rc = ldap_simple_bind_s(ld, ldap_conf.binddn, ldap_conf.bindpw);          rc = ldap_simple_bind_s(ld, ldap_conf.binddn, ldap_conf.bindpw);
         if (rc != LDAP_SUCCESS) {          if (rc != LDAP_SUCCESS) {
             warningx("ldap_simple_bind_s(): %s", ldap_err2string(rc));              warningx("ldap_simple_bind_s(): %s", ldap_err2string(rc));
            debug_return_int(-1);            goto done;
         }          }
        DPRINTF(("ldap_simple_bind_s() ok"), 1);        DPRINTF1("ldap_simple_bind_s() ok");
     }      }
 #endif  #endif
    debug_return_int(0);done:
     debug_return_int(rc);
 }  }
   
 /*  /*
Line 2187  static int Line 2472  static int
 sudo_ldap_open(struct sudo_nss *nss)  sudo_ldap_open(struct sudo_nss *nss)
 {  {
     LDAP *ld;      LDAP *ld;
    int rc;    int rc = -1;
     sigaction_t sa, saved_sa_pipe;
     bool ldapnoinit = false;      bool ldapnoinit = false;
     struct sudo_ldap_handle *handle;      struct sudo_ldap_handle *handle;
     debug_decl(sudo_ldap_open, SUDO_DEBUG_LDAP)      debug_decl(sudo_ldap_open, SUDO_DEBUG_LDAP)
   
       /* Ignore SIGPIPE if we cannot bind to the server. */
       memset(&sa, 0, sizeof(sa));
       sigemptyset(&sa.sa_mask);
       sa.sa_handler = SIG_IGN;
       (void) sigaction(SIGPIPE, &sa, &saved_sa_pipe);
   
     if (!sudo_ldap_read_config())      if (!sudo_ldap_read_config())
        debug_return_int(-1);        goto done;
   
     /* Prevent reading of user ldaprc and system defaults. */      /* Prevent reading of user ldaprc and system defaults. */
     if (sudo_getenv("LDAPNOINIT") == NULL) {      if (sudo_getenv("LDAPNOINIT") == NULL) {
Line 2202  sudo_ldap_open(struct sudo_nss *nss) Line 2494  sudo_ldap_open(struct sudo_nss *nss)
     }      }
   
     /* Set global LDAP options */      /* Set global LDAP options */
    if (sudo_ldap_set_options_global() < 0)    if (sudo_ldap_set_options_global() != LDAP_SUCCESS)
        debug_return_int(-1);        goto done;
   
     /* Connect to LDAP server */      /* Connect to LDAP server */
 #ifdef HAVE_LDAP_INITIALIZE  #ifdef HAVE_LDAP_INITIALIZE
    if (ldap_conf.uri != NULL) {    if (!STAILQ_EMPTY(&ldap_conf.uri)) {
        char *buf = sudo_ldap_join_uri(ldap_conf.uri);        char *buf = sudo_ldap_join_uri(&ldap_conf.uri);
        DPRINTF(("ldap_initialize(ld, %s)", buf), 2);        if (buf != NULL) {
        rc = ldap_initialize(&ld, buf);            DPRINTF2("ldap_initialize(ld, %s)", buf);
        efree(buf);            rc = ldap_initialize(&ld, buf);
        if (rc != LDAP_SUCCESS)            efree(buf);
            warningx(_("unable to initialize LDAP: %s"), ldap_err2string(rc));            if (rc != LDAP_SUCCESS) {
                 warningx(U_("unable to initialize LDAP: %s"),
                     ldap_err2string(rc));
             }
         }
     } else      } else
 #endif  #endif
         rc = sudo_ldap_init(&ld, ldap_conf.host, ldap_conf.port);          rc = sudo_ldap_init(&ld, ldap_conf.host, ldap_conf.port);
     if (rc != LDAP_SUCCESS)      if (rc != LDAP_SUCCESS)
        debug_return_int(-1);        goto done;
   
     /* Set LDAP per-connection options */      /* Set LDAP per-connection options */
    if (sudo_ldap_set_options_conn(ld) < 0)    rc = sudo_ldap_set_options_conn(ld);
        debug_return_int(-1);    if (rc != LDAP_SUCCESS)
         goto done;
   
     if (ldapnoinit)      if (ldapnoinit)
         sudo_unsetenv("LDAPNOINIT");          sudo_unsetenv("LDAPNOINIT");
Line 2232  sudo_ldap_open(struct sudo_nss *nss) Line 2529  sudo_ldap_open(struct sudo_nss *nss)
         rc = ldap_start_tls_s(ld, NULL, NULL);          rc = ldap_start_tls_s(ld, NULL, NULL);
         if (rc != LDAP_SUCCESS) {          if (rc != LDAP_SUCCESS) {
             warningx("ldap_start_tls_s(): %s", ldap_err2string(rc));              warningx("ldap_start_tls_s(): %s", ldap_err2string(rc));
            debug_return_int(-1);            goto done;
         }          }
        DPRINTF(("ldap_start_tls_s() ok"), 1);        DPRINTF1("ldap_start_tls_s() ok");
 #elif defined(HAVE_LDAP_SSL_CLIENT_INIT) && defined(HAVE_LDAP_START_TLS_S_NP)  #elif defined(HAVE_LDAP_SSL_CLIENT_INIT) && defined(HAVE_LDAP_START_TLS_S_NP)
        if (ldap_ssl_client_init(NULL, NULL, 0, &rc) != LDAP_SUCCESS) {        int sslrc;
            warningx("ldap_ssl_client_init(): %s", ldap_err2string(rc));        rc = ldap_ssl_client_init(ldap_conf.tls_keyfile, ldap_conf.tls_keypw,
            debug_return_int(-1);            0, &sslrc);
         if (rc != LDAP_SUCCESS) {
             warningx("ldap_ssl_client_init(): %s (SSL reason code %d)",
                 ldap_err2string(rc), sslrc);
             goto done;
         }          }
         rc = ldap_start_tls_s_np(ld, NULL);          rc = ldap_start_tls_s_np(ld, NULL);
         if (rc != LDAP_SUCCESS) {          if (rc != LDAP_SUCCESS) {
             warningx("ldap_start_tls_s_np(): %s", ldap_err2string(rc));              warningx("ldap_start_tls_s_np(): %s", ldap_err2string(rc));
            debug_return_int(-1);            goto done;
         }          }
        DPRINTF(("ldap_start_tls_s_np() ok"), 1);        DPRINTF1("ldap_start_tls_s_np() ok");
 #else  #else
        warningx(_("start_tls specified but LDAP libs do not support ldap_start_tls_s() or ldap_start_tls_s_np()"));        warningx(U_("start_tls specified but LDAP libs do not support ldap_start_tls_s() or ldap_start_tls_s_np()"));
 #endif /* !HAVE_LDAP_START_TLS_S && !HAVE_LDAP_START_TLS_S_NP */  #endif /* !HAVE_LDAP_START_TLS_S && !HAVE_LDAP_START_TLS_S_NP */
     }      }
   
     /* Actually connect */      /* Actually connect */
    if (sudo_ldap_bind_s(ld) != 0)    rc = sudo_ldap_bind_s(ld);
        debug_return_int(-1);    if (rc != LDAP_SUCCESS)
         goto done;
   
     /* Create a handle container. */      /* Create a handle container. */
     handle = ecalloc(1, sizeof(struct sudo_ldap_handle));      handle = ecalloc(1, sizeof(struct sudo_ldap_handle));
Line 2263  sudo_ldap_open(struct sudo_nss *nss) Line 2565  sudo_ldap_open(struct sudo_nss *nss)
     /* handle->grlist = NULL; */      /* handle->grlist = NULL; */
     nss->handle = handle;      nss->handle = handle;
   
    debug_return_int(0);done:
     (void) sigaction(SIGPIPE, &saved_sa_pipe, NULL);
     debug_return_int(rc == LDAP_SUCCESS ? 0 : -1);
 }  }
   
 static int  static int
 sudo_ldap_setdefs(struct sudo_nss *nss)  sudo_ldap_setdefs(struct sudo_nss *nss)
 {  {
    struct ldap_config_list_str *base;    struct ldap_config_str *base;
     struct sudo_ldap_handle *handle = nss->handle;      struct sudo_ldap_handle *handle = nss->handle;
     struct timeval tv, *tvp = NULL;      struct timeval tv, *tvp = NULL;
     LDAP *ld;      LDAP *ld;
Line 2283  sudo_ldap_setdefs(struct sudo_nss *nss) Line 2587  sudo_ldap_setdefs(struct sudo_nss *nss)
     ld = handle->ld;      ld = handle->ld;
   
     filt = sudo_ldap_build_default_filter();      filt = sudo_ldap_build_default_filter();
    DPRINTF(("Looking for cn=defaults: %s", filt), 1);    DPRINTF1("Looking for cn=defaults: %s", filt);
   
    for (base = ldap_conf.base; base != NULL; base = base->next) {    STAILQ_FOREACH(base, &ldap_conf.base, entries) {
         if (ldap_conf.timeout > 0) {          if (ldap_conf.timeout > 0) {
             tv.tv_sec = ldap_conf.timeout;              tv.tv_sec = ldap_conf.timeout;
             tv.tv_usec = 0;              tv.tv_usec = 0;
Line 2295  sudo_ldap_setdefs(struct sudo_nss *nss) Line 2599  sudo_ldap_setdefs(struct sudo_nss *nss)
         rc = ldap_search_ext_s(ld, base->val, LDAP_SCOPE_SUBTREE,          rc = ldap_search_ext_s(ld, base->val, LDAP_SCOPE_SUBTREE,
             filt, NULL, 0, NULL, NULL, tvp, 0, &result);              filt, NULL, 0, NULL, NULL, tvp, 0, &result);
         if (rc == LDAP_SUCCESS && (entry = ldap_first_entry(ld, result))) {          if (rc == LDAP_SUCCESS && (entry = ldap_first_entry(ld, result))) {
            DPRINTF(("found:%s", ldap_get_dn(ld, entry)), 1);            DPRINTF1("found:%s", ldap_get_dn(ld, entry));
             sudo_ldap_parse_options(ld, entry);              sudo_ldap_parse_options(ld, entry);
        } else        } else {
            DPRINTF(("no default options found in %s", base->val), 1);            DPRINTF1("no default options found in %s", base->val);
        }
         if (result)          if (result)
             ldap_msgfree(result);              ldap_msgfree(result);
     }      }
Line 2338  sudo_ldap_lookup(struct sudo_nss *nss, int ret, int pw Line 2642  sudo_ldap_lookup(struct sudo_nss *nss, int ret, int pw
         enum def_tuple pwcheck =           enum def_tuple pwcheck = 
             (pwflag == -1) ? never : sudo_defs_table[pwflag].sd_un.tuple;              (pwflag == -1) ? never : sudo_defs_table[pwflag].sd_un.tuple;
   
        DPRINTF(("perform search for pwflag %d", pwflag), 1);        DPRINTF1("perform search for pwflag %d", pwflag);
         for (i = 0; i < lres->nentries; i++) {          for (i = 0; i < lres->nentries; i++) {
             entry = lres->entries[i].entry;              entry = lres->entries[i].entry;
             if ((pwcheck == any && doauth != false) ||              if ((pwcheck == any && doauth != false) ||
Line 2377  sudo_ldap_lookup(struct sudo_nss *nss, int ret, int pw Line 2681  sudo_ldap_lookup(struct sudo_nss *nss, int ret, int pw
         goto done;          goto done;
     }      }
   
    DPRINTF(("searching LDAP for sudoers entries"), 1);    DPRINTF1("searching LDAP for sudoers entries");
   
     setenv_implied = false;      setenv_implied = false;
     for (i = 0; i < lres->nentries; i++) {      for (i = 0; i < lres->nentries; i++) {
Line 2387  sudo_ldap_lookup(struct sudo_nss *nss, int ret, int pw Line 2691  sudo_ldap_lookup(struct sudo_nss *nss, int ret, int pw
         rc = sudo_ldap_check_command(ld, entry, &setenv_implied);          rc = sudo_ldap_check_command(ld, entry, &setenv_implied);
         if (rc != UNSPEC) {          if (rc != UNSPEC) {
             /* We have a match. */              /* We have a match. */
            DPRINTF(("Command %sallowed", rc == true ? "" : "NOT "), 1);            DPRINTF1("Command %sallowed", rc == true ? "" : "NOT ");
             if (rc == true) {              if (rc == true) {
                DPRINTF(("LDAP entry: %p", entry), 1);                DPRINTF1("LDAP entry: %p", entry);
                 /* Apply entry-specific options. */                  /* Apply entry-specific options. */
                 if (setenv_implied)                  if (setenv_implied)
                     def_setenv = true;                      def_setenv = true;
Line 2412  sudo_ldap_lookup(struct sudo_nss *nss, int ret, int pw Line 2716  sudo_ldap_lookup(struct sudo_nss *nss, int ret, int pw
     }      }
   
 done:  done:
    DPRINTF(("done with LDAP searches"), 1);    DPRINTF1("done with LDAP searches");
    DPRINTF(("user_matches=%d", lres->user_matches), 1);    DPRINTF1("user_matches=%d", lres->user_matches);
    DPRINTF(("host_matches=%d", lres->host_matches), 1);    DPRINTF1("host_matches=%d", lres->host_matches);
   
     if (!ISSET(ret, VALIDATE_OK)) {      if (!ISSET(ret, VALIDATE_OK)) {
         /* No matching entries. */          /* No matching entries. */
Line 2425  done: Line 2729  done:
         CLR(ret, FLAG_NO_USER);          CLR(ret, FLAG_NO_USER);
     if (lres->host_matches)      if (lres->host_matches)
         CLR(ret, FLAG_NO_HOST);          CLR(ret, FLAG_NO_HOST);
    DPRINTF(("sudo_ldap_lookup(%d)=0x%02x", pwflag, ret), 1);    DPRINTF1("sudo_ldap_lookup(%d)=0x%02x", pwflag, ret);
   
     debug_return_int(ret);      debug_return_int(ret);
 }  }
Line 2445  ldap_entry_compare(const void *a, const void *b) Line 2749  ldap_entry_compare(const void *a, const void *b)
 }  }
   
 /*  /*
 * Find the last entry in the list of searches, usually the * Return the last entry in the list of searches, usually the
  * one currently being used to add entries.   * one currently being used to add entries.
  * XXX - use a tailq instead?  
  */   */
static struct ldap_search_list *static struct ldap_search_result *
 sudo_ldap_result_last_search(struct ldap_result *lres)  sudo_ldap_result_last_search(struct ldap_result *lres)
 {  {
     struct ldap_search_list *result = lres->searches;  
     debug_decl(sudo_ldap_result_last_search, SUDO_DEBUG_LDAP)      debug_decl(sudo_ldap_result_last_search, SUDO_DEBUG_LDAP)
   
    if (result) {    debug_return_ptr(STAILQ_LAST(&lres->searches, ldap_search_result, entries));
        while (result->next) 
            result = result->next; 
    } 
    debug_return_ptr(result); 
 }  }
   
 /*  /*
Line 2468  sudo_ldap_result_last_search(struct ldap_result *lres) Line 2766  sudo_ldap_result_last_search(struct ldap_result *lres)
 static struct ldap_entry_wrapper *  static struct ldap_entry_wrapper *
 sudo_ldap_result_add_entry(struct ldap_result *lres, LDAPMessage *entry)  sudo_ldap_result_add_entry(struct ldap_result *lres, LDAPMessage *entry)
 {  {
    struct ldap_search_list *last;    struct ldap_search_result *last;
     struct berval **bv;      struct berval **bv;
     double order = 0.0;      double order = 0.0;
     char *ep;      char *ep;
Line 2480  sudo_ldap_result_add_entry(struct ldap_result *lres, L Line 2778  sudo_ldap_result_add_entry(struct ldap_result *lres, L
     if (bv != NULL) {      if (bv != NULL) {
         if (ldap_count_values_len(bv) > 0) {          if (ldap_count_values_len(bv) > 0) {
             /* Get the value of this attribute, 0 if not present. */              /* Get the value of this attribute, 0 if not present. */
            DPRINTF(("order attribute raw: %s", (*bv)->bv_val), 1);            DPRINTF2("order attribute raw: %s", (*bv)->bv_val);
             order = strtod((*bv)->bv_val, &ep);              order = strtod((*bv)->bv_val, &ep);
             if (ep == (*bv)->bv_val || *ep != '\0') {              if (ep == (*bv)->bv_val || *ep != '\0') {
                warningx(_("invalid sudoOrder attribute: %s"), (*bv)->bv_val);                warningx(U_("invalid sudoOrder attribute: %s"), (*bv)->bv_val);
                 order = 0.0;                  order = 0.0;
             }              }
            DPRINTF(("order attribute: %f", order), 1);            DPRINTF2("order attribute: %f", order);
         }          }
         ldap_value_free_len(bv);          ldap_value_free_len(bv);
     }      }
Line 2518  sudo_ldap_result_free_nss(struct sudo_nss *nss) Line 2816  sudo_ldap_result_free_nss(struct sudo_nss *nss)
     debug_decl(sudo_ldap_result_free_nss, SUDO_DEBUG_LDAP)      debug_decl(sudo_ldap_result_free_nss, SUDO_DEBUG_LDAP)
   
     if (handle->result != NULL) {      if (handle->result != NULL) {
        DPRINTF(("removing reusable search result"), 1);        DPRINTF1("removing reusable search result");
         sudo_ldap_result_free(handle->result);          sudo_ldap_result_free(handle->result);
         if (handle->username) {          if (handle->username) {
             efree(handle->username);              efree(handle->username);
Line 2538  static struct ldap_result * Line 2836  static struct ldap_result *
 sudo_ldap_result_get(struct sudo_nss *nss, struct passwd *pw)  sudo_ldap_result_get(struct sudo_nss *nss, struct passwd *pw)
 {  {
     struct sudo_ldap_handle *handle = nss->handle;      struct sudo_ldap_handle *handle = nss->handle;
    struct ldap_config_list_str *base;    struct ldap_config_str *base;
     struct ldap_result *lres;      struct ldap_result *lres;
     struct timeval tv, *tvp = NULL;      struct timeval tv, *tvp = NULL;
     LDAPMessage *entry, *result;      LDAPMessage *entry, *result;
     LDAP *ld = handle->ld;      LDAP *ld = handle->ld;
    int do_netgr, rc;    int pass, rc;
     char *filt;      char *filt;
     debug_decl(sudo_ldap_result_get, SUDO_DEBUG_LDAP)      debug_decl(sudo_ldap_result_get, SUDO_DEBUG_LDAP)
   
Line 2554  sudo_ldap_result_get(struct sudo_nss *nss, struct pass Line 2852  sudo_ldap_result_get(struct sudo_nss *nss, struct pass
     if (handle->result) {      if (handle->result) {
         if (handle->grlist == user_group_list &&          if (handle->grlist == user_group_list &&
             strcmp(pw->pw_name, handle->username) == 0) {              strcmp(pw->pw_name, handle->username) == 0) {
            DPRINTF(("reusing previous result (user %s) with %d entries",            DPRINTF1("reusing previous result (user %s) with %d entries",
                handle->username, handle->result->nentries), 1);                handle->username, handle->result->nentries);
             debug_return_ptr(handle->result);              debug_return_ptr(handle->result);
         }          }
         /* User mismatch, cached result cannot be used. */          /* User mismatch, cached result cannot be used. */
        DPRINTF(("removing result (user %s), new search (user %s)",        DPRINTF1("removing result (user %s), new search (user %s)",
            handle->username, pw->pw_name), 1);            handle->username, pw->pw_name);
         sudo_ldap_result_free_nss(nss);          sudo_ldap_result_free_nss(nss);
     }      }
   
Line 2574  sudo_ldap_result_get(struct sudo_nss *nss, struct pass Line 2872  sudo_ldap_result_get(struct sudo_nss *nss, struct pass
      * sudoUser in this pass since the LDAP server already scanned       * sudoUser in this pass since the LDAP server already scanned
      * it for us.       * it for us.
      *       *
     * The second pass will return all the entries that contain     * The second pass will return all the entries that contain non-
     * user netgroups.  Then we take the netgroups returned and     * Unix groups, including netgroups.  Then we take the non-Unix
     * try to match them against the username.     * groups returned and try to match them against the username.
      *       *
      * Since we have to sort the possible entries before we make a       * Since we have to sort the possible entries before we make a
      * decision, we perform the queries and store all of the results in       * decision, we perform the queries and store all of the results in
      * an ldap_result object.  The results are then sorted by sudoOrder.       * an ldap_result object.  The results are then sorted by sudoOrder.
      */       */
     lres = sudo_ldap_result_alloc();      lres = sudo_ldap_result_alloc();
    for (do_netgr = 0; do_netgr < 2; do_netgr++) {    for (pass = 0; pass < 2; pass++) {
        filt = do_netgr ? sudo_ldap_build_pass2() : sudo_ldap_build_pass1(pw);        filt = pass ? sudo_ldap_build_pass2() : sudo_ldap_build_pass1(pw);
        DPRINTF(("ldap search '%s'", filt), 1);        if (filt != NULL) {
        for (base = ldap_conf.base; base != NULL; base = base->next) {            DPRINTF1("ldap search '%s'", filt);
            DPRINTF(("searching from base '%s'", base->val), 1);            STAILQ_FOREACH(base, &ldap_conf.base, entries) {
            if (ldap_conf.timeout > 0) {                DPRINTF1("searching from base '%s'",
                tv.tv_sec = ldap_conf.timeout;                    base->val);
                tv.tv_usec = 0;                if (ldap_conf.timeout > 0) {
                tvp = &tv;                    tv.tv_sec = ldap_conf.timeout;
            }                    tv.tv_usec = 0;
            result = NULL;                    tvp = &tv;
            rc = ldap_search_ext_s(ld, base->val, LDAP_SCOPE_SUBTREE, filt,                }
                NULL, 0, NULL, NULL, tvp, 0, &result);                result = NULL;
            if (rc != LDAP_SUCCESS) {                rc = ldap_search_ext_s(ld, base->val, LDAP_SCOPE_SUBTREE, filt,
                DPRINTF(("nothing found for '%s'", filt), 1);                    NULL, 0, NULL, NULL, tvp, 0, &result);
                continue;                if (rc != LDAP_SUCCESS) {
            }                    DPRINTF1("nothing found for '%s'", filt);
            lres->user_matches = true;                    continue;
                 }
                 lres->user_matches = true;
   
            /* Add the seach result to list of search results. */                /* Add the seach result to list of search results. */
            DPRINTF(("adding search result"), 1);                DPRINTF1("adding search result");
            sudo_ldap_result_add_search(lres, ld, result);                sudo_ldap_result_add_search(lres, ld, result);
            LDAP_FOREACH(entry, ld, result) {                LDAP_FOREACH(entry, ld, result) {
                if ((!do_netgr ||                    if ((!pass ||
                    sudo_ldap_check_user_netgroup(ld, entry, pw->pw_name)) &&                        sudo_ldap_check_non_unix_group(ld, entry, pw)) &&
                    sudo_ldap_check_host(ld, entry)) {                        sudo_ldap_check_host(ld, entry)) {
                    lres->host_matches = true;                        lres->host_matches = true;
                    sudo_ldap_result_add_entry(lres, entry);                        sudo_ldap_result_add_entry(lres, entry);
                     }
                 }                  }
                   DPRINTF1("result now has %d entries", lres->nentries);
             }              }
            DPRINTF(("result now has %d entries", lres->nentries), 1);            efree(filt);
         }          }
         efree(filt);  
     }      }
   
     /* Sort the entries by the sudoOrder attribute. */      /* Sort the entries by the sudoOrder attribute. */
    DPRINTF(("sorting remaining %d entries", lres->nentries), 1);    DPRINTF1("sorting remaining %d entries", lres->nentries);
     qsort(lres->entries, lres->nentries, sizeof(lres->entries[0]),      qsort(lres->entries, lres->nentries, sizeof(lres->entries[0]),
         ldap_entry_compare);          ldap_entry_compare);
   
Line 2688  sudo_ldap_result_from_search(LDAP *ldap, LDAPMessage * Line 2989  sudo_ldap_result_from_search(LDAP *ldap, LDAPMessage *
      * Build a new list node for the search result, this creates the       * Build a new list node for the search result, this creates the
      * list node.       * list node.
      */       */
    struct ldap_search_list *last = sudo_ldap_result_add_search(result,    struct ldap_search_result *last = sudo_ldap_result_add_search(result,
         ldap, searchresult);          ldap, searchresult);
   
     /*      /*
Line 2699  sudo_ldap_result_from_search(LDAP *ldap, LDAPMessage * Line 3000  sudo_ldap_result_from_search(LDAP *ldap, LDAPMessage *
     LDAP_FOREACH(entry, last->ldap, last->searchresult) {      LDAP_FOREACH(entry, last->ldap, last->searchresult) {
         sudo_ldap_result_add_entry(result, entry);          sudo_ldap_result_add_entry(result, entry);
     }      }
    DPRINTF(("sudo_ldap_result_from_search: %d entries found",    DPRINTF1("sudo_ldap_result_from_search: %d entries found", result->nentries);
        result->nentries), 2); 
     return result;      return result;
 }  }
 #endif  #endif

Removed from v.1.1.1.2  
changed lines
  Added in v.1.1.1.6


FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>