drs: Send DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP by default
[samba.git] / source3 / winbindd / winbindd_pam.c
index 23ffb87b7e09416e8019944b02800f6af6e86a81..891042355554adc4eba035dff55cc79dd0d0c579 100644 (file)
@@ -25,7 +25,8 @@
 #include "includes.h"
 #include "winbindd.h"
 #include "../libcli/auth/libcli_auth.h"
-#include "../librpc/gen_ndr/cli_samr.h"
+#include "../librpc/gen_ndr/ndr_samr_c.h"
+#include "rpc_client/cli_pipe.h"
 #include "rpc_client/cli_samr.h"
 #include "../librpc/gen_ndr/ndr_netlogon.h"
 #include "rpc_client/cli_netlogon.h"
 #include "../libcli/security/security.h"
 #include "ads.h"
 #include "../librpc/gen_ndr/krb5pac.h"
+#include "passdb/machine_sid.h"
+#include "auth.h"
+#include "../lib/tsocket/tsocket.h"
+#include "auth/kerberos/pac_utils.h"
+#include "auth/gensec/gensec.h"
+#include "librpc/crypto/gse_krb5.h"
+#include "lib/afs/afs_funcs.h"
 
 #undef DBGC_CLASS
 #define DBGC_CLASS DBGC_WINBIND
