r10268: Fix for bug #3095 - winbindd checking credentials.
[samba.git] / source / nsswitch / winbindd_pam.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Winbind daemon - pam auth funcions
5
6    Copyright (C) Andrew Tridgell 2000
7    Copyright (C) Tim Potter 2001
8    Copyright (C) Andrew Bartlett 2001-2002
9    
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 */
24
25 #include "includes.h"
26 #include "winbindd.h"
27 #undef DBGC_CLASS
28 #define DBGC_CLASS DBGC_WINBIND
29
30
31 static NTSTATUS append_info3_as_ndr(TALLOC_CTX *mem_ctx, 
32                                     struct winbindd_cli_state *state, 
33                                     NET_USER_INFO_3 *info3) 
34 {
35         prs_struct ps;
36         uint32 size;
37         if (!prs_init(&ps, 256 /* Random, non-zero number */, mem_ctx, MARSHALL)) {
38                 return NT_STATUS_NO_MEMORY;
39         }
40         if (!net_io_user_info3("", info3, &ps, 1, 3)) {
41                 prs_mem_free(&ps);
42                 return NT_STATUS_UNSUCCESSFUL;
43         }
44
45         size = prs_data_size(&ps);
46         state->response.extra_data = SMB_MALLOC(size);
47         if (!state->response.extra_data) {
48                 prs_mem_free(&ps);
49                 return NT_STATUS_NO_MEMORY;
50         }
51         memset( state->response.extra_data, '\0', size );
52         prs_copy_all_data_out(state->response.extra_data, &ps);
53         state->response.length += size;
54         prs_mem_free(&ps);
55         return NT_STATUS_OK;
56 }
57
58 static NTSTATUS check_info3_in_group(TALLOC_CTX *mem_ctx, 
59                                      NET_USER_INFO_3 *info3,
60                                      const char *group_sid) 
61 {
62         DOM_SID require_membership_of_sid;
63         DOM_SID *all_sids;
64         size_t num_all_sids = (2 + info3->num_groups2 + info3->num_other_sids);
65         size_t i, j = 0;
66
67         /* Parse the 'required group' SID */
68         
69         if (!group_sid || !group_sid[0]) {
70                 /* NO sid supplied, all users may access */
71                 return NT_STATUS_OK;
72         }
73         
74         if (!string_to_sid(&require_membership_of_sid, group_sid)) {
75                 DEBUG(0, ("check_info3_in_group: could not parse %s as a SID!", 
76                           group_sid));
77
78                 return NT_STATUS_INVALID_PARAMETER;
79         }
80
81         all_sids = TALLOC_ARRAY(mem_ctx, DOM_SID, num_all_sids);
82         if (!all_sids)
83                 return NT_STATUS_NO_MEMORY;
84
85         /* and create (by appending rids) the 'domain' sids */
86         
87         sid_copy(&all_sids[0], &(info3->dom_sid.sid));
88         
89         if (!sid_append_rid(&all_sids[0], info3->user_rid)) {
90                 DEBUG(3,("could not append user's primary RID 0x%x\n",
91                          info3->user_rid));                     
92                 
93                 return NT_STATUS_INVALID_PARAMETER;
94         }
95         j++;
96
97         sid_copy(&all_sids[1], &(info3->dom_sid.sid));
98                 
99         if (!sid_append_rid(&all_sids[1], info3->group_rid)) {
100                 DEBUG(3,("could not append additional group rid 0x%x\n",
101                          info3->group_rid));                    
102                 
103                 return NT_STATUS_INVALID_PARAMETER;
104         }
105         j++;    
106
107         for (i = 0; i < info3->num_groups2; i++) {
108         
109                 sid_copy(&all_sids[j], &(info3->dom_sid.sid));
110                 
111                 if (!sid_append_rid(&all_sids[j], info3->gids[i].g_rid)) {
112                         DEBUG(3,("could not append additional group rid 0x%x\n",
113                                 info3->gids[i].g_rid));                 
114                                 
115                         return NT_STATUS_INVALID_PARAMETER;
116                 }
117                 j++;
118         }
119
120         /* Copy 'other' sids.  We need to do sid filtering here to
121            prevent possible elevation of privileges.  See:
122
123            http://www.microsoft.com/windows2000/techinfo/administration/security/sidfilter.asp
124          */
125
126         for (i = 0; i < info3->num_other_sids; i++) {
127                 sid_copy(&all_sids[info3->num_groups2 + i + 2],
128                          &info3->other_sids[i].sid);
129                 j++;
130         }
131
132         for (i = 0; i < j; i++) {
133                 fstring sid1, sid2;
134                 DEBUG(10, ("User has SID: %s\n", 
135                            sid_to_string(sid1, &all_sids[i])));
136                 if (sid_equal(&require_membership_of_sid, &all_sids[i])) {
137                         DEBUG(10, ("SID %s matches %s - user permitted to authenticate!\n", 
138                                    sid_to_string(sid1, &require_membership_of_sid), sid_to_string(sid2, &all_sids[i])));
139                         return NT_STATUS_OK;
140                 }
141         }
142         
143         /* Do not distinguish this error from a wrong username/pw */
144
145         return NT_STATUS_LOGON_FAILURE;
146 }
147
148 static struct winbindd_domain *find_auth_domain(const char *domain_name)
149 {
150         struct winbindd_domain *domain;
151
152         if (IS_DC) {
153                 domain = find_domain_from_name_noinit(domain_name);
154                 if (domain == NULL) {
155                         DEBUG(3, ("Authentication for domain [%s] "
156                                   "as it is not a trusted domain\n", 
157                                   domain_name));
158                 }
159                 return domain;
160         }
161
162         if (is_myname(domain_name)) {
163                 DEBUG(3, ("Authentication for domain %s (local domain "
164                           "to this server) not supported at this "
165                           "stage\n", domain_name));
166                 return NULL;
167         }
168
169         return find_our_domain();
170 }
171
172 static void set_auth_errors(struct winbindd_response *resp, NTSTATUS result)
173 {
174         resp->data.auth.nt_status = NT_STATUS_V(result);
175         fstrcpy(resp->data.auth.nt_status_string, nt_errstr(result));
176
177         /* we might have given a more useful error above */
178         if (*resp->data.auth.error_string == '\0') 
179                 fstrcpy(resp->data.auth.error_string,
180                         get_friendly_nt_error_msg(result));
181         resp->data.auth.pam_error = nt_status_to_pam(result);
182 }
183
184 /**********************************************************************
185  Authenticate a user with a clear text password
186 **********************************************************************/
187
188 void winbindd_pam_auth(struct winbindd_cli_state *state)
189 {
190         struct winbindd_domain *domain;
191         fstring name_domain, name_user;
192
193         /* Ensure null termination */
194         state->request.data.auth.user
195                 [sizeof(state->request.data.auth.user)-1]='\0';
196
197         /* Ensure null termination */
198         state->request.data.auth.pass
199                 [sizeof(state->request.data.auth.pass)-1]='\0';
200
201         DEBUG(3, ("[%5lu]: pam auth %s\n", (unsigned long)state->pid,
202                   state->request.data.auth.user));
203
204         /* Parse domain and username */
205         
206         parse_domain_user(state->request.data.auth.user,
207                           name_domain, name_user);
208
209         domain = find_auth_domain(name_domain);
210
211         if (domain == NULL) {
212                 set_auth_errors(&state->response, NT_STATUS_NO_SUCH_USER);
213                 DEBUG(5, ("Plain text authentication for %s returned %s "
214                           "(PAM: %d)\n",
215                           state->request.data.auth.user, 
216                           state->response.data.auth.nt_status_string,
217                           state->response.data.auth.pam_error));
218                 request_error(state);
219                 return;
220         }
221
222         sendto_domain(state, domain);
223 }
224
225 enum winbindd_result winbindd_dual_pam_auth(struct winbindd_domain *domain,
226                                             struct winbindd_cli_state *state) 
227 {
228         NTSTATUS result;
229         fstring name_domain, name_user;
230         const char *srv_name_slash;
231         NET_USER_INFO_3 info3;
232         unsigned char *session_key;
233         struct rpc_pipe_client *pipe_cli;
234         uchar chal[8];
235         DATA_BLOB lm_resp;
236         DATA_BLOB nt_resp;
237         DOM_CRED ret_creds;
238         DOM_CRED *credentials;
239         int attempts = 0;
240         unsigned char local_lm_response[24];
241         unsigned char local_nt_response[24];
242         struct winbindd_domain *contact_domain;
243         BOOL retry;
244
245         /* Ensure null termination */
246         state->request.data.auth.user[sizeof(state->request.data.auth.user)-1]='\0';
247
248         /* Ensure null termination */
249         state->request.data.auth.pass[sizeof(state->request.data.auth.pass)-1]='\0';
250
251         DEBUG(3, ("[%5lu]: pam auth %s\n", (unsigned long)state->pid,
252                   state->request.data.auth.user));
253
254         /* Parse domain and username */
255         
256         parse_domain_user(state->request.data.auth.user, name_domain, name_user);
257
258         /* do password magic */
259         
260
261         generate_random_buffer(chal, 8);
262         if (lp_client_ntlmv2_auth()) {
263                 DATA_BLOB server_chal;
264                 DATA_BLOB names_blob;
265                 DATA_BLOB nt_response;
266                 DATA_BLOB lm_response;
267                 server_chal = data_blob_talloc(state->mem_ctx, chal, 8); 
268                 
269                 /* note that the 'workgroup' here is a best guess - we don't know
270                    the server's domain at this point.  The 'server name' is also
271                    dodgy... 
272                 */
273                 names_blob = NTLMv2_generate_names_blob(global_myname(), lp_workgroup());
274                 
275                 if (!SMBNTLMv2encrypt(name_user, name_domain, 
276                                       state->request.data.auth.pass, 
277                                       &server_chal, 
278                                       &names_blob,
279                                       &lm_response, &nt_response, NULL)) {
280                         data_blob_free(&names_blob);
281                         data_blob_free(&server_chal);
282                         DEBUG(0, ("winbindd_pam_auth: SMBNTLMv2encrypt() failed!\n"));
283                         result = NT_STATUS_NO_MEMORY;
284                         goto done;
285                 }
286                 data_blob_free(&names_blob);
287                 data_blob_free(&server_chal);
288                 lm_resp = data_blob_talloc(state->mem_ctx, lm_response.data,
289                                            lm_response.length);
290                 nt_resp = data_blob_talloc(state->mem_ctx, nt_response.data,
291                                            nt_response.length);
292                 data_blob_free(&lm_response);
293                 data_blob_free(&nt_response);
294
295         } else {
296                 if (lp_client_lanman_auth() 
297                     && SMBencrypt(state->request.data.auth.pass, 
298                                   chal, 
299                                   local_lm_response)) {
300                         lm_resp = data_blob_talloc(state->mem_ctx, 
301                                                    local_lm_response, 
302                                                    sizeof(local_lm_response));
303                 } else {
304                         lm_resp = data_blob(NULL, 0);
305                 }
306                 SMBNTencrypt(state->request.data.auth.pass, 
307                              chal,
308                              local_nt_response);
309
310                 nt_resp = data_blob_talloc(state->mem_ctx, 
311                                            local_nt_response, 
312                                            sizeof(local_nt_response));
313         }
314
315         
316         /* what domain should we contact? */
317         
318         if ( IS_DC ) {
319                 if (!(contact_domain = find_domain_from_name(name_domain))) {
320                         DEBUG(3, ("Authentication for domain for [%s] -> [%s]\\[%s] failed as %s is not a trusted domain\n", 
321                                   state->request.data.auth.user, name_domain, name_user, name_domain)); 
322                         result = NT_STATUS_NO_SUCH_USER;
323                         goto done;
324                 }
325                 
326         } else {
327                 if (is_myname(name_domain)) {
328                         DEBUG(3, ("Authentication for domain %s (local domain to this server) not supported at this stage\n", name_domain));
329                         result =  NT_STATUS_NO_SUCH_USER;
330                         goto done;
331                 }
332
333                 contact_domain = find_our_domain();
334         }
335
336         srv_name_slash = talloc_asprintf(state->mem_ctx, "\\\\%s",
337                                          contact_domain->dcname);
338         if (srv_name_slash == NULL) {
339                 DEBUG(0, ("talloc_asprintf failed\n"));
340                 return WINBINDD_ERROR;
341         }
342                 
343         /* check authentication loop */
344
345         do {
346                 DOM_CRED clnt_creds;
347
348                 ZERO_STRUCT(info3);
349                 ZERO_STRUCT(ret_creds);
350                 retry = False;
351
352                 result = cm_connect_netlogon(contact_domain, state->mem_ctx,
353                                              &pipe_cli, &session_key,
354                                              &credentials);
355
356                 if (!NT_STATUS_IS_OK(result)) {
357                         DEBUG(3, ("could not open handle to NETLOGON pipe\n"));
358                         goto done;
359                 }
360
361                 credentials->timestamp.time = time(NULL);
362                 memcpy(&clnt_creds, credentials, sizeof(clnt_creds));
363
364                 /* Calculate the new credentials. */
365                 cred_create(session_key, &credentials->challenge,
366                             clnt_creds.timestamp, &(clnt_creds.challenge));
367
368                 result = rpccli_netlogon_sam_network_logon(pipe_cli,
369                                                            state->mem_ctx,
370                                                            srv_name_slash,
371                                                            &clnt_creds,
372                                                            &ret_creds,
373                                                            name_user,
374                                                            name_domain, 
375                                                            global_myname(),
376                                                            chal, lm_resp,
377                                                            nt_resp, &info3,
378                                                            session_key);
379                 attempts += 1;
380
381                 /* We have to try a second time as cm_connect_netlogon
382                    might not yet have noticed that the DC has killed
383                    our connection. */
384
385                 if (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)) {
386                         retry = True;
387                         continue;
388                 }
389                 
390                 /* if we get access denied, a possible cause was that we had
391                    and open connection to the DC, but someone changed our
392                    machine account password out from underneath us using 'net
393                    rpc changetrustpw' */
394                    
395                 if ( NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED) ) {
396                         DEBUG(3,("winbindd_pam_auth: sam_logon returned "
397                                  "ACCESS_DENIED.  Maybe the trust account "
398                                 "password was changed and we didn't know it. "
399                                  "Killing connections to domain %s\n",
400                                 name_domain));
401                         invalidate_cm_connection(&contact_domain->conn);
402                         retry = True;
403                 } 
404                 
405         } while ( (attempts < 2) && retry );
406
407         /* Only check creds if we got a connection. */
408         if (contact_domain->conn.cli &&
409                         !(NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) ||
410                                 NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL))) {
411                 if (!clnt_deal_with_creds(session_key, credentials, &ret_creds)) {
412                         DEBUG(3, ("DC %s sent wrong credentials\n",
413                                 pipe_cli->cli->srv_name_slash));
414                         result = NT_STATUS_ACCESS_DENIED;
415                 }
416         }
417
418         if (NT_STATUS_IS_OK(result)) {
419                 /* Check if the user is in the right group */
420
421                 if (!NT_STATUS_IS_OK(result = check_info3_in_group(state->mem_ctx, &info3, state->request.data.auth.require_membership_of_sid))) {
422                         DEBUG(3, ("User %s is not in the required group (%s), so plaintext authentication is rejected\n",
423                                   state->request.data.auth.user, 
424                                   state->request.data.auth.require_membership_of_sid));
425                 }
426         }
427
428 done:
429         /* give us a more useful (more correct?) error code */
430         if ((NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) || (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)))) {
431                 result = NT_STATUS_NO_LOGON_SERVERS;
432         }
433         
434         state->response.data.auth.nt_status = NT_STATUS_V(result);
435         fstrcpy(state->response.data.auth.nt_status_string, nt_errstr(result));
436
437         /* we might have given a more useful error above */
438         if (!*state->response.data.auth.error_string) 
439                 fstrcpy(state->response.data.auth.error_string, get_friendly_nt_error_msg(result));
440         state->response.data.auth.pam_error = nt_status_to_pam(result);
441
442         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, ("Plain-text authentication for user %s returned %s (PAM: %d)\n", 
443               state->request.data.auth.user, 
444               state->response.data.auth.nt_status_string,
445               state->response.data.auth.pam_error));          
446
447         if ( NT_STATUS_IS_OK(result) &&
448              (state->request.flags & WBFLAG_PAM_AFS_TOKEN) ) {
449
450                 char *afsname = SMB_STRDUP(lp_afs_username_map());
451                 char *cell;
452
453                 if (afsname == NULL) goto no_token;
454
455                 afsname = realloc_string_sub(afsname, "%D", name_domain);
456                 afsname = realloc_string_sub(afsname, "%u", name_user);
457                 afsname = realloc_string_sub(afsname, "%U", name_user);
458
459                 {
460                         DOM_SID user_sid;
461                         fstring sidstr;
462
463                         sid_copy(&user_sid, &info3.dom_sid.sid);
464                         sid_append_rid(&user_sid, info3.user_rid);
465                         sid_to_string(sidstr, &user_sid);
466                         afsname = realloc_string_sub(afsname, "%s", sidstr);
467                 }
468
469                 if (afsname == NULL) goto no_token;
470
471                 strlower_m(afsname);
472
473                 DEBUG(10, ("Generating token for user %s\n", afsname));
474
475                 cell = strchr(afsname, '@');
476
477                 if (cell == NULL) goto no_token;
478
479                 *cell = '\0';
480                 cell += 1;
481
482                 /* Append an AFS token string */
483                 state->response.extra_data =
484                         afs_createtoken_str(afsname, cell);
485
486                 if (state->response.extra_data != NULL)
487                         state->response.length +=
488                                 strlen(state->response.extra_data)+1;
489
490         no_token:
491                 SAFE_FREE(afsname);
492         }
493                 
494         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
495 }
496
497 /**********************************************************************
498  Challenge Response Authentication Protocol 
499 **********************************************************************/
500
501 void winbindd_pam_auth_crap(struct winbindd_cli_state *state)
502 {
503         struct winbindd_domain *domain = NULL;
504         const char *domain_name = NULL;
505         NTSTATUS result;
506
507         if (!state->privileged) {
508                 char *error_string = NULL;
509                 DEBUG(2, ("winbindd_pam_auth_crap: non-privileged access "
510                           "denied.  !\n"));
511                 DEBUGADD(2, ("winbindd_pam_auth_crap: Ensure permissions "
512                              "on %s are set correctly.\n",
513                              get_winbind_priv_pipe_dir()));
514                 /* send a better message than ACCESS_DENIED */
515                 error_string = talloc_asprintf(state->mem_ctx,
516                                                "winbind client not authorized "
517                                                "to use winbindd_pam_auth_crap."
518                                                " Ensure permissions on %s "
519                                                "are set correctly.",
520                                                get_winbind_priv_pipe_dir());
521                 fstrcpy(state->response.data.auth.error_string, error_string);
522                 result = NT_STATUS_ACCESS_DENIED;
523                 goto done;
524         }
525
526         /* Ensure null termination */
527         state->request.data.auth_crap.user
528                 [sizeof(state->request.data.auth_crap.user)-1]=0;
529         state->request.data.auth_crap.domain
530                 [sizeof(state->request.data.auth_crap.domain)-1]=0;
531
532         DEBUG(3, ("[%5lu]: pam auth crap domain: [%s] user: %s\n",
533                   (unsigned long)state->pid,
534                   state->request.data.auth_crap.domain,
535                   state->request.data.auth_crap.user));
536
537         if (*state->request.data.auth_crap.domain != '\0') {
538                 domain_name = state->request.data.auth_crap.domain;
539         } else if (lp_winbind_use_default_domain()) {
540                 domain_name = lp_workgroup();
541         }
542
543         if (domain_name != NULL)
544                 domain = find_auth_domain(domain_name);
545
546         if (domain != NULL) {
547                 sendto_domain(state, domain);
548                 return;
549         }
550
551         result = NT_STATUS_NO_SUCH_USER;
552
553  done:
554         set_auth_errors(&state->response, result);
555         DEBUG(5, ("CRAP authentication for %s returned %s (PAM: %d)\n",
556                   state->request.data.auth.user, 
557                   state->response.data.auth.nt_status_string,
558                   state->response.data.auth.pam_error));
559         request_error(state);
560         return;
561 }
562
563
564 enum winbindd_result winbindd_dual_pam_auth_crap(struct winbindd_domain *domain,
565                                                  struct winbindd_cli_state *state) 
566 {
567         NTSTATUS result;
568         const char *srv_name_slash;
569         NET_USER_INFO_3 info3;
570         unsigned char *session_key;
571         struct rpc_pipe_client *pipe_cli;
572         DOM_CRED *credentials;
573         const char *name_user = NULL;
574         const char *name_domain = NULL;
575         const char *workstation;
576         struct winbindd_domain *contact_domain;
577         DOM_CRED ret_creds;
578         int attempts = 0;
579         BOOL retry;
580
581         DATA_BLOB lm_resp, nt_resp;
582
583         /* This is child-only, so no check for privileged access is needed
584            anymore */
585
586         /* Ensure null termination */
587         state->request.data.auth_crap.user[sizeof(state->request.data.auth_crap.user)-1]=0;
588         state->request.data.auth_crap.domain[sizeof(state->request.data.auth_crap.domain)-1]=0;
589
590         name_user = state->request.data.auth_crap.user;
591
592         if (*state->request.data.auth_crap.domain) {
593                 name_domain = state->request.data.auth_crap.domain;
594         } else if (lp_winbind_use_default_domain()) {
595                 name_domain = lp_workgroup();
596         } else {
597                 DEBUG(5,("no domain specified with username (%s) - failing auth\n", 
598                          name_user));
599                 result = NT_STATUS_NO_SUCH_USER;
600                 goto done;
601         }
602
603         DEBUG(3, ("[%5lu]: pam auth crap domain: %s user: %s\n", (unsigned long)state->pid,
604                   name_domain, name_user));
605            
606         if (*state->request.data.auth_crap.workstation) {
607                 workstation = state->request.data.auth_crap.workstation;
608         } else {
609                 workstation = global_myname();
610         }
611
612         if (state->request.data.auth_crap.lm_resp_len > sizeof(state->request.data.auth_crap.lm_resp)
613                 || state->request.data.auth_crap.nt_resp_len > sizeof(state->request.data.auth_crap.nt_resp)) {
614                 DEBUG(0, ("winbindd_pam_auth_crap: invalid password length %u/%u\n", 
615                           state->request.data.auth_crap.lm_resp_len, 
616                           state->request.data.auth_crap.nt_resp_len));
617                 result = NT_STATUS_INVALID_PARAMETER;
618                 goto done;
619         }
620
621         lm_resp = data_blob_talloc(state->mem_ctx, state->request.data.auth_crap.lm_resp, state->request.data.auth_crap.lm_resp_len);
622         nt_resp = data_blob_talloc(state->mem_ctx, state->request.data.auth_crap.nt_resp, state->request.data.auth_crap.nt_resp_len);
623         
624
625         /* what domain should we contact? */
626         
627         if ( IS_DC ) {
628                 if (!(contact_domain = find_domain_from_name(name_domain))) {
629                         DEBUG(3, ("Authentication for domain for [%s] -> [%s]\\[%s] failed as %s is not a trusted domain\n", 
630                                   state->request.data.auth_crap.user, name_domain, name_user, name_domain)); 
631                         result = NT_STATUS_NO_SUCH_USER;
632                         goto done;
633                 }
634                 
635         } else {
636                 if (is_myname(name_domain)) {
637                         DEBUG(3, ("Authentication for domain %s (local domain to this server) not supported at this stage\n", name_domain));
638                         result =  NT_STATUS_NO_SUCH_USER;
639                         goto done;
640                 }
641
642                 contact_domain = find_our_domain();
643         }
644
645         srv_name_slash = talloc_asprintf(state->mem_ctx, "\\\\%s",
646                                          contact_domain->dcname);
647         if (srv_name_slash == NULL) {
648                 DEBUG(0, ("talloc_asprintf failed\n"));
649                 return WINBINDD_ERROR;
650         }
651                 
652         do {
653                 DOM_CRED clnt_creds;
654                 ZERO_STRUCT(info3);
655                 ZERO_STRUCT(ret_creds);
656                 retry = False;
657
658                 result = cm_connect_netlogon(contact_domain, state->mem_ctx,
659                                              &pipe_cli, &session_key,
660                                              &credentials);
661
662                 if (!NT_STATUS_IS_OK(result)) {
663                         DEBUG(3, ("could not open handle to NETLOGON pipe (error: %s)\n",
664                                   nt_errstr(result)));
665                         goto done;
666                 }
667
668                 credentials->timestamp.time = time(NULL);
669                 memcpy(&clnt_creds, credentials, sizeof(clnt_creds));
670
671                 /* Calculate the new credentials. */
672                 cred_create(session_key, &credentials->challenge,
673                             clnt_creds.timestamp, &(clnt_creds.challenge));
674
675                 result = rpccli_netlogon_sam_network_logon(pipe_cli,
676                                                            state->mem_ctx,
677                                                            srv_name_slash,
678                                                            &clnt_creds,
679                                                            &ret_creds,
680                                                            name_user,
681                                                            name_domain, 
682                                                            global_myname(),
683                                                            state->request.data.auth_crap.chal,
684                                                            lm_resp,
685                                                            nt_resp, &info3,
686                                                            session_key);
687
688                 attempts += 1;
689
690                 /* We have to try a second time as cm_connect_netlogon
691                    might not yet have noticed that the DC has killed
692                    our connection. */
693
694                 if (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)) {
695                         retry = True;
696                         continue;
697                 }
698
699                 /* if we get access denied, a possible cause was that we had and open
700                    connection to the DC, but someone changed our machine account password
701                    out from underneath us using 'net rpc changetrustpw' */
702                    
703                 if ( NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED) ) {
704                         DEBUG(3,("winbindd_pam_auth: sam_logon returned "
705                                  "ACCESS_DENIED.  Maybe the trust account "
706                                 "password was changed and we didn't know it. "
707                                  "Killing connections to domain %s\n",
708                                 name_domain));
709                         invalidate_cm_connection(&contact_domain->conn);
710                         retry = True;
711                 } 
712
713         } while ( (attempts < 2) && retry );
714
715         /* Only check creds if we got a connection. */
716         if (contact_domain->conn.cli &&
717                         !(NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) ||
718                                         (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)))) {
719                 if (!clnt_deal_with_creds(session_key, credentials, &ret_creds)) {
720                         DEBUG(3, ("DC %s sent wrong credentials\n",
721                                 pipe_cli->cli->srv_name_slash));
722                         result = NT_STATUS_ACCESS_DENIED;
723                 }
724         }
725
726         if (NT_STATUS_IS_OK(result)) {
727                 if (!NT_STATUS_IS_OK(result = check_info3_in_group(state->mem_ctx, &info3, state->request.data.auth_crap.require_membership_of_sid))) {
728                         DEBUG(3, ("User %s is not in the required group (%s), so plaintext authentication is rejected\n",
729                                   state->request.data.auth_crap.user, 
730                                   state->request.data.auth_crap.require_membership_of_sid));
731                         goto done;
732                 }
733
734                 if (state->request.flags & WBFLAG_PAM_INFO3_NDR) {
735                         result = append_info3_as_ndr(state->mem_ctx, state, &info3);
736                 } else if (state->request.flags & WBFLAG_PAM_UNIX_NAME) {
737                         /* ntlm_auth should return the unix username, per 
738                            'winbind use default domain' settings and the like */
739                         
740                         fstring username_out;
741                         const char *nt_username, *nt_domain;
742                         if (!(nt_username = unistr2_tdup(state->mem_ctx, &(info3.uni_user_name)))) {
743                                 /* If the server didn't give us one, just use the one we sent them */
744                                 nt_username = name_user;
745                         }
746                         
747                         if (!(nt_domain = unistr2_tdup(state->mem_ctx, &(info3.uni_logon_dom)))) {
748                                 /* If the server didn't give us one, just use the one we sent them */
749                                 nt_domain = name_domain;
750                         }
751
752                         fill_domain_username(username_out, nt_domain, nt_username);
753
754                         DEBUG(5, ("Setting unix username to [%s]\n", username_out));
755
756                         state->response.extra_data = SMB_STRDUP(username_out);
757                         if (!state->response.extra_data) {
758                                 result = NT_STATUS_NO_MEMORY;
759                                 goto done;
760                         }
761                         state->response.length +=  strlen(state->response.extra_data)+1;
762                 }
763                 
764                 if (state->request.flags & WBFLAG_PAM_USER_SESSION_KEY) {
765                         memcpy(state->response.data.auth.user_session_key, info3.user_sess_key, sizeof(state->response.data.auth.user_session_key) /* 16 */);
766                 }
767                 if (state->request.flags & WBFLAG_PAM_LMKEY) {
768                         memcpy(state->response.data.auth.first_8_lm_hash, info3.lm_sess_key, sizeof(state->response.data.auth.first_8_lm_hash) /* 8 */);
769                 }
770         }
771
772 done:
773         /* give us a more useful (more correct?) error code */
774         if ((NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) || (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)))) {
775                 result = NT_STATUS_NO_LOGON_SERVERS;
776         }
777
778         if (state->request.flags & WBFLAG_PAM_NT_STATUS_SQUASH) {
779                 result = nt_status_squash(result);
780         }
781         
782         state->response.data.auth.nt_status = NT_STATUS_V(result);
783         fstrcpy(state->response.data.auth.nt_status_string, nt_errstr(result));
784         
785         /* we might have given a more useful error above */
786         if (!*state->response.data.auth.error_string) 
787                 fstrcpy(state->response.data.auth.error_string, get_friendly_nt_error_msg(result));
788         state->response.data.auth.pam_error = nt_status_to_pam(result);
789
790         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, 
791               ("NTLM CRAP authentication for user [%s]\\[%s] returned %s (PAM: %d)\n", 
792                name_domain,
793                name_user,
794                state->response.data.auth.nt_status_string,
795                state->response.data.auth.pam_error));         
796
797         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
798 }
799
800 /* Change a user password */
801
802 void winbindd_pam_chauthtok(struct winbindd_cli_state *state)
803 {
804         NTSTATUS result;
805         char *oldpass, *newpass;
806         fstring domain, user;
807         POLICY_HND dom_pol;
808         struct winbindd_domain *contact_domain;
809         struct rpc_pipe_client *cli;
810
811         DEBUG(3, ("[%5lu]: pam chauthtok %s\n", (unsigned long)state->pid,
812                 state->request.data.chauthtok.user));
813
814         /* Setup crap */
815
816         parse_domain_user(state->request.data.chauthtok.user, domain, user);
817
818         if (!(contact_domain = find_domain_from_name(domain))) {
819                 DEBUG(3, ("Cannot change password for [%s] -> [%s]\\[%s] as %s is not a trusted domain\n", 
820                           state->request.data.chauthtok.user, domain, user, domain)); 
821                 result = NT_STATUS_NO_SUCH_USER;
822                 goto done;
823         }
824
825         /* Change password */
826
827         oldpass = state->request.data.chauthtok.oldpass;
828         newpass = state->request.data.chauthtok.newpass;
829
830         /* Get sam handle */
831
832         result = cm_connect_sam(contact_domain, state->mem_ctx, &cli,
833                                 &dom_pol);
834         if (!NT_STATUS_IS_OK(result)) {
835                 DEBUG(1, ("could not get SAM handle on DC for %s\n", domain));
836                 goto done;
837         }
838
839         result = rpccli_samr_chgpasswd_user(cli, state->mem_ctx, user, newpass,
840                                             oldpass);
841
842 done:    
843         state->response.data.auth.nt_status = NT_STATUS_V(result);
844         fstrcpy(state->response.data.auth.nt_status_string, nt_errstr(result));
845         fstrcpy(state->response.data.auth.error_string, nt_errstr(result));
846         state->response.data.auth.pam_error = nt_status_to_pam(result);
847
848         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, 
849               ("Password change for user [%s]\\[%s] returned %s (PAM: %d)\n", 
850                domain,
851                user,
852                state->response.data.auth.nt_status_string,
853                state->response.data.auth.pam_error));         
854
855         if (NT_STATUS_IS_OK(result))
856                 request_ok(state);
857         else
858                 request_error(state);
859 }