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