s4:kdc: Implement KDC plugin hardware authentication policy
[samba.git] / source3 / libads / ldap.c
old mode 100755 (executable)
new mode 100644 (file)
index 4fc0ab9..08f3a13
@@ -1,4 +1,4 @@
-/* 
+/*
    Unix SMB/CIFS implementation.
    ads (active directory) utility library
    Copyright (C) Andrew Tridgell 2001
@@ -25,6 +25,7 @@
 #include "ads.h"
 #include "libads/sitename_cache.h"
 #include "libads/cldap.h"
+#include "../lib/tsocket/tsocket.h"
 #include "../lib/addns/dnsquery.h"
 #include "../libds/common/flags.h"
 #include "smbldap.h"
@@ -32,6 +33,9 @@
 #include "../librpc/gen_ndr/netlogon.h"
 #include "lib/param/loadparm.h"
 #include "libsmb/namequery.h"
+#include "../librpc/gen_ndr/ndr_ads.h"
+#include "auth/credentials/credentials.h"
+#include "passdb.h"
 
 #ifdef HAVE_LDAP
 
@@ -41,7 +45,7 @@
  *
  * The routines contained here should do the necessary ldap calls for
  * ads setups.
- * 
+ *
  * Important note: attribute names passed into ads_ routines must
  * already be in UTF-8 format.  We do not convert them because in almost
  * all cases, they are just ascii (which is represented with the same
@@ -152,6 +156,11 @@ static int ldap_search_with_timeout(LDAP *ld,
        struct timeval *timeout_ptr = NULL;
        int result;
 
+       DBG_DEBUG("ldap_search: base => [%s], filter => [%s], scope => [%d]\n",
+                base,
+                filter,
+                scope);
+
        /* Setup timeout for the ldap_search_ext_s call - local and remote. */
        gotalarm = 0;
 
@@ -163,7 +172,7 @@ static int ldap_search_with_timeout(LDAP *ld,
                /* Setup alarm timeout. */
                CatchSignal(SIGALRM, gotalarm_sig);
                /* Make the alarm time one second beyond
-                  the timout we're setting for the
+                  the timeout we're setting for the
                   remote search timeout, to allow that
                   to fire in preference. */
                alarm(to+1);
@@ -243,111 +252,111 @@ bool ads_closest_dc(ADS_STRUCT *ads)
                return True;
        }
 