@@ -48,11 +56,11 @@ static NTSTATUS append_info3_as_txt(TALLOC_CTX *mem_ctx,
        uint32_t i;
 
        resp->data.auth.info3.logon_time =
-               nt_time_to_unix(info3->base.last_logon);
+               nt_time_to_unix(info3->base.logon_time);
        resp->data.auth.info3.logoff_time =
-               nt_time_to_unix(info3->base.last_logoff);
+               nt_time_to_unix(info3->base.logoff_time);
        resp->data.auth.info3.kickoff_time =
-               nt_time_to_unix(info3->base.acct_expiry);
+               nt_time_to_unix(info3->base.kickoff_time);
        resp->data.auth.info3.pass_last_set_time =
                nt_time_to_unix(info3->base.last_password_change);
        resp->data.auth.info3.pass_can_change_time =
@@ -89,7 +97,7 @@ static NTSTATUS append_info3_as_txt(TALLOC_CTX *mem_ctx,
        fstrcpy(resp->data.auth.info3.logon_srv,
                info3->base.logon_server.string);
        fstrcpy(resp->data.auth.info3.logon_dom,
-               info3->base.domain.string);
+               info3->base.logon_domain.string);
 
        ex = talloc_strdup(mem_ctx, "");
        NT_STATUS_HAVE_NO_MEMORY(ex);
@@ -152,7 +160,7 @@ static NTSTATUS append_unix_username(TALLOC_CTX *mem_ctx,
 
        const char *nt_username, *nt_domain;
 
-       nt_domain = talloc_strdup(mem_ctx, info3->base.domain.string);
+       nt_domain = talloc_strdup(mem_ctx, info3->base.logon_domain.string);
        if (!nt_domain) {
                /* If the server didn't give us one, just use the one
                 * we sent them */
@@ -213,7 +221,9 @@ static NTSTATUS append_afs_token(TALLOC_CTX *mem_ctx,
                return NT_STATUS_NO_MEMORY;
        }
 
-       strlower_m(afsname);
+       if (!strlower_m(afsname)) {
+               return NT_STATUS_INVALID_PARAMETER;
+       }
 
        DEBUG(10, ("Generating token for user %s\n", afsname));
 
@@ -267,6 +277,7 @@ static NTSTATUS check_info3_in_group(struct netr_SamInfo3 *info3,
 
        if (!group_sid || !group_sid[0]) {
                /* NO sid supplied, all users may access */
+               TALLOC_FREE(frame);
                return NT_STATUS_OK;
        }
 
@@ -303,7 +314,7 @@ static NTSTATUS check_info3_in_group(struct netr_SamInfo3 *info3,
        status = sid_array_from_info3(talloc_tos(), info3,
                                      &token->sids,
                                      &token->num_sids,
-                                     true, false);
+                                     true);
        if (!NT_STATUS_IS_OK(status)) {
                TALLOC_FREE(frame);
                return status;
@@ -382,39 +393,43 @@ static void fill_in_password_policy(struct winbindd_response *r,
        r->data.auth.policy.password_properties =
                p->password_properties;
        r->data.auth.policy.expire      =
-               nt_time_to_unix_abs((NTTIME *)&(p->max_password_age));
+               nt_time_to_unix_abs((const NTTIME *)&(p->max_password_age));
        r->data.auth.policy.min_passwordage =
-               nt_time_to_unix_abs((NTTIME *)&(p->min_password_age));
+               nt_time_to_unix_abs((const NTTIME *)&(p->min_password_age));
 }
 
 static NTSTATUS fillup_password_policy(struct winbindd_domain *domain,
-                                      struct winbindd_cli_state *state)
+                                      struct winbindd_response *response)
 {
+       TALLOC_CTX *frame = talloc_stackframe();
        struct winbindd_methods *methods;
-       NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
+       NTSTATUS status;
        struct samr_DomInfo1 password_policy;
 
        if ( !winbindd_can_contact_domain( domain ) ) {
                DEBUG(5,("fillup_password_policy: No inbound trust to "
                         "contact domain %s\n", domain->name));
-               return NT_STATUS_NOT_SUPPORTED;
+               status = NT_STATUS_NOT_SUPPORTED;
+               goto done;
        }
 
        methods = domain->methods;
 
-       status = methods->password_policy(domain, state->mem_ctx, &password_policy);
+       status = methods->password_policy(domain, talloc_tos(), &password_policy);
        if (NT_STATUS_IS_ERR(status)) {
-               return status;
+               goto done;
        }
 
-       fill_in_password_policy(state->response, &password_policy);
+       fill_in_password_policy(response, &password_policy);
 
+done:
+       TALLOC_FREE(frame);
        return NT_STATUS_OK;
 }
 
 static NTSTATUS get_max_bad_attempts_from_lockout_policy(struct winbindd_domain *domain,
                                                         TALLOC_CTX *mem_ctx,
-                                                        uint16 *lockout_threshold)
+                                                        uint16_t *lockout_threshold)
 {
        struct winbindd_methods *methods;
        NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
@@ -436,7 +451,7 @@ static NTSTATUS get_max_bad_attempts_from_lockout_policy(struct winbindd_domain
 
 static NTSTATUS get_pwd_properties(struct winbindd_domain *domain,
                                   TALLOC_CTX *mem_ctx,
-                                  uint32 *password_properties)
+                                  uint32_t *password_properties)
 {
        struct winbindd_methods *methods;
        NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
@@ -478,6 +493,42 @@ static const char *generate_krb5_ccache(TALLOC_CTX *mem_ctx,
                        gen_cc = talloc_asprintf(
                                mem_ctx, "WRFILE:/tmp/krb5cc_%d", uid);
                }
+               if (strequal(type, "KEYRING")) {
+                       gen_cc = talloc_asprintf(
+                               mem_ctx, "KEYRING:persistent:%d", uid);
+               }
+
+               if (strnequal(type, "FILE:/", 6) ||
+                   strnequal(type, "WRFILE:/", 8) ||
+                   strnequal(type, "DIR:/", 5)) {
+
+                       /* we allow only one "%u" substitution */
+
+                       char *p;
+
+                       p = strchr(type, '%');
+                       if (p != NULL) {
+
+                               p++;
+
+                               if (p != NULL && *p == 'u' && strchr(p, '%') == NULL) {
+                                       char uid_str[sizeof("18446744073709551615")];
+
+                                       snprintf(uid_str, sizeof(uid_str), "%u", uid);
+
+                                       gen_cc = talloc_string_sub2(mem_ctx,
+                                                       type,
+                                                       "%u",
+                                                       uid_str,
+                                                       /* remove_unsafe_characters */
+                                                       false,
+                                                       /* replace_once */
+                                                       true,
+                                                       /* allow_trailing_dollar */
+                                                       false);
+                               }
+                       }
+               }
        }
 
        *user_ccache_file = gen_cc;
@@ -511,19 +562,19 @@ uid_t get_uid_from_request(struct winbindd_request *request)
        return uid;
 }
 
-static uid_t get_uid_from_state(struct winbindd_cli_state *state)
-{
-       return get_uid_from_request(state->request);
-}
-
 /**********************************************************************
  Authenticate a user with a clear text password using Kerberos and fill up
  ccache if required
  **********************************************************************/
 
-static NTSTATUS winbindd_raw_kerberos_login(struct winbindd_domain *domain,
-                                           struct winbindd_cli_state *state,
-                                           struct netr_SamInfo3 **info3)
+static NTSTATUS winbindd_raw_kerberos_login(TALLOC_CTX *mem_ctx,
+                                           struct winbindd_domain *domain,
+                                           const char *user,
+                                           const char *pass,
+                                           const char *krb5_cc_type,
+                                           uid_t uid,
+                                           struct netr_SamInfo3 **info3,
+                                           fstring krb5ccname)
 {
 #ifdef HAVE_KRB5
        NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
@@ -535,25 +586,32 @@ static NTSTATUS winbindd_raw_kerberos_login(struct winbindd_domain *domain,
        fstring name_domain, name_user;
        time_t ticket_lifetime = 0;
        time_t renewal_until = 0;
-       uid_t uid = -1;
        ADS_STRUCT *ads;
        time_t time_offset = 0;
        const char *user_ccache_file;
        struct PAC_LOGON_INFO *logon_info = NULL;
+       struct PAC_DATA *pac_data = NULL;
+       struct PAC_DATA_CTR *pac_data_ctr = NULL;
+       const char *local_service;
+       int i;
+       struct netr_SamInfo3 *info3_copy = NULL;
 
        *info3 = NULL;
 
+       if (domain->alt_name == NULL) {
+               return NT_STATUS_INVALID_PARAMETER;
+       }
+
        /* 1st step:
         * prepare a krb5_cc_cache string for the user */
 
-       uid = get_uid_from_state(state);
        if (uid == -1) {
                DEBUG(0,("no valid uid\n"));
        }
 
-       cc = generate_krb5_ccache(state->mem_ctx,
-                                 state->request->data.auth.krb5_cc_type,
-                                 state->request->data.auth.uid,
+       cc = generate_krb5_ccache(mem_ctx,
+                                 krb5_cc_type,
+                                 uid,
                                  &user_ccache_file);
        if (cc == NULL) {
                return NT_STATUS_NO_MEMORY;
@@ -572,21 +630,34 @@ static NTSTATUS winbindd_raw_kerberos_login(struct winbindd_domain *domain,
        /* 3rd step:
         * do kerberos auth and setup ccache as the user */
 
-       parse_domain_user(state->request->data.auth.user, name_domain, name_user);
+       parse_domain_user(user, name_domain, name_user);
 
-       realm = domain->alt_name;
-       strupper_m(realm);
+       realm = talloc_strdup(mem_ctx, domain->alt_name);
+       if (realm == NULL) {
+               return NT_STATUS_NO_MEMORY;
+       }
+
+       if (!strupper_m(realm)) {
+               return NT_STATUS_INVALID_PARAMETER;
+       }
 
-       principal_s = talloc_asprintf(state->mem_ctx, "%s@%s", name_user, realm);
+       principal_s = talloc_asprintf(mem_ctx, "%s@%s", name_user, realm);
        if (principal_s == NULL) {
                return NT_STATUS_NO_MEMORY;
        }
 
-       service = talloc_asprintf(state->mem_ctx, "%s/%s@%s", KRB5_TGS_NAME, realm, realm);
+       service = talloc_asprintf(mem_ctx, "%s/%s@%s", KRB5_TGS_NAME, realm, realm);
        if (service == NULL) {
                return NT_STATUS_NO_MEMORY;
        }
 
+       local_service = talloc_asprintf(mem_ctx, "%s$@%s",
+                                       lp_netbios_name(), lp_realm());
+       if (local_service == NULL) {
+               return NT_STATUS_NO_MEMORY;
+       }
+
+
        /* if this is a user ccache, we need to act as the user to let the krb5
         * library handle the chown, etc. */
 
@@ -597,9 +668,9 @@ static NTSTATUS winbindd_raw_kerberos_login(struct winbindd_domain *domain,
                DEBUG(10,("winbindd_raw_kerberos_login: uid is %d\n", uid));
        }
 
-       result = kerberos_return_pac(state->mem_ctx,
+       result = kerberos_return_pac(mem_ctx,
                                     principal_s,
-                                    state->request->data.auth.pass,
+                                    pass,
                                     time_offset,
                                     &ticket_lifetime,
                                     &renewal_until,
@@ -608,7 +679,8 @@ static NTSTATUS winbindd_raw_kerberos_login(struct winbindd_domain *domain,
                                     true,
                                     WINBINDD_PAM_AUTH_KRB5_RENEW_TIME,
                                     NULL,
-                                    &logon_info);
+                                    local_service,
+                                    &pac_data_ctr);
        if (user_ccache_file != NULL) {
                gain_root_privilege();
        }
@@ -619,23 +691,55 @@ static NTSTATUS winbindd_raw_kerberos_login(struct winbindd_domain *domain,
                goto failed;
        }
 
-       *info3 = &logon_info->info3;
+       if (pac_data_ctr == NULL) {
+               goto failed;
+       }
+
+       pac_data = pac_data_ctr->pac_data;
+       if (pac_data == NULL) {
+               goto failed;
+       }
+
+       for (i=0; i < pac_data->num_buffers; i++) {
+
+               if (pac_data->buffers[i].type != PAC_TYPE_LOGON_INFO) {
+                       continue;
+               }
+
+               logon_info = pac_data->buffers[i].info->logon_info.info;
+               if (!logon_info) {
+                       return NT_STATUS_INVALID_PARAMETER;
+               }
+
+               break;
+       }
+
+       if (logon_info == NULL) {
+               DEBUG(10,("Missing logon_info in ticket of %s\n",
+                       principal_s));
+               return NT_STATUS_INVALID_PARAMETER;
+       }
 
        DEBUG(10,("winbindd_raw_kerberos_login: winbindd validated ticket of %s\n",
                principal_s));
 
+       result = create_info3_from_pac_logon_info(mem_ctx, logon_info, &info3_copy);
+       if (!NT_STATUS_IS_OK(result)) {
+               goto failed;
+       }
+
        /* if we had a user's ccache then return that string for the pam
         * environment */
 
        if (user_ccache_file != NULL) {
 
-               fstrcpy(state->response->data.auth.krb5ccname,
-                       user_ccache_file);
+               fstrcpy(krb5ccname, user_ccache_file);
 
                result = add_ccache_to_list(principal_s,
                                            cc,
                                            service,
-                                           state->request->data.auth.user,
+                                           user,
+                                           pass,
                                            realm,
                                            uid,
                                            time(NULL),
@@ -659,10 +763,18 @@ static NTSTATUS winbindd_raw_kerberos_login(struct winbindd_domain *domain,
                }
 
        }
-
+       *info3 = info3_copy;
        return NT_STATUS_OK;
 
 failed:
+       /*
+        * Do not delete an existing valid credential cache, if the user
+        * e.g. enters a wrong password
+        */
+       if ((strequal(krb5_cc_type, "FILE") || strequal(krb5_cc_type, "WRFILE"))
+           && user_ccache_file != NULL) {
+               return result;
+       }
 
        /* we could have created a new credential cache with a valid tgt in it
         * but we werent able to get or verify the service ticket for this
@@ -676,10 +788,10 @@ failed:
                         "%s\n", error_message(krb5_ret)));
        }
 
-       if (!NT_STATUS_IS_OK(remove_ccache(state->request->data.auth.user))) {
+       if (!NT_STATUS_IS_OK(remove_ccache(user))) {
                DEBUG(3,("winbindd_raw_kerberos_login: "
                          "could not remove ccache for user %s\n",
-                       state->request->data.auth.user));
+                       user));
        }
 
        return result;
@@ -713,12 +825,12 @@ bool check_request_flags(uint32_t flags)
 /****************************************************************
 ****************************************************************/
 
-static NTSTATUS append_auth_data(TALLOC_CTX *mem_ctx,
-                                struct winbindd_response *resp,
-                                uint32_t request_flags,
-                                struct netr_SamInfo3 *info3,
-                                const char *name_domain,
-                                const char *name_user)
+NTSTATUS append_auth_data(TALLOC_CTX *mem_ctx,
+                         struct winbindd_response *resp,
+                         uint32_t request_flags,
+                         struct netr_SamInfo3 *info3,
+                         const char *name_domain,
+                         const char *name_user)
 {
        NTSTATUS result;
 
@@ -784,13 +896,13 @@ static NTSTATUS winbindd_dual_pam_auth_cached(struct winbindd_domain *domain,
                                              struct netr_SamInfo3 **info3)
 {
        NTSTATUS result = NT_STATUS_LOGON_FAILURE;
-       uint16 max_allowed_bad_attempts;
+       uint16_t max_allowed_bad_attempts;
        fstring name_domain, name_user;
        struct dom_sid sid;
        enum lsa_SidType type;
        uchar new_nt_pass[NT_HASH_LEN];
-       const uint8 *cached_nt_pass;
-       const uint8 *cached_salt;
+       const uint8_t *cached_nt_pass;
+       const uint8_t *cached_salt;
        struct netr_SamInfo3 *my_info3;
        time_t kickoff_time, must_change_time;
        bool password_good = false;
@@ -890,7 +1002,7 @@ static NTSTATUS winbindd_dual_pam_auth_cached(struct winbindd_domain *domain,
                        return NT_STATUS_LOGON_FAILURE;
                }
 
-               kickoff_time = nt_time_to_unix(my_info3->base.acct_expiry);
+               kickoff_time = nt_time_to_unix(my_info3->base.kickoff_time);
                if (kickoff_time != 0 && time(NULL) > kickoff_time) {
                        return NT_STATUS_ACCOUNT_EXPIRED;
                }
@@ -906,7 +1018,7 @@ static NTSTATUS winbindd_dual_pam_auth_cached(struct winbindd_domain *domain,
 #ifdef HAVE_KRB5
                if ((state->request->flags & WBFLAG_PAM_KRB5) &&
                    ((tdc_domain = wcache_tdc_fetch_domain(state->mem_ctx, name_domain)) != NULL) &&
-                   ((tdc_domain->trust_type & NETR_TRUST_TYPE_UPLEVEL) ||
+                   ((tdc_domain->trust_type & LSA_TRUST_TYPE_UPLEVEL) ||
                    /* used to cope with the case winbindd starting without network. */
                    !strequal(tdc_domain->domain_name, tdc_domain->dns_name))) {
 
@@ -917,7 +1029,11 @@ static NTSTATUS winbindd_dual_pam_auth_cached(struct winbindd_domain *domain,
                        const char *service = NULL;
                        const char *user_ccache_file;
 
-                       uid = get_uid_from_state(state);
+                       if (domain->alt_name == NULL) {
+                               return NT_STATUS_INVALID_PARAMETER;
+                       }
+
+                       uid = get_uid_from_request(state->request);
                        if (uid == -1) {
                                DEBUG(0,("winbindd_dual_pam_auth_cached: invalid uid\n"));
                                return NT_STATUS_INVALID_PARAMETER;
@@ -931,8 +1047,14 @@ static NTSTATUS winbindd_dual_pam_auth_cached(struct winbindd_domain *domain,
                                return NT_STATUS_NO_MEMORY;
                        }
 
-                       realm = domain->alt_name;
-                       strupper_m(realm);
+                       realm = talloc_strdup(state->mem_ctx, domain->alt_name);
+                       if (realm == NULL) {
+                               return NT_STATUS_NO_MEMORY;
+                       }
+
+                       if (!strupper_m(realm)) {
+                               return NT_STATUS_INVALID_PARAMETER;
+                       }
 
                        principal_s = talloc_asprintf(state->mem_ctx, "%s@%s", name_user, realm);
                        if (principal_s == NULL) {
@@ -953,7 +1075,8 @@ static NTSTATUS winbindd_dual_pam_auth_cached(struct winbindd_domain *domain,
                                                            cc,
                                                            service,
                                                            state->request->data.auth.user,
-                                                           domain->alt_name,
+                                                           state->request->data.auth.pass,
+                                                           realm,
                                                            uid,
                                                            time(NULL),
                                                            time(NULL) + lp_winbind_cache_time(),
@@ -972,7 +1095,7 @@ static NTSTATUS winbindd_dual_pam_auth_cached(struct winbindd_domain *domain,
                /* FIXME: we possibly should handle logon hours as well (does xp when
                 * offline?) see auth/auth_sam.c:sam_account_ok for details */
 
-               unix_to_nt_time(&my_info3->base.last_logon, time(NULL));
+               unix_to_nt_time(&my_info3->base.logon_time, time(NULL));
                my_info3->base.bad_password_count = 0;
 
                result = winbindd_update_creds_by_info3(domain,
@@ -989,7 +1112,10 @@ static NTSTATUS winbindd_dual_pam_auth_cached(struct winbindd_domain *domain,
 
        }
 
-       /* User does *NOT* know the correct password, modify info3 accordingly */
+       /* User does *NOT* know the correct password, modify info3 accordingly, but only if online */
+       if (domain->online == false) {
+               goto failed;
+       }
 
        /* failure of this is not critical */
        result = get_max_bad_attempts_from_lockout_policy(domain, state->mem_ctx, &max_allowed_bad_attempts);
@@ -1008,7 +1134,7 @@ static NTSTATUS winbindd_dual_pam_auth_cached(struct winbindd_domain *domain,
        /* lockout user */
        if (my_info3->base.bad_password_count >= max_allowed_bad_attempts) {
 
-               uint32 password_properties;
+               uint32_t password_properties;
 
                result = get_pwd_properties(domain, state->mem_ctx, &password_properties);
                if (!NT_STATUS_IS_OK(result)) {
@@ -1071,7 +1197,8 @@ static NTSTATUS winbindd_dual_pam_auth_kerberos(struct winbindd_domain *domain,
                        DEBUG(3, ("Authentication for domain for [%s] -> [%s]\\[%s] failed as %s is not a trusted domain\n",
                                  state->request->data.auth.user, name_domain, name_user, name_domain));
 
-                       contact_domain = find_our_domain();
+                       result =  NT_STATUS_NO_SUCH_USER;
+                       goto done;
                }
        }
 
@@ -1081,7 +1208,7 @@ static NTSTATUS winbindd_dual_pam_auth_kerberos(struct winbindd_domain *domain,
        }
 
        if (!contact_domain->initialized) {
-               init_dc_connection(contact_domain);
+               init_dc_connection(contact_domain, false);
        }
 
        if (!contact_domain->active_directory) {
@@ -1089,65 +1216,280 @@ static NTSTATUS winbindd_dual_pam_auth_kerberos(struct winbindd_domain *domain,
                return NT_STATUS_INVALID_LOGON_TYPE;
        }
 try_login:
-       result = winbindd_raw_kerberos_login(contact_domain, state, info3);
+       result = winbindd_raw_kerberos_login(
+               state->mem_ctx, contact_domain,
+               state->request->data.auth.user,
+               state->request->data.auth.pass,
+               state->request->data.auth.krb5_cc_type,
+               get_uid_from_request(state->request),
+               info3, state->response->data.auth.krb5ccname);
 done:
        return result;
 }
 
 static NTSTATUS winbindd_dual_auth_passdb(TALLOC_CTX *mem_ctx,
+                                         uint32_t logon_parameters,
                                          const char *domain, const char *user,
                                          const DATA_BLOB *challenge,
                                          const DATA_BLOB *lm_resp,
                                          const DATA_BLOB *nt_resp,
                                          struct netr_SamInfo3 **pinfo3)
 {
+       struct auth_context *auth_context;
+       struct auth_serversupplied_info *server_info;
        struct auth_usersupplied_info *user_info = NULL;
+       struct tsocket_address *local;
+       struct netr_SamInfo3 *info3;
        NTSTATUS status;
+       int rc;
+       TALLOC_CTX *frame = talloc_stackframe();
 
-       status = make_user_info(&user_info, user, user, domain, domain,
-                               global_myname(), lm_resp, nt_resp, NULL, NULL,
+       rc = tsocket_address_inet_from_strings(frame,
+                                              "ip",
+                                              "127.0.0.1",
+                                              0,
+                                              &local);
+       if (rc < 0) {
+               TALLOC_FREE(frame);
+               return NT_STATUS_NO_MEMORY;
+       }
+       status = make_user_info(frame, &user_info, user, user, domain, domain,
+                               lp_netbios_name(), local, lm_resp, nt_resp, NULL, NULL,
                                NULL, AUTH_PASSWORD_RESPONSE);
        if (!NT_STATUS_IS_OK(status)) {
                DEBUG(10, ("make_user_info failed: %s\n", nt_errstr(status)));
+               TALLOC_FREE(frame);
                return status;
        }
 
+       user_info->logon_parameters = logon_parameters;
+
        /* We don't want any more mapping of the username */
        user_info->mapped_state = True;
 
-       status = check_sam_security_info3(challenge, talloc_tos(), user_info,
-                                         pinfo3);
-       free_user_info(&user_info);
+       /* We don't want to come back to winbindd or to do PAM account checks */
+       user_info->flags |= USER_INFO_LOCAL_SAM_ONLY | USER_INFO_INFO3_AND_NO_AUTHZ;
+
+       status = make_auth_context_fixed(frame, &auth_context, challenge->data);
+
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(0, ("Failed to test authentication with check_sam_security_info3: %s\n", nt_errstr(status)));
+               TALLOC_FREE(frame);
+               return status;
+       }
+
+       status = auth_check_ntlm_password(mem_ctx,
+                                         auth_context,
+                                         user_info,
+                                         &server_info);
+
+       if (!NT_STATUS_IS_OK(status)) {
+               TALLOC_FREE(frame);
+               return status;
+       }
+
+       info3 = talloc_zero(mem_ctx, struct netr_SamInfo3);
+       if (info3 == NULL) {
+               TALLOC_FREE(frame);
+               return NT_STATUS_NO_MEMORY;
+       }
+
+       status = serverinfo_to_SamInfo3(server_info, info3);
+       if (!NT_STATUS_IS_OK(status)) {
+               TALLOC_FREE(frame);
+               TALLOC_FREE(info3);
+               DEBUG(0, ("serverinfo_to_SamInfo3 failed: %s\n",
+                         nt_errstr(status)));
+               return status;
+       }
+
+       *pinfo3 = info3;
        DEBUG(10, ("Authenticaticating user %s\\%s returned %s\n", domain,
                   user, nt_errstr(status)));
+       TALLOC_FREE(frame);
        return status;
 }
 
-typedef        NTSTATUS (*netlogon_fn_t)(struct rpc_pipe_client *cli,
-                                 TALLOC_CTX *mem_ctx,
-                                 uint32 logon_parameters,
-                                 const char *server,
-                                 const char *username,
-                                 const char *domain,
-                                 const char *workstation,
-                                 const uint8 chal[8],
-                                 DATA_BLOB lm_response,
-                                 DATA_BLOB nt_response,
-                                 struct netr_SamInfo3 **info3);
-
-static NTSTATUS winbindd_dual_pam_auth_samlogon(struct winbindd_domain *domain,
-                                               struct winbindd_cli_state *state,
+static NTSTATUS winbind_samlogon_retry_loop(struct winbindd_domain *domain,
+                                           TALLOC_CTX *mem_ctx,
+                                           uint32_t logon_parameters,
+                                           const char *username,
+                                           const char *password,
+                                           const char *domainname,
+                                           const char *workstation,
+                                           const uint8_t chal[8],
+                                           DATA_BLOB lm_response,
+                                           DATA_BLOB nt_response,
+                                           bool interactive,
+                                           struct netr_SamInfo3 **info3)
+{
+       int attempts = 0;
+       int netr_attempts = 0;
+       bool retry = false;
+       NTSTATUS result;
+
+       do {
+               struct rpc_pipe_client *netlogon_pipe;
+               uint8_t authoritative = 0;
+               uint32_t flags = 0;
+
+               ZERO_STRUCTP(info3);
+               retry = false;
+
+               result = cm_connect_netlogon(domain, &netlogon_pipe);
+
+               if (!NT_STATUS_IS_OK(result)) {
+                       DEBUG(3,("Could not open handle to NETLOGON pipe "
+                                "(error: %s, attempts: %d)\n",
+                                 nt_errstr(result), netr_attempts));
+
+                       /* After the first retry always close the connection */
+                       if (netr_attempts > 0) {
+                               DEBUG(3, ("This is again a problem for this "
+                                         "particular call, forcing the close "
+                                         "of this connection\n"));
+                               invalidate_cm_connection(domain);
+                       }
+
+                       /* After the second retry failover to the next DC */
+                       if (netr_attempts > 1) {
+                               /*
+                                * If the netlogon server is not reachable then
+                                * it is possible that the DC is rebuilding
+                                * sysvol and shutdown netlogon for that time.
+                                * We should failover to the next dc.
+                                */
+                               DEBUG(3, ("This is the third problem for this "
+                                         "particular call, adding DC to the "
+                                         "negative cache list\n"));
+                               add_failed_connection_entry(domain->name,
+                                                           domain->dcname,
+                                                           result);
+                               saf_delete(domain->name);
+                       }
+
+                       /* Only allow 3 retries */
+                       if (netr_attempts < 3) {
+                               DEBUG(3, ("The connection to netlogon "
+                                         "failed, retrying\n"));
+                               netr_attempts++;
+                               retry = true;
+                               continue;
+                       }
+                       return result;
+               }
+               netr_attempts = 0;
+               if (domain->conn.netlogon_creds == NULL) {
+                       DBG_NOTICE("No security credentials available for "
+                                 "domain [%s]\n", domainname);
+                       result = NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
+               } else if (interactive && username != NULL && password != NULL) {
+                       result = rpccli_netlogon_password_logon(domain->conn.netlogon_creds,
+                                                               netlogon_pipe->binding_handle,
+                                                               mem_ctx,
+                                                               logon_parameters,
+                                                               domainname,
+                                                               username,
+                                                               password,
+                                                               workstation,
+                                                               NetlogonInteractiveInformation,
+                                                               info3);
+               } else {
+                       result = rpccli_netlogon_network_logon(domain->conn.netlogon_creds,
+                                                       netlogon_pipe->binding_handle,
+                                                       mem_ctx,
+                                                       logon_parameters,
+                                                       username,
+                                                       domainname,
+                                                       workstation,
+                                                       chal,
+                                                       lm_response,
+                                                       nt_response,
+                                                       &authoritative,
+                                                       &flags,
+                                                       info3);
+               }
+
+               /*
+                * we increment this after the "feature negotiation"
+                * for can_do_samlogon_ex and can_do_validation6
+                */
+               attempts += 1;
+
+               /* We have to try a second time as cm_connect_netlogon
+                  might not yet have noticed that the DC has killed
+                  our connection. */
+
+               if (!rpccli_is_connected(netlogon_pipe)) {
+                       retry = true;
+                       continue;
+               }
+
+               /* if we get access denied, a possible cause was that we had
+                  and open connection to the DC, but someone changed our
+                  machine account password out from underneath us using 'net
+                  rpc changetrustpw' */
+
+               if ( NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED) ) {
+                       DEBUG(1,("winbind_samlogon_retry_loop: sam_logon returned "
+                                "ACCESS_DENIED.  Maybe the DC has Restrict "
+                                "NTLM set or the trust account "
+                               "password was changed and we didn't know it. "
+                                "Killing connections to domain %s\n",
+                               domainname));
+                       invalidate_cm_connection(domain);
+                       retry = true;
+               }
+
+               if (NT_STATUS_EQUAL(result, NT_STATUS_RPC_PROCNUM_OUT_OF_RANGE)) {
+                       /*
+                        * Got DCERPC_FAULT_OP_RNG_ERROR for SamLogon
+                        * (no Ex). This happens against old Samba
+                        * DCs, if LogonSamLogonEx() fails with an error
+                        * e.g. NT_STATUS_NO_SUCH_USER or NT_STATUS_WRONG_PASSWORD.
+                        *
+                        * The server will log something like this:
+                        * api_net_sam_logon_ex: Failed to marshall NET_R_SAM_LOGON_EX.
+                        *
+                        * This sets the whole connection into a fault_state mode
+                        * and all following request get NT_STATUS_RPC_PROCNUM_OUT_OF_RANGE.
+                        *
+                        * This also happens to our retry with LogonSamLogonWithFlags()
+                        * and LogonSamLogon().
+                        *
+                        * In order to recover from this situation, we need to
+                        * drop the connection.
+                        */
+                       invalidate_cm_connection(domain);
+                       result = NT_STATUS_LOGON_FAILURE;
+                       break;
+               }
+
+       } while ( (attempts < 2) && retry );
+
+       if (NT_STATUS_EQUAL(result, NT_STATUS_IO_TIMEOUT)) {
+               DEBUG(3,("winbind_samlogon_retry_loop: sam_network_logon(ex) "
+                               "returned NT_STATUS_IO_TIMEOUT after the retry."
+                               "Killing connections to domain %s\n",
+                       domainname));
+               invalidate_cm_connection(domain);
+       }
+       return result;
+}
+
+static NTSTATUS winbindd_dual_pam_auth_samlogon(TALLOC_CTX *mem_ctx,
+                                               struct winbindd_domain *domain,
+                                               const char *user,
+                                               const char *pass,
+                                               uint32_t request_flags,
                                                struct netr_SamInfo3 **info3)
 {
 
-       struct rpc_pipe_client *netlogon_pipe;
        uchar chal[8];
        DATA_BLOB lm_resp;
        DATA_BLOB nt_resp;
-       int attempts = 0;
        unsigned char local_nt_response[24];
        fstring name_domain, name_user;
-       bool retry;
        NTSTATUS result;
        struct netr_SamInfo3 *my_info3 = NULL;
 
@@ -1157,7 +1499,7 @@ static NTSTATUS winbindd_dual_pam_auth_samlogon(struct winbindd_domain *domain,
 
        /* Parse domain and username */
 
-       parse_domain_user(state->request->data.auth.user, name_domain, name_user);
+       parse_domain_user(user, name_domain, name_user);
 
        /* do password magic */
 
@@ -1166,44 +1508,31 @@ static NTSTATUS winbindd_dual_pam_auth_samlogon(struct winbindd_domain *domain,
        if (lp_client_ntlmv2_auth()) {
                DATA_BLOB server_chal;
                DATA_BLOB names_blob;
-               DATA_BLOB nt_response;
-               DATA_BLOB lm_response;
-               server_chal = data_blob_talloc(state->mem_ctx, chal, 8);
+               server_chal = data_blob_const(chal, 8);
 
-               /* note that the 'workgroup' here is a best guess - we don't know
-                  the server's domain at this point.  The 'server name' is also
-                  dodgy...
+               /* note that the 'workgroup' here is for the local
+                  machine.  The 'server name' must match the
+                  'workstation' passed to the actual SamLogon call.
                */
-               names_blob = NTLMv2_generate_names_blob(state->mem_ctx, global_myname(), lp_workgroup());
+               names_blob = NTLMv2_generate_names_blob(
+                       mem_ctx, lp_netbios_name(), lp_workgroup());
 
-               if (!SMBNTLMv2encrypt(NULL, name_user, name_domain,
-                                     state->request->data.auth.pass,
+               if (!SMBNTLMv2encrypt(mem_ctx, name_user, name_domain,
+                                     pass,
                                      &server_chal,
                                      &names_blob,
-                                     &lm_response, &nt_response, NULL, NULL)) {
+                                     &lm_resp, &nt_resp, NULL, NULL)) {
                        data_blob_free(&names_blob);
-                       data_blob_free(&server_chal);
                        DEBUG(0, ("winbindd_pam_auth: SMBNTLMv2encrypt() failed!\n"));
                        result = NT_STATUS_NO_MEMORY;
                        goto done;
                }
                data_blob_free(&names_blob);
-               data_blob_free(&server_chal);
-               lm_resp = data_blob_talloc(state->mem_ctx, lm_response.data,
-                                          lm_response.length);
-               nt_resp = data_blob_talloc(state->mem_ctx, nt_response.data,
-                                          nt_response.length);
-               data_blob_free(&lm_response);
-               data_blob_free(&nt_response);
-
        } else {
                lm_resp = data_blob_null;
-               SMBNTencrypt(state->request->data.auth.pass,
-                            chal,
-                            local_nt_response);
+               SMBNTencrypt(pass, chal, local_nt_response);
 
-               nt_resp = data_blob_talloc(state->mem_ctx,
-                                          local_nt_response,
+               nt_resp = data_blob_talloc(mem_ctx, local_nt_response,
                                           sizeof(local_nt_response));
        }
 
@@ -1211,111 +1540,50 @@ static NTSTATUS winbindd_dual_pam_auth_samlogon(struct winbindd_domain *domain,
                DATA_BLOB chal_blob = data_blob_const(chal, sizeof(chal));
 
                result = winbindd_dual_auth_passdb(
-                       state->mem_ctx, name_domain, name_user,
+                       mem_ctx, 0, name_domain, name_user,
                        &chal_blob, &lm_resp, &nt_resp, info3);
-               goto done;
-       }
-
-       /* check authentication loop */
-
-       do {
-               netlogon_fn_t logon_fn;
 
-               ZERO_STRUCTP(my_info3);
-               retry = false;
-
-               result = cm_connect_netlogon(domain, &netlogon_pipe);
-
-               if (!NT_STATUS_IS_OK(result)) {
-                       DEBUG(3, ("could not open handle to NETLOGON pipe\n"));
-                       goto done;
-               }
-
-               /* It is really important to try SamLogonEx here,
-                * because in a clustered environment, we want to use
-                * one machine account from multiple physical
-                * computers.
-                *
-                * With a normal SamLogon call, we must keep the
-                * credentials chain updated and intact between all
-                * users of the machine account (which would imply
-                * cross-node communication for every NTLM logon).
-                *
-                * (The credentials chain is not per NETLOGON pipe
-                * connection, but globally on the server/client pair
-                * by machine name).
-                *
-                * When using SamLogonEx, the credentials are not
-                * supplied, but the session key is implied by the
-                * wrapping SamLogon context.
-                *
-                *  -- abartlet 21 April 2008
+               /* 
+                * We need to try the remote NETLOGON server if this is NOT_IMPLEMENTED 
                 */
-
-               logon_fn = domain->can_do_samlogon_ex
-                       ? rpccli_netlogon_sam_network_logon_ex
-                       : rpccli_netlogon_sam_network_logon;
-
-               result = logon_fn(netlogon_pipe,
-                                 state->mem_ctx,
-                                 0,
-                                 domain->dcname,         /* server name */
-                                 name_user,              /* user name */
-                                 name_domain,            /* target domain */
-                                 global_myname(),        /* workstation */
-                                 chal,
-                                 lm_resp,
-                                 nt_resp,
-                                 &my_info3);
-               attempts += 1;
-
-               if ((NT_STATUS_V(result) == DCERPC_FAULT_OP_RNG_ERROR)
-                   && domain->can_do_samlogon_ex) {
-                       DEBUG(3, ("Got a DC that can not do NetSamLogonEx, "
-                                 "retrying with NetSamLogon\n"));
-                       domain->can_do_samlogon_ex = false;
-                       continue;
-               }
-
-               /* We have to try a second time as cm_connect_netlogon
-                  might not yet have noticed that the DC has killed
-                  our connection. */
-
-               if (!rpccli_is_connected(netlogon_pipe)) {
-                       continue;
+               if (!NT_STATUS_EQUAL(result, NT_STATUS_NOT_IMPLEMENTED)) {
+                       goto done;
                }
+       }
 
-               /* if we get access denied, a possible cause was that we had
-                  and open connection to the DC, but someone changed our
-                  machine account password out from underneath us using 'net
-                  rpc changetrustpw' */
-
-               if ( NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED) ) {
-                       DEBUG(3,("winbindd_pam_auth: sam_logon returned "
-                                "ACCESS_DENIED.  Maybe the trust account "
-                               "password was changed and we didn't know it. "
-                                "Killing connections to domain %s\n",
-                               name_domain));
-                       invalidate_cm_connection(&domain->conn);
-                       retry = true;
-               }
+       /* check authentication loop */
 
-       } while ( (attempts < 2) && retry );
+       result = winbind_samlogon_retry_loop(domain,
+                                            mem_ctx,
+                                            0,
+                                            name_user,
+                                            pass,
+                                            name_domain,
+                                            lp_netbios_name(),
+                                            chal,
+                                            lm_resp,
+                                            nt_resp,
+                                            true, /* interactive */
+                                            &my_info3);
+       if (!NT_STATUS_IS_OK(result)) {
+               goto done;
+       }
 
        /* handle the case where a NT4 DC does not fill in the acct_flags in
         * the samlogon reply info3. When accurate info3 is required by the
         * caller, we look up the account flags ourselve - gd */
 
-       if ((state->request->flags & WBFLAG_PAM_INFO3_TEXT) &&
+       if ((request_flags & WBFLAG_PAM_INFO3_TEXT) &&
            NT_STATUS_IS_OK(result) && (my_info3->base.acct_flags == 0)) {
 
                struct rpc_pipe_client *samr_pipe;
                struct policy_handle samr_domain_handle, user_pol;
                union samr_UserInfo *info = NULL;
-               NTSTATUS status_tmp;
-               uint32 acct_flags;
+               NTSTATUS status_tmp, result_tmp;
+               uint32_t acct_flags;
+               struct dcerpc_binding_handle *b;
 
-               status_tmp = cm_connect_sam(domain, state->mem_ctx,
+               status_tmp = cm_connect_sam(domain, mem_ctx, false,
                                            &samr_pipe, &samr_domain_handle);
 
                if (!NT_STATUS_IS_OK(status_tmp)) {
@@ -1324,34 +1592,49 @@ static NTSTATUS winbindd_dual_pam_auth_samlogon(struct winbindd_domain *domain,
                        goto done;
                }
 
-               status_tmp = rpccli_samr_OpenUser(samr_pipe, state->mem_ctx,
+               b = samr_pipe->binding_handle;
+
+               status_tmp = dcerpc_samr_OpenUser(b, mem_ctx,
                                                  &samr_domain_handle,
                                                  MAXIMUM_ALLOWED_ACCESS,
                                                  my_info3->base.rid,
-                                                 &user_pol);
+                                                 &user_pol,
+                                                 &result_tmp);
 
                if (!NT_STATUS_IS_OK(status_tmp)) {
                        DEBUG(3, ("could not open user handle on SAMR pipe: %s\n",
                                nt_errstr(status_tmp)));
                        goto done;
                }
+               if (!NT_STATUS_IS_OK(result_tmp)) {
+                       DEBUG(3, ("could not open user handle on SAMR pipe: %s\n",
+                               nt_errstr(result_tmp)));
+                       goto done;
+               }
 
-               status_tmp = rpccli_samr_QueryUserInfo(samr_pipe, state->mem_ctx,
+               status_tmp = dcerpc_samr_QueryUserInfo(b, mem_ctx,
                                                       &user_pol,
                                                       16,
-                                                      &info);
+                                                      &info,
+                                                      &result_tmp);
 
                if (!NT_STATUS_IS_OK(status_tmp)) {
                        DEBUG(3, ("could not query user info on SAMR pipe: %s\n",
                                nt_errstr(status_tmp)));
-                       rpccli_samr_Close(samr_pipe, state->mem_ctx, &user_pol);
+                       dcerpc_samr_Close(b, mem_ctx, &user_pol, &result_tmp);
+                       goto done;
+               }
+               if (!NT_STATUS_IS_OK(result_tmp)) {
+                       DEBUG(3, ("could not query user info on SAMR pipe: %s\n",
+                               nt_errstr(result_tmp)));
+                       dcerpc_samr_Close(b, mem_ctx, &user_pol, &result_tmp);
                        goto done;
                }
 
                acct_flags = info->info16.acct_flags;
 
                if (acct_flags == 0) {
-                       rpccli_samr_Close(samr_pipe, state->mem_ctx, &user_pol);
+                       dcerpc_samr_Close(b, mem_ctx, &user_pol, &result_tmp);
                        goto done;
                }
 
@@ -1359,7 +1642,7 @@ static NTSTATUS winbindd_dual_pam_auth_samlogon(struct winbindd_domain *domain,
 
                DEBUG(10,("successfully retrieved acct_flags 0x%x\n", acct_flags));
 
-               rpccli_samr_Close(samr_pipe, state->mem_ctx, &user_pol);
+               dcerpc_samr_Close(b, mem_ctx, &user_pol, &result_tmp);
        }
 
        *info3 = my_info3;
@@ -1408,8 +1691,8 @@ enum winbindd_result winbindd_dual_pam_auth(struct winbindd_domain *domain,
                fstr_sprintf( domain_user, "%s%c%s", name_domain,
                        *lp_winbind_separator(),
                        name_user );
-               safe_strcpy( state->request->data.auth.user, domain_user,
-                            sizeof(state->request->data.auth.user)-1 );
+               strlcpy( state->request->data.auth.user, domain_user,
+                            sizeof(state->request->data.auth.user));
        }
 
        if (!domain->online) {
@@ -1423,7 +1706,7 @@ enum winbindd_result winbindd_dual_pam_auth(struct winbindd_domain *domain,
                                "request in startup mode.\n", domain->name ));
 
                        winbindd_flush_negative_conn_cache(domain);
-                       result = init_dc_connection(domain);
+                       result = init_dc_connection(domain, false);
                }
        }
 
@@ -1480,7 +1763,12 @@ enum winbindd_result winbindd_dual_pam_auth(struct winbindd_domain *domain,
 sam_logon:
        /* Check for Samlogon authentication */
        if (domain->online) {
-               result = winbindd_dual_pam_auth_samlogon(domain, state, &info3);
+               result = winbindd_dual_pam_auth_samlogon(
+                       state->mem_ctx, domain,
+                       state->request->data.auth.user,
+                       state->request->data.auth.pass,
+                       state->request->flags,
+                       &info3);
 
                if (NT_STATUS_IS_OK(result)) {
                        DEBUG(10,("winbindd_dual_pam_auth_samlogon succeeded\n"));
@@ -1538,7 +1826,31 @@ process_result:
                        goto done;
                }
 
-               wcache_invalidate_samlogon(find_domain_from_name(name_domain), info3);
+               sid_compose(&user_sid, info3->base.domain_sid,
+                           info3->base.rid);
+
+               if (info3->base.full_name.string == NULL) {
+                       struct netr_SamInfo3 *cached_info3;
+
+                       cached_info3 = netsamlogon_cache_get(state->mem_ctx,
+                                                            &user_sid);
+                       if (cached_info3 != NULL &&
+                           cached_info3->base.full_name.string != NULL) {
+                               info3->base.full_name.string =
+                                       talloc_strdup(info3,
+                                                     cached_info3->base.full_name.string);
+                       } else {
+
+                               /* this might fail so we don't check the return code */
+                               wcache_query_user_fullname(domain,
+                                               info3,
+                                               &user_sid,
+                                               &info3->base.full_name.string);
+                       }
+               }
+
+               wcache_invalidate_samlogon(find_domain_from_name(name_domain),
+                                          &user_sid);
                netsamlogon_cache_store(name_user, info3);
 
                /* save name_to_sid info as early as possible (only if
@@ -1546,8 +1858,6 @@ process_result:
                   the cache entry by storing the seq_num for the wrong
                   domain). */
                if ( domain->primary ) {
-                       sid_compose(&user_sid, info3->base.domain_sid,
-                                   info3->base.rid);
                        cache_name2sid(domain, name_domain, name_user,
                                       SID_NAME_USER, &user_sid);
                }
@@ -1591,7 +1901,8 @@ process_result:
 
                        result = NT_STATUS_NOT_SUPPORTED;
                        if (our_domain == domain ) {
-                               result = fillup_password_policy(our_domain, state);
+                               result = fillup_password_policy(
+                                       our_domain, state->response);
                        }
 
                        if (!NT_STATUS_IS_OK(result)
@@ -1623,17 +1934,112 @@ done:
        return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
 }
 
+NTSTATUS winbind_dual_SamLogon(struct winbindd_domain *domain,
+                              TALLOC_CTX *mem_ctx,
+                              uint32_t logon_parameters,
+                              const char *name_user,
+                              const char *name_domain,
+                              const char *workstation,
+                              const uint8_t chal[8],
+                              DATA_BLOB lm_response,
+                              DATA_BLOB nt_response,
+                              struct netr_SamInfo3 **info3)
+{
+       NTSTATUS result;
+
+       if (strequal(name_domain, get_global_sam_name())) {
+               DATA_BLOB chal_blob = data_blob_const(
+                       chal, 8);
+
+               result = winbindd_dual_auth_passdb(
+                       mem_ctx,
+                       logon_parameters,
+                       name_domain, name_user,
+                       &chal_blob, &lm_response, &nt_response, info3);
+
+               /* 
+                * We need to try the remote NETLOGON server if this is NOT_IMPLEMENTED 
+                */
+               if (!NT_STATUS_EQUAL(result, NT_STATUS_NOT_IMPLEMENTED)) {
+                       goto process_result;
+               }
+       }
+
+       result = winbind_samlogon_retry_loop(domain,
+                                            mem_ctx,
+                                            logon_parameters,
+                                            name_user,
+                                            NULL, /* password */
+                                            name_domain,
+                                            /* Bug #3248 - found by Stefan Burkei. */
+                                            workstation, /* We carefully set this above so use it... */
+                                            chal,
+                                            lm_response,
+                                            nt_response,
+                                            false, /* interactive */
+                                            info3);
+       if (!NT_STATUS_IS_OK(result)) {
+               goto done;
+       }
+
+process_result:
+
+       if (NT_STATUS_IS_OK(result)) {
+               struct dom_sid user_sid;
+
+               sid_compose(&user_sid, (*info3)->base.domain_sid,
+                           (*info3)->base.rid);
+
+               if ((*info3)->base.full_name.string == NULL) {
+                       struct netr_SamInfo3 *cached_info3;
+
+                       cached_info3 = netsamlogon_cache_get(mem_ctx,
+                                                            &user_sid);
+                       if (cached_info3 != NULL &&
+                           cached_info3->base.full_name.string != NULL) {
+                               (*info3)->base.full_name.string =
+                                       talloc_strdup(*info3,
+                                                     cached_info3->base.full_name.string);
+                       } else {
+
+                               /* this might fail so we don't check the return code */
+                               wcache_query_user_fullname(domain,
+                                               *info3,
+                                               &user_sid,
+                                               &(*info3)->base.full_name.string);
+                       }
+               }
+
+               wcache_invalidate_samlogon(find_domain_from_name(name_domain),
+                                          &user_sid);
+               netsamlogon_cache_store(name_user, *info3);
+       }
+
+done:
+
+       /* give us a more useful (more correct?) error code */
+       if ((NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) ||
+           (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)))) {
+               result = NT_STATUS_NO_LOGON_SERVERS;
+       }
+
+       DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2,
+             ("NTLM CRAP authentication for user [%s]\\[%s] returned %s\n",
+              name_domain,
+              name_user,
+              nt_errstr(result)));
+
+       return result;
+}
+
 enum winbindd_result winbindd_dual_pam_auth_crap(struct winbindd_domain *domain,
                                                 struct winbindd_cli_state *state)
 {
        NTSTATUS result;
        struct netr_SamInfo3 *info3 = NULL;
-       struct rpc_pipe_client *netlogon_pipe;
        const char *name_user = NULL;
        const char *name_domain = NULL;
        const char *workstation;
-       int attempts = 0;
-       bool retry;
 
        DATA_BLOB lm_resp, nt_resp;
 
@@ -1676,89 +2082,22 @@ enum winbindd_result winbindd_dual_pam_auth_crap(struct winbindd_domain *domain,
                                           state->request->data.auth_crap.nt_resp_len);
        }
 
-       if (strequal(name_domain, get_global_sam_name())) {
-               DATA_BLOB chal_blob = data_blob_const(
-                       state->request->data.auth_crap.chal,
-                       sizeof(state->request->data.auth_crap.chal));
-
-               result = winbindd_dual_auth_passdb(
-                       state->mem_ctx, name_domain, name_user,
-                       &chal_blob, &lm_resp, &nt_resp, &info3);
-               goto process_result;
+       result = winbind_dual_SamLogon(domain,
+                                      state->mem_ctx,
+                                      state->request->data.auth_crap.logon_parameters,
+                                      name_user,
+                                      name_domain,
+                                      /* Bug #3248 - found by Stefan Burkei. */
+                                      workstation, /* We carefully set this above so use it... */
+                                      state->request->data.auth_crap.chal,
+                                      lm_resp,
+                                      nt_resp,
+                                      &info3);
+       if (!NT_STATUS_IS_OK(result)) {
+               goto done;
        }
 
-       do {
-               netlogon_fn_t logon_fn;
-
-               retry = false;
-
-               netlogon_pipe = NULL;
-               result = cm_connect_netlogon(domain, &netlogon_pipe);
-
-               if (!NT_STATUS_IS_OK(result)) {
-                       DEBUG(3, ("could not open handle to NETLOGON pipe (error: %s)\n",
-                                 nt_errstr(result)));
-                       goto done;
-               }
-
-               logon_fn = domain->can_do_samlogon_ex
-                       ? rpccli_netlogon_sam_network_logon_ex
-                       : rpccli_netlogon_sam_network_logon;
-
-               result = logon_fn(netlogon_pipe,
-                                 state->mem_ctx,
-                                 state->request->data.auth_crap.logon_parameters,
-                                 domain->dcname,
-                                 name_user,
-                                 name_domain,
-                                 /* Bug #3248 - found by Stefan Burkei. */
-                                 workstation, /* We carefully set this above so use it... */
-                                 state->request->data.auth_crap.chal,
-                                 lm_resp,
-                                 nt_resp,
-                                 &info3);
-
-               if ((NT_STATUS_V(result) == DCERPC_FAULT_OP_RNG_ERROR)
-                   && domain->can_do_samlogon_ex) {
-                       DEBUG(3, ("Got a DC that can not do NetSamLogonEx, "
-                                 "retrying with NetSamLogon\n"));
-                       domain->can_do_samlogon_ex = false;
-                       continue;
-               }
-
-               attempts += 1;
-
-               /* We have to try a second time as cm_connect_netlogon
-                  might not yet have noticed that the DC has killed
-                  our connection. */
-
-               if (!rpccli_is_connected(netlogon_pipe)) {
-                       continue;
-               }
-
-               /* if we get access denied, a possible cause was that we had and open
-                  connection to the DC, but someone changed our machine account password
-                  out from underneath us using 'net rpc changetrustpw' */
-
-               if ( NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED) ) {
-                       DEBUG(3,("winbindd_pam_auth: sam_logon returned "
-                                "ACCESS_DENIED.  Maybe the trust account "
-                               "password was changed and we didn't know it. "
-                                "Killing connections to domain %s\n",
-                               name_domain));
-                       invalidate_cm_connection(&domain->conn);
-                       retry = true;
-               }
-
-       } while ( (attempts < 2) && retry );
-
-process_result:
-
        if (NT_STATUS_IS_OK(result)) {
-
-               wcache_invalidate_samlogon(find_domain_from_name(name_domain), info3);
-               netsamlogon_cache_store(name_user, info3);
-
                /* Check if the user is in the right group */
 
                result = check_info3_in_group(
@@ -1782,25 +2121,12 @@ process_result:
 
 done:
 
-       /* give us a more useful (more correct?) error code */
-       if ((NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) ||
-           (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)))) {
-               result = NT_STATUS_NO_LOGON_SERVERS;
-       }
-
        if (state->request->flags & WBFLAG_PAM_NT_STATUS_SQUASH) {
                result = nt_status_squash(result);
        }
 
        set_auth_errors(state->response, result);
 
-       DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2,
-             ("NTLM CRAP authentication for user [%s]\\[%s] returned %s (PAM: %d)\n",
-              name_domain,
-              name_user,
-              state->response->data.auth.nt_status_string,
-              state->response->data.auth.pam_error));
-
        return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
 }
 
@@ -1816,6 +2142,7 @@ enum winbindd_result winbindd_dual_pam_chauthtok(struct winbindd_domain *contact
        struct userPwdChangeFailureInformation *reject = NULL;
        NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
        fstring domain, user;
+       struct dcerpc_binding_handle *b = NULL;
 
        ZERO_STRUCT(dom_pol);
 
@@ -1836,13 +2163,15 @@ enum winbindd_result winbindd_dual_pam_chauthtok(struct winbindd_domain *contact
 
        /* Get sam handle */
 
-       result = cm_connect_sam(contact_domain, state->mem_ctx, &cli,
+       result = cm_connect_sam(contact_domain, state->mem_ctx, true, &cli,
                                &dom_pol);
        if (!NT_STATUS_IS_OK(result)) {
                DEBUG(1, ("could not get SAM handle on DC for %s\n", domain));
                goto done;
        }
 
+       b = cli->binding_handle;
+
        result = rpccli_samr_chgpasswd_user3(cli, state->mem_ctx,
                                             user,
                                             newpass,
@@ -1868,10 +2197,10 @@ enum winbindd_result winbindd_dual_pam_chauthtok(struct winbindd_domain *contact
         * short to comply with the samr_ChangePasswordUser3 idl - gd */
 
        /* only fallback when the chgpasswd_user3 call is not supported */
-       if ((NT_STATUS_EQUAL(result, NT_STATUS(DCERPC_FAULT_OP_RNG_ERROR))) ||
-                  (NT_STATUS_EQUAL(result, NT_STATUS_NOT_SUPPORTED)) ||
-                  (NT_STATUS_EQUAL(result, NT_STATUS_BUFFER_TOO_SMALL)) ||
-                  (NT_STATUS_EQUAL(result, NT_STATUS_NOT_IMPLEMENTED))) {
+       if (NT_STATUS_EQUAL(result, NT_STATUS_RPC_PROCNUM_OUT_OF_RANGE) ||
+           NT_STATUS_EQUAL(result, NT_STATUS_NOT_SUPPORTED) ||
+           NT_STATUS_EQUAL(result, NT_STATUS_BUFFER_TOO_SMALL) ||
+           NT_STATUS_EQUAL(result, NT_STATUS_NOT_IMPLEMENTED)) {
 
                DEBUG(10,("Password change with chgpasswd_user3 failed with: %s, retrying chgpasswd_user2\n",
                        nt_errstr(result)));
@@ -1915,7 +2244,8 @@ done:
 
                NTSTATUS policy_ret;
 
-               policy_ret = fillup_password_policy(contact_domain, state);
+               policy_ret = fillup_password_policy(
+                       contact_domain, state->response);
 
                /* failure of this is non critical, it will just provide no
                 * additional information to the client why the change has
@@ -1931,9 +2261,10 @@ process_result:
 
        if (strequal(contact_domain->name, get_global_sam_name())) {
                /* FIXME: internal rpc pipe does not cache handles yet */
-               if (cli) {
+               if (b) {
                        if (is_valid_policy_hnd(&dom_pol)) {
-                               rpccli_samr_Close(cli, state->mem_ctx, &dom_pol);
+                               NTSTATUS _result;
+                               dcerpc_samr_Close(b, state->mem_ctx, &dom_pol, &_result);
                        }
                        TALLOC_FREE(cli);
                }
@@ -1999,6 +2330,13 @@ enum winbindd_result winbindd_dual_pam_logoff(struct winbindd_domain *domain,
                goto process_result;
        }
 
+       /*
+        * Remove any mlock'ed memory creds in the child
+        * we might be using for krb5 ticket renewal.
+        */
+
+       winbindd_delete_memory_creds(state->request->data.logoff.user);
+
 #else
        result = NT_STATUS_NOT_SUPPORTED;
 #endif
@@ -2024,6 +2362,7 @@ enum winbindd_result winbindd_dual_pam_chng_pswd_auth_crap(struct winbindd_domai
        struct policy_handle dom_pol;
        struct winbindd_domain *contact_domain = domainSt;
        struct rpc_pipe_client *cli = NULL;
+       struct dcerpc_binding_handle *b = NULL;
 
        ZERO_STRUCT(dom_pol);
 
@@ -2063,7 +2402,7 @@ enum winbindd_result winbindd_dual_pam_chng_pswd_auth_crap(struct winbindd_domai
        }
 
        if (!*domain && lp_winbind_use_default_domain()) {
-               fstrcpy(domain,(char *)lp_workgroup());
+               fstrcpy(domain,lp_workgroup());
        }
 
        if(!*user) {
@@ -2091,18 +2430,20 @@ enum winbindd_result winbindd_dual_pam_chng_pswd_auth_crap(struct winbindd_domai
                        state->request->data.chng_pswd_auth_crap.old_lm_hash_enc,
                        state->request->data.chng_pswd_auth_crap.old_lm_hash_enc_len);
        } else {
-               new_lm_password.length = 0;
-               old_lm_hash_enc.length = 0;
+               new_lm_password = data_blob_null;
+               old_lm_hash_enc = data_blob_null;
        }
 
        /* Get sam handle */
 
-       result = cm_connect_sam(contact_domain, state->mem_ctx, &cli, &dom_pol);
+       result = cm_connect_sam(contact_domain, state->mem_ctx, true, &cli, &dom_pol);
        if (!NT_STATUS_IS_OK(result)) {
                DEBUG(1, ("could not get SAM handle on DC for %s\n", domain));
                goto done;
        }
 
+       b = cli->binding_handle;
+
        result = rpccli_samr_chng_pswd_auth_crap(
                cli, state->mem_ctx, user, new_nt_password, old_nt_hash_enc,
                new_lm_password, old_lm_hash_enc);
@@ -2111,9 +2452,10 @@ enum winbindd_result winbindd_dual_pam_chng_pswd_auth_crap(struct winbindd_domai
 
        if (strequal(contact_domain->name, get_global_sam_name())) {
                /* FIXME: internal rpc pipe does not cache handles yet */
-               if (cli) {
+               if (b) {
                        if (is_valid_policy_hnd(&dom_pol)) {
-                               rpccli_samr_Close(cli, state->mem_ctx, &dom_pol);
+                               NTSTATUS _result;
+                               dcerpc_samr_Close(b, state->mem_ctx, &dom_pol, &_result);
                        }
                        TALLOC_FREE(cli);
                }
@@ -2129,3 +2471,136 @@ enum winbindd_result winbindd_dual_pam_chng_pswd_auth_crap(struct winbindd_domai
 
        return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
 }
+
+#ifdef HAVE_KRB5
+static NTSTATUS extract_pac_vrfy_sigs(TALLOC_CTX *mem_ctx, DATA_BLOB pac_blob,
+                                     struct PAC_LOGON_INFO **logon_info)
+{
+       krb5_context krbctx = NULL;
+       krb5_error_code k5ret;
+       krb5_keytab keytab;
+       krb5_kt_cursor cursor;
+       krb5_keytab_entry entry;
+       NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
+
+       ZERO_STRUCT(entry);
+       ZERO_STRUCT(cursor);
+
+       k5ret = krb5_init_context(&krbctx);
+       if (k5ret) {
+               DEBUG(1, ("Failed to initialize kerberos context: %s\n",
+                         error_message(k5ret)));
+               status = krb5_to_nt_status(k5ret);
+               goto out;
+       }
+
+       k5ret =  gse_krb5_get_server_keytab(krbctx, &keytab);
+       if (k5ret) {
+               DEBUG(1, ("Failed to get keytab: %s\n",
+                         error_message(k5ret)));
+               status = krb5_to_nt_status(k5ret);
+               goto out_free;
+       }
+
+       k5ret = krb5_kt_start_seq_get(krbctx, keytab, &cursor);
+       if (k5ret) {
+               DEBUG(1, ("Failed to start seq: %s\n",
+                         error_message(k5ret)));
+               status = krb5_to_nt_status(k5ret);
+               goto out_keytab;
+       }
+
+       k5ret = krb5_kt_next_entry(krbctx, keytab, &entry, &cursor);
+       while (k5ret == 0) {
+               status = kerberos_pac_logon_info(mem_ctx, pac_blob,
+                                                krbctx, NULL,
+                                                KRB5_KT_KEY(&entry), NULL, 0,
+                                                logon_info);
+               if (NT_STATUS_IS_OK(status)) {
+                       break;
+               }
+               k5ret = smb_krb5_kt_free_entry(krbctx, &entry);
+               k5ret = krb5_kt_next_entry(krbctx, keytab, &entry, &cursor);
+       }
+
+       k5ret = krb5_kt_end_seq_get(krbctx, keytab, &cursor);
+       if (k5ret) {
+               DEBUG(1, ("Failed to end seq: %s\n",
+                         error_message(k5ret)));
+       }
+out_keytab:
+       k5ret = krb5_kt_close(krbctx, keytab);
+       if (k5ret) {
+               DEBUG(1, ("Failed to close keytab: %s\n",
+                         error_message(k5ret)));
+       }
+out_free:
+       krb5_free_context(krbctx);
+out:
+       return status;
+}
+
+NTSTATUS winbindd_pam_auth_pac_send(struct winbindd_cli_state *state,
+                                   struct netr_SamInfo3 **info3)
+{
+       struct winbindd_request *req = state->request;
+       DATA_BLOB pac_blob;
+       struct PAC_LOGON_INFO *logon_info = NULL;
+       struct netr_SamInfo3 *info3_copy = NULL;
+       NTSTATUS result;
+
+       pac_blob = data_blob_const(req->extra_data.data, req->extra_len);
+       result = extract_pac_vrfy_sigs(state->mem_ctx, pac_blob, &logon_info);
+       if (!NT_STATUS_IS_OK(result) &&
+           !NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
+               DEBUG(1, ("Error during PAC signature verification: %s\n",
+                         nt_errstr(result)));
+               return result;
+       }
+
+       if (logon_info) {
+               /* Signature verification succeeded, trust the PAC */
+               result = create_info3_from_pac_logon_info(state->mem_ctx,
+                                                       logon_info,
+                                                       &info3_copy);
+               if (!NT_STATUS_IS_OK(result)) {
+                       return result;
+               }
+               netsamlogon_cache_store(NULL, info3_copy);
+
+       } else {
+               /* Try without signature verification */
+               result = kerberos_pac_logon_info(state->mem_ctx, pac_blob, NULL,
+                                                NULL, NULL, NULL, 0,
+                                                &logon_info);
+               if (!NT_STATUS_IS_OK(result)) {
+                       DEBUG(10, ("Could not extract PAC: %s\n",
+                                  nt_errstr(result)));
+                       return result;
+               }
+               if (logon_info) {
+                       /*
+                        * Don't strictly need to copy here,
+                        * but it makes it explicit we're
+                        * returning a copy talloc'ed off
+                        * the state->mem_ctx.
+                        */
+                       info3_copy = copy_netr_SamInfo3(state->mem_ctx,
+                                       &logon_info->info3);
+                       if (info3_copy == NULL) {
+                               return NT_STATUS_NO_MEMORY;
+                       }
+               }
+       }
+
+       *info3 = info3_copy;
+
+       return NT_STATUS_OK;
+}
+#else /* HAVE_KRB5 */
+NTSTATUS winbindd_pam_auth_pac_send(struct winbindd_cli_state *state,
+                                   struct netr_SamInfo3 **info3)
+{
+       return NT_STATUS_NO_SUCH_USER;
+}
+#endif /* HAVE_KRB5 */