e4acb051b30fee67b049edd58d237f7dacc1f580
[samba.git] / source3 / 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    Copyright (C) Guenther Deschner 2005
10    
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 2 of the License, or
14    (at your option) any later version.
15    
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20    
21    You should have received a copy of the GNU General Public License
22    along with this program; if not, write to the Free Software
23    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 */
25
26 #include "includes.h"
27 #include "winbindd.h"
28 #undef DBGC_CLASS
29 #define DBGC_CLASS DBGC_WINBIND
30
31 static NTSTATUS append_info3_as_txt(TALLOC_CTX *mem_ctx, 
32                                     struct winbindd_cli_state *state, 
33                                     NET_USER_INFO_3 *info3) 
34 {
35         fstring str_sid;
36
37         state->response.data.auth.info3.logon_time = 
38                 nt_time_to_unix(info3->logon_time);
39         state->response.data.auth.info3.logoff_time = 
40                 nt_time_to_unix(info3->logoff_time);
41         state->response.data.auth.info3.kickoff_time = 
42                 nt_time_to_unix(info3->kickoff_time);
43         state->response.data.auth.info3.pass_last_set_time = 
44                 nt_time_to_unix(info3->pass_last_set_time);
45         state->response.data.auth.info3.pass_can_change_time = 
46                 nt_time_to_unix(info3->pass_can_change_time);
47         state->response.data.auth.info3.pass_must_change_time = 
48                 nt_time_to_unix(info3->pass_must_change_time);
49
50         state->response.data.auth.info3.logon_count = info3->logon_count;
51         state->response.data.auth.info3.bad_pw_count = info3->bad_pw_count;
52
53         state->response.data.auth.info3.user_rid = info3->user_rid;
54         state->response.data.auth.info3.group_rid = info3->group_rid;
55         sid_to_string(str_sid, &(info3->dom_sid.sid));
56         fstrcpy(state->response.data.auth.info3.dom_sid, str_sid);
57
58         state->response.data.auth.info3.num_groups = info3->num_groups;
59         state->response.data.auth.info3.user_flgs = info3->user_flgs;
60
61         state->response.data.auth.info3.acct_flags = info3->acct_flags;
62         state->response.data.auth.info3.num_other_sids = info3->num_other_sids;
63
64         unistr2_to_ascii(state->response.data.auth.info3.user_name, 
65                 &info3->uni_user_name, -1);
66         unistr2_to_ascii(state->response.data.auth.info3.full_name, 
67                 &info3->uni_full_name, -1);
68         unistr2_to_ascii(state->response.data.auth.info3.logon_script, 
69                 &info3->uni_logon_script, -1);
70         unistr2_to_ascii(state->response.data.auth.info3.profile_path, 
71                 &info3->uni_profile_path, -1);
72         unistr2_to_ascii(state->response.data.auth.info3.home_dir, 
73                 &info3->uni_home_dir, -1);
74         unistr2_to_ascii(state->response.data.auth.info3.dir_drive, 
75                 &info3->uni_dir_drive, -1);
76
77         unistr2_to_ascii(state->response.data.auth.info3.logon_srv, 
78                 &info3->uni_logon_srv, -1);
79         unistr2_to_ascii(state->response.data.auth.info3.logon_dom, 
80                 &info3->uni_logon_dom, -1);
81
82         return NT_STATUS_OK;
83 }
84
85 static NTSTATUS append_info3_as_ndr(TALLOC_CTX *mem_ctx, 
86                                     struct winbindd_cli_state *state, 
87                                     NET_USER_INFO_3 *info3) 
88 {
89         prs_struct ps;
90         uint32 size;
91         if (!prs_init(&ps, 256 /* Random, non-zero number */, mem_ctx, MARSHALL)) {
92                 return NT_STATUS_NO_MEMORY;
93         }
94         if (!net_io_user_info3("", info3, &ps, 1, 3, False)) {
95                 prs_mem_free(&ps);
96                 return NT_STATUS_UNSUCCESSFUL;
97         }
98
99         size = prs_data_size(&ps);
100         SAFE_FREE(state->response.extra_data.data);
101         state->response.extra_data.data = SMB_MALLOC(size);
102         if (!state->response.extra_data.data) {
103                 prs_mem_free(&ps);
104                 return NT_STATUS_NO_MEMORY;
105         }
106         memset( state->response.extra_data.data, '\0', size );
107         prs_copy_all_data_out((char *)state->response.extra_data.data, &ps);
108         state->response.length += size;
109         prs_mem_free(&ps);
110         return NT_STATUS_OK;
111 }
112
113 static NTSTATUS check_info3_in_group(TALLOC_CTX *mem_ctx, 
114                                      NET_USER_INFO_3 *info3,
115                                      const char *group_sid) 
116 /**
117  * Check whether a user belongs to a group or list of groups.
118  *
119  * @param mem_ctx talloc memory context.
120  * @param info3 user information, including group membership info.
121  * @param group_sid One or more groups , separated by commas.
122  *
123  * @return NT_STATUS_OK on success,
124  *    NT_STATUS_LOGON_FAILURE if the user does not belong,
125  *    or other NT_STATUS_IS_ERR(status) for other kinds of failure.
126  */
127 {
128         DOM_SID *require_membership_of_sid;
129         size_t num_require_membership_of_sid;
130         fstring req_sid;
131         const char *p;
132         DOM_SID sid;
133         size_t i;
134         struct nt_user_token *token;
135         NTSTATUS status;
136
137         /* Parse the 'required group' SID */
138         
139         if (!group_sid || !group_sid[0]) {
140                 /* NO sid supplied, all users may access */
141                 return NT_STATUS_OK;
142         }
143
144         if (!(token = TALLOC_ZERO_P(mem_ctx, struct nt_user_token))) {
145                 DEBUG(0, ("talloc failed\n"));
146                 return NT_STATUS_NO_MEMORY;
147         }
148
149         num_require_membership_of_sid = 0;
150         require_membership_of_sid = NULL;
151
152         p = group_sid;
153
154         while (next_token(&p, req_sid, ",", sizeof(req_sid))) {
155                 if (!string_to_sid(&sid, req_sid)) {
156                         DEBUG(0, ("check_info3_in_group: could not parse %s "
157                                   "as a SID!", req_sid));
158                         return NT_STATUS_INVALID_PARAMETER;
159                 }
160
161                 if (!add_sid_to_array(mem_ctx, &sid,
162                                       &require_membership_of_sid,
163                                       &num_require_membership_of_sid)) {
164                         DEBUG(0, ("add_sid_to_array failed\n"));
165                         return NT_STATUS_NO_MEMORY;
166                 }
167         }
168
169         if (!sid_compose(&sid, &(info3->dom_sid.sid),
170                          info3->user_rid)
171             || !add_sid_to_array(mem_ctx, &sid,
172                                  &token->user_sids, &token->num_sids)) {
173                 DEBUG(3,("could not add user SID from rid 0x%x\n",
174                          info3->user_rid));                     
175                 return NT_STATUS_INVALID_PARAMETER;
176         }
177
178         if (!sid_compose(&sid, &(info3->dom_sid.sid),
179                          info3->group_rid)
180             || !add_sid_to_array(mem_ctx, &sid, 
181                                  &token->user_sids, &token->num_sids)) {
182                 DEBUG(3,("could not append additional group rid 0x%x\n",
183                          info3->group_rid));                    
184                 
185                 return NT_STATUS_INVALID_PARAMETER;
186         }
187
188         for (i = 0; i < info3->num_groups2; i++) {
189                 if (!sid_compose(&sid, &(info3->dom_sid.sid),
190                                  info3->gids[i].g_rid)
191                     || !add_sid_to_array(mem_ctx, &sid,
192                                          &token->user_sids, &token->num_sids)) {
193                         DEBUG(3,("could not append additional group rid 0x%x\n",
194                                  info3->gids[i].g_rid));        
195                         return NT_STATUS_INVALID_PARAMETER;
196                 }
197         }
198
199         /* Copy 'other' sids.  We need to do sid filtering here to
200            prevent possible elevation of privileges.  See:
201
202            http://www.microsoft.com/windows2000/techinfo/administration/security/sidfilter.asp
203          */
204
205         for (i = 0; i < info3->num_other_sids; i++) {
206                 if (!add_sid_to_array(mem_ctx, &info3->other_sids[i].sid,
207                                       &token->user_sids, &token->num_sids)) {
208                         DEBUG(3, ("could not add SID to array: %s\n",
209                                   sid_string_static(&info3->other_sids[i].sid)));
210                         return NT_STATUS_NO_MEMORY;
211                 }
212         }
213
214         if (!NT_STATUS_IS_OK(status = add_aliases(get_global_sam_sid(),
215                                                   token))
216             || !NT_STATUS_IS_OK(status = add_aliases(&global_sid_Builtin,
217                                                      token))) {
218                 DEBUG(3, ("could not add aliases: %s\n",
219                           nt_errstr(status)));
220                 return status;
221         }
222
223         debug_nt_user_token(DBGC_CLASS, 10, token);
224
225         for (i=0; i<num_require_membership_of_sid; i++) {
226                 DEBUG(10, ("Checking SID %s\n", sid_string_static(
227                                    &require_membership_of_sid[i])));
228                 if (nt_token_check_sid(&require_membership_of_sid[i],
229                                        token)) {
230                         DEBUG(10, ("Access ok\n"));
231                         return NT_STATUS_OK;
232                 }
233         }
234         
235         /* Do not distinguish this error from a wrong username/pw */
236
237         return NT_STATUS_LOGON_FAILURE;
238 }
239
240 struct winbindd_domain *find_auth_domain(struct winbindd_cli_state *state, 
241                                         const char *domain_name)
242 {
243         struct winbindd_domain *domain;
244
245         if (IS_DC) {
246                 domain = find_domain_from_name_noinit(domain_name);
247                 if (domain == NULL) {
248                         DEBUG(3, ("Authentication for domain [%s] refused"
249                                   "as it is not a trusted domain\n", 
250                                   domain_name));
251                 }
252                 return domain;
253         }
254
255         if (is_myname(domain_name)) {
256                 DEBUG(3, ("Authentication for domain %s (local domain "
257                           "to this server) not supported at this "
258                           "stage\n", domain_name));
259                 return NULL;
260         }
261
262         /* we can auth against trusted domains */
263         if (state->request.flags & WBFLAG_PAM_CONTACT_TRUSTDOM) {
264                 domain = find_domain_from_name_noinit(domain_name);
265                 if (domain == NULL) {
266                         DEBUG(3, ("Authentication for domain [%s] skipped " 
267                                   "as it is not a trusted domain\n", 
268                                   domain_name));
269                 } else {
270                         return domain;
271                 } 
272                 }
273
274         return find_our_domain();
275 }
276
277 static void set_auth_errors(struct winbindd_response *resp, NTSTATUS result)
278 {
279         resp->data.auth.nt_status = NT_STATUS_V(result);
280         fstrcpy(resp->data.auth.nt_status_string, nt_errstr(result));
281
282         /* we might have given a more useful error above */
283         if (*resp->data.auth.error_string == '\0') 
284                 fstrcpy(resp->data.auth.error_string,
285                         get_friendly_nt_error_msg(result));
286         resp->data.auth.pam_error = nt_status_to_pam(result);
287 }
288
289 static NTSTATUS fillup_password_policy(struct winbindd_domain *domain,
290                                        struct winbindd_cli_state *state)
291 {
292         struct winbindd_methods *methods;
293         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
294         SAM_UNK_INFO_1 password_policy;
295
296         if ( !winbindd_can_contact_domain( domain ) ) {
297                 DEBUG(5,("fillup_password_policy: No inbound trust to "
298                          "contact domain %s\n", domain->name));         
299                 return NT_STATUS_NOT_SUPPORTED;
300         }       
301
302         methods = domain->methods;
303
304         status = methods->password_policy(domain, state->mem_ctx, &password_policy);
305         if (NT_STATUS_IS_ERR(status)) {
306                 return status;
307         }
308
309         state->response.data.auth.policy.min_length_password =
310                 password_policy.min_length_password;
311         state->response.data.auth.policy.password_history =
312                 password_policy.password_history;
313         state->response.data.auth.policy.password_properties =
314                 password_policy.password_properties;
315         state->response.data.auth.policy.expire =
316                 nt_time_to_unix_abs(&(password_policy.expire));
317         state->response.data.auth.policy.min_passwordage = 
318                 nt_time_to_unix_abs(&(password_policy.min_passwordage));
319
320         return NT_STATUS_OK;
321 }
322
323 static NTSTATUS get_max_bad_attempts_from_lockout_policy(struct winbindd_domain *domain, 
324                                                          TALLOC_CTX *mem_ctx, 
325                                                          uint16 *max_allowed_bad_attempts)
326 {
327         struct winbindd_methods *methods;
328         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
329         SAM_UNK_INFO_12 lockout_policy;
330
331         *max_allowed_bad_attempts = 0;
332
333         methods = domain->methods;
334
335         status = methods->lockout_policy(domain, mem_ctx, &lockout_policy);
336         if (NT_STATUS_IS_ERR(status)) {
337                 return status;
338         }
339
340         *max_allowed_bad_attempts = lockout_policy.bad_attempt_lockout;
341
342         return NT_STATUS_OK;
343 }
344
345 static NTSTATUS get_pwd_properties(struct winbindd_domain *domain, 
346                                    TALLOC_CTX *mem_ctx, 
347                                    uint32 *password_properties)
348 {
349         struct winbindd_methods *methods;
350         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
351         SAM_UNK_INFO_1 password_policy;
352
353         *password_properties = 0;
354
355         methods = domain->methods;
356
357         status = methods->password_policy(domain, mem_ctx, &password_policy);
358         if (NT_STATUS_IS_ERR(status)) {
359                 return status;
360         }
361
362         *password_properties = password_policy.password_properties;
363
364         return NT_STATUS_OK;
365 }
366
367 #ifdef HAVE_KRB5
368
369 static const char *generate_krb5_ccache(TALLOC_CTX *mem_ctx, 
370                                         const char *type,
371                                         uid_t uid,
372                                         BOOL *internal_ccache)
373 {
374         /* accept FILE and WRFILE as krb5_cc_type from the client and then
375          * build the full ccname string based on the user's uid here -
376          * Guenther*/
377
378         const char *gen_cc = NULL;
379
380         *internal_ccache = True;
381
382         if (uid == -1) {
383                 goto memory_ccache;
384         }
385
386         if (!type || type[0] == '\0') {
387                 goto memory_ccache;
388         }
389
390         if (strequal(type, "FILE")) {
391                 gen_cc = talloc_asprintf(mem_ctx, "FILE:/tmp/krb5cc_%d", uid);
392         } else if (strequal(type, "WRFILE")) {
393                 gen_cc = talloc_asprintf(mem_ctx, "WRFILE:/tmp/krb5cc_%d", uid);
394         } else {
395                 DEBUG(10,("we don't allow to set a %s type ccache\n", type));
396                 goto memory_ccache;
397         }
398
399         *internal_ccache = False;
400         goto done;
401
402   memory_ccache:
403         gen_cc = talloc_strdup(mem_ctx, "MEMORY:winbindd_pam_ccache");
404
405   done:
406         if (gen_cc == NULL) {
407                 DEBUG(0,("out of memory\n"));
408                 return NULL;
409         }
410
411         DEBUG(10,("using ccache: %s %s\n", gen_cc, *internal_ccache ? "(internal)":""));
412
413         return gen_cc;
414 }
415
416 static void setup_return_cc_name(struct winbindd_cli_state *state, const char *cc)
417 {
418         const char *type = state->request.data.auth.krb5_cc_type;
419
420         state->response.data.auth.krb5ccname[0] = '\0';
421
422         if (type[0] == '\0') {
423                 return;
424         }
425
426         if (!strequal(type, "FILE") &&
427             !strequal(type, "WRFILE")) {
428                 DEBUG(10,("won't return krbccname for a %s type ccache\n", 
429                         type));
430                 return;
431         }
432         
433         fstrcpy(state->response.data.auth.krb5ccname, cc);
434 }
435
436 #endif
437
438 static uid_t get_uid_from_state(struct winbindd_cli_state *state)
439 {
440         uid_t uid = -1;
441
442         uid = state->request.data.auth.uid;
443
444         if (uid < 0) {
445                 DEBUG(1,("invalid uid: '%d'\n", uid));
446                 return -1;
447         }
448         return uid;
449 }
450
451 /**********************************************************************
452  Authenticate a user with a clear text password using Kerberos and fill up
453  ccache if required
454  **********************************************************************/
455
456 static NTSTATUS winbindd_raw_kerberos_login(struct winbindd_domain *domain,
457                                             struct winbindd_cli_state *state,
458                                             NET_USER_INFO_3 **info3)
459 {
460 #ifdef HAVE_KRB5
461         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
462         krb5_error_code krb5_ret;
463         DATA_BLOB tkt, session_key_krb5;
464         DATA_BLOB ap_rep, session_key;
465         PAC_DATA *pac_data = NULL;
466         PAC_LOGON_INFO *logon_info = NULL;
467         char *client_princ = NULL;
468         char *client_princ_out = NULL;
469         char *local_service = NULL;
470         const char *cc = NULL;
471         const char *principal_s = NULL;
472         const char *service = NULL;
473         char *realm = NULL;
474         fstring name_domain, name_user;
475         time_t ticket_lifetime = 0;
476         time_t renewal_until = 0;
477         uid_t uid = -1;
478         ADS_STRUCT *ads;
479         time_t time_offset = 0;
480         BOOL internal_ccache = True;
481
482         ZERO_STRUCT(session_key);
483         ZERO_STRUCT(session_key_krb5);
484         ZERO_STRUCT(tkt);
485         ZERO_STRUCT(ap_rep);
486
487         ZERO_STRUCTP(info3);
488
489         *info3 = NULL;
490         
491         /* 1st step: 
492          * prepare a krb5_cc_cache string for the user */
493
494         uid = get_uid_from_state(state);
495         if (uid == -1) {
496                 DEBUG(0,("no valid uid\n"));
497         }
498
499         cc = generate_krb5_ccache(state->mem_ctx,
500                                   state->request.data.auth.krb5_cc_type,
501                                   state->request.data.auth.uid, 
502                                   &internal_ccache);
503         if (cc == NULL) {
504                 return NT_STATUS_NO_MEMORY;
505         }
506
507
508         /* 2nd step: 
509          * get kerberos properties */
510         
511         if (domain->private_data) {
512                 ads = (ADS_STRUCT *)domain->private_data;
513                 time_offset = ads->auth.time_offset; 
514         }
515
516
517         /* 3rd step: 
518          * do kerberos auth and setup ccache as the user */
519
520         parse_domain_user(state->request.data.auth.user, name_domain, name_user);
521
522         realm = domain->alt_name;
523         strupper_m(realm);
524         
525         principal_s = talloc_asprintf(state->mem_ctx, "%s@%s", name_user, realm); 
526         if (principal_s == NULL) {
527                 return NT_STATUS_NO_MEMORY;
528         }
529
530         service = talloc_asprintf(state->mem_ctx, "%s/%s@%s", KRB5_TGS_NAME, realm, realm);
531         if (service == NULL) {
532                 return NT_STATUS_NO_MEMORY;
533         }
534
535         /* if this is a user ccache, we need to act as the user to let the krb5
536          * library handle the chown, etc. */
537
538         /************************ NON-ROOT **********************/
539
540         if (!internal_ccache) {
541
542                 set_effective_uid(uid);
543                 DEBUG(10,("winbindd_raw_kerberos_login: uid is %d\n", uid));
544         }
545
546         krb5_ret = kerberos_kinit_password_ext(principal_s, 
547                                                state->request.data.auth.pass, 
548                                                time_offset, 
549                                                &ticket_lifetime,
550                                                &renewal_until,
551                                                cc, 
552                                                True,
553                                                True,
554                                                WINBINDD_PAM_AUTH_KRB5_RENEW_TIME,
555                                                &result);
556
557         if (krb5_ret) {
558                 DEBUG(1,("winbindd_raw_kerberos_login: kinit failed for '%s' with: %s (%d)\n", 
559                         principal_s, error_message(krb5_ret), krb5_ret));
560                 goto failed;
561         }
562
563         /* does http_timestring use heimdals libroken strftime?? - Guenther */
564         DEBUG(10,("got TGT for %s in %s (valid until: %s (%d), renewable till: %s (%d))\n", 
565                 principal_s, cc, 
566                 http_timestring(ticket_lifetime), (int)ticket_lifetime, 
567                 http_timestring(renewal_until), (int)renewal_until));
568
569         client_princ = talloc_strdup(state->mem_ctx, global_myname());
570         if (client_princ == NULL) {
571                 result = NT_STATUS_NO_MEMORY;
572                 goto failed;
573         }
574         strlower_m(client_princ);
575
576         local_service = talloc_asprintf(state->mem_ctx, "%s$@%s", client_princ, lp_realm());
577         if (local_service == NULL) {
578                 DEBUG(0,("winbindd_raw_kerberos_login: out of memory\n"));
579                 result = NT_STATUS_NO_MEMORY;
580                 goto failed;
581         }
582
583         krb5_ret = cli_krb5_get_ticket(local_service, 
584                                        time_offset, 
585                                        &tkt, 
586                                        &session_key_krb5, 
587                                        0, 
588                                        cc,
589                                        NULL);
590         if (krb5_ret) {
591                 DEBUG(1,("winbindd_raw_kerberos_login: failed to get ticket for %s: %s\n", 
592                         local_service, error_message(krb5_ret)));
593                 result = krb5_to_nt_status(krb5_ret);
594                 goto failed;
595         }
596
597         if (!internal_ccache) {
598                 gain_root_privilege();
599         }
600
601         /************************ NON-ROOT **********************/
602
603         result = ads_verify_ticket(state->mem_ctx, 
604                                    lp_realm(), 
605                                    time_offset,
606                                    &tkt, 
607                                    &client_princ_out, 
608                                    &pac_data, 
609                                    &ap_rep, 
610                                    &session_key);       
611         if (!NT_STATUS_IS_OK(result)) {
612                 DEBUG(0,("winbindd_raw_kerberos_login: ads_verify_ticket failed: %s\n", 
613                         nt_errstr(result)));
614                 goto failed;
615         }
616
617         if (!pac_data) {
618                 DEBUG(3,("winbindd_raw_kerberos_login: no pac data\n"));
619                 result = NT_STATUS_INVALID_PARAMETER;
620                 goto failed;
621         }
622                         
623         logon_info = get_logon_info_from_pac(pac_data);
624         if (logon_info == NULL) {
625                 DEBUG(1,("winbindd_raw_kerberos_login: no logon info\n"));
626                 result = NT_STATUS_INVALID_PARAMETER;
627                 goto failed;
628         }
629
630         DEBUG(10,("winbindd_raw_kerberos_login: winbindd validated ticket of %s\n", 
631                 local_service));
632
633
634         /* last step: 
635          * put results together */
636
637         *info3 = &logon_info->info3;
638
639         /* if we had a user's ccache then return that string for the pam
640          * environment */
641
642         if (!internal_ccache) {
643                 
644                 setup_return_cc_name(state, cc);
645
646                 result = add_ccache_to_list(principal_s,
647                                             cc,
648                                             service,
649                                             state->request.data.auth.user,
650                                             realm,
651                                             uid,
652                                             time(NULL),
653                                             ticket_lifetime,
654                                             renewal_until, 
655                                             False);
656
657                 if (!NT_STATUS_IS_OK(result)) {
658                         DEBUG(10,("winbindd_raw_kerberos_login: failed to add ccache to list: %s\n", 
659                                 nt_errstr(result)));
660                 }
661         } else {
662
663                 /* need to delete the memory cred cache, it is not used anymore */
664
665                 krb5_ret = ads_kdestroy(cc);
666                 if (krb5_ret) {
667                         DEBUG(3,("winbindd_raw_kerberos_login: "
668                                  "could not destroy krb5 credential cache: "
669                                  "%s\n", error_message(krb5_ret)));
670                 }
671
672         }
673
674         result = NT_STATUS_OK;
675
676         goto done;
677
678 failed:
679
680         /* we could have created a new credential cache with a valid tgt in it
681          * but we werent able to get or verify the service ticket for this
682          * local host and therefor didn't get the PAC, we need to remove that
683          * cache entirely now */
684
685         krb5_ret = ads_kdestroy(cc);
686         if (krb5_ret) {
687                 DEBUG(3,("winbindd_raw_kerberos_login: "
688                          "could not destroy krb5 credential cache: "
689                          "%s\n", error_message(krb5_ret)));
690         }
691
692         if (!NT_STATUS_IS_OK(remove_ccache(state->request.data.auth.user))) {
693                 DEBUG(3,("winbindd_raw_kerberos_login: "
694                           "could not remove ccache for user %s\n",
695                         state->request.data.auth.user));
696         }
697
698 done:
699         data_blob_free(&session_key);
700         data_blob_free(&session_key_krb5);
701         data_blob_free(&ap_rep);
702         data_blob_free(&tkt);
703
704         SAFE_FREE(client_princ_out);
705
706         if (!internal_ccache) {
707                 gain_root_privilege();
708         }
709
710         return result;
711 #else 
712         return NT_STATUS_NOT_SUPPORTED;
713 #endif /* HAVE_KRB5 */
714 }
715
716 void winbindd_pam_auth(struct winbindd_cli_state *state)
717 {
718         struct winbindd_domain *domain;
719         fstring name_domain, name_user;
720
721         /* Ensure null termination */
722         state->request.data.auth.user
723                 [sizeof(state->request.data.auth.user)-1]='\0';
724
725         /* Ensure null termination */
726         state->request.data.auth.pass
727                 [sizeof(state->request.data.auth.pass)-1]='\0';
728
729         DEBUG(3, ("[%5lu]: pam auth %s\n", (unsigned long)state->pid,
730                   state->request.data.auth.user));
731
732         /* Parse domain and username */
733         
734         ws_name_return( state->request.data.auth.user, WB_REPLACE_CHAR );
735
736         if (!canonicalize_username(state->request.data.auth.user,
737                                name_domain, name_user)) {
738                 set_auth_errors(&state->response, NT_STATUS_NO_SUCH_USER);
739                 DEBUG(5, ("Plain text authentication for %s returned %s "
740                           "(PAM: %d)\n",
741                           state->request.data.auth.user, 
742                           state->response.data.auth.nt_status_string,
743                           state->response.data.auth.pam_error));
744                 request_error(state);
745                 return;
746         }
747
748         domain = find_auth_domain(state, name_domain);
749
750         if (domain == NULL) {
751                 set_auth_errors(&state->response, NT_STATUS_NO_SUCH_USER);
752                 DEBUG(5, ("Plain text authentication for %s returned %s "
753                           "(PAM: %d)\n",
754                           state->request.data.auth.user, 
755                           state->response.data.auth.nt_status_string,
756                           state->response.data.auth.pam_error));
757                 request_error(state);
758                 return;
759         }
760
761         sendto_domain(state, domain);
762 }
763
764 NTSTATUS winbindd_dual_pam_auth_cached(struct winbindd_domain *domain,
765                                        struct winbindd_cli_state *state,
766                                        NET_USER_INFO_3 **info3)
767 {
768         NTSTATUS result = NT_STATUS_LOGON_FAILURE;
769         uint16 max_allowed_bad_attempts; 
770         fstring name_domain, name_user;
771         DOM_SID sid;
772         enum lsa_SidType type;
773         uchar new_nt_pass[NT_HASH_LEN];
774         const uint8 *cached_nt_pass;
775         const uint8 *cached_salt;
776         NET_USER_INFO_3 *my_info3;
777         time_t kickoff_time, must_change_time;
778         BOOL password_good = False;
779
780         *info3 = NULL;
781
782         ZERO_STRUCTP(info3);
783
784         DEBUG(10,("winbindd_dual_pam_auth_cached\n"));
785
786         /* Parse domain and username */
787         
788         parse_domain_user(state->request.data.auth.user, name_domain, name_user);
789
790
791         if (!lookup_cached_name(state->mem_ctx,
792                                 name_domain,
793                                 name_user,
794                                 &sid,
795                                 &type)) {
796                 DEBUG(10,("winbindd_dual_pam_auth_cached: no such user in the cache\n"));
797                 return NT_STATUS_NO_SUCH_USER;
798         }
799
800         if (type != SID_NAME_USER) {
801                 DEBUG(10,("winbindd_dual_pam_auth_cached: not a user (%s)\n", sid_type_lookup(type)));
802                 return NT_STATUS_LOGON_FAILURE;
803         }
804
805         result = winbindd_get_creds(domain, 
806                                     state->mem_ctx, 
807                                     &sid, 
808                                     &my_info3, 
809                                     &cached_nt_pass,
810                                     &cached_salt);
811         if (!NT_STATUS_IS_OK(result)) {
812                 DEBUG(10,("winbindd_dual_pam_auth_cached: failed to get creds: %s\n", nt_errstr(result)));
813                 return result;
814         }
815
816         *info3 = my_info3;
817
818         E_md4hash(state->request.data.auth.pass, new_nt_pass);
819
820 #if DEBUG_PASSWORD
821         dump_data(100, new_nt_pass, NT_HASH_LEN);
822         dump_data(100, cached_nt_pass, NT_HASH_LEN);
823         if (cached_salt) {
824                 dump_data(100, cached_salt, NT_HASH_LEN);
825         }
826 #endif
827
828         if (cached_salt) {
829                 /* In this case we didn't store the nt_hash itself,
830                    but the MD5 combination of salt + nt_hash. */
831                 uchar salted_hash[NT_HASH_LEN];
832                 E_md5hash(cached_salt, new_nt_pass, salted_hash);
833
834                 password_good = (memcmp(cached_nt_pass, salted_hash, NT_HASH_LEN) == 0) ?
835                         True : False;
836         } else {
837                 /* Old cached cred - direct store of nt_hash (bad bad bad !). */
838                 password_good = (memcmp(cached_nt_pass, new_nt_pass, NT_HASH_LEN) == 0) ?
839                         True : False;
840         }
841
842         if (password_good) {
843
844                 /* User *DOES* know the password, update logon_time and reset
845                  * bad_pw_count */
846         
847                 my_info3->user_flgs |= LOGON_CACHED_ACCOUNT;
848         
849                 if (my_info3->acct_flags & ACB_AUTOLOCK) {
850                         return NT_STATUS_ACCOUNT_LOCKED_OUT;
851                 }
852         
853                 if (my_info3->acct_flags & ACB_DISABLED) {
854                         return NT_STATUS_ACCOUNT_DISABLED;
855                 }
856         
857                 if (my_info3->acct_flags & ACB_WSTRUST) {
858                         return NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT;
859                 }
860         
861                 if (my_info3->acct_flags & ACB_SVRTRUST) {
862                         return NT_STATUS_NOLOGON_SERVER_TRUST_ACCOUNT;
863                 }
864         
865                 if (my_info3->acct_flags & ACB_DOMTRUST) {
866                         return NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT;
867                 }
868
869                 if (!(my_info3->acct_flags & ACB_NORMAL)) {
870                         DEBUG(0,("winbindd_dual_pam_auth_cached: whats wrong with that one?: 0x%08x\n", 
871                                 my_info3->acct_flags));
872                         return NT_STATUS_LOGON_FAILURE;
873                 }
874
875                 kickoff_time = nt_time_to_unix(my_info3->kickoff_time);
876                 if (kickoff_time != 0 && time(NULL) > kickoff_time) {
877                         return NT_STATUS_ACCOUNT_EXPIRED;
878                 }
879
880                 must_change_time = nt_time_to_unix(my_info3->pass_must_change_time);
881                 if (must_change_time != 0 && must_change_time < time(NULL)) {
882                         /* we allow grace logons when the password has expired */
883                         my_info3->user_flgs |= LOGON_GRACE_LOGON;
884                         /* return NT_STATUS_PASSWORD_EXPIRED; */
885                         goto success;
886                 }
887         
888 #ifdef HAVE_KRB5
889                 /* FIXME: what else points out that the remote domain is AD ? */
890                 if (!strequal(domain->name, domain->alt_name) &&
891                     (state->request.flags & WBFLAG_PAM_KRB5)) {
892
893                         uid_t uid = -1;
894                         const char *cc = NULL;
895                         char *realm = NULL;
896                         const char *principal_s = NULL;
897                         const char *service = NULL;
898                         BOOL internal_ccache = False;
899
900                         uid = get_uid_from_state(state);
901                         if (uid == -1) {
902                                 DEBUG(0,("winbindd_dual_pam_auth_cached: invalid uid\n"));
903                                 return NT_STATUS_INVALID_PARAMETER;
904                         }
905
906                         cc = generate_krb5_ccache(state->mem_ctx,
907                                                 state->request.data.auth.krb5_cc_type,
908                                                 state->request.data.auth.uid,
909                                                 &internal_ccache);
910                         if (cc == NULL) {
911                                 return NT_STATUS_NO_MEMORY;
912                         }
913
914                         realm = domain->alt_name;
915                         strupper_m(realm);
916
917                         principal_s = talloc_asprintf(state->mem_ctx, "%s@%s", name_user, realm);
918                         if (principal_s == NULL) {
919                                 return NT_STATUS_NO_MEMORY;
920                         }
921
922                         service = talloc_asprintf(state->mem_ctx, "%s/%s@%s", KRB5_TGS_NAME, realm, realm);
923                         if (service == NULL) {
924                                 return NT_STATUS_NO_MEMORY;
925                         }
926
927                         if (!internal_ccache) {
928
929                                 setup_return_cc_name(state, cc);
930
931                                 result = add_ccache_to_list(principal_s,
932                                                             cc,
933                                                             service,
934                                                             state->request.data.auth.user,
935                                                             domain->alt_name,
936                                                             uid,
937                                                             time(NULL),
938                                                             time(NULL) + lp_winbind_cache_time(),
939                                                             time(NULL) + WINBINDD_PAM_AUTH_KRB5_RENEW_TIME,
940                                                             True);
941
942                                 if (!NT_STATUS_IS_OK(result)) {
943                                         DEBUG(10,("winbindd_dual_pam_auth_cached: failed "
944                                                 "to add ccache to list: %s\n",
945                                                 nt_errstr(result)));
946                                 }
947                         }
948                 }
949 #endif /* HAVE_KRB5 */
950  success:
951                 /* FIXME: we possibly should handle logon hours as well (does xp when
952                  * offline?) see auth/auth_sam.c:sam_account_ok for details */
953
954                 unix_to_nt_time(&my_info3->logon_time, time(NULL));
955                 my_info3->bad_pw_count = 0;
956
957                 result = winbindd_update_creds_by_info3(domain,
958                                                         state->mem_ctx,
959                                                         state->request.data.auth.user,
960                                                         state->request.data.auth.pass,
961                                                         my_info3);
962                 if (!NT_STATUS_IS_OK(result)) {
963                         DEBUG(1,("winbindd_dual_pam_auth_cached: failed to update creds: %s\n",
964                                 nt_errstr(result)));
965                         return result;
966                 }
967
968                 return NT_STATUS_OK;
969
970         }
971
972         /* User does *NOT* know the correct password, modify info3 accordingly */
973
974         /* failure of this is not critical */
975         result = get_max_bad_attempts_from_lockout_policy(domain, state->mem_ctx, &max_allowed_bad_attempts);
976         if (!NT_STATUS_IS_OK(result)) {
977                 DEBUG(10,("winbindd_dual_pam_auth_cached: failed to get max_allowed_bad_attempts. "
978                           "Won't be able to honour account lockout policies\n"));
979         }
980
981         /* increase counter */
982         my_info3->bad_pw_count++;
983
984         if (max_allowed_bad_attempts == 0) {
985                 goto failed;
986         }
987
988         /* lockout user */
989         if (my_info3->bad_pw_count >= max_allowed_bad_attempts) {
990
991                 uint32 password_properties;
992
993                 result = get_pwd_properties(domain, state->mem_ctx, &password_properties);
994                 if (!NT_STATUS_IS_OK(result)) {
995                         DEBUG(10,("winbindd_dual_pam_auth_cached: failed to get password properties.\n"));
996                 }
997
998                 if ((my_info3->user_rid != DOMAIN_USER_RID_ADMIN) || 
999                     (password_properties & DOMAIN_LOCKOUT_ADMINS)) {
1000                         my_info3->acct_flags |= ACB_AUTOLOCK;
1001                 }
1002         }
1003
1004 failed:
1005         result = winbindd_update_creds_by_info3(domain,
1006                                                 state->mem_ctx,
1007                                                 state->request.data.auth.user,
1008                                                 NULL,
1009                                                 my_info3);
1010
1011         if (!NT_STATUS_IS_OK(result)) {
1012                 DEBUG(0,("winbindd_dual_pam_auth_cached: failed to update creds %s\n", 
1013                         nt_errstr(result)));
1014         }
1015
1016         return NT_STATUS_LOGON_FAILURE;
1017 }
1018
1019 NTSTATUS winbindd_dual_pam_auth_kerberos(struct winbindd_domain *domain,
1020                                          struct winbindd_cli_state *state, 
1021                                          NET_USER_INFO_3 **info3)
1022 {
1023         struct winbindd_domain *contact_domain;
1024         fstring name_domain, name_user;
1025         NTSTATUS result;
1026
1027         DEBUG(10,("winbindd_dual_pam_auth_kerberos\n"));
1028         
1029         /* Parse domain and username */
1030         
1031         parse_domain_user(state->request.data.auth.user, name_domain, name_user);
1032
1033         /* what domain should we contact? */
1034         
1035         if ( IS_DC ) {
1036                 if (!(contact_domain = find_domain_from_name(name_domain))) {
1037                         DEBUG(3, ("Authentication for domain for [%s] -> [%s]\\[%s] failed as %s is not a trusted domain\n", 
1038                                   state->request.data.auth.user, name_domain, name_user, name_domain)); 
1039                         result = NT_STATUS_NO_SUCH_USER;
1040                         goto done;
1041                 }
1042                 
1043         } else {
1044                 if (is_myname(name_domain)) {
1045                         DEBUG(3, ("Authentication for domain %s (local domain to this server) not supported at this stage\n", name_domain));
1046                         result =  NT_STATUS_NO_SUCH_USER;
1047                         goto done;
1048                 }
1049                 
1050                 contact_domain = find_domain_from_name(name_domain);
1051                 if (contact_domain == NULL) {
1052                         DEBUG(3, ("Authentication for domain for [%s] -> [%s]\\[%s] failed as %s is not a trusted domain\n", 
1053                                   state->request.data.auth.user, name_domain, name_user, name_domain)); 
1054
1055                         contact_domain = find_our_domain();
1056                 }
1057         }
1058
1059         if (contact_domain->initialized && 
1060             contact_domain->active_directory) {
1061                 goto try_login;
1062         }
1063
1064         if (!contact_domain->initialized) {
1065                 init_dc_connection(contact_domain);
1066         }
1067
1068         if (!contact_domain->active_directory) {
1069                 DEBUG(3,("krb5 auth requested but domain is not Active Directory\n"));
1070                 return NT_STATUS_INVALID_LOGON_TYPE;
1071         }
1072 try_login:
1073         result = winbindd_raw_kerberos_login(contact_domain, state, info3);
1074 done:
1075         return result;
1076 }
1077
1078 NTSTATUS winbindd_dual_pam_auth_samlogon(struct winbindd_domain *domain,
1079                                          struct winbindd_cli_state *state,
1080                                          NET_USER_INFO_3 **info3)
1081 {
1082
1083         struct rpc_pipe_client *netlogon_pipe;
1084         uchar chal[8];
1085         DATA_BLOB lm_resp;
1086         DATA_BLOB nt_resp;
1087         int attempts = 0;
1088         unsigned char local_lm_response[24];
1089         unsigned char local_nt_response[24];
1090         struct winbindd_domain *contact_domain;
1091         fstring name_domain, name_user;
1092         BOOL retry;
1093         NTSTATUS result;
1094         NET_USER_INFO_3 *my_info3;
1095
1096         ZERO_STRUCTP(info3);
1097
1098         *info3 = NULL;
1099
1100         my_info3 = TALLOC_ZERO_P(state->mem_ctx, NET_USER_INFO_3);
1101         if (my_info3 == NULL) {
1102                 return NT_STATUS_NO_MEMORY;
1103         }
1104
1105
1106         DEBUG(10,("winbindd_dual_pam_auth_samlogon\n"));
1107         
1108         /* Parse domain and username */
1109         
1110         parse_domain_user(state->request.data.auth.user, name_domain, name_user);
1111
1112         /* do password magic */
1113         
1114
1115         generate_random_buffer(chal, 8);
1116         if (lp_client_ntlmv2_auth()) {
1117                 DATA_BLOB server_chal;
1118                 DATA_BLOB names_blob;
1119                 DATA_BLOB nt_response;
1120                 DATA_BLOB lm_response;
1121                 server_chal = data_blob_talloc(state->mem_ctx, chal, 8); 
1122                 
1123                 /* note that the 'workgroup' here is a best guess - we don't know
1124                    the server's domain at this point.  The 'server name' is also
1125                    dodgy... 
1126                 */
1127                 names_blob = NTLMv2_generate_names_blob(global_myname(), lp_workgroup());
1128                 
1129                 if (!SMBNTLMv2encrypt(name_user, name_domain, 
1130                                       state->request.data.auth.pass, 
1131                                       &server_chal, 
1132                                       &names_blob,
1133                                       &lm_response, &nt_response, NULL)) {
1134                         data_blob_free(&names_blob);
1135                         data_blob_free(&server_chal);
1136                         DEBUG(0, ("winbindd_pam_auth: SMBNTLMv2encrypt() failed!\n"));
1137                         result = NT_STATUS_NO_MEMORY;
1138                         goto done;
1139                 }
1140                 data_blob_free(&names_blob);
1141                 data_blob_free(&server_chal);
1142                 lm_resp = data_blob_talloc(state->mem_ctx, lm_response.data,
1143                                            lm_response.length);
1144                 nt_resp = data_blob_talloc(state->mem_ctx, nt_response.data,
1145                                            nt_response.length);
1146                 data_blob_free(&lm_response);
1147                 data_blob_free(&nt_response);
1148
1149         } else {
1150                 if (lp_client_lanman_auth() 
1151                     && SMBencrypt(state->request.data.auth.pass, 
1152                                   chal, 
1153                                   local_lm_response)) {
1154                         lm_resp = data_blob_talloc(state->mem_ctx, 
1155                                                    local_lm_response, 
1156                                                    sizeof(local_lm_response));
1157                 } else {
1158                         lm_resp = data_blob(NULL, 0);
1159                 }
1160                 SMBNTencrypt(state->request.data.auth.pass, 
1161                              chal,
1162                              local_nt_response);
1163
1164                 nt_resp = data_blob_talloc(state->mem_ctx, 
1165                                            local_nt_response, 
1166                                            sizeof(local_nt_response));
1167         }
1168         
1169         /* what domain should we contact? */
1170         
1171         if ( IS_DC ) {
1172                 if (!(contact_domain = find_domain_from_name(name_domain))) {
1173                         DEBUG(3, ("Authentication for domain for [%s] -> [%s]\\[%s] failed as %s is not a trusted domain\n", 
1174                                   state->request.data.auth.user, name_domain, name_user, name_domain)); 
1175                         result = NT_STATUS_NO_SUCH_USER;
1176                         goto done;
1177                 }
1178                 
1179         } else {
1180                 if (is_myname(name_domain)) {
1181                         DEBUG(3, ("Authentication for domain %s (local domain to this server) not supported at this stage\n", name_domain));
1182                         result =  NT_STATUS_NO_SUCH_USER;
1183                         goto done;
1184                 }
1185
1186                 contact_domain = find_our_domain();
1187         }
1188
1189         /* check authentication loop */
1190
1191         do {
1192
1193                 ZERO_STRUCTP(my_info3);
1194                 retry = False;
1195
1196                 result = cm_connect_netlogon(contact_domain, &netlogon_pipe);
1197
1198                 if (!NT_STATUS_IS_OK(result)) {
1199                         DEBUG(3, ("could not open handle to NETLOGON pipe\n"));
1200                         goto done;
1201                 }
1202
1203                 result = rpccli_netlogon_sam_network_logon(netlogon_pipe,
1204                                                            state->mem_ctx,
1205                                                            0,
1206                                                            contact_domain->dcname, /* server name */
1207                                                            name_user,              /* user name */
1208                                                            name_domain,            /* target domain */
1209                                                            global_myname(),        /* workstation */
1210                                                            chal,
1211                                                            lm_resp,
1212                                                            nt_resp,
1213                                                            my_info3);
1214                 attempts += 1;
1215
1216                 /* We have to try a second time as cm_connect_netlogon
1217                    might not yet have noticed that the DC has killed
1218                    our connection. */
1219
1220                 if (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)) {
1221                         retry = True;
1222                         continue;
1223                 }
1224                 
1225                 /* if we get access denied, a possible cause was that we had
1226                    and open connection to the DC, but someone changed our
1227                    machine account password out from underneath us using 'net
1228                    rpc changetrustpw' */
1229                    
1230                 if ( NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED) ) {
1231                         DEBUG(3,("winbindd_pam_auth: sam_logon returned "
1232                                  "ACCESS_DENIED.  Maybe the trust account "
1233                                 "password was changed and we didn't know it. "
1234                                  "Killing connections to domain %s\n",
1235                                 name_domain));
1236                         invalidate_cm_connection(&contact_domain->conn);
1237                         retry = True;
1238                 } 
1239                 
1240         } while ( (attempts < 2) && retry );
1241
1242         /* handle the case where a NT4 DC does not fill in the acct_flags in
1243          * the samlogon reply info3. When accurate info3 is required by the
1244          * caller, we look up the account flags ourselve - gd */
1245
1246         if ((state->request.flags & WBFLAG_PAM_INFO3_TEXT) && 
1247             (my_info3->acct_flags == 0) && NT_STATUS_IS_OK(result)) {
1248
1249                 struct rpc_pipe_client *samr_pipe;
1250                 POLICY_HND samr_domain_handle, user_pol;
1251                 SAM_USERINFO_CTR *user_ctr;
1252                 NTSTATUS status_tmp;
1253                 uint32 acct_flags;
1254
1255                 ZERO_STRUCT(user_ctr);
1256
1257                 status_tmp = cm_connect_sam(contact_domain, state->mem_ctx, 
1258                                             &samr_pipe, &samr_domain_handle);
1259
1260                 if (!NT_STATUS_IS_OK(status_tmp)) {
1261                         DEBUG(3, ("could not open handle to SAMR pipe: %s\n", 
1262                                 nt_errstr(status_tmp)));
1263                         goto done;
1264                 }
1265
1266                 status_tmp = rpccli_samr_open_user(samr_pipe, state->mem_ctx, 
1267                                                    &samr_domain_handle,
1268                                                    MAXIMUM_ALLOWED_ACCESS,
1269                                                    my_info3->user_rid, &user_pol);
1270
1271                 if (!NT_STATUS_IS_OK(status_tmp)) {
1272                         DEBUG(3, ("could not open user handle on SAMR pipe: %s\n",
1273                                 nt_errstr(status_tmp)));
1274                         goto done;
1275                 }
1276
1277                 status_tmp = rpccli_samr_query_userinfo(samr_pipe, state->mem_ctx, 
1278                                                         &user_pol, 16, &user_ctr);
1279
1280                 if (!NT_STATUS_IS_OK(status_tmp)) {
1281                         DEBUG(3, ("could not query user info on SAMR pipe: %s\n",
1282                                 nt_errstr(status_tmp)));
1283                         rpccli_samr_close(samr_pipe, state->mem_ctx, &user_pol);
1284                         goto done;
1285                 }
1286
1287                 acct_flags = user_ctr->info.id16->acb_info;
1288
1289                 if (acct_flags == 0) {
1290                         rpccli_samr_close(samr_pipe, state->mem_ctx, &user_pol);
1291                         goto done;
1292                 }
1293
1294                 my_info3->acct_flags = acct_flags;
1295
1296                 DEBUG(10,("successfully retrieved acct_flags 0x%x\n", acct_flags));
1297
1298                 rpccli_samr_close(samr_pipe, state->mem_ctx, &user_pol);
1299         }
1300
1301         *info3 = my_info3;
1302 done:
1303         return result;
1304 }
1305
1306 enum winbindd_result winbindd_dual_pam_auth(struct winbindd_domain *domain,
1307                                             struct winbindd_cli_state *state) 
1308 {
1309         NTSTATUS result = NT_STATUS_LOGON_FAILURE;
1310         NTSTATUS krb5_result = NT_STATUS_OK;    
1311         fstring name_domain, name_user;
1312         NET_USER_INFO_3 *info3 = NULL;
1313         
1314         /* Ensure null termination */
1315         state->request.data.auth.user[sizeof(state->request.data.auth.user)-1]='\0';
1316
1317         /* Ensure null termination */
1318         state->request.data.auth.pass[sizeof(state->request.data.auth.pass)-1]='\0';
1319
1320         DEBUG(3, ("[%5lu]: dual pam auth %s\n", (unsigned long)state->pid,
1321                   state->request.data.auth.user));
1322
1323         /* Parse domain and username */
1324         
1325         ws_name_return( state->request.data.auth.user, WB_REPLACE_CHAR );
1326
1327         parse_domain_user(state->request.data.auth.user, name_domain, name_user);
1328
1329         if (domain->online == False) {
1330                 result = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1331                 if (domain->startup) {
1332                         /* Logons are very important to users. If we're offline and
1333                            we get a request within the first 30 seconds of startup,
1334                            try very hard to find a DC and go online. */
1335
1336                         DEBUG(10,("winbindd_dual_pam_auth: domain: %s offline and auth "
1337                                 "request in startup mode.\n", domain->name ));
1338
1339                         winbindd_flush_negative_conn_cache(domain);
1340                         result = init_dc_connection(domain);
1341                 }
1342         }
1343
1344         DEBUG(10,("winbindd_dual_pam_auth: domain: %s last was %s\n", domain->name, domain->online ? "online":"offline"));
1345
1346         /* Check for Kerberos authentication */
1347         if (domain->online && (state->request.flags & WBFLAG_PAM_KRB5)) {
1348         
1349                 result = winbindd_dual_pam_auth_kerberos(domain, state, &info3);
1350                 /* save for later */
1351                 krb5_result = result;
1352                 
1353
1354                 if (NT_STATUS_IS_OK(result)) {
1355                         DEBUG(10,("winbindd_dual_pam_auth_kerberos succeeded\n"));
1356                         goto process_result;
1357                 } else {
1358                         DEBUG(10,("winbindd_dual_pam_auth_kerberos failed: %s\n", nt_errstr(result)));
1359                 }
1360
1361                 if (NT_STATUS_EQUAL(result, NT_STATUS_NO_LOGON_SERVERS) ||
1362                     NT_STATUS_EQUAL(result, NT_STATUS_IO_TIMEOUT) ||
1363                     NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
1364                         DEBUG(10,("winbindd_dual_pam_auth_kerberos setting domain to offline\n"));
1365                         set_domain_offline( domain );
1366                         goto cached_logon;                      
1367                 }
1368
1369                 /* there are quite some NT_STATUS errors where there is no
1370                  * point in retrying with a samlogon, we explictly have to take
1371                  * care not to increase the bad logon counter on the DC */
1372
1373                 if (NT_STATUS_EQUAL(result, NT_STATUS_ACCOUNT_DISABLED) ||
1374                     NT_STATUS_EQUAL(result, NT_STATUS_ACCOUNT_EXPIRED) ||
1375                     NT_STATUS_EQUAL(result, NT_STATUS_ACCOUNT_LOCKED_OUT) ||
1376                     NT_STATUS_EQUAL(result, NT_STATUS_INVALID_LOGON_HOURS) ||
1377                     NT_STATUS_EQUAL(result, NT_STATUS_INVALID_WORKSTATION) ||
1378                     NT_STATUS_EQUAL(result, NT_STATUS_LOGON_FAILURE) ||
1379                     NT_STATUS_EQUAL(result, NT_STATUS_NO_SUCH_USER) ||
1380                     NT_STATUS_EQUAL(result, NT_STATUS_PASSWORD_EXPIRED) ||
1381                     NT_STATUS_EQUAL(result, NT_STATUS_PASSWORD_MUST_CHANGE) ||
1382                     NT_STATUS_EQUAL(result, NT_STATUS_WRONG_PASSWORD)) {
1383                         goto process_result;
1384                 }
1385                 
1386                 if (state->request.flags & WBFLAG_PAM_FALLBACK_AFTER_KRB5) {
1387                         DEBUG(3,("falling back to samlogon\n"));
1388                         goto sam_logon;
1389                 } else {
1390                         goto cached_logon;
1391                 }
1392         }
1393
1394 sam_logon:
1395         /* Check for Samlogon authentication */
1396         if (domain->online) {
1397                 result = winbindd_dual_pam_auth_samlogon(domain, state, &info3);
1398         
1399                 if (NT_STATUS_IS_OK(result)) {
1400                         DEBUG(10,("winbindd_dual_pam_auth_samlogon succeeded\n"));
1401                         /* add the Krb5 err if we have one */
1402                         if ( NT_STATUS_EQUAL(krb5_result, NT_STATUS_TIME_DIFFERENCE_AT_DC ) ) {
1403                                 info3->user_flgs |= LOGON_KRB5_FAIL_CLOCK_SKEW;                         
1404                         }
1405                         goto process_result;
1406                 } 
1407
1408                 DEBUG(10,("winbindd_dual_pam_auth_samlogon failed: %s\n", 
1409                           nt_errstr(result)));
1410
1411                 if (NT_STATUS_EQUAL(result, NT_STATUS_NO_LOGON_SERVERS) ||
1412                     NT_STATUS_EQUAL(result, NT_STATUS_IO_TIMEOUT) ||
1413                     NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) 
1414                 {
1415                         DEBUG(10,("winbindd_dual_pam_auth_samlogon setting domain to offline\n"));
1416                         set_domain_offline( domain );
1417                         goto cached_logon;                      
1418                 }
1419
1420                         if (domain->online) {
1421                                 /* We're still online - fail. */
1422                                 goto done;
1423                         }
1424         }
1425
1426 cached_logon:
1427         /* Check for Cached logons */
1428         if (!domain->online && (state->request.flags & WBFLAG_PAM_CACHED_LOGIN) && 
1429             lp_winbind_offline_logon()) {
1430         
1431                 result = winbindd_dual_pam_auth_cached(domain, state, &info3);
1432
1433                 if (NT_STATUS_IS_OK(result)) {
1434                         DEBUG(10,("winbindd_dual_pam_auth_cached succeeded\n"));
1435                         goto process_result;
1436                 } else {
1437                         DEBUG(10,("winbindd_dual_pam_auth_cached failed: %s\n", nt_errstr(result)));
1438                         goto done;
1439                 }
1440         }
1441
1442 process_result:
1443
1444         if (NT_STATUS_IS_OK(result)) {
1445         
1446                 DOM_SID user_sid;
1447
1448                 /* In all codepaths where result == NT_STATUS_OK info3 must have
1449                    been initialized. */
1450                 if (!info3) {
1451                         result = NT_STATUS_INTERNAL_ERROR;
1452                         goto done;
1453                 }
1454
1455                 netsamlogon_cache_store(name_user, info3);
1456                 wcache_invalidate_samlogon(find_domain_from_name(name_domain), info3);
1457
1458                 /* save name_to_sid info as early as possible (only if
1459                    this is our primary domain so we don't invalidate
1460                    the cache entry by storing the seq_num for the wrong
1461                    domain). */
1462                 if ( domain->primary ) {                        
1463                         sid_compose(&user_sid, &info3->dom_sid.sid, 
1464                                     info3->user_rid);
1465                         cache_name2sid(domain, name_domain, name_user, 
1466                                        SID_NAME_USER, &user_sid);
1467                 }
1468                 
1469                 /* Check if the user is in the right group */
1470
1471                 if (!NT_STATUS_IS_OK(result = check_info3_in_group(state->mem_ctx, info3,
1472                                         state->request.data.auth.require_membership_of_sid))) {
1473                         DEBUG(3, ("User %s is not in the required group (%s), so plaintext authentication is rejected\n",
1474                                   state->request.data.auth.user, 
1475                                   state->request.data.auth.require_membership_of_sid));
1476                         goto done;
1477                 }
1478
1479                 if (state->request.flags & WBFLAG_PAM_INFO3_NDR) {
1480                         result = append_info3_as_ndr(state->mem_ctx, state, info3);
1481                         if (!NT_STATUS_IS_OK(result)) {
1482                                 DEBUG(10,("Failed to append INFO3 (NDR): %s\n", nt_errstr(result)));
1483                                 goto done;
1484                         }
1485                 }
1486
1487                 if (state->request.flags & WBFLAG_PAM_INFO3_TEXT) {
1488                         result = append_info3_as_txt(state->mem_ctx, state, info3);
1489                         if (!NT_STATUS_IS_OK(result)) {
1490                                 DEBUG(10,("Failed to append INFO3 (TXT): %s\n", nt_errstr(result)));
1491                                 goto done;
1492                         }
1493
1494                 }
1495
1496                 if ((state->request.flags & WBFLAG_PAM_CACHED_LOGIN)) {
1497
1498                         /* Store in-memory creds for single-signon using ntlm_auth. */
1499                         result = winbindd_add_memory_creds(state->request.data.auth.user,
1500                                                         get_uid_from_state(state),
1501                                                         state->request.data.auth.pass);
1502
1503                         if (!NT_STATUS_IS_OK(result)) {
1504                                 DEBUG(10,("Failed to store memory creds: %s\n", nt_errstr(result)));
1505                                 goto done;
1506                         }
1507
1508                         if (lp_winbind_offline_logon()) {
1509                                 result = winbindd_store_creds(domain,
1510                                                       state->mem_ctx,
1511                                                       state->request.data.auth.user,
1512                                                       state->request.data.auth.pass,
1513                                                       info3, NULL);
1514                                 if (!NT_STATUS_IS_OK(result)) {
1515
1516                                         /* Release refcount. */
1517                                         winbindd_delete_memory_creds(state->request.data.auth.user);
1518
1519                                         DEBUG(10,("Failed to store creds: %s\n", nt_errstr(result)));
1520                                         goto done;
1521                                 }
1522                         }
1523                 }
1524
1525                 result = fillup_password_policy(domain, state);
1526
1527                 if (!NT_STATUS_IS_OK(result) 
1528                     && !NT_STATUS_EQUAL(result, NT_STATUS_NOT_SUPPORTED) ) 
1529                 {
1530                         DEBUG(10,("Failed to get password policies: %s\n", nt_errstr(result)));
1531                         goto done;
1532                 }
1533
1534                 result = NT_STATUS_OK;          
1535
1536                 if (state->request.flags & WBFLAG_PAM_UNIX_NAME) {
1537                         /* We've been asked to return the unix username, per 
1538                            'winbind use default domain' settings and the like */
1539
1540                         fstring username_out;
1541                         const char *nt_username, *nt_domain;
1542
1543                         if (!(nt_username = unistr2_tdup(state->mem_ctx, &info3->uni_user_name))) {
1544                                 /* If the server didn't give us one, just use the one we sent them */
1545                                 nt_username = name_user;
1546                         }
1547
1548                         if (!(nt_domain = unistr2_tdup(state->mem_ctx, &info3->uni_logon_dom))) {
1549                                 /* If the server didn't give us one, just use the one we sent them */
1550                                 nt_domain = name_domain;
1551                         }
1552
1553                         fill_domain_username(username_out, nt_domain, nt_username, True);
1554
1555                         DEBUG(5, ("Setting unix username to [%s]\n", username_out));
1556
1557                         SAFE_FREE(state->response.extra_data.data);
1558                         state->response.extra_data.data = SMB_STRDUP(username_out);
1559                         if (!state->response.extra_data.data) {
1560                                 result = NT_STATUS_NO_MEMORY;
1561                                 goto done;
1562                         }
1563                         state->response.length +=
1564                                 strlen((const char *)state->response.extra_data.data)+1;
1565                 }
1566         }
1567  
1568
1569 done:
1570         /* give us a more useful (more correct?) error code */
1571         if ((NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) ||
1572             (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)))) {
1573                 result = NT_STATUS_NO_LOGON_SERVERS;
1574         }
1575         
1576         state->response.data.auth.nt_status = NT_STATUS_V(result);
1577         fstrcpy(state->response.data.auth.nt_status_string, nt_errstr(result));
1578
1579         /* we might have given a more useful error above */
1580         if (!*state->response.data.auth.error_string) 
1581                 fstrcpy(state->response.data.auth.error_string, get_friendly_nt_error_msg(result));
1582         state->response.data.auth.pam_error = nt_status_to_pam(result);
1583
1584         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, ("Plain-text authentication for user %s returned %s (PAM: %d)\n", 
1585               state->request.data.auth.user, 
1586               state->response.data.auth.nt_status_string,
1587               state->response.data.auth.pam_error));          
1588
1589         if ( NT_STATUS_IS_OK(result) && info3 &&
1590              (state->request.flags & WBFLAG_PAM_AFS_TOKEN) ) {
1591
1592                 char *afsname = talloc_strdup(state->mem_ctx,
1593                                               lp_afs_username_map());
1594                 char *cell;
1595
1596                 if (afsname == NULL) {
1597                         goto no_token;
1598                 }
1599
1600                 afsname = talloc_string_sub(state->mem_ctx,
1601                                             lp_afs_username_map(),
1602                                             "%D", name_domain);
1603                 afsname = talloc_string_sub(state->mem_ctx, afsname,
1604                                             "%u", name_user);
1605                 afsname = talloc_string_sub(state->mem_ctx, afsname,
1606                                             "%U", name_user);
1607
1608                 {
1609                         DOM_SID user_sid;
1610                         fstring sidstr;
1611
1612                         sid_copy(&user_sid, &info3->dom_sid.sid);
1613                         sid_append_rid(&user_sid, info3->user_rid);
1614                         sid_to_string(sidstr, &user_sid);
1615                         afsname = talloc_string_sub(state->mem_ctx, afsname,
1616                                                     "%s", sidstr);
1617                 }
1618
1619                 if (afsname == NULL) {
1620                         goto no_token;
1621                 }
1622
1623                 strlower_m(afsname);
1624
1625                 DEBUG(10, ("Generating token for user %s\n", afsname));
1626
1627                 cell = strchr(afsname, '@');
1628
1629                 if (cell == NULL) {
1630                         goto no_token;
1631                 }
1632
1633                 *cell = '\0';
1634                 cell += 1;
1635
1636                 /* Append an AFS token string */
1637                 SAFE_FREE(state->response.extra_data.data);
1638                 state->response.extra_data.data =
1639                         afs_createtoken_str(afsname, cell);
1640
1641                 if (state->response.extra_data.data != NULL) {
1642                         state->response.length +=
1643                                 strlen((const char *)state->response.extra_data.data)+1;
1644                 }
1645
1646         no_token:
1647                 TALLOC_FREE(afsname);
1648         }
1649         
1650         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
1651 }
1652
1653
1654 /**********************************************************************
1655  Challenge Response Authentication Protocol 
1656 **********************************************************************/
1657
1658 void winbindd_pam_auth_crap(struct winbindd_cli_state *state)
1659 {
1660         struct winbindd_domain *domain = NULL;
1661         const char *domain_name = NULL;
1662         NTSTATUS result;
1663
1664         if (!state->privileged) {
1665                 char *error_string = NULL;
1666                 DEBUG(2, ("winbindd_pam_auth_crap: non-privileged access "
1667                           "denied.  !\n"));
1668                 DEBUGADD(2, ("winbindd_pam_auth_crap: Ensure permissions "
1669                              "on %s are set correctly.\n",
1670                              get_winbind_priv_pipe_dir()));
1671                 /* send a better message than ACCESS_DENIED */
1672                 error_string = talloc_asprintf(state->mem_ctx,
1673                                                "winbind client not authorized "
1674                                                "to use winbindd_pam_auth_crap."
1675                                                " Ensure permissions on %s "
1676                                                "are set correctly.",
1677                                                get_winbind_priv_pipe_dir());
1678                 fstrcpy(state->response.data.auth.error_string, error_string);
1679                 result = NT_STATUS_ACCESS_DENIED;
1680                 goto done;
1681         }
1682
1683         /* Ensure null termination */
1684         state->request.data.auth_crap.user
1685                 [sizeof(state->request.data.auth_crap.user)-1]=0;
1686         state->request.data.auth_crap.domain
1687                 [sizeof(state->request.data.auth_crap.domain)-1]=0;
1688
1689         DEBUG(3, ("[%5lu]: pam auth crap domain: [%s] user: %s\n",
1690                   (unsigned long)state->pid,
1691                   state->request.data.auth_crap.domain,
1692                   state->request.data.auth_crap.user));
1693
1694         if (*state->request.data.auth_crap.domain != '\0') {
1695                 domain_name = state->request.data.auth_crap.domain;
1696         } else if (lp_winbind_use_default_domain()) {
1697                 domain_name = lp_workgroup();
1698         }
1699
1700         if (domain_name != NULL)
1701                 domain = find_auth_domain(state, domain_name);
1702
1703         if (domain != NULL) {
1704                 sendto_domain(state, domain);
1705                 return;
1706         }
1707
1708         result = NT_STATUS_NO_SUCH_USER;
1709
1710  done:
1711         set_auth_errors(&state->response, result);
1712         DEBUG(5, ("CRAP authentication for %s\\%s returned %s (PAM: %d)\n",
1713                   state->request.data.auth_crap.domain,
1714                   state->request.data.auth_crap.user, 
1715                   state->response.data.auth.nt_status_string,
1716                   state->response.data.auth.pam_error));
1717         request_error(state);
1718         return;
1719 }
1720
1721
1722 enum winbindd_result winbindd_dual_pam_auth_crap(struct winbindd_domain *domain,
1723                                                  struct winbindd_cli_state *state) 
1724 {
1725         NTSTATUS result;
1726         NET_USER_INFO_3 info3;
1727         struct rpc_pipe_client *netlogon_pipe;
1728         const char *name_user = NULL;
1729         const char *name_domain = NULL;
1730         const char *workstation;
1731         struct winbindd_domain *contact_domain;
1732         int attempts = 0;
1733         BOOL retry;
1734
1735         DATA_BLOB lm_resp, nt_resp;
1736
1737         /* This is child-only, so no check for privileged access is needed
1738            anymore */
1739
1740         /* Ensure null termination */
1741         state->request.data.auth_crap.user[sizeof(state->request.data.auth_crap.user)-1]=0;
1742         state->request.data.auth_crap.domain[sizeof(state->request.data.auth_crap.domain)-1]=0;
1743
1744         name_user = state->request.data.auth_crap.user;
1745
1746         if (*state->request.data.auth_crap.domain) {
1747                 name_domain = state->request.data.auth_crap.domain;
1748         } else if (lp_winbind_use_default_domain()) {
1749                 name_domain = lp_workgroup();
1750         } else {
1751                 DEBUG(5,("no domain specified with username (%s) - failing auth\n", 
1752                          name_user));
1753                 result = NT_STATUS_NO_SUCH_USER;
1754                 goto done;
1755         }
1756
1757         DEBUG(3, ("[%5lu]: pam auth crap domain: %s user: %s\n", (unsigned long)state->pid,
1758                   name_domain, name_user));
1759            
1760         if (*state->request.data.auth_crap.workstation) {
1761                 workstation = state->request.data.auth_crap.workstation;
1762         } else {
1763                 workstation = global_myname();
1764         }
1765
1766         if (state->request.data.auth_crap.lm_resp_len > sizeof(state->request.data.auth_crap.lm_resp)
1767                 || state->request.data.auth_crap.nt_resp_len > sizeof(state->request.data.auth_crap.nt_resp)) {
1768                 DEBUG(0, ("winbindd_pam_auth_crap: invalid password length %u/%u\n", 
1769                           state->request.data.auth_crap.lm_resp_len, 
1770                           state->request.data.auth_crap.nt_resp_len));
1771                 result = NT_STATUS_INVALID_PARAMETER;
1772                 goto done;
1773         }
1774
1775         lm_resp = data_blob_talloc(state->mem_ctx, state->request.data.auth_crap.lm_resp,
1776                                         state->request.data.auth_crap.lm_resp_len);
1777         nt_resp = data_blob_talloc(state->mem_ctx, state->request.data.auth_crap.nt_resp,
1778                                         state->request.data.auth_crap.nt_resp_len);
1779
1780         /* what domain should we contact? */
1781         
1782         if ( IS_DC ) {
1783                 if (!(contact_domain = find_domain_from_name(name_domain))) {
1784                         DEBUG(3, ("Authentication for domain for [%s] -> [%s]\\[%s] failed as %s is not a trusted domain\n", 
1785                                   state->request.data.auth_crap.user, name_domain, name_user, name_domain)); 
1786                         result = NT_STATUS_NO_SUCH_USER;
1787                         goto done;
1788                 }
1789         } else {
1790                 if (is_myname(name_domain)) {
1791                         DEBUG(3, ("Authentication for domain %s (local domain to this server) not supported at this stage\n", name_domain));
1792                         result =  NT_STATUS_NO_SUCH_USER;
1793                         goto done;
1794                 }
1795                 contact_domain = find_our_domain();
1796         }
1797
1798         do {
1799                 ZERO_STRUCT(info3);
1800                 retry = False;
1801
1802                 netlogon_pipe = NULL;
1803                 result = cm_connect_netlogon(contact_domain, &netlogon_pipe);
1804
1805                 if (!NT_STATUS_IS_OK(result)) {
1806                         DEBUG(3, ("could not open handle to NETLOGON pipe (error: %s)\n",
1807                                   nt_errstr(result)));
1808                         goto done;
1809                 }
1810
1811                 result = rpccli_netlogon_sam_network_logon(netlogon_pipe,
1812                                                            state->mem_ctx,
1813                                                            state->request.data.auth_crap.logon_parameters,
1814                                                            contact_domain->dcname,
1815                                                            name_user,
1816                                                            name_domain, 
1817                                                                         /* Bug #3248 - found by Stefan Burkei. */
1818                                                            workstation, /* We carefully set this above so use it... */
1819                                                            state->request.data.auth_crap.chal,
1820                                                            lm_resp,
1821                                                            nt_resp,
1822                                                            &info3);
1823
1824                 attempts += 1;
1825
1826                 /* We have to try a second time as cm_connect_netlogon
1827                    might not yet have noticed that the DC has killed
1828                    our connection. */
1829
1830                 if (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)) {
1831                         retry = True;
1832                         continue;
1833                 }
1834
1835                 /* if we get access denied, a possible cause was that we had and open
1836                    connection to the DC, but someone changed our machine account password
1837                    out from underneath us using 'net rpc changetrustpw' */
1838                    
1839                 if ( NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED) ) {
1840                         DEBUG(3,("winbindd_pam_auth: sam_logon returned "
1841                                  "ACCESS_DENIED.  Maybe the trust account "
1842                                 "password was changed and we didn't know it. "
1843                                  "Killing connections to domain %s\n",
1844                                 name_domain));
1845                         invalidate_cm_connection(&contact_domain->conn);
1846                         retry = True;
1847                 } 
1848
1849         } while ( (attempts < 2) && retry );
1850
1851         if (NT_STATUS_IS_OK(result)) {
1852
1853                 netsamlogon_cache_store(name_user, &info3);
1854                 wcache_invalidate_samlogon(find_domain_from_name(name_domain), &info3);
1855
1856                 /* Check if the user is in the right group */
1857
1858                 if (!NT_STATUS_IS_OK(result = check_info3_in_group(state->mem_ctx, &info3,
1859                                                         state->request.data.auth_crap.require_membership_of_sid))) {
1860                         DEBUG(3, ("User %s is not in the required group (%s), so "
1861                                   "crap authentication is rejected\n",
1862                                   state->request.data.auth_crap.user, 
1863                                   state->request.data.auth_crap.require_membership_of_sid));
1864                         goto done;
1865                 }
1866
1867                 if (state->request.flags & WBFLAG_PAM_INFO3_NDR) {
1868                         result = append_info3_as_ndr(state->mem_ctx, state, &info3);
1869                 } else if (state->request.flags & WBFLAG_PAM_UNIX_NAME) {
1870                         /* ntlm_auth should return the unix username, per 
1871                            'winbind use default domain' settings and the like */
1872
1873                         fstring username_out;
1874                         const char *nt_username, *nt_domain;
1875                         if (!(nt_username = unistr2_tdup(state->mem_ctx, &(info3.uni_user_name)))) {
1876                                 /* If the server didn't give us one, just use the one we sent them */
1877                                 nt_username = name_user;
1878                         }
1879
1880                         if (!(nt_domain = unistr2_tdup(state->mem_ctx, &(info3.uni_logon_dom)))) {
1881                                 /* If the server didn't give us one, just use the one we sent them */
1882                                 nt_domain = name_domain;
1883                         }
1884
1885                         fill_domain_username(username_out, nt_domain, nt_username, True);
1886
1887                         DEBUG(5, ("Setting unix username to [%s]\n", username_out));
1888
1889                         SAFE_FREE(state->response.extra_data.data);
1890                         state->response.extra_data.data = SMB_STRDUP(username_out);
1891                         if (!state->response.extra_data.data) {
1892                                 result = NT_STATUS_NO_MEMORY;
1893                                 goto done;
1894                         }
1895                         state->response.length +=
1896                                 strlen((const char *)state->response.extra_data.data)+1;
1897                 }
1898                 
1899                 if (state->request.flags & WBFLAG_PAM_USER_SESSION_KEY) {
1900                         memcpy(state->response.data.auth.user_session_key, info3.user_sess_key,
1901                                         sizeof(state->response.data.auth.user_session_key) /* 16 */);
1902                 }
1903                 if (state->request.flags & WBFLAG_PAM_LMKEY) {
1904                         memcpy(state->response.data.auth.first_8_lm_hash, info3.lm_sess_key,
1905                                         sizeof(state->response.data.auth.first_8_lm_hash) /* 8 */);
1906                 }
1907         }
1908
1909 done:
1910
1911         /* give us a more useful (more correct?) error code */
1912         if ((NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) ||
1913             (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)))) {
1914                 result = NT_STATUS_NO_LOGON_SERVERS;
1915         }
1916
1917         if (state->request.flags & WBFLAG_PAM_NT_STATUS_SQUASH) {
1918                 result = nt_status_squash(result);
1919         }
1920
1921         state->response.data.auth.nt_status = NT_STATUS_V(result);
1922         fstrcpy(state->response.data.auth.nt_status_string, nt_errstr(result));
1923
1924         /* we might have given a more useful error above */
1925         if (!*state->response.data.auth.error_string) {
1926                 fstrcpy(state->response.data.auth.error_string, get_friendly_nt_error_msg(result));
1927         }
1928         state->response.data.auth.pam_error = nt_status_to_pam(result);
1929
1930         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, 
1931               ("NTLM CRAP authentication for user [%s]\\[%s] returned %s (PAM: %d)\n", 
1932                name_domain,
1933                name_user,
1934                state->response.data.auth.nt_status_string,
1935                state->response.data.auth.pam_error));         
1936
1937         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
1938 }
1939
1940 /* Change a user password */
1941
1942 void winbindd_pam_chauthtok(struct winbindd_cli_state *state)
1943 {
1944         fstring domain, user;
1945         struct winbindd_domain *contact_domain;
1946
1947         DEBUG(3, ("[%5lu]: pam chauthtok %s\n", (unsigned long)state->pid,
1948                 state->request.data.chauthtok.user));
1949
1950         /* Setup crap */
1951
1952         ws_name_return( state->request.data.auth.user, WB_REPLACE_CHAR );
1953
1954         if (!canonicalize_username(state->request.data.chauthtok.user, domain, user)) {
1955                 set_auth_errors(&state->response, NT_STATUS_NO_SUCH_USER);
1956                 DEBUG(5, ("winbindd_pam_chauthtok: canonicalize_username %s failed with %s"
1957                           "(PAM: %d)\n",
1958                           state->request.data.auth.user, 
1959                           state->response.data.auth.nt_status_string,
1960                           state->response.data.auth.pam_error));
1961                 request_error(state);
1962                 return;
1963         }
1964
1965         contact_domain = find_domain_from_name(domain);
1966         if (!contact_domain) {
1967                 set_auth_errors(&state->response, NT_STATUS_NO_SUCH_USER);
1968                 DEBUG(3, ("Cannot change password for [%s] -> [%s]\\[%s] as %s is not a trusted domain\n", 
1969                           state->request.data.chauthtok.user, domain, user, domain)); 
1970                 request_error(state);
1971                 return;
1972         }
1973
1974         sendto_domain(state, contact_domain);
1975 }
1976
1977 enum winbindd_result winbindd_dual_pam_chauthtok(struct winbindd_domain *contact_domain,
1978                                                  struct winbindd_cli_state *state)
1979 {
1980         char *oldpass;
1981         char *newpass = NULL;
1982         POLICY_HND dom_pol;
1983         struct rpc_pipe_client *cli;
1984         BOOL got_info = False;
1985         SAM_UNK_INFO_1 info;
1986         SAMR_CHANGE_REJECT reject;
1987         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
1988         fstring domain, user;
1989
1990         DEBUG(3, ("[%5lu]: dual pam chauthtok %s\n", (unsigned long)state->pid,
1991                   state->request.data.auth.user));
1992
1993         if (!parse_domain_user(state->request.data.chauthtok.user, domain, user)) {
1994                 goto done;
1995         }
1996
1997         /* Change password */
1998
1999         oldpass = state->request.data.chauthtok.oldpass;
2000         newpass = state->request.data.chauthtok.newpass;
2001
2002         /* Initialize reject reason */
2003         state->response.data.auth.reject_reason = Undefined;
2004
2005         /* Get sam handle */
2006
2007         result = cm_connect_sam(contact_domain, state->mem_ctx, &cli,
2008                                 &dom_pol);
2009         if (!NT_STATUS_IS_OK(result)) {
2010                 DEBUG(1, ("could not get SAM handle on DC for %s\n", domain));
2011                 goto done;
2012         }
2013
2014         result = rpccli_samr_chgpasswd3(cli, state->mem_ctx, user, newpass, oldpass, &info, &reject);
2015
2016         /* Windows 2003 returns NT_STATUS_PASSWORD_RESTRICTION */
2017
2018         if (NT_STATUS_EQUAL(result, NT_STATUS_PASSWORD_RESTRICTION) ) {
2019                 state->response.data.auth.policy.min_length_password = 
2020                         info.min_length_password;
2021                 state->response.data.auth.policy.password_history = 
2022                         info.password_history;
2023                 state->response.data.auth.policy.password_properties = 
2024                         info.password_properties;
2025                 state->response.data.auth.policy.expire = 
2026                         nt_time_to_unix_abs(&info.expire);
2027                 state->response.data.auth.policy.min_passwordage = 
2028                         nt_time_to_unix_abs(&info.min_passwordage);
2029
2030                 state->response.data.auth.reject_reason = 
2031                         reject.reject_reason;
2032
2033                 got_info = True;
2034         }
2035
2036         /* only fallback when the chgpasswd3 call is not supported */
2037         if ((NT_STATUS_EQUAL(result, NT_STATUS(DCERPC_FAULT_OP_RNG_ERROR))) ||
2038                    (NT_STATUS_EQUAL(result, NT_STATUS_NOT_SUPPORTED)) ||
2039                    (NT_STATUS_EQUAL(result, NT_STATUS_NOT_IMPLEMENTED))) {
2040
2041                 DEBUG(10,("Password change with chgpasswd3 failed with: %s, retrying chgpasswd_user\n", 
2042                         nt_errstr(result)));
2043                 
2044                 result = rpccli_samr_chgpasswd_user(cli, state->mem_ctx, user, newpass, oldpass);
2045
2046                 /* Windows 2000 returns NT_STATUS_ACCOUNT_RESTRICTION.
2047                    Map to the same status code as Windows 2003. */
2048
2049                 if ( NT_STATUS_EQUAL(NT_STATUS_ACCOUNT_RESTRICTION, result ) ) {
2050                         result = NT_STATUS_PASSWORD_RESTRICTION;                        
2051                 }
2052         }
2053
2054 done: 
2055
2056         if (NT_STATUS_IS_OK(result) && (state->request.flags & WBFLAG_PAM_CACHED_LOGIN)) {
2057                 
2058                 /* Update the single sign-on memory creds. */
2059                 result = winbindd_replace_memory_creds(state->request.data.chauthtok.user,
2060                                                         newpass);
2061
2062                 if (!NT_STATUS_IS_OK(result)) {
2063                         DEBUG(10,("Failed to replace memory creds: %s\n", nt_errstr(result)));
2064                         goto process_result;
2065                 }
2066
2067                 if (lp_winbind_offline_logon()) {
2068                         result = winbindd_update_creds_by_name(contact_domain,
2069                                                          state->mem_ctx, user,
2070                                                          newpass);
2071                         if (!NT_STATUS_IS_OK(result)) {
2072                                 DEBUG(10,("Failed to store creds: %s\n", nt_errstr(result)));
2073                                 goto process_result;
2074                         }
2075                 }
2076         }               
2077
2078         if (!NT_STATUS_IS_OK(result) && !got_info && contact_domain) {
2079
2080                 NTSTATUS policy_ret;
2081                 
2082                 policy_ret = fillup_password_policy(contact_domain, state);
2083
2084                 /* failure of this is non critical, it will just provide no
2085                  * additional information to the client why the change has
2086                  * failed - Guenther */
2087
2088                 if (!NT_STATUS_IS_OK(policy_ret)) {
2089                         DEBUG(10,("Failed to get password policies: %s\n", nt_errstr(policy_ret)));
2090                         goto process_result;
2091                 }
2092         }
2093
2094 process_result:
2095
2096         state->response.data.auth.nt_status = NT_STATUS_V(result);
2097         fstrcpy(state->response.data.auth.nt_status_string, nt_errstr(result));
2098         fstrcpy(state->response.data.auth.error_string, get_friendly_nt_error_msg(result));
2099         state->response.data.auth.pam_error = nt_status_to_pam(result);
2100
2101         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, 
2102               ("Password change for user [%s]\\[%s] returned %s (PAM: %d)\n", 
2103                domain,
2104                user,
2105                state->response.data.auth.nt_status_string,
2106                state->response.data.auth.pam_error));         
2107
2108         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
2109 }
2110
2111 void winbindd_pam_logoff(struct winbindd_cli_state *state)
2112 {
2113         struct winbindd_domain *domain;
2114         fstring name_domain, user;
2115         uid_t caller_uid = (uid_t)-1;
2116         uid_t request_uid = state->request.data.logoff.uid;
2117
2118         DEBUG(3, ("[%5lu]: pam logoff %s\n", (unsigned long)state->pid,
2119                 state->request.data.logoff.user));
2120
2121         /* Ensure null termination */
2122         state->request.data.logoff.user
2123                 [sizeof(state->request.data.logoff.user)-1]='\0';
2124
2125         state->request.data.logoff.krb5ccname
2126                 [sizeof(state->request.data.logoff.krb5ccname)-1]='\0';
2127
2128         if (request_uid == (gid_t)-1) {
2129                 goto failed;
2130         }
2131
2132         if (!canonicalize_username(state->request.data.logoff.user, name_domain, user)) {
2133                 goto failed;
2134         }
2135
2136         if ((domain = find_auth_domain(state, name_domain)) == NULL) {
2137                 goto failed;
2138         }
2139
2140         if ((sys_getpeereid(state->sock, &caller_uid)) != 0) {
2141                 DEBUG(1,("winbindd_pam_logoff: failed to check peerid: %s\n", 
2142                         strerror(errno)));
2143                 goto failed;
2144         }
2145
2146         switch (caller_uid) {
2147                 case -1:
2148                         goto failed;
2149                 case 0:
2150                         /* root must be able to logoff any user - gd */
2151                         state->request.data.logoff.uid = request_uid;
2152                         break;
2153                 default:
2154                         if (caller_uid != request_uid) {
2155                                 DEBUG(1,("winbindd_pam_logoff: caller requested invalid uid\n"));
2156                                 goto failed;
2157                         }
2158                         state->request.data.logoff.uid = caller_uid;
2159                         break;
2160         }
2161
2162         sendto_domain(state, domain);
2163         return;
2164
2165  failed:
2166         set_auth_errors(&state->response, NT_STATUS_NO_SUCH_USER);
2167         DEBUG(5, ("Pam Logoff for %s returned %s "
2168                   "(PAM: %d)\n",
2169                   state->request.data.logoff.user,
2170                   state->response.data.auth.nt_status_string,
2171                   state->response.data.auth.pam_error));
2172         request_error(state);
2173         return;
2174 }
2175
2176 enum winbindd_result winbindd_dual_pam_logoff(struct winbindd_domain *domain,
2177                                               struct winbindd_cli_state *state) 
2178 {
2179         NTSTATUS result = NT_STATUS_NOT_SUPPORTED;
2180
2181         DEBUG(3, ("[%5lu]: pam dual logoff %s\n", (unsigned long)state->pid,
2182                 state->request.data.logoff.user));
2183
2184         if (!(state->request.flags & WBFLAG_PAM_KRB5)) {
2185                 result = NT_STATUS_OK;
2186                 goto process_result;
2187         }
2188
2189         if (state->request.data.logoff.krb5ccname[0] == '\0') {
2190                 result = NT_STATUS_OK;
2191                 goto process_result;
2192         }
2193
2194 #ifdef HAVE_KRB5
2195         
2196         if (state->request.data.logoff.uid < 0) {
2197                 DEBUG(0,("winbindd_pam_logoff: invalid uid\n"));
2198                 goto process_result;
2199         }
2200
2201         /* what we need here is to find the corresponding krb5 ccache name *we*
2202          * created for a given username and destroy it */
2203
2204         if (!ccache_entry_exists(state->request.data.logoff.user)) {
2205                 result = NT_STATUS_OK;
2206                 DEBUG(10,("winbindd_pam_logoff: no entry found.\n"));
2207                 goto process_result;
2208         }
2209
2210         if (!ccache_entry_identical(state->request.data.logoff.user, 
2211                                         state->request.data.logoff.uid,
2212                                         state->request.data.logoff.krb5ccname)) {
2213                 DEBUG(0,("winbindd_pam_logoff: cached entry differs.\n"));
2214                 goto process_result;
2215         }
2216
2217         result = remove_ccache(state->request.data.logoff.user);
2218         if (!NT_STATUS_IS_OK(result)) {
2219                 DEBUG(0,("winbindd_pam_logoff: failed to remove ccache: %s\n",
2220                         nt_errstr(result)));
2221                 goto process_result;
2222         }
2223
2224 #else
2225         result = NT_STATUS_NOT_SUPPORTED;
2226 #endif
2227
2228 process_result:
2229
2230         winbindd_delete_memory_creds(state->request.data.logoff.user);
2231
2232         state->response.data.auth.nt_status = NT_STATUS_V(result);
2233         fstrcpy(state->response.data.auth.nt_status_string, nt_errstr(result));
2234         fstrcpy(state->response.data.auth.error_string, get_friendly_nt_error_msg(result));
2235         state->response.data.auth.pam_error = nt_status_to_pam(result);
2236
2237         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
2238 }
2239
2240 /* Change user password with auth crap*/
2241
2242 void winbindd_pam_chng_pswd_auth_crap(struct winbindd_cli_state *state)
2243 {
2244         struct winbindd_domain *domain = NULL;
2245         const char *domain_name = NULL;
2246
2247         /* Ensure null termination */
2248         state->request.data.chng_pswd_auth_crap.user[
2249                 sizeof(state->request.data.chng_pswd_auth_crap.user)-1]=0;
2250         state->request.data.chng_pswd_auth_crap.domain[
2251                 sizeof(state->request.data.chng_pswd_auth_crap.domain)-1]=0;
2252         
2253         DEBUG(3, ("[%5lu]: pam change pswd auth crap domain: %s user: %s\n",
2254                   (unsigned long)state->pid,
2255                   state->request.data.chng_pswd_auth_crap.domain,
2256                   state->request.data.chng_pswd_auth_crap.user));
2257         
2258         if (*state->request.data.chng_pswd_auth_crap.domain != '\0') {
2259                 domain_name = state->request.data.chng_pswd_auth_crap.domain;
2260         } else if (lp_winbind_use_default_domain()) {
2261                 domain_name = lp_workgroup();
2262         }
2263
2264         if (domain_name != NULL)
2265                 domain = find_domain_from_name(domain_name);
2266
2267         if (domain != NULL) {
2268                 DEBUG(7, ("[%5lu]: pam auth crap changing pswd in domain: "
2269                           "%s\n", (unsigned long)state->pid,domain->name));
2270                 sendto_domain(state, domain);
2271                 return;
2272         }
2273
2274         set_auth_errors(&state->response, NT_STATUS_NO_SUCH_USER);
2275         DEBUG(5, ("CRAP change password  for %s\\%s returned %s (PAM: %d)\n",
2276                   state->request.data.chng_pswd_auth_crap.domain,
2277                   state->request.data.chng_pswd_auth_crap.user, 
2278                   state->response.data.auth.nt_status_string,
2279                   state->response.data.auth.pam_error));
2280         request_error(state);
2281         return;
2282 }
2283
2284 enum winbindd_result winbindd_dual_pam_chng_pswd_auth_crap(struct winbindd_domain *domainSt, struct winbindd_cli_state *state)
2285 {
2286         NTSTATUS result;
2287         DATA_BLOB new_nt_password;
2288         DATA_BLOB old_nt_hash_enc;
2289         DATA_BLOB new_lm_password;
2290         DATA_BLOB old_lm_hash_enc;
2291         fstring  domain,user;
2292         POLICY_HND dom_pol;
2293         struct winbindd_domain *contact_domain = domainSt;
2294         struct rpc_pipe_client *cli;
2295
2296         /* Ensure null termination */
2297         state->request.data.chng_pswd_auth_crap.user[
2298                 sizeof(state->request.data.chng_pswd_auth_crap.user)-1]=0;
2299         state->request.data.chng_pswd_auth_crap.domain[
2300                 sizeof(state->request.data.chng_pswd_auth_crap.domain)-1]=0;
2301         *domain = 0;
2302         *user = 0;
2303         
2304         DEBUG(3, ("[%5lu]: pam change pswd auth crap domain: %s user: %s\n",
2305                   (unsigned long)state->pid,
2306                   state->request.data.chng_pswd_auth_crap.domain,
2307                   state->request.data.chng_pswd_auth_crap.user));
2308
2309         if (lp_winbind_offline_logon()) {
2310                 DEBUG(0,("Refusing password change as winbind offline logons are enabled. "));
2311                 DEBUGADD(0,("Changing passwords here would risk inconsistent logons\n"));
2312                 result = NT_STATUS_ACCESS_DENIED;
2313                 goto done;
2314         }
2315
2316         if (*state->request.data.chng_pswd_auth_crap.domain) {
2317                 fstrcpy(domain,state->request.data.chng_pswd_auth_crap.domain);
2318         } else {
2319                 parse_domain_user(state->request.data.chng_pswd_auth_crap.user,
2320                                   domain, user);
2321
2322                 if(!*domain) {
2323                         DEBUG(3,("no domain specified with username (%s) - "
2324                                  "failing auth\n",
2325                                  state->request.data.chng_pswd_auth_crap.user));
2326                         result = NT_STATUS_NO_SUCH_USER;
2327                         goto done;
2328                 }
2329         }
2330
2331         if (!*domain && lp_winbind_use_default_domain()) {
2332                 fstrcpy(domain,(char *)lp_workgroup());
2333         }
2334
2335         if(!*user) {
2336                 fstrcpy(user, state->request.data.chng_pswd_auth_crap.user);
2337         }
2338
2339         DEBUG(3, ("[%5lu]: pam auth crap domain: %s user: %s\n",
2340                   (unsigned long)state->pid, domain, user));
2341         
2342         /* Change password */
2343         new_nt_password = data_blob_talloc(
2344                 state->mem_ctx,
2345                 state->request.data.chng_pswd_auth_crap.new_nt_pswd,
2346                 state->request.data.chng_pswd_auth_crap.new_nt_pswd_len);
2347
2348         old_nt_hash_enc = data_blob_talloc(
2349                 state->mem_ctx,
2350                 state->request.data.chng_pswd_auth_crap.old_nt_hash_enc,
2351                 state->request.data.chng_pswd_auth_crap.old_nt_hash_enc_len);
2352
2353         if(state->request.data.chng_pswd_auth_crap.new_lm_pswd_len > 0) {
2354                 new_lm_password = data_blob_talloc(
2355                         state->mem_ctx,
2356                         state->request.data.chng_pswd_auth_crap.new_lm_pswd,
2357                         state->request.data.chng_pswd_auth_crap.new_lm_pswd_len);
2358
2359                 old_lm_hash_enc = data_blob_talloc(
2360                         state->mem_ctx,
2361                         state->request.data.chng_pswd_auth_crap.old_lm_hash_enc,
2362                         state->request.data.chng_pswd_auth_crap.old_lm_hash_enc_len);
2363         } else {
2364                 new_lm_password.length = 0;
2365                 old_lm_hash_enc.length = 0;
2366         }
2367
2368         /* Get sam handle */
2369
2370         result = cm_connect_sam(contact_domain, state->mem_ctx, &cli, &dom_pol);
2371         if (!NT_STATUS_IS_OK(result)) {
2372                 DEBUG(1, ("could not get SAM handle on DC for %s\n", domain));
2373                 goto done;
2374         }
2375
2376         result = rpccli_samr_chng_pswd_auth_crap(
2377                 cli, state->mem_ctx, user, new_nt_password, old_nt_hash_enc,
2378                 new_lm_password, old_lm_hash_enc);
2379
2380  done:    
2381         state->response.data.auth.nt_status = NT_STATUS_V(result);
2382         fstrcpy(state->response.data.auth.nt_status_string, nt_errstr(result));
2383         fstrcpy(state->response.data.auth.error_string,
2384                 get_friendly_nt_error_msg(result));
2385         state->response.data.auth.pam_error = nt_status_to_pam(result);
2386
2387         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, 
2388               ("Password change for user [%s]\\[%s] returned %s (PAM: %d)\n", 
2389                domain, user,
2390                state->response.data.auth.nt_status_string,
2391                state->response.data.auth.pam_error));         
2392
2393         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
2394 }