-       DEBUG(10,("ads_closest_dc: %s is not the closest DC\n", 
+       DEBUG(10,("ads_closest_dc: %s is not the closest DC\n",
                ads->config.ldap_server_name));
 
        return False;
 }
 
-
-/*
-  try a connection to a given ldap server, returning True and setting the servers IP
-  in the ads struct if successful
- */
-static bool ads_try_connect(ADS_STRUCT *ads, bool gc,
-                           struct sockaddr_storage *ss)
+static bool ads_fill_cldap_reply(ADS_STRUCT *ads,
+                                bool gc,
+                                const struct sockaddr_storage *ss,
+                                const struct NETLOGON_SAM_LOGON_RESPONSE_EX *cldap_reply)
 {
-       struct NETLOGON_SAM_LOGON_RESPONSE_EX cldap_reply;
        TALLOC_CTX *frame = talloc_stackframe();
        bool ret = false;
        char addr[INET6_ADDRSTRLEN];
        ADS_STATUS status;
-
-       if (ss == NULL) {
-               TALLOC_FREE(frame);
-               return False;
-       }
+       char *dn;
 
        print_sockaddr(addr, sizeof(addr), ss);
 
-       DEBUG(5,("ads_try_connect: sending CLDAP request to %s (realm: %s)\n", 
-               addr, ads->server.realm));
-
-       ZERO_STRUCT( cldap_reply );
+       /* Check the CLDAP reply flags */
 
-       if ( !ads_cldap_netlogon_5(frame, ss, ads->server.realm, &cldap_reply ) ) {
-               DEBUG(3,("ads_try_connect: CLDAP request %s failed.\n", addr));
+       if (!(cldap_reply->server_type & NBT_SERVER_LDAP)) {
+               DBG_WARNING("%s's CLDAP reply says it is not an LDAP server!\n",
+                           addr);
                ret = false;
                goto out;
        }
 
-       /* Check the CLDAP reply flags */
+       /* Fill in the ads->config values */
+
+       ADS_TALLOC_CONST_FREE(ads->config.workgroup);
+       ADS_TALLOC_CONST_FREE(ads->config.realm);
+       ADS_TALLOC_CONST_FREE(ads->config.bind_path);
+       ADS_TALLOC_CONST_FREE(ads->config.ldap_server_name);
+       ADS_TALLOC_CONST_FREE(ads->config.server_site_name);
+       ADS_TALLOC_CONST_FREE(ads->config.client_site_name);
 
-       if ( !(cldap_reply.server_type & NBT_SERVER_LDAP) ) {
-               DEBUG(1,("ads_try_connect: %s's CLDAP reply says it is not an LDAP server!\n",
-                       addr));
+       if (!check_cldap_reply_required_flags(cldap_reply->server_type,
+                                             ads->config.flags)) {
                ret = false;
                goto out;
        }
 
-       /* Fill in the ads->config values */
-
-       TALLOC_FREE(ads->config.realm);
-       SAFE_FREE(ads->config.bind_path);
-       SAFE_FREE(ads->config.ldap_server_name);
-       SAFE_FREE(ads->config.server_site_name);
-       SAFE_FREE(ads->config.client_site_name);
-       TALLOC_FREE(ads->server.workgroup);
+       ads->config.ldap_server_name = talloc_strdup(ads,
+                                                    cldap_reply->pdc_dns_name);
+       if (ads->config.ldap_server_name == NULL) {
+               DBG_WARNING("Out of memory\n");
+               ret = false;
+               goto out;
+       }
 
-       if (!check_cldap_reply_required_flags(cldap_reply.server_type,
-                                             ads->config.flags)) {
+       ads->config.workgroup = talloc_strdup(ads, cldap_reply->domain_name);
+       if (ads->config.workgroup == NULL) {
+               DBG_WARNING("Out of memory\n");
                ret = false;
                goto out;
        }
 
-       ads->config.ldap_server_name   = SMB_STRDUP(cldap_reply.pdc_dns_name);
        ads->config.realm = talloc_asprintf_strupper_m(ads,
                                                       "%s",
-                                                      cldap_reply.dns_domain);
+                                                      cldap_reply->dns_domain);
        if (ads->config.realm == NULL) {
                DBG_WARNING("Out of memory\n");
                ret = false;
                goto out;
        }
 
-       status = ads_build_dn(ads->config.realm, &ads->config.bind_path);
+       status = ads_build_dn(ads->config.realm, ads, &dn);
        if (!ADS_ERR_OK(status)) {
                DBG_DEBUG("Failed to build bind path: %s\n",
                          ads_errstr(status));
                ret = false;
                goto out;
        }
+       ads->config.bind_path = dn;
 
-       if (*cldap_reply.server_site) {
+       if (*cldap_reply->server_site) {
                ads->config.server_site_name =
-                       SMB_STRDUP(cldap_reply.server_site);
-       }
-       if (*cldap_reply.client_site) {
-               ads->config.client_site_name =
-                       SMB_STRDUP(cldap_reply.client_site);
+                       talloc_strdup(ads, cldap_reply->server_site);
+               if (ads->config.server_site_name == NULL) {
+                       DBG_WARNING("Out of memory\n");
+                       ret = false;
+                       goto out;
+               }
        }
 
-       ads->server.workgroup = talloc_strdup(ads, cldap_reply.domain_name);
-       if (ads->server.workgroup == NULL) {
-               DBG_WARNING("Out of memory\n");
-               ret = false;
-               goto out;
+       if (*cldap_reply->client_site) {
+               ads->config.client_site_name =
+                       talloc_strdup(ads, cldap_reply->client_site);
+               if (ads->config.client_site_name == NULL) {
+                       DBG_WARNING("Out of memory\n");
+                       ret = false;
+                       goto out;
+               }
        }
 
        ads->ldap.port = gc ? LDAP_GC_PORT : LDAP_PORT;
        ads->ldap.ss = *ss;
 
        /* Store our site name. */
-       sitename_store( cldap_reply.domain_name, cldap_reply.client_site);
-       sitename_store( cldap_reply.dns_domain, cldap_reply.client_site);
+       sitename_store(cldap_reply->domain_name, cldap_reply->client_site);
+       sitename_store(cldap_reply->dns_domain, cldap_reply->client_site);
 
        /* Leave this until last so that the flags are not clobbered */
-       ads->config.flags              = cldap_reply.server_type;
+       ads->config.flags = cldap_reply->server_type;
 
        ret = true;
 
@@ -357,6 +366,48 @@ static bool ads_try_connect(ADS_STRUCT *ads, bool gc,
        return ret;
 }
 
+/*
+  try a connection to a given ldap server, returning True and setting the servers IP
+  in the ads struct if successful
+ */
+static bool ads_try_connect(ADS_STRUCT *ads, bool gc,
+                           struct sockaddr_storage *ss)
+{
+       struct NETLOGON_SAM_LOGON_RESPONSE_EX cldap_reply = {};
+       TALLOC_CTX *frame = talloc_stackframe();
+       bool ok;
+       char addr[INET6_ADDRSTRLEN] = { 0, };
+
+       if (ss == NULL) {
+               TALLOC_FREE(frame);
+               return false;
+       }
+
+       print_sockaddr(addr, sizeof(addr), ss);
+
+       DBG_INFO("ads_try_connect: sending CLDAP request to %s (realm: %s)\n",
+                addr, ads->server.realm);
+
+       ok = ads_cldap_netlogon_5(frame, ss, ads->server.realm, &cldap_reply);
+       if (!ok) {
+               DBG_NOTICE("ads_cldap_netlogon_5(%s, %s) failed.\n",
+                          addr, ads->server.realm);
+               TALLOC_FREE(frame);
+               return false;
+       }
+
+       ok = ads_fill_cldap_reply(ads, gc, ss, &cldap_reply);
+       if (!ok) {
+               DBG_NOTICE("ads_fill_cldap_reply(%s, %s) failed.\n",
+                          addr, ads->server.realm);
+               TALLOC_FREE(frame);
+               return false;
+       }
+
+       TALLOC_FREE(frame);
+       return true;
+}
+
 /**********************************************************************
  send a cldap ping to list of servers, one at a time, until one of
  them answers it's an ldap server. Record success in the ADS_STRUCT.
@@ -368,30 +419,176 @@ static NTSTATUS cldap_ping_list(ADS_STRUCT *ads,
                        struct samba_sockaddr *sa_list,
                        size_t count)
 {
+       TALLOC_CTX *frame = talloc_stackframe();
+       struct timeval endtime = timeval_current_ofs(MAX(3,lp_ldap_timeout()/2), 0);
+       uint32_t nt_version = NETLOGON_NT_VERSION_5 | NETLOGON_NT_VERSION_5EX;
+       struct tsocket_address **ts_list = NULL;
+       const struct tsocket_address * const *ts_list_const = NULL;
+       struct samba_sockaddr **req_sa_list = NULL;
+       struct netlogon_samlogon_response **responses = NULL;
+       size_t num_requests = 0;
+       NTSTATUS status;
        size_t i;
-       bool ok;
+       bool ok = false;
+       bool retry;
+
+       ts_list = talloc_zero_array(frame,
+                                   struct tsocket_address *,
+                                   count);
+       if (ts_list == NULL) {
+               TALLOC_FREE(frame);
+               return NT_STATUS_NO_MEMORY;
+       }
+
+       req_sa_list = talloc_zero_array(frame,
+                                       struct samba_sockaddr *,
+                                       count);
+       if (req_sa_list == NULL) {
+               TALLOC_FREE(frame);
+               return NT_STATUS_NO_MEMORY;
+       }
+
+again:
+       /*
+        * The retry loop is bound by the timeout
+        */
+       retry = false;
+       num_requests = 0;
 
        for (i = 0; i < count; i++) {
                char server[INET6_ADDRSTRLEN];
+               int ret;
+
+               if (is_zero_addr(&sa_list[i].u.ss)) {
+                       continue;
+               }
 
                print_sockaddr(server, sizeof(server), &sa_list[i].u.ss);
 
-               if (!NT_STATUS_IS_OK(
-                       check_negative_conn_cache(domain, server)))
+               status = check_negative_conn_cache(domain, server);
+               if (!NT_STATUS_IS_OK(status)) {
                        continue;
+               }
 
-               /* Returns ok only if it matches the correct server type */
-               ok = ads_try_connect(ads, false, &sa_list[i].u.ss);
+               ret = tsocket_address_inet_from_strings(ts_list, "ip",
+                                                       server, LDAP_PORT,
+                                                       &ts_list[num_requests]);
+               if (ret != 0) {
+                       status = map_nt_error_from_unix(errno);
+                       DBG_WARNING("Failed to create tsocket_address for %s - %s\n",
+                                   server, nt_errstr(status));
+                       TALLOC_FREE(frame);
+                       return status;
+               }
+
+               req_sa_list[num_requests] = &sa_list[i];
+               num_requests += 1;
+       }
+
+       DBG_DEBUG("Try to create %zu netlogon connections for domain '%s' "
+                 "(provided count of addresses was %zu).\n",
+                 num_requests,
+                 domain,
+                 count);
 
+       if (num_requests == 0) {
+               status = NT_STATUS_NO_LOGON_SERVERS;
+               DBG_WARNING("domain[%s] num_requests[%zu] for count[%zu] - %s\n",
+                           domain, num_requests, count, nt_errstr(status));
+               TALLOC_FREE(frame);
+               return status;
+       }
+
+       ts_list_const = (const struct tsocket_address * const *)ts_list;
+
+       status = cldap_multi_netlogon(frame,
+                                     ts_list_const, num_requests,
+                                     ads->server.realm, NULL,
+                                     nt_version,
+                                     1, endtime, &responses);
+       if (!NT_STATUS_IS_OK(status)) {
+               DBG_WARNING("cldap_multi_netlogon(realm=%s, num_requests=%zu) "
+                           "for count[%zu] - %s\n",
+                           ads->server.realm,
+                           num_requests, count,
+                           nt_errstr(status));
+               TALLOC_FREE(frame);
+               return NT_STATUS_NO_LOGON_SERVERS;
+       }
+
+       for (i = 0; i < num_requests; i++) {
+               struct NETLOGON_SAM_LOGON_RESPONSE_EX *cldap_reply = NULL;
+               char server[INET6_ADDRSTRLEN];
+
+               if (responses[i] == NULL) {
+                       continue;
+               }
+
+               print_sockaddr(server, sizeof(server), &req_sa_list[i]->u.ss);
+
+               if (responses[i]->ntver != NETLOGON_NT_VERSION_5EX) {
+                       DBG_NOTICE("realm=[%s] nt_version mismatch: 0x%08x for %s\n",
+                                  ads->server.realm,
+                                  responses[i]->ntver, server);
+                       continue;
+               }
+
+               cldap_reply = &responses[i]->data.nt5_ex;
+
+               /* Returns ok only if it matches the correct server type */
+               ok = ads_fill_cldap_reply(ads,
+                                         false,
+                                         &req_sa_list[i]->u.ss,
+                                         cldap_reply);
                if (ok) {
+                       DBG_DEBUG("realm[%s]: selected %s => %s\n",
+                                 ads->server.realm,
+                                 server, cldap_reply->pdc_dns_name);
+                       if (CHECK_DEBUGLVL(DBGLVL_DEBUG)) {
+                               NDR_PRINT_DEBUG(NETLOGON_SAM_LOGON_RESPONSE_EX,
+                                               cldap_reply);
+                       }
+                       TALLOC_FREE(frame);
                        return NT_STATUS_OK;
                }
 
-               /* keep track of failures */
+               DBG_NOTICE("realm[%s] server %s %s - not usable\n",
+                          ads->server.realm,
+                          server, cldap_reply->pdc_dns_name);
+               if (CHECK_DEBUGLVL(DBGLVL_NOTICE)) {
+                       NDR_PRINT_DEBUG(NETLOGON_SAM_LOGON_RESPONSE_EX,
+                                       cldap_reply);
+               }
+               add_failed_connection_entry(domain, server,
+                               NT_STATUS_CLIENT_SERVER_PARAMETERS_INVALID);
+               retry = true;
+       }
+
+       if (retry) {
+               bool expired;
+
+               expired = timeval_expired(&endtime);
+               if (!expired) {
+                       goto again;
+               }
+       }
+
+       /* keep track of failures as all were not suitable */
+       for (i = 0; i < num_requests; i++) {
+               char server[INET6_ADDRSTRLEN];
+
+               print_sockaddr(server, sizeof(server), &req_sa_list[i]->u.ss);
+
                add_failed_connection_entry(domain, server,
                                            NT_STATUS_UNSUCCESSFUL);
        }
 
+       status = NT_STATUS_NO_LOGON_SERVERS;
+       DBG_WARNING("realm[%s] no valid response "
+                   "num_requests[%zu] for count[%zu] - %s\n",
+                   ads->server.realm,
+                   num_requests, count, nt_errstr(status));
+       TALLOC_FREE(frame);
        return NT_STATUS_NO_LOGON_SERVERS;
 }
 
@@ -481,7 +678,7 @@ static NTSTATUS resolve_and_ping_dns(ADS_STRUCT *ads, const char *sitename,
 
 /**********************************************************************
  Try to find an AD dc using our internal name resolution routines
- Try the realm first and then then workgroup name if netbios is not
+ Try the realm first and then the workgroup name if netbios is not
  disabled
 **********************************************************************/
 
@@ -535,7 +732,7 @@ static NTSTATUS ads_find_dc(ADS_STRUCT *ads)
         * In case of LDAP we use get_dc_name() as that
         * creates the custom krb5.conf file
         */
-       if (!(ads->auth.flags & ADS_AUTH_NO_BIND)) {
+       if (ads->auth.flags & ADS_AUTH_GENERATE_KRB5_CONFIG) {
                fstring srv_name;
                struct sockaddr_storage ip_out;
 
@@ -545,6 +742,10 @@ static NTSTATUS ads_find_dc(ADS_STRUCT *ads)
 
                ok = get_dc_name(c_domain, c_realm, srv_name, &ip_out);
                if (ok) {
+                       if (is_zero_addr(&ip_out)) {
+                               return NT_STATUS_NO_LOGON_SERVERS;
+                       }
+
                        /*
                         * we call ads_try_connect() to fill in the
                         * ads->config details
@@ -611,21 +812,41 @@ static NTSTATUS ads_find_dc(ADS_STRUCT *ads)
                  c_realm, c_domain, nt_errstr(status)));
        return status;
 }
+
 /**
  * Connect to the LDAP server
  * @param ads Pointer to an existing ADS_STRUCT
  * @return status of connection
  **/
-ADS_STATUS ads_connect(ADS_STRUCT *ads)
+static ADS_STATUS ads_connect_internal(ADS_STRUCT *ads,
+                                      struct cli_credentials *creds)
 {
        int version = LDAP_VERSION3;
        ADS_STATUS status;
        NTSTATUS ntstatus;
        char addr[INET6_ADDRSTRLEN];
        struct sockaddr_storage existing_ss;
+       bool tls = false;
+       bool start_tls = false;
 
        zero_sockaddr(&existing_ss);
 
+       if (!(ads->auth.flags & ADS_AUTH_NO_BIND)) {
+               SMB_ASSERT(creds != NULL);
+       }
+
+       if (ads->auth.flags & ADS_AUTH_ANON_BIND) {
+               /*
+                * Simple anonyous binds are only
+                * allowed for anonymous credentials
+                */
+               SMB_ASSERT(cli_credentials_is_anonymous(creds));
+       }
+
+       if (!(ads->auth.flags & (ADS_AUTH_NO_BIND|ADS_AUTH_ANON_BIND))) {
+               ads->auth.flags |= ADS_AUTH_GENERATE_KRB5_CONFIG;
+       }
+
        /*
         * ads_connect can be passed in a reused ADS_STRUCT
         * with an existing non-zero ads->ldap.ss IP address
@@ -650,6 +871,7 @@ ADS_STATUS ads_connect(ADS_STRUCT *ads)
        }
 
        ads_zero_ldap(ads);
+       ZERO_STRUCT(ads->ldap_tls_data);
        ZERO_STRUCT(ads->ldap_wrap_data);
        ads->ldap.last_attempt  = time_mono(NULL);
        ads->ldap_wrap_data.wrap_type   = ADS_SASLWRAP_TYPE_PLAIN;
@@ -667,6 +889,8 @@ ADS_STATUS ads_connect(ADS_STRUCT *ads)
                bool ok = false;
                struct sockaddr_storage ss;
 
+               DBG_DEBUG("Resolving name of LDAP server '%s'.\n",
+                         ads->server.ldap_server);
                ok = resolve_name(ads->server.ldap_server, &ss, 0x20, true);
                if (!ok) {
                        DEBUG(5,("ads_connect: unable to resolve name %s\n",
@@ -674,6 +898,12 @@ ADS_STATUS ads_connect(ADS_STRUCT *ads)
                        status = ADS_ERROR_NT(NT_STATUS_NOT_FOUND);
                        goto out;
                }
+
+               if (is_zero_addr(&ss)) {
+                       status = ADS_ERROR_NT(NT_STATUS_NOT_FOUND);
+                       goto out;
+               }
+
                ok = ads_try_connect(ads, ads->server.gc, &ss);
                if (ok) {
                        goto got_connection;
@@ -706,6 +936,8 @@ ADS_STATUS ads_connect(ADS_STRUCT *ads)
                 * Keep trying to find a server and fall through
                 * into ads_find_dc() again.
                 */
+               DBG_DEBUG("Failed to connect to DC via LDAP server IP address, "
+                         "trying to find another DC.\n");
        }
 
        ntstatus = ads_find_dc(ads);
@@ -721,27 +953,6 @@ got_connection:
        print_sockaddr(addr, sizeof(addr), &ads->ldap.ss);
        DEBUG(3,("Successfully contacted LDAP server %s\n", addr));
 
-       if (!ads->auth.user_name) {
-               /* Must use the userPrincipalName value here or sAMAccountName
-                  and not servicePrincipalName; found by Guenther Deschner */
-               ads->auth.user_name = talloc_asprintf(ads,
-                                                     "%s$",
-                                                     lp_netbios_name());
-               if (ads->auth.user_name == NULL) {
-                       DBG_ERR("talloc_asprintf failed\n");
-                       status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
-                       goto out;
-               }
-       }
-
-       if (ads->auth.realm == NULL) {
-               ads->auth.realm = talloc_strdup(ads, ads->config.realm);
-               if (ads->auth.realm == NULL) {
-                       status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
-                       goto out;
-               }
-       }
-
        if (!ads->auth.kdc_server) {
                print_sockaddr(addr, sizeof(addr), &ads->ldap.ss);
                ads->auth.kdc_server = talloc_strdup(ads, addr);
@@ -758,6 +969,12 @@ got_connection:
                goto out;
        }
 
+       ads->ldap_tls_data.mem_ctx = talloc_init("ads LDAP TLS connection memory");
+       if (!ads->ldap_tls_data.mem_ctx) {
+               status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
+               goto out;
+       }
+
        ads->ldap_wrap_data.mem_ctx = talloc_init("ads LDAP connection memory");
        if (!ads->ldap_wrap_data.mem_ctx) {
                status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
@@ -766,6 +983,17 @@ got_connection:
 
        /* Otherwise setup the TCP LDAP session */
 
+       if (ads->auth.flags & ADS_AUTH_SASL_LDAPS) {
+               tls = true;
+               ads->ldap.port = 636;
+       } else if (ads->auth.flags & ADS_AUTH_SASL_STARTTLS) {
+               tls = true;
+               start_tls = true;
+               ads->ldap.port = 389;
+       } else {
+               ads->ldap.port = 389;
+       }
+
        ads->ldap.ld = ldap_open_with_timeout(ads->config.ldap_server_name,
                                              &ads->ldap.ss,
                                              ads->ldap.port, lp_ldap_timeout());
@@ -775,14 +1003,85 @@ got_connection:
        }
        DEBUG(3,("Connected to LDAP server %s\n", ads->config.ldap_server_name));
 
+       ldap_set_option(ads->ldap.ld, LDAP_OPT_PROTOCOL_VERSION, &version);
+
+       if (start_tls) {
+               unsigned int to = lp_ldap_connection_timeout();
+               struct berval *rspdata = NULL;
+               char *rspoid = NULL;
+               int rc;
+
+               if (to) {
+                       /* Setup timeout */
+                       gotalarm = 0;
+                       CatchSignal(SIGALRM, gotalarm_sig);
+                       alarm(to);
+                       /* End setup timeout. */
+               }
+
+               rc = ldap_extended_operation_s(ads->ldap.ld,
+                                              LDAP_EXOP_START_TLS,
+                                              NULL,
+                                              NULL,
+                                              NULL,
+                                              &rspoid,
+                                              &rspdata);
+               if (gotalarm != 0 && rc == LDAP_SUCCESS) {
+                       rc = LDAP_TIMEOUT;
+               }
+
+               if (to) {
+                       /* Teardown timeout. */
+                       alarm(0);
+                       CatchSignal(SIGALRM, SIG_IGN);
+               }
+
+               if (rspoid != NULL) {
+                       ldap_memfree(rspoid);
+               }
+
+               if (rspdata != NULL) {
+                       ber_bvfree(rspdata);
+               }
+
+               if (rc != LDAP_SUCCESS) {
+                       status = ADS_ERROR_LDAP(rc);
+                       goto out;
+               }
+       }
+
+       if (tls) {
+               unsigned int to = lp_ldap_connection_timeout();
+
+               if (to) {
+                       /* Setup timeout */
+                       gotalarm = 0;
+                       CatchSignal(SIGALRM, gotalarm_sig);
+                       alarm(to);
+                       /* End setup timeout. */
+               }
+
+               status = ads_setup_tls_wrapping(&ads->ldap_tls_data,
+                                               ads->ldap.ld,
+                                               ads->config.ldap_server_name);
+
+               if (to) {
+                       /* Teardown timeout. */
+                       alarm(0);
+                       CatchSignal(SIGALRM, SIG_IGN);
+               }
+
+               if ( !ADS_ERR_OK(status) ) {
+                       goto out;
+               }
+       }
+
        /* cache the successful connection for workgroup and realm */
        if (ads_closest_dc(ads)) {
                saf_store( ads->server.workgroup, ads->config.ldap_server_name);
                saf_store( ads->server.realm, ads->config.ldap_server_name);
        }
 
-       ldap_set_option(ads->ldap.ld, LDAP_OPT_PROTOCOL_VERSION, &version);
-
        /* fill in the current time and offsets */
 
        status = ads_current_time( ads );
@@ -797,12 +1096,7 @@ got_connection:
                goto out;
        }
 
-       if (ads->auth.flags & ADS_AUTH_SIMPLE_BIND) {
-               status = ADS_ERROR(ldap_simple_bind_s(ads->ldap.ld, ads->auth.user_name, ads->auth.password));
-               goto out;
-       }
-
-       status = ads_sasl_bind(ads);
+       status = ads_sasl_bind(ads, creds);
 
  out:
        if (DEBUGLEVEL >= 11) {
@@ -817,18 +1111,98 @@ got_connection:
 }
 
 /**
- * Connect to the LDAP server using given credentials
+ * Connect to the LDAP server using without a bind
+ * and without a tcp connection at all
+ *
  * @param ads Pointer to an existing ADS_STRUCT
  * @return status of connection
  **/
-ADS_STATUS ads_connect_user_creds(ADS_STRUCT *ads)
+ADS_STATUS ads_connect_cldap_only(ADS_STRUCT *ads)
 {
-       ads->auth.flags |= ADS_AUTH_USER_CREDS;
+       ads->auth.flags |= ADS_AUTH_NO_BIND;
+       return ads_connect_internal(ads, NULL);
+}
+
+/**
+ * Connect to the LDAP server
+ * @param ads Pointer to an existing ADS_STRUCT
+ * @return status of connection
+ **/
+ADS_STATUS ads_connect_creds(ADS_STRUCT *ads, struct cli_credentials *creds)
+{
+       SMB_ASSERT(creds != NULL);
+
+       /*
+        * We allow upgrades from
+        * ADS_AUTH_NO_BIND if credentials
+        * are specified
+        */
+       ads->auth.flags &= ~ADS_AUTH_NO_BIND;
+
+       /*
+        * We allow upgrades from ADS_AUTH_ANON_BIND,
+        * as we don't want to use simple binds with
+        * non-anon credentials
+        */
+       if (!cli_credentials_is_anonymous(creds)) {
+               ads->auth.flags &= ~ADS_AUTH_ANON_BIND;
+       }
 
-       return ads_connect(ads);
+       return ads_connect_internal(ads, creds);
+}
+
+/**
+ * Connect to the LDAP server using anonymous credentials
+ * using a simple bind without username/password
+ *
+ * @param ads Pointer to an existing ADS_STRUCT
+ * @return status of connection
+ **/
+ADS_STATUS ads_connect_simple_anon(ADS_STRUCT *ads)
+{
+       TALLOC_CTX *frame = talloc_stackframe();
+       struct cli_credentials *creds = NULL;
+       ADS_STATUS status;
+
+       creds = cli_credentials_init_anon(frame);
+       if (creds == NULL) {
+               TALLOC_FREE(frame);
+               return ADS_ERROR_SYSTEM(errno);
+       }
+
+       ads->auth.flags |= ADS_AUTH_ANON_BIND;
+       status = ads_connect_creds(ads, creds);
+       TALLOC_FREE(frame);
+       return status;
 }
 
 /**
+ * Connect to the LDAP server using the machine account
+ * @param ads Pointer to an existing ADS_STRUCT
+ * @return status of connection
+ **/
+ADS_STATUS ads_connect_machine(ADS_STRUCT *ads)
+{
+       TALLOC_CTX *frame = talloc_stackframe();
+       struct cli_credentials *creds = NULL;
+       ADS_STATUS status;
+       NTSTATUS ntstatus;
+
+       ntstatus = pdb_get_trust_credentials(ads->server.workgroup,
+                                            ads->server.realm,
+                                            frame,
+                                            &creds);
+       if (!NT_STATUS_IS_OK(ntstatus)) {
+               TALLOC_FREE(frame);
+               return ADS_ERROR_NT(ntstatus);
+       }
+
+       status = ads_connect_creds(ads, creds);
+       TALLOC_FREE(frame);
+       return status;
+}
+
+/*
  * Zero out the internal ads->ldap struct and initialize the address to zero IP.
  * @param ads Pointer to an existing ADS_STRUCT
  *
@@ -857,6 +1231,9 @@ void ads_disconnect(ADS_STRUCT *ads)
                ldap_unbind(ads->ldap.ld);
                ads->ldap.ld = NULL;
        }
+       if (ads->ldap_tls_data.mem_ctx) {
+               talloc_free(ads->ldap_tls_data.mem_ctx);
+       }
        if (ads->ldap_wrap_data.wrap_ops &&
                ads->ldap_wrap_data.wrap_ops->disconnect) {
                ads->ldap_wrap_data.wrap_ops->disconnect(&ads->ldap_wrap_data);
@@ -865,6 +1242,7 @@ void ads_disconnect(ADS_STRUCT *ads)
                talloc_free(ads->ldap_wrap_data.mem_ctx);
        }
        ads_zero_ldap(ads);
+       ZERO_STRUCT(ads->ldap_tls_data);
        ZERO_STRUCT(ads->ldap_wrap_data);
 }
 
@@ -891,7 +1269,7 @@ static struct berval *dup_berval(TALLOC_CTX *ctx, const struct berval *in_val)
 /*
   Make a values list out of an array of (struct berval *)
  */
-static struct berval **ads_dup_values(TALLOC_CTX *ctx, 
+static struct berval **ads_dup_values(TALLOC_CTX *ctx,
                                      const struct berval **in_vals)
 {
        struct berval **values;
@@ -952,7 +1330,7 @@ static char **ads_pull_strvals(TALLOC_CTX *ctx, const char **in_vals)
                if (!pull_utf8_talloc(ctx, &values[i], in_vals[i],
                                      &converted_size)) {
                        DEBUG(0,("ads_pull_strvals: pull_utf8_talloc failed: "
-                                "%s", strerror(errno)));
+                                "%s\n", strerror(errno)));
                }
        }
        return values;
@@ -961,8 +1339,8 @@ static char **ads_pull_strvals(TALLOC_CTX *ctx, const char **in_vals)
 /**
  * Do a search with paged results.  cookie must be null on the first
  *  call, and then returned on each subsequent call.  It will be null
- *  again when the entire search is complete 
- * @param ads connection to ads server 
+ *  again when the entire search is complete
+ * @param ads connection to ads server
  * @param bind_path Base dn for the search
  * @param scope Scope of search (LDAP_SCOPE_BASE | LDAP_SCOPE_ONE | LDAP_SCOPE_SUBTREE)
  * @param expr Search expression - specified in local charset
@@ -976,7 +1354,7 @@ static ADS_STATUS ads_do_paged_search_args(ADS_STRUCT *ads,
                                           const char *bind_path,
                                           int scope, const char *expr,
                                           const char **attrs, void *args,
-                                          LDAPMessage **res, 
+                                          LDAPMessage **res,
                                           int *count, struct berval **cookie)
 {
        int rc, i, version;
@@ -996,8 +1374,8 @@ static ADS_STATUS ads_do_paged_search_args(ADS_STRUCT *ads,
        if (!(ctx = talloc_init("ads_do_paged_search_args")))
                return ADS_ERROR(LDAP_NO_MEMORY);
 
-       /* 0 means the conversion worked but the result was empty 
-          so we only fail if it's -1.  In any case, it always 
+       /* 0 means the conversion worked but the result was empty
+          so we only fail if it's -1.  In any case, it always
           at least nulls out the dest */
        if (!push_utf8_talloc(ctx, &utf8_expr, expr, &converted_size) ||
            !push_utf8_talloc(ctx, &utf8_path, bind_path, &converted_size))
@@ -1043,14 +1421,14 @@ static ADS_STATUS ads_do_paged_search_args(ADS_STRUCT *ads,
        NoReferrals.ldctl_value.bv_len = 0;
        NoReferrals.ldctl_value.bv_val = discard_const_p(char, "");
 
-       if (external_control && 
-           (strequal(external_control->control, ADS_EXTENDED_DN_OID) || 
+       if (external_control &&
+           (strequal(external_control->control, ADS_EXTENDED_DN_OID) ||
             strequal(external_control->control, ADS_SD_FLAGS_OID))) {
 
                ExternalCtrl.ldctl_oid = discard_const_p(char, external_control->control);
                ExternalCtrl.ldctl_iscritical = (char) external_control->critical;
 
-               /* win2k does not accept a ldctl_value beeing passed in */
+               /* win2k does not accept a ldctl_value being passed in */
 
                if (external_control->val != 0) {
 
@@ -1089,15 +1467,15 @@ static ADS_STATUS ads_do_paged_search_args(ADS_STRUCT *ads,
 
        /* we need to disable referrals as the openldap libs don't
           handle them and paged results at the same time.  Using them
-          together results in the result record containing the server 
-          page control being removed from the result list (tridge/jmcd) 
+          together results in the result record containing the server
+          page control being removed from the result list (tridge/jmcd)
 
           leaving this in despite the control that says don't generate
           referrals, in case the server doesn't support it (jmcd)
        */
        ldap_set_option(ads->ldap.ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF);
 
-       rc = ldap_search_with_timeout(ads->ldap.ld, utf8_path, scope, utf8_expr, 
+       rc = ldap_search_with_timeout(ads->ldap.ld, utf8_path, scope, utf8_expr,
                                      search_attrs, 0, controls,
                                      NULL, LDAP_NO_LIMIT,
                                      (LDAPMessage **)res);
@@ -1178,7 +1556,7 @@ done:
 
 static ADS_STATUS ads_do_paged_search(ADS_STRUCT *ads, const char *bind_path,
                                      int scope, const char *expr,
-                                     const char **attrs, LDAPMessage **res, 
+                                     const char **attrs, LDAPMessage **res,
                                      int *count, struct berval **cookie)
 {
        return ads_do_paged_search_args(ads, bind_path, scope, expr, attrs, NULL, res, count, cookie);
@@ -1186,9 +1564,9 @@ static ADS_STATUS ads_do_paged_search(ADS_STRUCT *ads, const char *bind_path,
 
 
 /**
- * Get all results for a search.  This uses ads_do_paged_search() to return 
+ * Get all results for a search.  This uses ads_do_paged_search() to return
  * all entries in a large search.
- * @param ads connection to ads server 
+ * @param ads connection to ads server
  * @param bind_path Base dn for the search
  * @param scope Scope of search (LDAP_SCOPE_BASE | LDAP_SCOPE_ONE | LDAP_SCOPE_SUBTREE)
  * @param expr Search expression
@@ -1209,7 +1587,7 @@ static ADS_STATUS ads_do_paged_search(ADS_STRUCT *ads, const char *bind_path,
        status = ads_do_paged_search_args(ads, bind_path, scope, expr, attrs, args, res,
                                     &count, &cookie);
 
-       if (!ADS_ERR_OK(status)) 
+       if (!ADS_ERR_OK(status))
                return status;
 
 #ifdef HAVE_LDAP_ADD_RESULT_ENTRY
@@ -1249,7 +1627,7 @@ static ADS_STATUS ads_do_paged_search(ADS_STRUCT *ads, const char *bind_path,
 
  ADS_STATUS ads_do_search_all_sd_flags(ADS_STRUCT *ads, const char *bind_path,
                                       int scope, const char *expr,
-                                      const char **attrs, uint32_t sd_flags, 
+                                      const char **attrs, uint32_t sd_flags,
                                       LDAPMessage **res)
 {
        ads_control args;
@@ -1276,7 +1654,7 @@ static ADS_STATUS ads_do_paged_search(ADS_STRUCT *ads, const char *bind_path,
  **/
 ADS_STATUS ads_do_search_all_fn(ADS_STRUCT *ads, const char *bind_path,
                                int scope, const char *expr, const char **attrs,
-                               bool (*fn)(ADS_STRUCT *, char *, void **, void *), 
+                               bool (*fn)(ADS_STRUCT *, char *, void **, void *),
                                void *data_area)
 {
        struct berval *cookie = NULL;
@@ -1315,7 +1693,7 @@ ADS_STATUS ads_do_search_all_fn(ADS_STRUCT *ads, const char *bind_path,
  * @param res ** which will contain results - free res* with ads_msgfree()
  * @return status of search
  **/
- ADS_STATUS ads_do_search(ADS_STRUCT *ads, const char *bind_path, int scope, 
+ ADS_STATUS ads_do_search(ADS_STRUCT *ads, const char *bind_path, int scope,
                          const char *expr,
                          const char **attrs, LDAPMessage **res)
 {
@@ -1326,17 +1704,17 @@ ADS_STATUS ads_do_search_all_fn(ADS_STRUCT *ads, const char *bind_path,
 
        *res = NULL;
        if (!(ctx = talloc_init("ads_do_search"))) {
-               DEBUG(1,("ads_do_search: talloc_init() failed!"));
+               DEBUG(1,("ads_do_search: talloc_init() failed!\n"));
                return ADS_ERROR(LDAP_NO_MEMORY);
        }
 
-       /* 0 means the conversion worked but the result was empty 
-          so we only fail if it's negative.  In any case, it always 
+       /* 0 means the conversion worked but the result was empty
+          so we only fail if it's negative.  In any case, it always
           at least nulls out the dest */
        if (!push_utf8_talloc(ctx, &utf8_expr, expr, &converted_size) ||
            !push_utf8_talloc(ctx, &utf8_path, bind_path, &converted_size))
        {
-               DEBUG(1,("ads_do_search: push_utf8_talloc() failed!"));
+               DEBUG(1,("ads_do_search: push_utf8_talloc() failed!\n"));
                rc = LDAP_NO_MEMORY;
                goto done;
        }
@@ -1348,7 +1726,7 @@ ADS_STATUS ads_do_search_all_fn(ADS_STRUCT *ads, const char *bind_path,
                /* if (!(search_attrs = ads_push_strvals(ctx, attrs)))  */
                if (!(search_attrs = str_list_copy(talloc_tos(), attrs)))
                {
-                       DEBUG(1,("ads_do_search: str_list_copy() failed!"));
+                       DEBUG(1,("ads_do_search: str_list_copy() failed!\n"));
                        rc = LDAP_NO_MEMORY;
                        goto done;
                }
@@ -1358,7 +1736,7 @@ ADS_STATUS ads_do_search_all_fn(ADS_STRUCT *ads, const char *bind_path,
        ldap_set_option(ads->ldap.ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF);
 
        rc = ldap_search_with_timeout(ads->ldap.ld, utf8_path, scope, utf8_expr,
-                                     search_attrs, 0, NULL, NULL, 
+                                     search_attrs, 0, NULL, NULL,
                                      LDAP_NO_LIMIT,
                                      (LDAPMessage **)res);
 
@@ -1381,10 +1759,10 @@ ADS_STATUS ads_do_search_all_fn(ADS_STRUCT *ads, const char *bind_path,
  * @param attrs Attributes to retrieve
  * @return status of search
  **/
- ADS_STATUS ads_search(ADS_STRUCT *ads, LDAPMessage **res, 
+ ADS_STATUS ads_search(ADS_STRUCT *ads, LDAPMessage **res,
                       const char *expr, const char **attrs)
 {
-       return ads_do_search(ads, ads->config.bind_path, LDAP_SCOPE_SUBTREE, 
+       return ads_do_search(ads, ads->config.bind_path, LDAP_SCOPE_SUBTREE,
                             expr, attrs, res);
 }
 
@@ -1392,11 +1770,11 @@ ADS_STATUS ads_do_search_all_fn(ADS_STRUCT *ads, const char *bind_path,
  * Do a search on a specific DistinguishedName
  * @param ads connection to ads server
  * @param res ** which will contain results - free res* with ads_msgfree()
- * @param dn DistinguishName to search
+ * @param dn DistinguishedName to search
  * @param attrs Attributes to retrieve
  * @return status of search
  **/
- ADS_STATUS ads_search_dn(ADS_STRUCT *ads, LDAPMessage **res, 
+ ADS_STATUS ads_search_dn(ADS_STRUCT *ads, LDAPMessage **res,
                          const char *dn, const char **attrs)
 {
        return ads_do_search(ads, dn, LDAP_SCOPE_BASE, "(objectclass=*)",
@@ -1483,7 +1861,6 @@ char *ads_parent_dn(const char *dn)
                "DnsHostName",
                "ServicePrincipalName",
                "userPrincipalName",
-               "unicodePwd",
 
                /* Additional attributes Samba checks */
                "msDS-AdditionalDnsHostName",
@@ -1539,8 +1916,8 @@ ADS_MODLIST ads_init_mods(TALLOC_CTX *ctx)
 /*
   add an attribute to the list, with values list already constructed
 */
-static ADS_STATUS ads_modlist_add(TALLOC_CTX *ctx, ADS_MODLIST *mods, 
-                                 int mod_op, const char *name, 
+static ADS_STATUS ads_modlist_add(TALLOC_CTX *ctx, ADS_MODLIST *mods,
+                                 int mod_op, const char *name,
                                  const void *_invals)
 {
        int curmod;
@@ -1569,7 +1946,7 @@ static ADS_STATUS ads_modlist_add(TALLOC_CTX *ctx, ADS_MODLIST *mods,
                if (!(modlist = talloc_realloc(ctx, modlist, LDAPMod *,
                                curmod+ADS_MODLIST_ALLOC_SIZE+1)))
                        return ADS_ERROR(LDAP_NO_MEMORY);
-               memset(&modlist[curmod], 0, 
+               memset(&modlist[curmod], 0,
                       ADS_MODLIST_ALLOC_SIZE*sizeof(LDAPMod *));
                modlist[curmod+ADS_MODLIST_ALLOC_SIZE] = (LDAPMod *) -1;
                *mods = (ADS_MODLIST)modlist;
@@ -1598,7 +1975,7 @@ static ADS_STATUS ads_modlist_add(TALLOC_CTX *ctx, ADS_MODLIST *mods,
  * @param val The value to add - NULL means DELETE
  * @return ADS STATUS indicating success of add
  **/
-ADS_STATUS ads_mod_str(TALLOC_CTX *ctx, ADS_MODLIST *mods, 
+ADS_STATUS ads_mod_str(TALLOC_CTX *ctx, ADS_MODLIST *mods,
                       const char *name, const char *val)
 {
        const char *values[2];
@@ -1624,7 +2001,7 @@ ADS_STATUS ads_mod_strlist(TALLOC_CTX *ctx, ADS_MODLIST *mods,
 {
        if (!vals)
                return ads_modlist_add(ctx, mods, LDAP_MOD_DELETE, name, NULL);
-       return ads_modlist_add(ctx, mods, LDAP_MOD_REPLACE, 
+       return ads_modlist_add(ctx, mods, LDAP_MOD_REPLACE,
                               name, (const void **) vals);
 }
 
@@ -1636,7 +2013,7 @@ ADS_STATUS ads_mod_strlist(TALLOC_CTX *ctx, ADS_MODLIST *mods,
  * @param val The value to add - NULL means DELETE
  * @return ADS STATUS indicating success of add
  **/
-static ADS_STATUS ads_mod_ber(TALLOC_CTX *ctx, ADS_MODLIST *mods, 
+static ADS_STATUS ads_mod_ber(TALLOC_CTX *ctx, ADS_MODLIST *mods,
                              const char *name, const struct berval *val)
 {
        const struct berval *values[2];
@@ -1646,7 +2023,7 @@ static ADS_STATUS ads_mod_ber(TALLOC_CTX *ctx, ADS_MODLIST *mods,
        if (!val)
                return ads_modlist_add(ctx, mods, LDAP_MOD_DELETE, name, NULL);
        return ads_modlist_add(ctx, mods, LDAP_MOD_REPLACE|LDAP_MOD_BVALUES,
-                              name, (const void **) values);
+                              name, (const void *) values);
 }
 
 static void ads_print_error(int ret, LDAP *ld)
@@ -1674,8 +2051,8 @@ ADS_STATUS ads_gen_mod(ADS_STRUCT *ads, const char *mod_dn, ADS_MODLIST mods)
        int ret,i;
        char *utf8_dn = NULL;
        size_t converted_size;
-       /* 
-          this control is needed to modify that contains a currently 
+       /*
+          this control is needed to modify that contains a currently
           non-existent attribute (but allowable for the object) to run
        */
        LDAPControl PermitModify = {
@@ -1720,7 +2097,7 @@ ADS_STATUS ads_gen_add(ADS_STRUCT *ads, const char *new_dn, ADS_MODLIST mods)
        DBG_INFO("AD LDAP: Adding %s\n", new_dn);
 
        if (!push_utf8_talloc(talloc_tos(), &utf8_dn, new_dn, &converted_size)) {
-               DEBUG(1, ("ads_gen_add: push_utf8_talloc failed!"));
+               DEBUG(1, ("ads_gen_add: push_utf8_talloc failed!\n"));
                return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
        }
 
@@ -1747,7 +2124,7 @@ ADS_STATUS ads_del_dn(ADS_STRUCT *ads, char *del_dn)
        char *utf8_dn = NULL;
        size_t converted_size;
        if (!push_utf8_talloc(talloc_tos(), &utf8_dn, del_dn, &converted_size)) {
-               DEBUG(1, ("ads_del_dn: push_utf8_talloc failed!"));
+               DEBUG(1, ("ads_del_dn: push_utf8_talloc failed!\n"));
                return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
        }
 
@@ -1988,7 +2365,7 @@ uint32_t ads_get_machine_kvno(ADS_STRUCT *ads, const char *machine_name)
 
 /**
  * This clears out all registered spn's for a given hostname
- * @param ads An initilaized ADS_STRUCT
+ * @param ads An initialized ADS_STRUCT
  * @param machine_name the NetBIOS name of the computer.
  * @return 0 upon success, non-zero otherwise.
  **/
@@ -2148,7 +2525,7 @@ done:
  * @param machine_name the NetBIOS name of the computer, which is used to identify the computer account.
  * @param spns An array or strings for the service principals to add,
  *        i.e. 'cifs/machine_name', 'http/machine.full.domain.com' etc.
- * @return 0 upon sucess, or non-zero if a failure occurs
+ * @return 0 upon success, or non-zero if a failure occurs
  **/
 
 ADS_STATUS ads_add_service_principal_names(ADS_STRUCT *ads,
@@ -2340,7 +2717,7 @@ done:
 
 /**
  * adds a machine account to the ADS server
- * @param ads An intialized ADS_STRUCT
+ * @param ads An initialized ADS_STRUCT
  * @param machine_name - the NetBIOS machine name of this account.
  * @param account_type A number indicating the type of account to create
  * @param org_unit The LDAP path in which to place this account
@@ -2455,7 +2832,7 @@ ADS_STATUS ads_create_machine_acct(ADS_STRUCT *ads,
                        goto done;
                }
 
-               ok = add_string_to_array(spn_array,
+               ok = add_string_to_array(ctx,
                                         spn,
                                         &spn_array,
                                         &num_spns);
@@ -2476,7 +2853,7 @@ ADS_STATUS ads_create_machine_acct(ADS_STRUCT *ads,
                        goto done;
                }
 
-               ok = add_string_to_array(spn_array,
+               ok = add_string_to_array(ctx,
                                         spn,
                                         &spn_array,
                                         &num_spns);
@@ -2524,14 +2901,14 @@ done:
 
 /**
  * move a machine account to another OU on the ADS server
- * @param ads - An intialized ADS_STRUCT
+ * @param ads - An initialized ADS_STRUCT
  * @param machine_name - the NetBIOS machine name of this account.
  * @param org_unit - The LDAP path in which to place this account
  * @param moved - whether we moved the machine account (optional)
  * @return 0 upon success, or non-zero otherwise
 **/
 
-ADS_STATUS ads_move_machine_acct(ADS_STRUCT *ads, const char *machine_name, 
+ADS_STATUS ads_move_machine_acct(ADS_STRUCT *ads, const char *machine_name,
                                  const char *org_unit, bool *moved)
 {
        ADS_STATUS rc;
@@ -2572,7 +2949,7 @@ ADS_STATUS ads_move_machine_acct(ADS_STRUCT *ads, const char *machine_name,
                goto done;
        }
 
-       ldap_status = ldap_rename_s(ads->ldap.ld, computer_dn, computer_rdn, 
+       ldap_status = ldap_rename_s(ads->ldap.ld, computer_dn, computer_rdn,
                                    org_unit, 1, NULL, NULL);
        rc = ADS_ERROR(ldap_status);
 
@@ -2698,11 +3075,13 @@ static bool ads_dump_field(ADS_STRUCT *ads, char *field, void **values, void *da
                {"nTSecurityDescriptor", False, dump_sd},
                {"dnsRecord", False, dump_binary},
                {"objectSid", False, dump_sid},
+               {"securityIdentifier", False, dump_sid},
                {"tokenGroups", False, dump_sid},
                {"tokenGroupsNoGCAcceptable", False, dump_sid},
                {"tokengroupsGlobalandUniversal", False, dump_sid},
                {"mS-DS-CreatorSID", False, dump_sid},
                {"msExchMailboxGuid", False, dump_guid},
+               {"msDS-TrustForestTrustInfo", False, dump_binary},
                {NULL, True, NULL}
        };
        int i;
@@ -2762,13 +3141,13 @@ static bool ads_dump_field(ADS_STRUCT *ads, char *field, void **values, void *da
        if (!(ctx = talloc_init("ads_process_results")))
                return;
 
-       for (msg = ads_first_entry(ads, res); msg; 
+       for (msg = ads_first_entry(ads, res); msg;
             msg = ads_next_entry(ads, msg)) {
                char *utf8_field;
                BerElement *b;
 
                for (utf8_field=ldap_first_attribute(ads->ldap.ld,
-                                                    (LDAPMessage *)msg,&b); 
+                                                    (LDAPMessage *)msg,&b);
                     utf8_field;
                     utf8_field=ldap_next_attribute(ads->ldap.ld,
                                                    (LDAPMessage *)msg,b)) {
@@ -2776,13 +3155,13 @@ static bool ads_dump_field(ADS_STRUCT *ads, char *field, void **values, void *da
                        char **str_vals;
                        char **utf8_vals;
                        char *field;
-                       bool string; 
+                       bool string;
 
                        if (!pull_utf8_talloc(ctx, &field, utf8_field,
                                              &converted_size))
                        {
                                DEBUG(0,("ads_process_results: "
-                                        "pull_utf8_talloc failed: %s",
+                                        "pull_utf8_talloc failed: %s\n",
                                         strerror(errno)));
                        }
 
@@ -2798,7 +3177,7 @@ static bool ads_dump_field(ADS_STRUCT *ads, char *field, void **values, void *da
                                fn(ads, field, (void **) str_vals, data_area);
                                ldap_value_free(utf8_vals);
                        } else {
-                               ber_vals = ldap_get_values_len(ads->ldap.ld, 
+                               ber_vals = ldap_get_values_len(ads->ldap.ld,
                                                 (LDAPMessage *)msg, field);
                                fn(ads, field, (void **) ber_vals, data_area);
 
@@ -2941,7 +3320,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
 }
 
 /**
- * pull an array of strings from a ADS result 
+ * pull an array of strings from a ADS result
  *  (handle large multivalue attributes with range retrieval)
  * @param ads connection to ads server
  * @param mem_ctx TALLOC_CTX to use for allocating result string
@@ -2953,7 +3332,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
  * @param more_values Are there more values to get?
  * @return Result strings in talloc context
  **/
- char **ads_pull_strings_range(ADS_STRUCT *ads, 
+ char **ads_pull_strings_range(ADS_STRUCT *ads,
                               TALLOC_CTX *mem_ctx,
                               LDAPMessage *msg, const char *field,
                               char **current_strings,
@@ -2962,7 +3341,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
                               bool *more_strings)
 {
        char *attr;
-       char *expected_range_attrib, *range_attr;
+       char *expected_range_attrib, *range_attr = NULL;
        BerElement *ptr = NULL;
        char **strings;
        char **new_strings;
@@ -2979,8 +3358,8 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
        expected_range_attrib = talloc_asprintf(mem_ctx, "%s;Range=", field);
 
        /* look for Range result */
-       for (attr = ldap_first_attribute(ads->ldap.ld, (LDAPMessage *)msg, &ptr); 
-            attr; 
+       for (attr = ldap_first_attribute(ads->ldap.ld, (LDAPMessage *)msg, &ptr);
+            attr;
             attr = ldap_next_attribute(ads->ldap.ld, (LDAPMessage *)msg, ptr)) {
                /* we ignore the fact that this is utf8, as all attributes are ascii... */
                if (strnequal(attr, expected_range_attrib, strlen(expected_range_attrib))) {
@@ -2989,22 +3368,22 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
                }
                ldap_memfree(attr);
        }
-       if (!attr) {
+       if (!range_attr) {
                ber_free(ptr, 0);
                /* nothing here - this field is just empty */
                *more_strings = False;
                return NULL;
        }
 
-       if (sscanf(&range_attr[strlen(expected_range_attrib)], "%lu-%lu", 
+       if (sscanf(&range_attr[strlen(expected_range_attrib)], "%lu-%lu",
                   &range_start, &range_end) == 2) {
                *more_strings = True;
        } else {
-               if (sscanf(&range_attr[strlen(expected_range_attrib)], "%lu-*", 
+               if (sscanf(&range_attr[strlen(expected_range_attrib)], "%lu-*",
                           &range_start) == 1) {
                        *more_strings = False;
                } else {
-                       DEBUG(1, ("ads_pull_strings_range:  Cannot parse Range attriubte (%s)\n", 
+                       DEBUG(1, ("ads_pull_strings_range:  Cannot parse Range attribute (%s)\n",
                                  range_attr));
                        ldap_memfree(range_attr);
                        *more_strings = False;
@@ -3014,7 +3393,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
 
        if ((*num_strings) != range_start) {
                DEBUG(1, ("ads_pull_strings_range: Range attribute (%s) doesn't start at %u, but at %lu"
-                         " - aborting range retreival\n",
+                         " - aborting range retrieval\n",
                          range_attr, (unsigned int)(*num_strings) + 1, range_start));
                ldap_memfree(range_attr);
                *more_strings = False;
@@ -3025,8 +3404,8 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
 
        if (*more_strings && ((*num_strings + num_new_strings) != (range_end + 1))) {
                DEBUG(1, ("ads_pull_strings_range: Range attribute (%s) tells us we have %lu "
-                         "strings in this bunch, but we only got %lu - aborting range retreival\n",
-                         range_attr, (unsigned long int)range_end - range_start + 1, 
+                         "strings in this bunch, but we only got %lu - aborting range retrieval\n",
+                         range_attr, (unsigned long int)range_end - range_start + 1,
                          (unsigned long int)num_new_strings));
                ldap_memfree(range_attr);
                *more_strings = False;
@@ -3051,7 +3430,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
 
        if (*more_strings) {
                *next_attribute = talloc_asprintf(mem_ctx,
-                                                 "%s;range=%d-*", 
+                                                 "%s;range=%d-*",
                                                  field,
                                                  (int)*num_strings);
 
@@ -3074,7 +3453,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
  * @param msg Results of search
  * @param field Attribute to retrieve
  * @param v Pointer to int to store result
- * @return boolean inidicating success
+ * @return boolean indicating success
 */
  bool ads_pull_uint32(ADS_STRUCT *ads, LDAPMessage *msg, const char *field,
                      uint32_t *v)
@@ -3123,7 +3502,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
  * @param msg Results of search
  * @param field Attribute to retrieve
  * @param sid Pointer to sid to store result
- * @return boolean inidicating success
+ * @return boolean indicating success
 */
  bool ads_pull_sid(ADS_STRUCT *ads, LDAPMessage *msg, const char *field,
                   struct dom_sid *sid)
@@ -3188,7 +3567,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
  * @param msg Results of search
  * @param field Attribute to retrieve
  * @param sd Pointer to *struct security_descriptor to store result (talloc()ed)
- * @return boolean inidicating success
+ * @return boolean indicating success
 */
  bool ads_pull_sd(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
                  LDAPMessage *msg, const char *field,
@@ -3217,9 +3596,9 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
        return ret;
 }
 
-/* 
- * in order to support usernames longer than 21 characters we need to 
- * use both the sAMAccountName and the userPrincipalName attributes 
+/*
+ * in order to support usernames longer than 21 characters we need to
+ * use both the sAMAccountName and the userPrincipalName attributes
  * It seems that not all users have the userPrincipalName attribute set
  *
  * @param ads connection to ads server
@@ -3233,7 +3612,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
 #if 0  /* JERRY */
        char *ret, *p;
 
-       /* lookup_name() only works on the sAMAccountName to 
+       /* lookup_name() only works on the sAMAccountName to
           returning the username portion of userPrincipalName
           breaks winbindd_getpwnam() */
 
@@ -3261,7 +3640,7 @@ ADS_STATUS ads_USN(ADS_STRUCT *ads, uint32_t *usn)
        LDAPMessage *res;
 
        status = ads_do_search_retry(ads, "", LDAP_SCOPE_BASE, "(objectclass=*)", attrs, &res);
-       if (!ADS_ERR_OK(status)) 
+       if (!ADS_ERR_OK(status))
                return status;
 
        if (ads_count_replies(ads, res) != 1) {
@@ -3287,8 +3666,8 @@ static time_t ads_parse_time(const char *str)
 
        ZERO_STRUCT(tm);
 
-       if (sscanf(str, "%4d%2d%2d%2d%2d%2d", 
-                  &tm.tm_year, &tm.tm_mon, &tm.tm_mday, 
+       if (sscanf(str, "%4d%2d%2d%2d%2d%2d",
+                  &tm.tm_year, &tm.tm_mon, &tm.tm_mday,
                   &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6) {
                return 0;
        }
@@ -3344,8 +3723,7 @@ ADS_STATUS ads_current_time(ADS_STRUCT *ads)
                 */
                ads_s->config.flags = 0;
 
-               ads_s->auth.flags = ADS_AUTH_ANON_BIND;
-               status = ads_connect( ads_s );
+               status = ads_connect_simple_anon(ads_s);
                if ( !ADS_ERR_OK(status))
                        goto done;
        }
@@ -3362,15 +3740,21 @@ ADS_STATUS ads_current_time(ADS_STRUCT *ads)
                goto done;
        }
 
-       /* but save the time and offset in the original ADS_STRUCT */   
+       /* but save the time and offset in the original ADS_STRUCT */
 
        ads->config.current_time = ads_parse_time(timestr);
 
        if (ads->config.current_time != 0) {
-               ads->auth.time_offset = ads->config.current_time - time(NULL);
-               DEBUG(4,("KDC time offset is %d seconds\n", ads->auth.time_offset));
+               ads->config.time_offset = ads->config.current_time - time(NULL);
+               DBG_INFO("server time offset is %d seconds\n",
+                        ads->config.time_offset);
+       } else {
+               ads->config.time_offset = 0;
        }
 
+       DBG_INFO("server time offset is %d seconds\n",
+                ads->config.time_offset);
+
        ads_msgfree(ads, res);
 
        status = ADS_SUCCESS;
@@ -3428,13 +3812,12 @@ ADS_STATUS ads_domain_func_level(ADS_STRUCT *ads, uint32_t *val)
                 */
                ads_s->config.flags = 0;
 
-               ads_s->auth.flags = ADS_AUTH_ANON_BIND;
-               status = ads_connect( ads_s );
+               status = ads_connect_simple_anon(ads_s);
                if ( !ADS_ERR_OK(status))
                        goto done;
        }
 
-       /* If the attribute does not exist assume it is a Windows 2000 
+       /* If the attribute does not exist assume it is a Windows 2000
           functional domain */
 
        status = ads_do_search(ads_s, "", LDAP_SCOPE_BASE, "(objectclass=*)", attrs, &res);
@@ -3471,7 +3854,7 @@ ADS_STATUS ads_domain_sid(ADS_STRUCT *ads, struct dom_sid *sid)
        LDAPMessage *res;
        ADS_STATUS rc;
 
-       rc = ads_do_search_retry(ads, ads->config.bind_path, LDAP_SCOPE_BASE, "(objectclass=*)", 
+       rc = ads_do_search_retry(ads, ads->config.bind_path, LDAP_SCOPE_BASE, "(objectclass=*)",
                           attrs, &res);
        if (!ADS_ERR_OK(rc)) return rc;
        if (!ads_pull_sid(ads, res, "objectSid", sid)) {
@@ -3484,7 +3867,7 @@ ADS_STATUS ads_domain_sid(ADS_STRUCT *ads, struct dom_sid *sid)
 }
 
 /**
- * find our site name 
+ * find our site name
  * @param ads connection to ads server
  * @param mem_ctx Pointer to talloc context
  * @param site_name Pointer to the sitename
@@ -3524,7 +3907,7 @@ ADS_STATUS ads_site_dn(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx, const char **site_n
        return status;
        /*
        dsServiceName: CN=NTDS Settings,CN=W2K3DC,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=ber,DC=suse,DC=de
-       */                                               
+       */
 }
 
 /**
@@ -3558,7 +3941,7 @@ ADS_STATUS ads_site_dn_for_machine(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx, const c
                return ADS_ERROR(LDAP_NO_MEMORY);
        }
 
-       status = ads_do_search(ads, config_context, LDAP_SCOPE_SUBTREE, 
+       status = ads_do_search(ads, config_context, LDAP_SCOPE_SUBTREE,
                               filter, NULL, &res);
        if (!ADS_ERR_OK(status)) {
                return status;
@@ -3836,7 +4219,7 @@ static char **get_addl_hosts(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
 
        /*
         * Windows DC implicitly adds a short name for each FQDN added to
-        * msDS-AdditionalDnsHostName, but it comes with a strage binary
+        * msDS-AdditionalDnsHostName, but it comes with a strange binary
         * suffix "\0$" which we should ignore (see bug #14406).
         */
 
@@ -4265,7 +4648,7 @@ ADS_STATUS ads_leave_realm(ADS_STRUCT *ads, const char *hostname)
 }
 
 /**
- * Find a sAMAccoutName in LDAP
+ * Find a sAMAccountName in LDAP
  * @param ads connection to ads server
  * @param mem_ctx TALLOC_CTX for allocating sid array
  * @param samaccountname to search
@@ -4336,14 +4719,14 @@ ADS_STATUS ads_find_samaccount(ADS_STRUCT *ads,
 }
 
 /**
- * find our configuration path 
+ * find our configuration path
  * @param ads connection to ads server
  * @param mem_ctx Pointer to talloc context
  * @param config_path Pointer to the config path
  * @return status of search
  **/
-ADS_STATUS ads_config_path(ADS_STRUCT *ads, 
-                          TALLOC_CTX *mem_ctx, 
+ADS_STATUS ads_config_path(ADS_STRUCT *ads,
+                          TALLOC_CTX *mem_ctx,
                           char **config_path)
 {
        ADS_STATUS status;
@@ -4351,13 +4734,13 @@ ADS_STATUS ads_config_path(ADS_STRUCT *ads,
        const char *config_context = NULL;
        const char *attrs[] = { "configurationNamingContext", NULL };
 
-       status = ads_do_search(ads, "", LDAP_SCOPE_BASE, 
+       status = ads_do_search(ads, "", LDAP_SCOPE_BASE,
                               "(objectclass=*)", attrs, &res);
        if (!ADS_ERR_OK(status)) {
                return status;
        }
 
-       config_context = ads_pull_string(ads, mem_ctx, res, 
+       config_context = ads_pull_string(ads, mem_ctx, res,
                                         "configurationNamingContext");
        ads_msgfree(ads, res);
        if (!config_context) {
@@ -4375,16 +4758,16 @@ ADS_STATUS ads_config_path(ADS_STRUCT *ads,
 }
 
 /**
- * find the displayName of an extended right 
+ * find the displayName of an extended right
  * @param ads connection to ads server
  * @param config_path The config path
  * @param mem_ctx Pointer to talloc context
  * @param GUID struct of the rightsGUID
  * @return status of search
  **/
-const char *ads_get_extended_right_name_by_guid(ADS_STRUCT *ads, 
-                                               const char *config_path, 
-                                               TALLOC_CTX *mem_ctx, 
+const char *ads_get_extended_right_name_by_guid(ADS_STRUCT *ads,
+                                               const char *config_path,
+                                               TALLOC_CTX *mem_ctx,
                                                const struct GUID *rights_guid)
 {
        ADS_STATUS rc;
@@ -4398,7 +4781,7 @@ const char *ads_get_extended_right_name_by_guid(ADS_STRUCT *ads,
                goto done;
        }
 
-       expr = talloc_asprintf(mem_ctx, "(rightsGuid=%s)", 
+       expr = talloc_asprintf(mem_ctx, "(rightsGuid=%s)",
                               GUID_string(mem_ctx, rights_guid));
        if (!expr) {
                goto done;
@@ -4409,7 +4792,7 @@ const char *ads_get_extended_right_name_by_guid(ADS_STRUCT *ads,
                goto done;
        }
 
-       rc = ads_do_search_retry(ads, path, LDAP_SCOPE_SUBTREE, 
+       rc = ads_do_search_retry(ads, path, LDAP_SCOPE_SUBTREE,
                                 expr, attrs, &res);
        if (!ADS_ERR_OK(rc)) {
                goto done;