r4088: Get medieval on our ass about malloc.... :-). Take control of all our allocation
[tprouty/samba.git] / source / nsswitch / winbindd_pam.c
index e49a95f4b879045f8feaa02cc67437bb4c484b9f..f7d3ac5aa41747ab8295edd5aa66d7c48127a852 100644 (file)
@@ -1,4 +1,4 @@
-/* 
+/*
    Unix SMB/CIFS implementation.
 
    Winbind daemon - pam auth funcions
@@ -22,6 +22,7 @@
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
 
+#include "includes.h"
 #include "winbindd.h"
 #undef DBGC_CLASS
 #define DBGC_CLASS DBGC_WINBIND
@@ -42,18 +43,111 @@ static NTSTATUS append_info3_as_ndr(TALLOC_CTX *mem_ctx,
        }
 
        size = prs_data_size(&ps);
-       state->response.extra_data = malloc(size);
+       state->response.extra_data = SMB_MALLOC(size);
        if (!state->response.extra_data) {
                prs_mem_free(&ps);
                return NT_STATUS_NO_MEMORY;
        }
+       memset( state->response.extra_data, '\0', size );
        prs_copy_all_data_out(state->response.extra_data, &ps);
        state->response.length += size;
        prs_mem_free(&ps);
        return NT_STATUS_OK;
 }
 
-/* Return a password structure from a username.  */
+static NTSTATUS check_info3_in_group(TALLOC_CTX *mem_ctx, 
+                                    NET_USER_INFO_3 *info3,
+                                    const char *group_sid) 
+{
+       DOM_SID require_membership_of_sid;
+       DOM_SID *all_sids;
+       size_t num_all_sids = (2 + info3->num_groups2 + info3->num_other_sids);
+       size_t i, j = 0;
+
+       /* Parse the 'required group' SID */
+       
+       if (!group_sid || !group_sid[0]) {
+               /* NO sid supplied, all users may access */
+               return NT_STATUS_OK;
+       }
+       
+       if (!string_to_sid(&require_membership_of_sid, group_sid)) {
+               DEBUG(0, ("check_info3_in_group: could not parse %s as a SID!", 
+                         group_sid));
+
+               return NT_STATUS_INVALID_PARAMETER;
+       }
+
+       all_sids = TALLOC_ARRAY(mem_ctx, DOM_SID, num_all_sids);
+       if (!all_sids)
+               return NT_STATUS_NO_MEMORY;
+
+       /* and create (by appending rids) the 'domain' sids */
+       
+       sid_copy(&all_sids[0], &(info3->dom_sid.sid));
+       
+       if (!sid_append_rid(&all_sids[0], info3->user_rid)) {
+               DEBUG(3,("could not append user's primary RID 0x%x\n",
+                        info3->user_rid));                     
+               
+               return NT_STATUS_INVALID_PARAMETER;
+       }
+       j++;
+
+       sid_copy(&all_sids[1], &(info3->dom_sid.sid));
+               
+       if (!sid_append_rid(&all_sids[1], info3->group_rid)) {
+               DEBUG(3,("could not append additional group rid 0x%x\n",
+                        info3->group_rid));                    
+               
+               return NT_STATUS_INVALID_PARAMETER;
+       }
+       j++;    
+
+       for (i = 0; i < info3->num_groups2; i++) {
+       
+               sid_copy(&all_sids[j], &(info3->dom_sid.sid));
+               
+               if (!sid_append_rid(&all_sids[j], info3->gids[i].g_rid)) {
+                       DEBUG(3,("could not append additional group rid 0x%x\n",
+                               info3->gids[i].g_rid));                 
+                               
+                       return NT_STATUS_INVALID_PARAMETER;
+               }
+               j++;
+       }
+
+       /* Copy 'other' sids.  We need to do sid filtering here to
+          prevent possible elevation of privileges.  See:
+
+           http://www.microsoft.com/windows2000/techinfo/administration/security/sidfilter.asp
+         */
+
+       for (i = 0; i < info3->num_other_sids; i++) {
+               sid_copy(&all_sids[info3->num_groups2 + i + 2],
+                        &info3->other_sids[i].sid);
+               j++;
+       }
+
+       for (i = 0; i < j; i++) {
+               fstring sid1, sid2;
+               DEBUG(10, ("User has SID: %s\n", 
+                          sid_to_string(sid1, &all_sids[i])));
+               if (sid_equal(&require_membership_of_sid, &all_sids[i])) {
+                       DEBUG(10, ("SID %s matches %s - user permitted to authenticate!\n", 
+                                  sid_to_string(sid1, &require_membership_of_sid), sid_to_string(sid2, &all_sids[i])));
+                       return NT_STATUS_OK;
+               }
+       }
+       
+       /* Do not distinguish this error from a wrong username/pw */
+
+       return NT_STATUS_LOGON_FAILURE;
+}
+
+/**********************************************************************
+ Authenticate a user with a clear text password
+**********************************************************************/
 
 enum winbindd_result winbindd_pam_auth(struct winbindd_cli_state *state) 
 {
@@ -61,13 +155,19 @@ enum winbindd_result winbindd_pam_auth(struct winbindd_cli_state *state)
        fstring name_domain, name_user;
        unsigned char trust_passwd[16];
        time_t last_change_time;
-        uint32 smb_uid_low;
+       uint32 sec_channel_type;
         NET_USER_INFO_3 info3;
         struct cli_state *cli = NULL;
        uchar chal[8];
        TALLOC_CTX *mem_ctx = NULL;
        DATA_BLOB lm_resp;
        DATA_BLOB nt_resp;
+       DOM_CRED ret_creds;
+       int attempts = 0;
+       unsigned char local_lm_response[24];
+       unsigned char local_nt_response[24];
+       struct winbindd_domain *contact_domain;
+       BOOL retry;
 
        /* Ensure null termination */
        state->request.data.auth.user[sizeof(state->request.data.auth.user)-1]='\0';
@@ -75,7 +175,7 @@ enum winbindd_result winbindd_pam_auth(struct winbindd_cli_state *state)
        /* Ensure null termination */
        state->request.data.auth.pass[sizeof(state->request.data.auth.pass)-1]='\0';
 
-       DEBUG(3, ("[%5d]: pam auth %s\n", state->pid,
+       DEBUG(3, ("[%5lu]: pam auth %s\n", (unsigned long)state->pid,
                  state->request.data.auth.user));
 
        if (!(mem_ctx = talloc_init("winbind pam auth for %s", state->request.data.auth.user))) {
@@ -86,61 +186,162 @@ enum winbindd_result winbindd_pam_auth(struct winbindd_cli_state *state)
 
        /* Parse domain and username */
        
-       if (!parse_domain_user(state->request.data.auth.user, name_domain, 
-                              name_user)) {
-               DEBUG(5,("no domain separator (%s) in username (%s) - failing auth\n", lp_winbind_separator(), state->request.data.auth.user));
-               result = NT_STATUS_INVALID_PARAMETER;
-               goto done;
-       }
+       parse_domain_user(state->request.data.auth.user, name_domain, name_user);
+
+       /* do password magic */
+       
 
-       {
-               unsigned char local_lm_response[24];
-               unsigned char local_nt_response[24];
+       generate_random_buffer(chal, 8);
+       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(mem_ctx, chal, 8); 
                
-               generate_random_buffer(chal, 8, False);
-               SMBencrypt(state->request.data.auth.pass, chal, local_lm_response);
+               /* 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... 
+               */
+               names_blob = NTLMv2_generate_names_blob(global_myname(), lp_workgroup());
                
-               SMBNTencrypt(state->request.data.auth.pass, chal, local_nt_response);
+               if (!SMBNTLMv2encrypt(name_user, name_domain, 
+                                     state->request.data.auth.pass, 
+                                     &server_chal, 
+                                     &names_blob,
+                                     &lm_response, &nt_response, 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(mem_ctx, lm_response.data, lm_response.length);
+               nt_resp = data_blob_talloc(mem_ctx, nt_response.data, nt_response.length);
+               data_blob_free(&lm_response);
+               data_blob_free(&nt_response);
+
+       } else {
+               if (lp_client_lanman_auth() 
+                   && SMBencrypt(state->request.data.auth.pass, 
+                                 chal, 
+                                 local_lm_response)) {
+                       lm_resp = data_blob_talloc(mem_ctx, 
+                                                  local_lm_response, 
+                                                  sizeof(local_lm_response));
+               } else {
+                       lm_resp = data_blob(NULL, 0);
+               }
+               SMBNTencrypt(state->request.data.auth.pass, 
+                            chal,
+                            local_nt_response);
 
-               lm_resp = data_blob_talloc(mem_ctx, local_lm_response, sizeof(local_lm_response));
-               nt_resp = data_blob_talloc(mem_ctx, local_nt_response, sizeof(local_nt_response));
+               nt_resp = data_blob_talloc(mem_ctx, 
+                                          local_nt_response, 
+                                          sizeof(local_nt_response));
        }
+
+       
+       /* what domain should we contact? */
        
-       /*
-        * Get the machine account password for our primary domain
-        */
-
-       if (!secrets_fetch_trust_account_password(
-                lp_workgroup(), trust_passwd, &last_change_time)) {
-               DEBUG(0, ("winbindd_pam_auth: could not fetch trust account "
-                          "password for domain %s\n", lp_workgroup()));
+       if ( IS_DC ) {
+               if (!(contact_domain = find_domain_from_name(name_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)); 
+                       result = NT_STATUS_NO_SUCH_USER;
+                       goto done;
+               }
+               
+       } else {
+               if (is_myname(name_domain)) {
+                       DEBUG(3, ("Authentication for domain %s (local domain to this server) not supported at this stage\n", name_domain));
+                       result =  NT_STATUS_NO_SUCH_USER;
+                       goto done;
+               }
+
+               if (!(contact_domain = find_our_domain())) {
+                       DEBUG(1, ("Authentication for [%s] -> [%s]\\[%s] in our domain failed - we can't find our domain!\n", 
+                                 state->request.data.auth.user, name_domain, name_user)); 
+                       result = NT_STATUS_NO_SUCH_USER;
+                       goto done;
+               }
+       }
+
+       if ( !get_trust_pw(contact_domain->name, trust_passwd, &last_change_time, &sec_channel_type) ) {
                result = NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
                goto done;
        }
 
-       /* We really don't care what LUID we give the user. */
+       /* check authentication loop */
+
+       do {
+               ZERO_STRUCT(info3);
+               ZERO_STRUCT(ret_creds);
+               retry = False;
+       
+               /* Don't shut this down - it belongs to the connection cache code */
+               result = cm_get_netlogon_cli(contact_domain, trust_passwd, 
+                                            sec_channel_type, False, &cli);
+
+               if (!NT_STATUS_IS_OK(result)) {
+                       DEBUG(3, ("could not open handle to NETLOGON pipe\n"));
+                       goto done;
+               }
 
-       generate_random_buffer( (unsigned char *)&smb_uid_low, 4, False);
+               result = cli_netlogon_sam_network_logon(cli, mem_ctx,
+                                                       &ret_creds,
+                                                       name_user, name_domain, 
+                                                       global_myname(), chal, 
+                                                       lm_resp, nt_resp,
+                                                       &info3);
+               attempts += 1;
+               
+               /* We have to try a second time as cm_get_netlogon_cli
+                  might not yet have noticed that the DC has killed
+                  our connection. */
+
+               if ( cli->fd == -1 ) {
+                       retry = True;
+                       continue;
+               } 
+               
+               /* if we get access denied, a possible cuase 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_V(result) == NT_STATUS_V(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));
+                       winbindd_cm_flush();
+                       retry = True;
+                       cli = NULL;
+               } 
+               
+       } while ( (attempts < 2) && retry );
 
-       ZERO_STRUCT(info3);
+        if (cli != NULL) {
+               /* We might have come out of the loop above with cli == NULL,
+                  so don't dereference that. */
+               clnt_deal_with_creds(cli->sess_key, &(cli->clnt_cred), &ret_creds);
+       }
        
-       /* Don't shut this down - it belongs to the connection cache code */
-        result = cm_get_netlogon_cli(lp_workgroup(), trust_passwd, &cli);
-
-        if (!NT_STATUS_IS_OK(result)) {
-                DEBUG(3, ("could not open handle to NETLOGON pipe\n"));
-                goto done;
-        }
-
-       result = cli_netlogon_sam_network_logon(cli, mem_ctx,
-                                               name_user, name_domain, 
-                                               global_myname(), chal, 
-                                               lm_resp, nt_resp, 
-                                               &info3);
-        
-       uni_group_cache_store_netlogon(mem_ctx, &info3);
+       if (NT_STATUS_IS_OK(result)) {
+               netsamlogon_cache_store( cli->mem_ctx, name_user, &info3 );
+               wcache_invalidate_samlogon(find_domain_from_name(name_domain), &info3);
+
+               /* Check if the user is in the right group */
+
+               if (!NT_STATUS_IS_OK(result = check_info3_in_group(mem_ctx, &info3, state->request.data.auth.require_membership_of_sid))) {
+                       DEBUG(3, ("User %s is not in the required group (%s), so plaintext authentication is rejected\n",
+                                 state->request.data.auth.user, 
+                                 state->request.data.auth.require_membership_of_sid));
+               }
+       }
+
 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;
@@ -148,7 +349,10 @@ done:
        
        state->response.data.auth.nt_status = NT_STATUS_V(result);
        fstrcpy(state->response.data.auth.nt_status_string, nt_errstr(result));
-       fstrcpy(state->response.data.auth.error_string, get_friendly_nt_error_msg(result));
+
+       /* we might have given a more useful error above */
+       if (!*state->response.data.auth.error_string) 
+               fstrcpy(state->response.data.auth.error_string, get_friendly_nt_error_msg(result));
        state->response.data.auth.pam_error = nt_status_to_pam(result);
 
        DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, ("Plain-text authentication for user %s returned %s (PAM: %d)\n", 
@@ -156,83 +360,112 @@ done:
              state->response.data.auth.nt_status_string,
              state->response.data.auth.pam_error));          
 
+       if ( NT_STATUS_IS_OK(result) &&
+            (state->request.flags & WBFLAG_PAM_AFS_TOKEN) ) {
+
+               char *afsname = SMB_STRDUP(lp_afs_username_map());
+               char *cell;
+
+               if (afsname == NULL) goto no_token;
+
+               afsname = realloc_string_sub(afsname, "%D", name_domain);
+               afsname = realloc_string_sub(afsname, "%u", name_user);
+               afsname = realloc_string_sub(afsname, "%U", name_user);
+
+               if (afsname == NULL) goto no_token;
+
+               strlower_m(afsname);
+
+               cell = strchr(afsname, '@');
+
+               if (cell == NULL) goto no_token;
+
+               *cell = '\0';
+               cell += 1;
+
+               /* Append an AFS token string */
+               state->response.extra_data =
+                       afs_createtoken_str(afsname, cell);
+
+               if (state->response.extra_data != NULL)
+                       state->response.length +=
+                               strlen(state->response.extra_data)+1;
+
+       no_token:
+               SAFE_FREE(afsname);
+       }
+               
        if (mem_ctx) 
                talloc_destroy(mem_ctx);
        
        return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
 }
-       
-/* Challenge Response Authentication Protocol */
+
+/**********************************************************************
+ Challenge Response Authentication Protocol 
+**********************************************************************/
 
 enum winbindd_result winbindd_pam_auth_crap(struct winbindd_cli_state *state) 
 {
        NTSTATUS result;
        unsigned char trust_passwd[16];
        time_t last_change_time;
+       uint32 sec_channel_type;
         NET_USER_INFO_3 info3;
         struct cli_state *cli = NULL;
        TALLOC_CTX *mem_ctx = NULL;
-       char *user = NULL;
-       const char *domain = NULL;
-       const char *contact_domain;
+       const char *name_user = NULL;
+       const char *name_domain = NULL;
        const char *workstation;
+       struct winbindd_domain *contact_domain;
+       DOM_CRED ret_creds;
+       int attempts = 0;
+       BOOL retry;
 
        DATA_BLOB lm_resp, nt_resp;
 
        if (!state->privileged) {
-               DEBUG(2, ("winbindd_pam_auth_crap: non-privileged access denied!\n"));
+               char *error_string = NULL;
+               DEBUG(2, ("winbindd_pam_auth_crap: non-privileged access denied.  !\n"));
+               DEBUGADD(2, ("winbindd_pam_auth_crap: Ensure permissions on %s are set correctly.\n", 
+                            get_winbind_priv_pipe_dir()));
                /* send a better message than ACCESS_DENIED */
-               push_utf8_fstring(state->response.data.auth.error_string, "winbind client not authorized to use winbindd_pam_auth_crap");
+               asprintf(&error_string, "winbind client not authorized to use winbindd_pam_auth_crap.  Ensure permissions on %s are set correctly.",
+                        get_winbind_priv_pipe_dir());
+               fstrcpy(state->response.data.auth.error_string, error_string);
+               SAFE_FREE(error_string);
                result =  NT_STATUS_ACCESS_DENIED;
                goto done;
        }
 
        /* Ensure null termination */
-       state->request.data.auth_crap.user[sizeof(state->request.data.auth_crap.user)-1]='\0';
-
-       /* Ensure null termination */
-       state->request.data.auth_crap.domain[sizeof(state->request.data.auth_crap.domain)-1]='\0';
+       state->request.data.auth_crap.user[sizeof(state->request.data.auth_crap.user)-1]=0;
+       state->request.data.auth_crap.domain[sizeof(state->request.data.auth_crap.domain)-1]=0;
 
-       if (!(mem_ctx = talloc_init("winbind pam auth crap for (utf8) %s", state->request.data.auth_crap.user))) {
+       if (!(mem_ctx = talloc_init("winbind pam auth crap for %s", state->request.data.auth_crap.user))) {
                DEBUG(0, ("winbindd_pam_auth_crap: could not talloc_init()!\n"));
                result = NT_STATUS_NO_MEMORY;
                goto done;
        }
 
-        if (pull_utf8_talloc(mem_ctx, &user, state->request.data.auth_crap.user) == (size_t)-1) {
-               DEBUG(0, ("winbindd_pam_auth_crap: pull_utf8_talloc failed!\n"));
-       }
+       name_user = state->request.data.auth_crap.user;
 
        if (*state->request.data.auth_crap.domain) {
-               char *dom = NULL;
-               if (pull_utf8_talloc(mem_ctx, &dom, state->request.data.auth_crap.domain) == (size_t)-1) {
-                       DEBUG(0, ("winbindd_pam_auth_crap: pull_utf8_talloc failed!\n"));
-               }
-               domain = dom;
+               name_domain = state->request.data.auth_crap.domain;
        } else if (lp_winbind_use_default_domain()) {
-               domain = lp_workgroup();
+               name_domain = lp_workgroup();
        } else {
                DEBUG(5,("no domain specified with username (%s) - failing auth\n", 
-                        user));
-               result = NT_STATUS_INVALID_PARAMETER;
+                        name_user));
+               result = NT_STATUS_NO_SUCH_USER;
                goto done;
        }
 
-       DEBUG(3, ("[%5d]: pam auth crap domain: %s user: %s\n", state->pid,
-                 domain, user));
-
-       if (lp_allow_trusted_domains() && (state->request.data.auth_crap.flags & WINBIND_PAM_CONTACT_TRUSTDOM)) {
-               contact_domain = domain;
-       } else {
-               contact_domain = lp_workgroup();
-       }
-
+       DEBUG(3, ("[%5lu]: pam auth crap domain: %s user: %s\n", (unsigned long)state->pid,
+                 name_domain, name_user));
+          
        if (*state->request.data.auth_crap.workstation) {
-               char *wrk = NULL;
-               if (pull_utf8_talloc(mem_ctx, &wrk, state->request.data.auth_crap.workstation) == (size_t)-1) {
-                       DEBUG(0, ("winbindd_pam_auth_crap: pull_utf8_talloc failed!\n"));
-               }
-               workstation = wrk;
+               workstation = state->request.data.auth_crap.workstation;
        } else {
                workstation = global_myname();
        }
@@ -249,67 +482,162 @@ enum winbindd_result winbindd_pam_auth_crap(struct winbindd_cli_state *state)
        lm_resp = data_blob_talloc(mem_ctx, state->request.data.auth_crap.lm_resp, state->request.data.auth_crap.lm_resp_len);
        nt_resp = data_blob_talloc(mem_ctx, state->request.data.auth_crap.nt_resp, state->request.data.auth_crap.nt_resp_len);
        
-       /*
-        * Get the machine account password for the domain to contact.
-        * This is either our own domain for a workstation, or possibly
-        * any domain for a PDC with trusted domains.
-        */
-
-       if (!secrets_fetch_trust_account_password (
-                contact_domain, trust_passwd, &last_change_time)) {
-               DEBUG(0, ("winbindd_pam_auth: could not fetch trust account "
-                          "password for domain %s\n", contact_domain));
+
+       /* what domain should we contact? */
+       
+       if ( IS_DC ) {
+               if (!(contact_domain = find_domain_from_name(name_domain))) {
+                       DEBUG(3, ("Authentication for domain for [%s] -> [%s]\\[%s] failed as %s is not a trusted domain\n", 
+                                 state->request.data.auth_crap.user, name_domain, name_user, name_domain)); 
+                       result = NT_STATUS_NO_SUCH_USER;
+                       goto done;
+               }
+               
+       } else {
+               if (is_myname(name_domain)) {
+                       DEBUG(3, ("Authentication for domain %s (local domain to this server) not supported at this stage\n", name_domain));
+                       result =  NT_STATUS_NO_SUCH_USER;
+                       goto done;
+               }
+
+               if (!(contact_domain = find_our_domain())) {
+                       DEBUG(1, ("Authenticatoin for [%s] -> [%s]\\[%s] in our domain failed - we can't find our domain!\n", 
+                                 state->request.data.auth_crap.user, name_domain, name_user)); 
+                       result = NT_STATUS_NO_SUCH_USER;
+                       goto done;
+               }
+       }
+               
+       if ( !get_trust_pw(contact_domain->name, trust_passwd, &last_change_time, &sec_channel_type) ) {
                result = NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
                goto done;
        }
 
-       ZERO_STRUCT(info3);
+       do {
+               ZERO_STRUCT(info3);
+               ZERO_STRUCT(ret_creds);
+               retry = False;
 
-       /* Don't shut this down - it belongs to the connection cache code */
-        result = cm_get_netlogon_cli(contact_domain, trust_passwd, &cli);
+               /* Don't shut this down - it belongs to the connection cache code */
+               result = cm_get_netlogon_cli(contact_domain, trust_passwd, sec_channel_type, False, &cli);
 
-        if (!NT_STATUS_IS_OK(result)) {
-                DEBUG(3, ("could not open handle to NETLOGON pipe (error: %s)\n", nt_errstr(result)));
-                goto done;
-        }
+               if (!NT_STATUS_IS_OK(result)) {
+                       DEBUG(3, ("could not open handle to NETLOGON pipe (error: %s)\n",
+                                 nt_errstr(result)));
+                       goto done;
+               }
+
+               result = cli_netlogon_sam_network_logon(cli, mem_ctx,
+                                                       &ret_creds,
+                                                       name_user, name_domain,
+                                                       workstation,
+                                                       state->request.data.auth_crap.chal, 
+                                                       lm_resp, nt_resp, 
+                                                       &info3);
+
+               attempts += 1;
+
+               /* We have to try a second time as cm_get_netlogon_cli
+                  might not yet have noticed that the DC has killed
+                  our connection. */
+
+               if ( cli->fd == -1 ) {
+                       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_V(result) == NT_STATUS_V(NT_STATUS_ACCESS_DENIED) ) {
+                       DEBUG(3,("winbindd_pam_auth_crap: sam_logon returned ACCESS_DENIED.  Maybe the trust account "
+                               "password was changed and we didn't know it.  Killing connections to domain %s\n",
+                               contact_domain->name));
+                       winbindd_cm_flush();
+                       retry = True;
+                       cli = NULL;
+               } 
+               
+       } while ( (attempts < 2) && retry );
+
+       if (cli != NULL) {
+               /* We might have come out of the loop above with cli == NULL,
+                  so don't dereference that. */
+               clnt_deal_with_creds(cli->sess_key, &(cli->clnt_cred), &ret_creds);
+       }
 
-       result = cli_netlogon_sam_network_logon(cli, mem_ctx,
-                                               user, domain,
-                                               workstation, state->request.data.auth_crap.chal, 
-                                               lm_resp, nt_resp, 
-                                               &info3);
-        
        if (NT_STATUS_IS_OK(result)) {
-               uni_group_cache_store_netlogon(mem_ctx, &info3);
-               if (state->request.data.auth_crap.flags & WINBIND_PAM_INFO3_NDR) {
-                       result = append_info3_as_ndr(mem_ctx, state, &info3);
+               netsamlogon_cache_store( cli->mem_ctx, name_user, &info3 );
+               wcache_invalidate_samlogon(find_domain_from_name(name_domain), &info3);
+               
+               if (!NT_STATUS_IS_OK(result = check_info3_in_group(mem_ctx, &info3, state->request.data.auth_crap.require_membership_of_sid))) {
+                       DEBUG(3, ("User %s is not in the required group (%s), so plaintext authentication is rejected\n",
+                                 state->request.data.auth_crap.user, 
+                                 state->request.data.auth_crap.require_membership_of_sid));
+                       goto done;
                }
 
-               if (state->request.data.auth_crap.flags & WINBIND_PAM_NTKEY) {
-                       memcpy(state->response.data.auth.nt_session_key, info3.user_sess_key, sizeof(state->response.data.auth.nt_session_key) /* 16 */);
+               if (state->request.flags & WBFLAG_PAM_INFO3_NDR) {
+                       result = append_info3_as_ndr(mem_ctx, state, &info3);
+               } else if (state->request.flags & WBFLAG_PAM_UNIX_NAME) {
+                       /* ntlm_auth should return the unix username, per 
+                          'winbind use default domain' settings and the like */
+                       
+                       fstring username_out;
+                       const char *nt_username, *nt_domain;
+                       if (!(nt_username = unistr2_tdup(mem_ctx, &(info3.uni_user_name)))) {
+                               /* If the server didn't give us one, just use the one we sent them */
+                               nt_username = name_user;
+                       }
+                       
+                       if (!(nt_domain = unistr2_tdup(mem_ctx, &(info3.uni_logon_dom)))) {
+                               /* If the server didn't give us one, just use the one we sent them */
+                               nt_domain = name_domain;
+                       }
+
+                       fill_domain_username(username_out, nt_domain, nt_username);
+
+                       DEBUG(5, ("Setting unix username to [%s]\n", username_out));
+
+                       state->response.extra_data = SMB_STRDUP(username_out);
+                       if (!state->response.extra_data) {
+                               result = NT_STATUS_NO_MEMORY;
+                               goto done;
+                       }
+                       state->response.length +=  strlen(state->response.extra_data)+1;
                }
-               if (state->request.data.auth_crap.flags & WINBIND_PAM_LMKEY) {
+               
+               if (state->request.flags & WBFLAG_PAM_USER_SESSION_KEY) {
+                       memcpy(state->response.data.auth.user_session_key, info3.user_sess_key, sizeof(state->response.data.auth.user_session_key) /* 16 */);
+               }
+               if (state->request.flags & WBFLAG_PAM_LMKEY) {
                        memcpy(state->response.data.auth.first_8_lm_hash, info3.padding, sizeof(state->response.data.auth.first_8_lm_hash) /* 8 */);
                }
        }
 
 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);
+       }
        
        state->response.data.auth.nt_status = NT_STATUS_V(result);
-       push_utf8_fstring(state->response.data.auth.nt_status_string, nt_errstr(result));
+       fstrcpy(state->response.data.auth.nt_status_string, nt_errstr(result));
+       
+       /* we might have given a more useful error above */
        if (!*state->response.data.auth.error_string) 
-               push_utf8_fstring(state->response.data.auth.error_string, get_friendly_nt_error_msg(result));
+               fstrcpy(state->response.data.auth.error_string, get_friendly_nt_error_msg(result));
        state->response.data.auth.pam_error = nt_status_to_pam(result);
 
        DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, 
              ("NTLM CRAP authentication for user [%s]\\[%s] returned %s (PAM: %d)\n", 
-              domain,
-              user,
+              name_domain,
+              name_user,
               state->response.data.auth.nt_status_string,
               state->response.data.auth.pam_error));         
 
@@ -327,18 +655,30 @@ enum winbindd_result winbindd_pam_chauthtok(struct winbindd_cli_state *state)
        char *oldpass, *newpass;
        fstring domain, user;
        CLI_POLICY_HND *hnd;
+       TALLOC_CTX *mem_ctx;
+       struct winbindd_domain *contact_domain;
 
-       DEBUG(3, ("[%5d]: pam chauthtok %s\n", state->pid,
+       DEBUG(3, ("[%5lu]: pam chauthtok %s\n", (unsigned long)state->pid,
                state->request.data.chauthtok.user));
 
+       if (!(mem_ctx = talloc_init("winbind password change for %s", 
+                                   state->request.data.chauthtok.user))) {
+               DEBUG(0, ("winbindd_pam_auth_crap: could not talloc_init()!\n"));
+               result = NT_STATUS_NO_MEMORY;
+               goto done;
+       }
+
        /* Setup crap */
 
        if (state == NULL)
                return WINBINDD_ERROR;
 
-       if (!parse_domain_user(state->request.data.chauthtok.user, domain, 
-                              user)) {
-               result = NT_STATUS_INVALID_PARAMETER;
+       parse_domain_user(state->request.data.chauthtok.user, domain, user);
+
+       if (!(contact_domain = find_domain_from_name(domain))) {
+               DEBUG(3, ("Cannot change password for [%s] -> [%s]\\[%s] as %s is not a trusted domain\n", 
+                         state->request.data.chauthtok.user, domain, user, domain)); 
+               result = NT_STATUS_NO_SUCH_USER;
                goto done;
        }
 
@@ -349,19 +689,12 @@ enum winbindd_result winbindd_pam_chauthtok(struct winbindd_cli_state *state)
 
        /* Get sam handle */
 
-       if (!(hnd = cm_get_sam_handle(domain))) {
+       if (!NT_STATUS_IS_OK(result = cm_get_sam_handle(contact_domain, &hnd)) ) {
                DEBUG(1, ("could not get SAM handle on DC for %s\n", domain));
-               result = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
                goto done;
        }
 
-       if (!cli_oem_change_password(hnd->cli, user, newpass, oldpass)) {
-               DEBUG(1, ("password change failed for user %s/%s\n", domain, 
-                         user));
-               result = NT_STATUS_WRONG_PASSWORD;
-       } else {
-               result = NT_STATUS_OK;
-       }
+       result = cli_samr_chgpasswd_user(hnd->cli, mem_ctx, user, newpass, oldpass);
 
 done:    
        state->response.data.auth.nt_status = NT_STATUS_V(result);
@@ -376,5 +709,8 @@ done:
               state->response.data.auth.nt_status_string,
               state->response.data.auth.pam_error));         
 
+       if (mem_ctx)
+               talloc_destroy(mem_ctx);
+
        return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
 }