r7454: couple of winbindd fixes
[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 enum winbindd_result 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                 return WINBINDD_ERROR;
219         }
220
221         async_domain_request(state->mem_ctx, domain,
222                              &state->request, &state->response,
223                              request_finished_cont, state);
224         return WINBINDD_PENDING;
225 }
226
227 enum winbindd_result winbindd_dual_pam_auth(struct winbindd_domain *domain,
228                                             struct winbindd_cli_state *state) 
229 {
230         NTSTATUS result;
231         fstring name_domain, name_user;
232         const char *srv_name_slash;
233         NET_USER_INFO_3 info3;
234         unsigned char *session_key;
235         struct rpc_pipe_client *pipe_cli;
236         uchar chal[8];
237         DATA_BLOB lm_resp;
238         DATA_BLOB nt_resp;
239         DOM_CRED ret_creds;
240         DOM_CRED *credentials;
241         int attempts = 0;
242         unsigned char local_lm_response[24];
243         unsigned char local_nt_response[24];
244         struct winbindd_domain *contact_domain;
245         BOOL retry;
246
247         /* Ensure null termination */
248         state->request.data.auth.user[sizeof(state->request.data.auth.user)-1]='\0';
249
250         /* Ensure null termination */
251         state->request.data.auth.pass[sizeof(state->request.data.auth.pass)-1]='\0';
252
253         DEBUG(3, ("[%5lu]: pam auth %s\n", (unsigned long)state->pid,
254                   state->request.data.auth.user));
255
256         /* Parse domain and username */
257         
258         parse_domain_user(state->request.data.auth.user, name_domain, name_user);
259
260         /* do password magic */
261         
262
263         generate_random_buffer(chal, 8);
264         if (lp_client_ntlmv2_auth()) {
265                 DATA_BLOB server_chal;
266                 DATA_BLOB names_blob;
267                 DATA_BLOB nt_response;
268                 DATA_BLOB lm_response;
269                 server_chal = data_blob_talloc(state->mem_ctx, chal, 8); 
270                 
271                 /* note that the 'workgroup' here is a best guess - we don't know
272                    the server's domain at this point.  The 'server name' is also
273                    dodgy... 
274                 */
275                 names_blob = NTLMv2_generate_names_blob(global_myname(), lp_workgroup());
276                 
277                 if (!SMBNTLMv2encrypt(name_user, name_domain, 
278                                       state->request.data.auth.pass, 
279                                       &server_chal, 
280                                       &names_blob,
281                                       &lm_response, &nt_response, NULL)) {
282                         data_blob_free(&names_blob);
283                         data_blob_free(&server_chal);
284                         DEBUG(0, ("winbindd_pam_auth: SMBNTLMv2encrypt() failed!\n"));
285                         result = NT_STATUS_NO_MEMORY;
286                         goto done;
287                 }
288                 data_blob_free(&names_blob);
289                 data_blob_free(&server_chal);
290                 lm_resp = data_blob_talloc(state->mem_ctx, lm_response.data,
291                                            lm_response.length);
292                 nt_resp = data_blob_talloc(state->mem_ctx, nt_response.data,
293                                            nt_response.length);
294                 data_blob_free(&lm_response);
295                 data_blob_free(&nt_response);
296
297         } else {
298                 if (lp_client_lanman_auth() 
299                     && SMBencrypt(state->request.data.auth.pass, 
300                                   chal, 
301                                   local_lm_response)) {
302                         lm_resp = data_blob_talloc(state->mem_ctx, 
303                                                    local_lm_response, 
304                                                    sizeof(local_lm_response));
305                 } else {
306                         lm_resp = data_blob(NULL, 0);
307                 }
308                 SMBNTencrypt(state->request.data.auth.pass, 
309                              chal,
310                              local_nt_response);
311
312                 nt_resp = data_blob_talloc(state->mem_ctx, 
313                                            local_nt_response, 
314                                            sizeof(local_nt_response));
315         }
316
317         
318         /* what domain should we contact? */
319         
320         if ( IS_DC ) {
321                 if (!(contact_domain = find_domain_from_name(name_domain))) {
322                         DEBUG(3, ("Authentication for domain for [%s] -> [%s]\\[%s] failed as %s is not a trusted domain\n", 
323                                   state->request.data.auth.user, name_domain, name_user, name_domain)); 
324                         result = NT_STATUS_NO_SUCH_USER;
325                         goto done;
326                 }
327                 
328         } else {
329                 if (is_myname(name_domain)) {
330                         DEBUG(3, ("Authentication for domain %s (local domain to this server) not supported at this stage\n", name_domain));
331                         result =  NT_STATUS_NO_SUCH_USER;
332                         goto done;
333                 }
334
335                 contact_domain = find_our_domain();
336         }
337
338         srv_name_slash = talloc_asprintf(state->mem_ctx, "\\\\%s",
339                                          contact_domain->dcname);
340         if (srv_name_slash == NULL) {
341                 DEBUG(0, ("talloc_asprintf failed\n"));
342                 return WINBINDD_ERROR;
343         }
344                 
345         /* check authentication loop */
346
347         do {
348                 DOM_CRED clnt_creds;
349
350                 ZERO_STRUCT(info3);
351                 ZERO_STRUCT(ret_creds);
352                 retry = False;
353
354                 result = cm_connect_netlogon(contact_domain, state->mem_ctx,
355                                              &pipe_cli, &session_key,
356                                              &credentials);
357
358                 if (!NT_STATUS_IS_OK(result)) {
359                         DEBUG(3, ("could not open handle to NETLOGON pipe\n"));
360                         goto done;
361                 }
362
363                 credentials->timestamp.time = time(NULL);
364                 memcpy(&clnt_creds, credentials, sizeof(clnt_creds));
365
366                 /* Calculate the new credentials. */
367                 cred_create(session_key, &credentials->challenge,
368                             clnt_creds.timestamp, &(clnt_creds.challenge));
369
370                 result = rpccli_netlogon_sam_network_logon(pipe_cli,
371                                                            state->mem_ctx,
372                                                            srv_name_slash,
373                                                            &clnt_creds,
374                                                            &ret_creds,
375                                                            name_user,
376                                                            name_domain, 
377                                                            global_myname(),
378                                                            chal, lm_resp,
379                                                            nt_resp, &info3,
380                                                            session_key);
381                 attempts += 1;
382
383                 /* We have to try a second time as cm_connect_netlogon
384                    might not yet have noticed that the DC has killed
385                    our connection. */
386
387                 if (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)) {
388                         retry = True;
389                         continue;
390                 }
391                 
392                 /* if we get access denied, a possible cause was that we had
393                    and open connection to the DC, but someone changed our
394                    machine account password out from underneath us using 'net
395                    rpc changetrustpw' */
396                    
397                 if ( NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED) ) {
398                         DEBUG(3,("winbindd_pam_auth: sam_logon returned "
399                                  "ACCESS_DENIED.  Maybe the trust account "
400                                 "password was changed and we didn't know it. "
401                                  "Killing connections to domain %s\n",
402                                 name_domain));
403                         invalidate_cm_connection(&contact_domain->conn);
404                         retry = True;
405                 } 
406                 
407         } while ( (attempts < 2) && retry );
408
409         if (NT_STATUS_IS_OK(result) &&
410             (!clnt_deal_with_creds(session_key, credentials,
411                                   &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         if (NT_STATUS_IS_OK(result)) {
418                 netsamlogon_cache_store(state->mem_ctx, name_user, &info3);
419                 wcache_invalidate_samlogon(find_domain_from_name(name_domain), &info3);
420
421                 /* Check if the user is in the right group */
422
423                 if (!NT_STATUS_IS_OK(result = check_info3_in_group(state->mem_ctx, &info3, state->request.data.auth.require_membership_of_sid))) {
424                         DEBUG(3, ("User %s is not in the required group (%s), so plaintext authentication is rejected\n",
425                                   state->request.data.auth.user, 
426                                   state->request.data.auth.require_membership_of_sid));
427                 }
428         }
429
430 done:
431         /* give us a more useful (more correct?) error code */
432         if ((NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) || (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)))) {
433                 result = NT_STATUS_NO_LOGON_SERVERS;
434         }
435         
436         state->response.data.auth.nt_status = NT_STATUS_V(result);
437         fstrcpy(state->response.data.auth.nt_status_string, nt_errstr(result));
438
439         /* we might have given a more useful error above */
440         if (!*state->response.data.auth.error_string) 
441                 fstrcpy(state->response.data.auth.error_string, get_friendly_nt_error_msg(result));
442         state->response.data.auth.pam_error = nt_status_to_pam(result);
443
444         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, ("Plain-text authentication for user %s returned %s (PAM: %d)\n", 
445               state->request.data.auth.user, 
446               state->response.data.auth.nt_status_string,
447               state->response.data.auth.pam_error));          
448
449         if ( NT_STATUS_IS_OK(result) &&
450              (state->request.flags & WBFLAG_PAM_AFS_TOKEN) ) {
451
452                 char *afsname = SMB_STRDUP(lp_afs_username_map());
453                 char *cell;
454
455                 if (afsname == NULL) goto no_token;
456
457                 afsname = realloc_string_sub(afsname, "%D", name_domain);
458                 afsname = realloc_string_sub(afsname, "%u", name_user);
459                 afsname = realloc_string_sub(afsname, "%U", name_user);
460
461                 {
462                         DOM_SID user_sid;
463                         fstring sidstr;
464
465                         sid_copy(&user_sid, &info3.dom_sid.sid);
466                         sid_append_rid(&user_sid, info3.user_rid);
467                         sid_to_string(sidstr, &user_sid);
468                         afsname = realloc_string_sub(afsname, "%s", sidstr);
469                 }
470
471                 if (afsname == NULL) goto no_token;
472
473                 strlower_m(afsname);
474
475                 DEBUG(10, ("Generating token for user %s\n", afsname));
476
477                 cell = strchr(afsname, '@');
478
479                 if (cell == NULL) goto no_token;
480
481                 *cell = '\0';
482                 cell += 1;
483
484                 /* Append an AFS token string */
485                 state->response.extra_data =
486                         afs_createtoken_str(afsname, cell);
487
488                 if (state->response.extra_data != NULL)
489                         state->response.length +=
490                                 strlen(state->response.extra_data)+1;
491
492         no_token:
493                 SAFE_FREE(afsname);
494         }
495                 
496         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
497 }
498
499 /**********************************************************************
500  Challenge Response Authentication Protocol 
501 **********************************************************************/
502
503 enum winbindd_result winbindd_pam_auth_crap(struct winbindd_cli_state *state)
504 {
505         struct winbindd_domain *domain = NULL;
506         const char *domain_name = NULL;
507         NTSTATUS result;
508
509         if (!state->privileged) {
510                 char *error_string = NULL;
511                 DEBUG(2, ("winbindd_pam_auth_crap: non-privileged access "
512                           "denied.  !\n"));
513                 DEBUGADD(2, ("winbindd_pam_auth_crap: Ensure permissions "
514                              "on %s are set correctly.\n",
515                              get_winbind_priv_pipe_dir()));
516                 /* send a better message than ACCESS_DENIED */
517                 error_string = talloc_asprintf(state->mem_ctx,
518                                                "winbind client not authorized "
519                                                "to use winbindd_pam_auth_crap."
520                                                " Ensure permissions on %s "
521                                                "are set correctly.",
522                                                get_winbind_priv_pipe_dir());
523                 fstrcpy(state->response.data.auth.error_string, error_string);
524                 result = NT_STATUS_ACCESS_DENIED;
525                 goto done;
526         }
527
528         /* Ensure null termination */
529         state->request.data.auth_crap.user
530                 [sizeof(state->request.data.auth_crap.user)-1]=0;
531         state->request.data.auth_crap.domain
532                 [sizeof(state->request.data.auth_crap.domain)-1]=0;
533
534         DEBUG(3, ("[%5lu]: pam auth crap domain: [%s] user: %s\n",
535                   (unsigned long)state->pid,
536                   state->request.data.auth_crap.domain,
537                   state->request.data.auth_crap.user));
538
539         if (*state->request.data.auth_crap.domain != '\0') {
540                 domain_name = state->request.data.auth_crap.domain;
541         } else if (lp_winbind_use_default_domain()) {
542                 domain_name = lp_workgroup();
543         }
544
545         if (domain_name != NULL)
546                 domain = find_auth_domain(domain_name);
547
548         if (domain != NULL) {
549                 async_domain_request(state->mem_ctx, domain,
550                                      &state->request, &state->response,
551                                      request_finished_cont, state);
552                 return WINBINDD_PENDING;
553         }
554
555         result = NT_STATUS_NO_SUCH_USER;
556
557  done:
558         set_auth_errors(&state->response, result);
559         DEBUG(5, ("CRAP authentication for %s returned %s (PAM: %d)\n",
560                   state->request.data.auth.user, 
561                   state->response.data.auth.nt_status_string,
562                   state->response.data.auth.pam_error));
563         return WINBINDD_ERROR;
564 }
565
566
567 enum winbindd_result winbindd_dual_pam_auth_crap(struct winbindd_domain *domain,
568                                                  struct winbindd_cli_state *state) 
569 {
570         NTSTATUS result;
571         const char *srv_name_slash;
572         NET_USER_INFO_3 info3;
573         unsigned char *session_key;
574         struct rpc_pipe_client *pipe_cli;
575         DOM_CRED *credentials;
576         const char *name_user = NULL;
577         const char *name_domain = NULL;
578         const char *workstation;
579         struct winbindd_domain *contact_domain;
580         DOM_CRED ret_creds;
581         int attempts = 0;
582         BOOL retry;
583
584         DATA_BLOB lm_resp, nt_resp;
585
586         /* This is child-only, so no check for privileged access is needed
587            anymore */
588
589         /* Ensure null termination */
590         state->request.data.auth_crap.user[sizeof(state->request.data.auth_crap.user)-1]=0;
591         state->request.data.auth_crap.domain[sizeof(state->request.data.auth_crap.domain)-1]=0;
592
593         name_user = state->request.data.auth_crap.user;
594
595         if (*state->request.data.auth_crap.domain) {
596                 name_domain = state->request.data.auth_crap.domain;
597         } else if (lp_winbind_use_default_domain()) {
598                 name_domain = lp_workgroup();
599         } else {
600                 DEBUG(5,("no domain specified with username (%s) - failing auth\n", 
601                          name_user));
602                 result = NT_STATUS_NO_SUCH_USER;
603                 goto done;
604         }
605
606         DEBUG(3, ("[%5lu]: pam auth crap domain: %s user: %s\n", (unsigned long)state->pid,
607                   name_domain, name_user));
608            
609         if (*state->request.data.auth_crap.workstation) {
610                 workstation = state->request.data.auth_crap.workstation;
611         } else {
612                 workstation = global_myname();
613         }
614
615         if (state->request.data.auth_crap.lm_resp_len > sizeof(state->request.data.auth_crap.lm_resp)
616                 || state->request.data.auth_crap.nt_resp_len > sizeof(state->request.data.auth_crap.nt_resp)) {
617                 DEBUG(0, ("winbindd_pam_auth_crap: invalid password length %u/%u\n", 
618                           state->request.data.auth_crap.lm_resp_len, 
619                           state->request.data.auth_crap.nt_resp_len));
620                 result = NT_STATUS_INVALID_PARAMETER;
621                 goto done;
622         }
623
624         lm_resp = data_blob_talloc(state->mem_ctx, state->request.data.auth_crap.lm_resp, state->request.data.auth_crap.lm_resp_len);
625         nt_resp = data_blob_talloc(state->mem_ctx, state->request.data.auth_crap.nt_resp, state->request.data.auth_crap.nt_resp_len);
626         
627
628         /* what domain should we contact? */
629         
630         if ( IS_DC ) {
631                 if (!(contact_domain = find_domain_from_name(name_domain))) {
632                         DEBUG(3, ("Authentication for domain for [%s] -> [%s]\\[%s] failed as %s is not a trusted domain\n", 
633                                   state->request.data.auth_crap.user, name_domain, name_user, name_domain)); 
634                         result = NT_STATUS_NO_SUCH_USER;
635                         goto done;
636                 }
637                 
638         } else {
639                 if (is_myname(name_domain)) {
640                         DEBUG(3, ("Authentication for domain %s (local domain to this server) not supported at this stage\n", name_domain));
641                         result =  NT_STATUS_NO_SUCH_USER;
642                         goto done;
643                 }
644
645                 contact_domain = find_our_domain();
646         }
647
648         srv_name_slash = talloc_asprintf(state->mem_ctx, "\\\\%s",
649                                          contact_domain->dcname);
650         if (srv_name_slash == NULL) {
651                 DEBUG(0, ("talloc_asprintf failed\n"));
652                 return WINBINDD_ERROR;
653         }
654                 
655         do {
656                 DOM_CRED clnt_creds;
657                 ZERO_STRUCT(info3);
658                 ZERO_STRUCT(ret_creds);
659                 retry = False;
660
661                 result = cm_connect_netlogon(contact_domain, state->mem_ctx,
662                                              &pipe_cli, &session_key,
663                                              &credentials);
664
665                 if (!NT_STATUS_IS_OK(result)) {
666                         DEBUG(3, ("could not open handle to NETLOGON pipe (error: %s)\n",
667                                   nt_errstr(result)));
668                         goto done;
669                 }
670
671                 credentials->timestamp.time = time(NULL);
672                 memcpy(&clnt_creds, credentials, sizeof(clnt_creds));
673
674                 /* Calculate the new credentials. */
675                 cred_create(session_key, &credentials->challenge,
676                             clnt_creds.timestamp, &(clnt_creds.challenge));
677
678                 result = rpccli_netlogon_sam_network_logon(pipe_cli,
679                                                            state->mem_ctx,
680                                                            srv_name_slash,
681                                                            &clnt_creds,
682                                                            &ret_creds,
683                                                            name_user,
684                                                            name_domain, 
685                                                            global_myname(),
686                                                            state->request.data.auth_crap.chal,
687                                                            lm_resp,
688                                                            nt_resp, &info3,
689                                                            session_key);
690
691                 attempts += 1;
692
693                 /* We have to try a second time as cm_connect_netlogon
694                    might not yet have noticed that the DC has killed
695                    our connection. */
696
697                 if (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)) {
698                         retry = True;
699                         continue;
700                 }
701
702                 /* if we get access denied, a possible cause was that we had and open
703                    connection to the DC, but someone changed our machine account password
704                    out from underneath us using 'net rpc changetrustpw' */
705                    
706                 if ( NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED) ) {
707                         DEBUG(3,("winbindd_pam_auth: sam_logon returned "
708                                  "ACCESS_DENIED.  Maybe the trust account "
709                                 "password was changed and we didn't know it. "
710                                  "Killing connections to domain %s\n",
711                                 name_domain));
712                         invalidate_cm_connection(&contact_domain->conn);
713                         retry = True;
714                 } 
715
716         } while ( (attempts < 2) && retry );
717
718         if (NT_STATUS_IS_OK(result) &&
719             (!clnt_deal_with_creds(session_key, credentials,
720                                   &ret_creds))) {
721                 DEBUG(3, ("DC %s sent wrong credentials\n",
722                           pipe_cli->cli->srv_name_slash));
723                 result = NT_STATUS_ACCESS_DENIED;
724         }
725
726         if (NT_STATUS_IS_OK(result)) {
727                 netsamlogon_cache_store( state->mem_ctx, name_user, &info3 );
728                 wcache_invalidate_samlogon(find_domain_from_name(name_domain), &info3);
729                 
730                 if (!NT_STATUS_IS_OK(result = check_info3_in_group(state->mem_ctx, &info3, state->request.data.auth_crap.require_membership_of_sid))) {
731                         DEBUG(3, ("User %s is not in the required group (%s), so plaintext authentication is rejected\n",
732                                   state->request.data.auth_crap.user, 
733                                   state->request.data.auth_crap.require_membership_of_sid));
734                         goto done;
735                 }
736
737                 if (state->request.flags & WBFLAG_PAM_INFO3_NDR) {
738                         result = append_info3_as_ndr(state->mem_ctx, state, &info3);
739                 } else if (state->request.flags & WBFLAG_PAM_UNIX_NAME) {
740                         /* ntlm_auth should return the unix username, per 
741                            'winbind use default domain' settings and the like */
742                         
743                         fstring username_out;
744                         const char *nt_username, *nt_domain;
745                         if (!(nt_username = unistr2_tdup(state->mem_ctx, &(info3.uni_user_name)))) {
746                                 /* If the server didn't give us one, just use the one we sent them */
747                                 nt_username = name_user;
748                         }
749                         
750                         if (!(nt_domain = unistr2_tdup(state->mem_ctx, &(info3.uni_logon_dom)))) {
751                                 /* If the server didn't give us one, just use the one we sent them */
752                                 nt_domain = name_domain;
753                         }
754
755                         fill_domain_username(username_out, nt_domain, nt_username);
756
757                         DEBUG(5, ("Setting unix username to [%s]\n", username_out));
758
759                         state->response.extra_data = SMB_STRDUP(username_out);
760                         if (!state->response.extra_data) {
761                                 result = NT_STATUS_NO_MEMORY;
762                                 goto done;
763                         }
764                         state->response.length +=  strlen(state->response.extra_data)+1;
765                 }
766                 
767                 if (state->request.flags & WBFLAG_PAM_USER_SESSION_KEY) {
768                         memcpy(state->response.data.auth.user_session_key, info3.user_sess_key, sizeof(state->response.data.auth.user_session_key) /* 16 */);
769                 }
770                 if (state->request.flags & WBFLAG_PAM_LMKEY) {
771                         memcpy(state->response.data.auth.first_8_lm_hash, info3.lm_sess_key, sizeof(state->response.data.auth.first_8_lm_hash) /* 8 */);
772                 }
773         }
774
775 done:
776         /* give us a more useful (more correct?) error code */
777         if ((NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) || (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)))) {
778                 result = NT_STATUS_NO_LOGON_SERVERS;
779         }
780
781         if (state->request.flags & WBFLAG_PAM_NT_STATUS_SQUASH) {
782                 result = nt_status_squash(result);
783         }
784         
785         state->response.data.auth.nt_status = NT_STATUS_V(result);
786         fstrcpy(state->response.data.auth.nt_status_string, nt_errstr(result));
787         
788         /* we might have given a more useful error above */
789         if (!*state->response.data.auth.error_string) 
790                 fstrcpy(state->response.data.auth.error_string, get_friendly_nt_error_msg(result));
791         state->response.data.auth.pam_error = nt_status_to_pam(result);
792
793         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, 
794               ("NTLM CRAP authentication for user [%s]\\[%s] returned %s (PAM: %d)\n", 
795                name_domain,
796                name_user,
797                state->response.data.auth.nt_status_string,
798                state->response.data.auth.pam_error));         
799
800         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
801 }
802
803 /* Change a user password */
804
805 enum winbindd_result winbindd_pam_chauthtok(struct winbindd_cli_state *state)
806 {
807         NTSTATUS result;
808         char *oldpass, *newpass;
809         fstring domain, user;
810         POLICY_HND dom_pol;
811         struct winbindd_domain *contact_domain;
812         struct rpc_pipe_client *cli;
813
814         DEBUG(3, ("[%5lu]: pam chauthtok %s\n", (unsigned long)state->pid,
815                 state->request.data.chauthtok.user));
816
817         /* Setup crap */
818
819         if (state == NULL)
820                 return WINBINDD_ERROR;
821
822         parse_domain_user(state->request.data.chauthtok.user, domain, user);
823
824         if (!(contact_domain = find_domain_from_name(domain))) {
825                 DEBUG(3, ("Cannot change password for [%s] -> [%s]\\[%s] as %s is not a trusted domain\n", 
826                           state->request.data.chauthtok.user, domain, user, domain)); 
827                 result = NT_STATUS_NO_SUCH_USER;
828                 goto done;
829         }
830
831         /* Change password */
832
833         oldpass = state->request.data.chauthtok.oldpass;
834         newpass = state->request.data.chauthtok.newpass;
835
836         /* Get sam handle */
837
838         result = cm_connect_sam(contact_domain, state->mem_ctx, &cli,
839                                 &dom_pol);
840         if (!NT_STATUS_IS_OK(result)) {
841                 DEBUG(1, ("could not get SAM handle on DC for %s\n", domain));
842                 goto done;
843         }
844
845         result = rpccli_samr_chgpasswd_user(cli, state->mem_ctx, user, newpass,
846                                             oldpass);
847
848 done:    
849         state->response.data.auth.nt_status = NT_STATUS_V(result);
850         fstrcpy(state->response.data.auth.nt_status_string, nt_errstr(result));
851         fstrcpy(state->response.data.auth.error_string, nt_errstr(result));
852         state->response.data.auth.pam_error = nt_status_to_pam(result);
853
854         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, 
855               ("Password change for user [%s]\\[%s] returned %s (PAM: %d)\n", 
856                domain,
857                user,
858                state->response.data.auth.nt_status_string,
859                state->response.data.auth.pam_error));         
860
861         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
862 }