[GLUE] Rsync SAMBA_3_2_0 SVN r25598 in order to create the v3-2-test branch.
[sfrench/samba-autobuild/.git] / source3 / 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
1265                 ZERO_STRUCTP(my_info3);
1266                 retry = False;
1267
1268                 result = cm_connect_netlogon(contact_domain, &netlogon_pipe);
1269
1270                 if (!NT_STATUS_IS_OK(result)) {
1271                         DEBUG(3, ("could not open handle to NETLOGON pipe\n"));
1272                         goto done;
1273                 }
1274
1275                 result = rpccli_netlogon_sam_network_logon(netlogon_pipe,
1276                                                            state->mem_ctx,
1277                                                            0,
1278                                                            contact_domain->dcname, /* server name */
1279                                                            name_user,              /* user name */
1280                                                            name_domain,            /* target domain */
1281                                                            global_myname(),        /* workstation */
1282                                                            chal,
1283                                                            lm_resp,
1284                                                            nt_resp,
1285                                                            my_info3);
1286                 attempts += 1;
1287
1288                 /* We have to try a second time as cm_connect_netlogon
1289                    might not yet have noticed that the DC has killed
1290                    our connection. */
1291
1292                 if (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)) {
1293                         retry = True;
1294                         continue;
1295                 }
1296                 
1297                 /* if we get access denied, a possible cause was that we had
1298                    and open connection to the DC, but someone changed our
1299                    machine account password out from underneath us using 'net
1300                    rpc changetrustpw' */
1301                    
1302                 if ( NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED) ) {
1303                         DEBUG(3,("winbindd_pam_auth: sam_logon returned "
1304                                  "ACCESS_DENIED.  Maybe the trust account "
1305                                 "password was changed and we didn't know it. "
1306                                  "Killing connections to domain %s\n",
1307                                 name_domain));
1308                         invalidate_cm_connection(&contact_domain->conn);
1309                         retry = True;
1310                 } 
1311                 
1312         } while ( (attempts < 2) && retry );
1313
1314         /* handle the case where a NT4 DC does not fill in the acct_flags in
1315          * the samlogon reply info3. When accurate info3 is required by the
1316          * caller, we look up the account flags ourselve - gd */
1317
1318         if ((state->request.flags & WBFLAG_PAM_INFO3_TEXT) && 
1319             (my_info3->acct_flags == 0) && NT_STATUS_IS_OK(result)) {
1320
1321                 struct rpc_pipe_client *samr_pipe;
1322                 POLICY_HND samr_domain_handle, user_pol;
1323                 SAM_USERINFO_CTR *user_ctr;
1324                 NTSTATUS status_tmp;
1325                 uint32 acct_flags;
1326
1327                 ZERO_STRUCT(user_ctr);
1328
1329                 status_tmp = cm_connect_sam(contact_domain, state->mem_ctx, 
1330                                             &samr_pipe, &samr_domain_handle);
1331
1332                 if (!NT_STATUS_IS_OK(status_tmp)) {
1333                         DEBUG(3, ("could not open handle to SAMR pipe: %s\n", 
1334                                 nt_errstr(status_tmp)));
1335                         goto done;
1336                 }
1337
1338                 status_tmp = rpccli_samr_open_user(samr_pipe, state->mem_ctx, 
1339                                                    &samr_domain_handle,
1340                                                    MAXIMUM_ALLOWED_ACCESS,
1341                                                    my_info3->user_rid, &user_pol);
1342
1343                 if (!NT_STATUS_IS_OK(status_tmp)) {
1344                         DEBUG(3, ("could not open user handle on SAMR pipe: %s\n",
1345                                 nt_errstr(status_tmp)));
1346                         goto done;
1347                 }
1348
1349                 status_tmp = rpccli_samr_query_userinfo(samr_pipe, state->mem_ctx, 
1350                                                         &user_pol, 16, &user_ctr);
1351
1352                 if (!NT_STATUS_IS_OK(status_tmp)) {
1353                         DEBUG(3, ("could not query user info on SAMR pipe: %s\n",
1354                                 nt_errstr(status_tmp)));
1355                         rpccli_samr_close(samr_pipe, state->mem_ctx, &user_pol);
1356                         goto done;
1357                 }
1358
1359                 acct_flags = user_ctr->info.id16->acb_info;
1360
1361                 if (acct_flags == 0) {
1362                         rpccli_samr_close(samr_pipe, state->mem_ctx, &user_pol);
1363                         goto done;
1364                 }
1365
1366                 my_info3->acct_flags = acct_flags;
1367
1368                 DEBUG(10,("successfully retrieved acct_flags 0x%x\n", acct_flags));
1369
1370                 rpccli_samr_close(samr_pipe, state->mem_ctx, &user_pol);
1371         }
1372
1373         *info3 = my_info3;
1374 done:
1375         return result;
1376 }
1377
1378 enum winbindd_result winbindd_dual_pam_auth(struct winbindd_domain *domain,
1379                                             struct winbindd_cli_state *state) 
1380 {
1381         NTSTATUS result = NT_STATUS_LOGON_FAILURE;
1382         NTSTATUS krb5_result = NT_STATUS_OK;    
1383         fstring name_domain, name_user;
1384         NET_USER_INFO_3 *info3 = NULL;
1385         
1386         /* Ensure null termination */
1387         state->request.data.auth.user[sizeof(state->request.data.auth.user)-1]='\0';
1388
1389         /* Ensure null termination */
1390         state->request.data.auth.pass[sizeof(state->request.data.auth.pass)-1]='\0';
1391
1392         DEBUG(3, ("[%5lu]: dual pam auth %s\n", (unsigned long)state->pid,
1393                   state->request.data.auth.user));
1394
1395         if (!check_request_flags(state->request.flags)) {
1396                 result = NT_STATUS_INVALID_PARAMETER_MIX;
1397                 goto done;
1398         }
1399
1400         /* Parse domain and username */
1401         
1402         ws_name_return( state->request.data.auth.user, WB_REPLACE_CHAR );
1403
1404         parse_domain_user(state->request.data.auth.user, name_domain, name_user);
1405
1406         if (domain->online == False) {
1407                 result = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1408                 if (domain->startup) {
1409                         /* Logons are very important to users. If we're offline and
1410                            we get a request within the first 30 seconds of startup,
1411                            try very hard to find a DC and go online. */
1412
1413                         DEBUG(10,("winbindd_dual_pam_auth: domain: %s offline and auth "
1414                                 "request in startup mode.\n", domain->name ));
1415
1416                         winbindd_flush_negative_conn_cache(domain);
1417                         result = init_dc_connection(domain);
1418                 }
1419         }
1420
1421         DEBUG(10,("winbindd_dual_pam_auth: domain: %s last was %s\n", domain->name, domain->online ? "online":"offline"));
1422
1423         /* Check for Kerberos authentication */
1424         if (domain->online && (state->request.flags & WBFLAG_PAM_KRB5)) {
1425         
1426                 result = winbindd_dual_pam_auth_kerberos(domain, state, &info3);
1427                 /* save for later */
1428                 krb5_result = result;
1429                 
1430
1431                 if (NT_STATUS_IS_OK(result)) {
1432                         DEBUG(10,("winbindd_dual_pam_auth_kerberos succeeded\n"));
1433                         goto process_result;
1434                 } else {
1435                         DEBUG(10,("winbindd_dual_pam_auth_kerberos failed: %s\n", nt_errstr(result)));
1436                 }
1437
1438                 if (NT_STATUS_EQUAL(result, NT_STATUS_NO_LOGON_SERVERS) ||
1439                     NT_STATUS_EQUAL(result, NT_STATUS_IO_TIMEOUT) ||
1440                     NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
1441                         DEBUG(10,("winbindd_dual_pam_auth_kerberos setting domain to offline\n"));
1442                         set_domain_offline( domain );
1443                         goto cached_logon;                      
1444                 }
1445
1446                 /* there are quite some NT_STATUS errors where there is no
1447                  * point in retrying with a samlogon, we explictly have to take
1448                  * care not to increase the bad logon counter on the DC */
1449
1450                 if (NT_STATUS_EQUAL(result, NT_STATUS_ACCOUNT_DISABLED) ||
1451                     NT_STATUS_EQUAL(result, NT_STATUS_ACCOUNT_EXPIRED) ||
1452                     NT_STATUS_EQUAL(result, NT_STATUS_ACCOUNT_LOCKED_OUT) ||
1453                     NT_STATUS_EQUAL(result, NT_STATUS_INVALID_LOGON_HOURS) ||
1454                     NT_STATUS_EQUAL(result, NT_STATUS_INVALID_WORKSTATION) ||
1455                     NT_STATUS_EQUAL(result, NT_STATUS_LOGON_FAILURE) ||
1456                     NT_STATUS_EQUAL(result, NT_STATUS_NO_SUCH_USER) ||
1457                     NT_STATUS_EQUAL(result, NT_STATUS_PASSWORD_EXPIRED) ||
1458                     NT_STATUS_EQUAL(result, NT_STATUS_PASSWORD_MUST_CHANGE) ||
1459                     NT_STATUS_EQUAL(result, NT_STATUS_WRONG_PASSWORD)) {
1460                         goto process_result;
1461                 }
1462                 
1463                 if (state->request.flags & WBFLAG_PAM_FALLBACK_AFTER_KRB5) {
1464                         DEBUG(3,("falling back to samlogon\n"));
1465                         goto sam_logon;
1466                 } else {
1467                         goto cached_logon;
1468                 }
1469         }
1470
1471 sam_logon:
1472         /* Check for Samlogon authentication */
1473         if (domain->online) {
1474                 result = winbindd_dual_pam_auth_samlogon(domain, state, &info3);
1475         
1476                 if (NT_STATUS_IS_OK(result)) {
1477                         DEBUG(10,("winbindd_dual_pam_auth_samlogon succeeded\n"));
1478                         /* add the Krb5 err if we have one */
1479                         if ( NT_STATUS_EQUAL(krb5_result, NT_STATUS_TIME_DIFFERENCE_AT_DC ) ) {
1480                                 info3->user_flgs |= LOGON_KRB5_FAIL_CLOCK_SKEW;                         
1481                         }
1482                         goto process_result;
1483                 } 
1484
1485                 DEBUG(10,("winbindd_dual_pam_auth_samlogon failed: %s\n", 
1486                           nt_errstr(result)));
1487
1488                 if (NT_STATUS_EQUAL(result, NT_STATUS_NO_LOGON_SERVERS) ||
1489                     NT_STATUS_EQUAL(result, NT_STATUS_IO_TIMEOUT) ||
1490                     NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) 
1491                 {
1492                         DEBUG(10,("winbindd_dual_pam_auth_samlogon setting domain to offline\n"));
1493                         set_domain_offline( domain );
1494                         goto cached_logon;                      
1495                 }
1496
1497                         if (domain->online) {
1498                                 /* We're still online - fail. */
1499                                 goto done;
1500                         }
1501         }
1502
1503 cached_logon:
1504         /* Check for Cached logons */
1505         if (!domain->online && (state->request.flags & WBFLAG_PAM_CACHED_LOGIN) && 
1506             lp_winbind_offline_logon()) {
1507         
1508                 result = winbindd_dual_pam_auth_cached(domain, state, &info3);
1509
1510                 if (NT_STATUS_IS_OK(result)) {
1511                         DEBUG(10,("winbindd_dual_pam_auth_cached succeeded\n"));
1512                         goto process_result;
1513                 } else {
1514                         DEBUG(10,("winbindd_dual_pam_auth_cached failed: %s\n", nt_errstr(result)));
1515                         goto done;
1516                 }
1517         }
1518
1519 process_result:
1520
1521         if (NT_STATUS_IS_OK(result)) {
1522         
1523                 DOM_SID user_sid;
1524
1525                 /* In all codepaths where result == NT_STATUS_OK info3 must have
1526                    been initialized. */
1527                 if (!info3) {
1528                         result = NT_STATUS_INTERNAL_ERROR;
1529                         goto done;
1530                 }
1531
1532                 netsamlogon_cache_store(name_user, info3);
1533                 wcache_invalidate_samlogon(find_domain_from_name(name_domain), info3);
1534
1535                 /* save name_to_sid info as early as possible (only if
1536                    this is our primary domain so we don't invalidate
1537                    the cache entry by storing the seq_num for the wrong
1538                    domain). */
1539                 if ( domain->primary ) {                        
1540                         sid_compose(&user_sid, &info3->dom_sid.sid, 
1541                                     info3->user_rid);
1542                         cache_name2sid(domain, name_domain, name_user, 
1543                                        SID_NAME_USER, &user_sid);
1544                 }
1545                 
1546                 /* Check if the user is in the right group */
1547
1548                 if (!NT_STATUS_IS_OK(result = check_info3_in_group(state->mem_ctx, info3,
1549                                         state->request.data.auth.require_membership_of_sid))) {
1550                         DEBUG(3, ("User %s is not in the required group (%s), so plaintext authentication is rejected\n",
1551                                   state->request.data.auth.user, 
1552                                   state->request.data.auth.require_membership_of_sid));
1553                         goto done;
1554                 }
1555
1556                 result = append_data(state, info3, name_domain, name_user);
1557                 if (!NT_STATUS_IS_OK(result)) {
1558                         goto done;
1559                 }
1560
1561                 if ((state->request.flags & WBFLAG_PAM_CACHED_LOGIN)) {
1562
1563                         /* Store in-memory creds for single-signon using ntlm_auth. */
1564                         result = winbindd_add_memory_creds(state->request.data.auth.user,
1565                                                         get_uid_from_state(state),
1566                                                         state->request.data.auth.pass);
1567
1568                         if (!NT_STATUS_IS_OK(result)) {
1569                                 DEBUG(10,("Failed to store memory creds: %s\n", nt_errstr(result)));
1570                                 goto done;
1571                         }
1572
1573                         if (lp_winbind_offline_logon()) {
1574                                 result = winbindd_store_creds(domain,
1575                                                       state->mem_ctx,
1576                                                       state->request.data.auth.user,
1577                                                       state->request.data.auth.pass,
1578                                                       info3, NULL);
1579                                 if (!NT_STATUS_IS_OK(result)) {
1580
1581                                         /* Release refcount. */
1582                                         winbindd_delete_memory_creds(state->request.data.auth.user);
1583
1584                                         DEBUG(10,("Failed to store creds: %s\n", nt_errstr(result)));
1585                                         goto done;
1586                                 }
1587                         }
1588                 }
1589
1590                 result = fillup_password_policy(domain, state);
1591
1592                 if (!NT_STATUS_IS_OK(result) 
1593                     && !NT_STATUS_EQUAL(result, NT_STATUS_NOT_SUPPORTED) ) 
1594                 {
1595                         DEBUG(10,("Failed to get password policies: %s\n", nt_errstr(result)));
1596                         goto done;
1597                 }
1598
1599                 result = NT_STATUS_OK;          
1600         }
1601
1602 done:
1603         /* give us a more useful (more correct?) error code */
1604         if ((NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) ||
1605             (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)))) {
1606                 result = NT_STATUS_NO_LOGON_SERVERS;
1607         }
1608         
1609         state->response.data.auth.nt_status = NT_STATUS_V(result);
1610         fstrcpy(state->response.data.auth.nt_status_string, nt_errstr(result));
1611
1612         /* we might have given a more useful error above */
1613         if (!*state->response.data.auth.error_string) 
1614                 fstrcpy(state->response.data.auth.error_string, get_friendly_nt_error_msg(result));
1615         state->response.data.auth.pam_error = nt_status_to_pam(result);
1616
1617         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, ("Plain-text authentication for user %s returned %s (PAM: %d)\n", 
1618               state->request.data.auth.user, 
1619               state->response.data.auth.nt_status_string,
1620               state->response.data.auth.pam_error));          
1621
1622         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
1623 }
1624
1625
1626 /**********************************************************************
1627  Challenge Response Authentication Protocol 
1628 **********************************************************************/
1629
1630 void winbindd_pam_auth_crap(struct winbindd_cli_state *state)
1631 {
1632         struct winbindd_domain *domain = NULL;
1633         const char *domain_name = NULL;
1634         NTSTATUS result;
1635
1636         if (!check_request_flags(state->request.flags)) {
1637                 result = NT_STATUS_INVALID_PARAMETER_MIX;
1638                 goto done;
1639         }
1640
1641         if (!state->privileged) {
1642                 char *error_string = NULL;
1643                 DEBUG(2, ("winbindd_pam_auth_crap: non-privileged access "
1644                           "denied.  !\n"));
1645                 DEBUGADD(2, ("winbindd_pam_auth_crap: Ensure permissions "
1646                              "on %s are set correctly.\n",
1647                              get_winbind_priv_pipe_dir()));
1648                 /* send a better message than ACCESS_DENIED */
1649                 error_string = talloc_asprintf(state->mem_ctx,
1650                                                "winbind client not authorized "
1651                                                "to use winbindd_pam_auth_crap."
1652                                                " Ensure permissions on %s "
1653                                                "are set correctly.",
1654                                                get_winbind_priv_pipe_dir());
1655                 fstrcpy(state->response.data.auth.error_string, error_string);
1656                 result = NT_STATUS_ACCESS_DENIED;
1657                 goto done;
1658         }
1659
1660         /* Ensure null termination */
1661         state->request.data.auth_crap.user
1662                 [sizeof(state->request.data.auth_crap.user)-1]=0;
1663         state->request.data.auth_crap.domain
1664                 [sizeof(state->request.data.auth_crap.domain)-1]=0;
1665
1666         DEBUG(3, ("[%5lu]: pam auth crap domain: [%s] user: %s\n",
1667                   (unsigned long)state->pid,
1668                   state->request.data.auth_crap.domain,
1669                   state->request.data.auth_crap.user));
1670
1671         if (*state->request.data.auth_crap.domain != '\0') {
1672                 domain_name = state->request.data.auth_crap.domain;
1673         } else if (lp_winbind_use_default_domain()) {
1674                 domain_name = lp_workgroup();
1675         }
1676
1677         if (domain_name != NULL)
1678                 domain = find_auth_domain(state, domain_name);
1679
1680         if (domain != NULL) {
1681                 sendto_domain(state, domain);
1682                 return;
1683         }
1684
1685         result = NT_STATUS_NO_SUCH_USER;
1686
1687  done:
1688         set_auth_errors(&state->response, result);
1689         DEBUG(5, ("CRAP authentication for %s\\%s returned %s (PAM: %d)\n",
1690                   state->request.data.auth_crap.domain,
1691                   state->request.data.auth_crap.user, 
1692                   state->response.data.auth.nt_status_string,
1693                   state->response.data.auth.pam_error));
1694         request_error(state);
1695         return;
1696 }
1697
1698
1699 enum winbindd_result winbindd_dual_pam_auth_crap(struct winbindd_domain *domain,
1700                                                  struct winbindd_cli_state *state) 
1701 {
1702         NTSTATUS result;
1703         NET_USER_INFO_3 info3;
1704         struct rpc_pipe_client *netlogon_pipe;
1705         const char *name_user = NULL;
1706         const char *name_domain = NULL;
1707         const char *workstation;
1708         struct winbindd_domain *contact_domain;
1709         int attempts = 0;
1710         BOOL retry;
1711
1712         DATA_BLOB lm_resp, nt_resp;
1713
1714         /* This is child-only, so no check for privileged access is needed
1715            anymore */
1716
1717         /* Ensure null termination */
1718         state->request.data.auth_crap.user[sizeof(state->request.data.auth_crap.user)-1]=0;
1719         state->request.data.auth_crap.domain[sizeof(state->request.data.auth_crap.domain)-1]=0;
1720
1721         if (!check_request_flags(state->request.flags)) {
1722                 result = NT_STATUS_INVALID_PARAMETER_MIX;
1723                 goto done;
1724         }
1725
1726         name_user = state->request.data.auth_crap.user;
1727
1728         if (*state->request.data.auth_crap.domain) {
1729                 name_domain = state->request.data.auth_crap.domain;
1730         } else if (lp_winbind_use_default_domain()) {
1731                 name_domain = lp_workgroup();
1732         } else {
1733                 DEBUG(5,("no domain specified with username (%s) - failing auth\n", 
1734                          name_user));
1735                 result = NT_STATUS_NO_SUCH_USER;
1736                 goto done;
1737         }
1738
1739         DEBUG(3, ("[%5lu]: pam auth crap domain: %s user: %s\n", (unsigned long)state->pid,
1740                   name_domain, name_user));
1741            
1742         if (*state->request.data.auth_crap.workstation) {
1743                 workstation = state->request.data.auth_crap.workstation;
1744         } else {
1745                 workstation = global_myname();
1746         }
1747
1748         if (state->request.data.auth_crap.lm_resp_len > sizeof(state->request.data.auth_crap.lm_resp)
1749                 || state->request.data.auth_crap.nt_resp_len > sizeof(state->request.data.auth_crap.nt_resp)) {
1750                 DEBUG(0, ("winbindd_pam_auth_crap: invalid password length %u/%u\n", 
1751                           state->request.data.auth_crap.lm_resp_len, 
1752                           state->request.data.auth_crap.nt_resp_len));
1753                 result = NT_STATUS_INVALID_PARAMETER;
1754                 goto done;
1755         }
1756
1757         lm_resp = data_blob_talloc(state->mem_ctx, state->request.data.auth_crap.lm_resp,
1758                                         state->request.data.auth_crap.lm_resp_len);
1759         nt_resp = data_blob_talloc(state->mem_ctx, state->request.data.auth_crap.nt_resp,
1760                                         state->request.data.auth_crap.nt_resp_len);
1761
1762         /* what domain should we contact? */
1763         
1764         if ( IS_DC ) {
1765                 if (!(contact_domain = find_domain_from_name(name_domain))) {
1766                         DEBUG(3, ("Authentication for domain for [%s] -> [%s]\\[%s] failed as %s is not a trusted domain\n", 
1767                                   state->request.data.auth_crap.user, name_domain, name_user, name_domain)); 
1768                         result = NT_STATUS_NO_SUCH_USER;
1769                         goto done;
1770                 }
1771         } else {
1772                 if (is_myname(name_domain)) {
1773                         DEBUG(3, ("Authentication for domain %s (local domain to this server) not supported at this stage\n", name_domain));
1774                         result =  NT_STATUS_NO_SUCH_USER;
1775                         goto done;
1776                 }
1777                 contact_domain = find_our_domain();
1778         }
1779
1780         do {
1781                 ZERO_STRUCT(info3);
1782                 retry = False;
1783
1784                 netlogon_pipe = NULL;
1785                 result = cm_connect_netlogon(contact_domain, &netlogon_pipe);
1786
1787                 if (!NT_STATUS_IS_OK(result)) {
1788                         DEBUG(3, ("could not open handle to NETLOGON pipe (error: %s)\n",
1789                                   nt_errstr(result)));
1790                         goto done;
1791                 }
1792
1793                 result = rpccli_netlogon_sam_network_logon(netlogon_pipe,
1794                                                            state->mem_ctx,
1795                                                            state->request.data.auth_crap.logon_parameters,
1796                                                            contact_domain->dcname,
1797                                                            name_user,
1798                                                            name_domain, 
1799                                                                         /* Bug #3248 - found by Stefan Burkei. */
1800                                                            workstation, /* We carefully set this above so use it... */
1801                                                            state->request.data.auth_crap.chal,
1802                                                            lm_resp,
1803                                                            nt_resp,
1804                                                            &info3);
1805
1806                 attempts += 1;
1807
1808                 /* We have to try a second time as cm_connect_netlogon
1809                    might not yet have noticed that the DC has killed
1810                    our connection. */
1811
1812                 if (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)) {
1813                         retry = True;
1814                         continue;
1815                 }
1816
1817                 /* if we get access denied, a possible cause was that we had and open
1818                    connection to the DC, but someone changed our machine account password
1819                    out from underneath us using 'net rpc changetrustpw' */
1820                    
1821                 if ( NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED) ) {
1822                         DEBUG(3,("winbindd_pam_auth: sam_logon returned "
1823                                  "ACCESS_DENIED.  Maybe the trust account "
1824                                 "password was changed and we didn't know it. "
1825                                  "Killing connections to domain %s\n",
1826                                 name_domain));
1827                         invalidate_cm_connection(&contact_domain->conn);
1828                         retry = True;
1829                 } 
1830
1831         } while ( (attempts < 2) && retry );
1832
1833         if (NT_STATUS_IS_OK(result)) {
1834
1835                 netsamlogon_cache_store(name_user, &info3);
1836                 wcache_invalidate_samlogon(find_domain_from_name(name_domain), &info3);
1837
1838                 /* Check if the user is in the right group */
1839
1840                 if (!NT_STATUS_IS_OK(result = check_info3_in_group(state->mem_ctx, &info3,
1841                                                         state->request.data.auth_crap.require_membership_of_sid))) {
1842                         DEBUG(3, ("User %s is not in the required group (%s), so "
1843                                   "crap authentication is rejected\n",
1844                                   state->request.data.auth_crap.user, 
1845                                   state->request.data.auth_crap.require_membership_of_sid));
1846                         goto done;
1847                 }
1848
1849                 result = append_data(state, &info3, name_domain, name_user);
1850                 if (!NT_STATUS_IS_OK(result)) {
1851                         goto done;
1852                 }
1853         }
1854
1855 done:
1856
1857         /* give us a more useful (more correct?) error code */
1858         if ((NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) ||
1859             (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)))) {
1860                 result = NT_STATUS_NO_LOGON_SERVERS;
1861         }
1862
1863         if (state->request.flags & WBFLAG_PAM_NT_STATUS_SQUASH) {
1864                 result = nt_status_squash(result);
1865         }
1866
1867         state->response.data.auth.nt_status = NT_STATUS_V(result);
1868         fstrcpy(state->response.data.auth.nt_status_string, nt_errstr(result));
1869
1870         /* we might have given a more useful error above */
1871         if (!*state->response.data.auth.error_string) {
1872                 fstrcpy(state->response.data.auth.error_string, get_friendly_nt_error_msg(result));
1873         }
1874         state->response.data.auth.pam_error = nt_status_to_pam(result);
1875
1876         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, 
1877               ("NTLM CRAP authentication for user [%s]\\[%s] returned %s (PAM: %d)\n", 
1878                name_domain,
1879                name_user,
1880                state->response.data.auth.nt_status_string,
1881                state->response.data.auth.pam_error));         
1882
1883         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
1884 }
1885
1886 /* Change a user password */
1887
1888 void winbindd_pam_chauthtok(struct winbindd_cli_state *state)
1889 {
1890         fstring domain, user;
1891         struct winbindd_domain *contact_domain;
1892
1893         DEBUG(3, ("[%5lu]: pam chauthtok %s\n", (unsigned long)state->pid,
1894                 state->request.data.chauthtok.user));
1895
1896         /* Setup crap */
1897
1898         ws_name_return( state->request.data.auth.user, WB_REPLACE_CHAR );
1899
1900         if (!canonicalize_username(state->request.data.chauthtok.user, domain, user)) {
1901                 set_auth_errors(&state->response, NT_STATUS_NO_SUCH_USER);
1902                 DEBUG(5, ("winbindd_pam_chauthtok: canonicalize_username %s failed with %s"
1903                           "(PAM: %d)\n",
1904                           state->request.data.auth.user, 
1905                           state->response.data.auth.nt_status_string,
1906                           state->response.data.auth.pam_error));
1907                 request_error(state);
1908                 return;
1909         }
1910
1911         contact_domain = find_domain_from_name(domain);
1912         if (!contact_domain) {
1913                 set_auth_errors(&state->response, NT_STATUS_NO_SUCH_USER);
1914                 DEBUG(3, ("Cannot change password for [%s] -> [%s]\\[%s] as %s is not a trusted domain\n", 
1915                           state->request.data.chauthtok.user, domain, user, domain)); 
1916                 request_error(state);
1917                 return;
1918         }
1919
1920         sendto_domain(state, contact_domain);
1921 }
1922
1923 enum winbindd_result winbindd_dual_pam_chauthtok(struct winbindd_domain *contact_domain,
1924                                                  struct winbindd_cli_state *state)
1925 {
1926         char *oldpass;
1927         char *newpass = NULL;
1928         POLICY_HND dom_pol;
1929         struct rpc_pipe_client *cli;
1930         BOOL got_info = False;
1931         SAM_UNK_INFO_1 info;
1932         SAMR_CHANGE_REJECT reject;
1933         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
1934         fstring domain, user;
1935
1936         DEBUG(3, ("[%5lu]: dual pam chauthtok %s\n", (unsigned long)state->pid,
1937                   state->request.data.auth.user));
1938
1939         if (!parse_domain_user(state->request.data.chauthtok.user, domain, user)) {
1940                 goto done;
1941         }
1942
1943         /* Change password */
1944
1945         oldpass = state->request.data.chauthtok.oldpass;
1946         newpass = state->request.data.chauthtok.newpass;
1947
1948         /* Initialize reject reason */
1949         state->response.data.auth.reject_reason = Undefined;
1950
1951         /* Get sam handle */
1952
1953         result = cm_connect_sam(contact_domain, state->mem_ctx, &cli,
1954                                 &dom_pol);
1955         if (!NT_STATUS_IS_OK(result)) {
1956                 DEBUG(1, ("could not get SAM handle on DC for %s\n", domain));
1957                 goto done;
1958         }
1959
1960         result = rpccli_samr_chgpasswd3(cli, state->mem_ctx, user, newpass, oldpass, &info, &reject);
1961
1962         /* Windows 2003 returns NT_STATUS_PASSWORD_RESTRICTION */
1963
1964         if (NT_STATUS_EQUAL(result, NT_STATUS_PASSWORD_RESTRICTION) ) {
1965                 state->response.data.auth.policy.min_length_password = 
1966                         info.min_length_password;
1967                 state->response.data.auth.policy.password_history = 
1968                         info.password_history;
1969                 state->response.data.auth.policy.password_properties = 
1970                         info.password_properties;
1971                 state->response.data.auth.policy.expire = 
1972                         nt_time_to_unix_abs(&info.expire);
1973                 state->response.data.auth.policy.min_passwordage = 
1974                         nt_time_to_unix_abs(&info.min_passwordage);
1975
1976                 state->response.data.auth.reject_reason = 
1977                         reject.reject_reason;
1978
1979                 got_info = True;
1980         }
1981
1982         /* only fallback when the chgpasswd3 call is not supported */
1983         if ((NT_STATUS_EQUAL(result, NT_STATUS(DCERPC_FAULT_OP_RNG_ERROR))) ||
1984                    (NT_STATUS_EQUAL(result, NT_STATUS_NOT_SUPPORTED)) ||
1985                    (NT_STATUS_EQUAL(result, NT_STATUS_NOT_IMPLEMENTED))) {
1986
1987                 DEBUG(10,("Password change with chgpasswd3 failed with: %s, retrying chgpasswd_user\n", 
1988                         nt_errstr(result)));
1989                 
1990                 result = rpccli_samr_chgpasswd_user(cli, state->mem_ctx, user, newpass, oldpass);
1991
1992                 /* Windows 2000 returns NT_STATUS_ACCOUNT_RESTRICTION.
1993                    Map to the same status code as Windows 2003. */
1994
1995                 if ( NT_STATUS_EQUAL(NT_STATUS_ACCOUNT_RESTRICTION, result ) ) {
1996                         result = NT_STATUS_PASSWORD_RESTRICTION;                        
1997                 }
1998         }
1999
2000 done: 
2001
2002         if (NT_STATUS_IS_OK(result) && (state->request.flags & WBFLAG_PAM_CACHED_LOGIN)) {
2003                 
2004                 /* Update the single sign-on memory creds. */
2005                 result = winbindd_replace_memory_creds(state->request.data.chauthtok.user,
2006                                                         newpass);
2007
2008                 if (!NT_STATUS_IS_OK(result)) {
2009                         DEBUG(10,("Failed to replace memory creds: %s\n", nt_errstr(result)));
2010                         goto process_result;
2011                 }
2012
2013                 if (lp_winbind_offline_logon()) {
2014                         result = winbindd_update_creds_by_name(contact_domain,
2015                                                          state->mem_ctx, user,
2016                                                          newpass);
2017                         if (!NT_STATUS_IS_OK(result)) {
2018                                 DEBUG(10,("Failed to store creds: %s\n", nt_errstr(result)));
2019                                 goto process_result;
2020                         }
2021                 }
2022         }               
2023
2024         if (!NT_STATUS_IS_OK(result) && !got_info && contact_domain) {
2025
2026                 NTSTATUS policy_ret;
2027                 
2028                 policy_ret = fillup_password_policy(contact_domain, state);
2029
2030                 /* failure of this is non critical, it will just provide no
2031                  * additional information to the client why the change has
2032                  * failed - Guenther */
2033
2034                 if (!NT_STATUS_IS_OK(policy_ret)) {
2035                         DEBUG(10,("Failed to get password policies: %s\n", nt_errstr(policy_ret)));
2036                         goto process_result;
2037                 }
2038         }
2039
2040 process_result:
2041
2042         state->response.data.auth.nt_status = NT_STATUS_V(result);
2043         fstrcpy(state->response.data.auth.nt_status_string, nt_errstr(result));
2044         fstrcpy(state->response.data.auth.error_string, get_friendly_nt_error_msg(result));
2045         state->response.data.auth.pam_error = nt_status_to_pam(result);
2046
2047         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, 
2048               ("Password change for user [%s]\\[%s] returned %s (PAM: %d)\n", 
2049                domain,
2050                user,
2051                state->response.data.auth.nt_status_string,
2052                state->response.data.auth.pam_error));         
2053
2054         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
2055 }
2056
2057 void winbindd_pam_logoff(struct winbindd_cli_state *state)
2058 {
2059         struct winbindd_domain *domain;
2060         fstring name_domain, user;
2061         uid_t caller_uid = (uid_t)-1;
2062         uid_t request_uid = state->request.data.logoff.uid;
2063
2064         DEBUG(3, ("[%5lu]: pam logoff %s\n", (unsigned long)state->pid,
2065                 state->request.data.logoff.user));
2066
2067         /* Ensure null termination */
2068         state->request.data.logoff.user
2069                 [sizeof(state->request.data.logoff.user)-1]='\0';
2070
2071         state->request.data.logoff.krb5ccname
2072                 [sizeof(state->request.data.logoff.krb5ccname)-1]='\0';
2073
2074         if (request_uid == (gid_t)-1) {
2075                 goto failed;
2076         }
2077
2078         if (!canonicalize_username(state->request.data.logoff.user, name_domain, user)) {
2079                 goto failed;
2080         }
2081
2082         if ((domain = find_auth_domain(state, name_domain)) == NULL) {
2083                 goto failed;
2084         }
2085
2086         if ((sys_getpeereid(state->sock, &caller_uid)) != 0) {
2087                 DEBUG(1,("winbindd_pam_logoff: failed to check peerid: %s\n", 
2088                         strerror(errno)));
2089                 goto failed;
2090         }
2091
2092         switch (caller_uid) {
2093                 case -1:
2094                         goto failed;
2095                 case 0:
2096                         /* root must be able to logoff any user - gd */
2097                         state->request.data.logoff.uid = request_uid;
2098                         break;
2099                 default:
2100                         if (caller_uid != request_uid) {
2101                                 DEBUG(1,("winbindd_pam_logoff: caller requested invalid uid\n"));
2102                                 goto failed;
2103                         }
2104                         state->request.data.logoff.uid = caller_uid;
2105                         break;
2106         }
2107
2108         sendto_domain(state, domain);
2109         return;
2110
2111  failed:
2112         set_auth_errors(&state->response, NT_STATUS_NO_SUCH_USER);
2113         DEBUG(5, ("Pam Logoff for %s returned %s "
2114                   "(PAM: %d)\n",
2115                   state->request.data.logoff.user,
2116                   state->response.data.auth.nt_status_string,
2117                   state->response.data.auth.pam_error));
2118         request_error(state);
2119         return;
2120 }
2121
2122 enum winbindd_result winbindd_dual_pam_logoff(struct winbindd_domain *domain,
2123                                               struct winbindd_cli_state *state) 
2124 {
2125         NTSTATUS result = NT_STATUS_NOT_SUPPORTED;
2126
2127         DEBUG(3, ("[%5lu]: pam dual logoff %s\n", (unsigned long)state->pid,
2128                 state->request.data.logoff.user));
2129
2130         if (!(state->request.flags & WBFLAG_PAM_KRB5)) {
2131                 result = NT_STATUS_OK;
2132                 goto process_result;
2133         }
2134
2135         if (state->request.data.logoff.krb5ccname[0] == '\0') {
2136                 result = NT_STATUS_OK;
2137                 goto process_result;
2138         }
2139
2140 #ifdef HAVE_KRB5
2141         
2142         if (state->request.data.logoff.uid < 0) {
2143                 DEBUG(0,("winbindd_pam_logoff: invalid uid\n"));
2144                 goto process_result;
2145         }
2146
2147         /* what we need here is to find the corresponding krb5 ccache name *we*
2148          * created for a given username and destroy it */
2149
2150         if (!ccache_entry_exists(state->request.data.logoff.user)) {
2151                 result = NT_STATUS_OK;
2152                 DEBUG(10,("winbindd_pam_logoff: no entry found.\n"));
2153                 goto process_result;
2154         }
2155
2156         if (!ccache_entry_identical(state->request.data.logoff.user, 
2157                                         state->request.data.logoff.uid,
2158                                         state->request.data.logoff.krb5ccname)) {
2159                 DEBUG(0,("winbindd_pam_logoff: cached entry differs.\n"));
2160                 goto process_result;
2161         }
2162
2163         result = remove_ccache(state->request.data.logoff.user);
2164         if (!NT_STATUS_IS_OK(result)) {
2165                 DEBUG(0,("winbindd_pam_logoff: failed to remove ccache: %s\n",
2166                         nt_errstr(result)));
2167                 goto process_result;
2168         }
2169
2170 #else
2171         result = NT_STATUS_NOT_SUPPORTED;
2172 #endif
2173
2174 process_result:
2175
2176         winbindd_delete_memory_creds(state->request.data.logoff.user);
2177
2178         state->response.data.auth.nt_status = NT_STATUS_V(result);
2179         fstrcpy(state->response.data.auth.nt_status_string, nt_errstr(result));
2180         fstrcpy(state->response.data.auth.error_string, get_friendly_nt_error_msg(result));
2181         state->response.data.auth.pam_error = nt_status_to_pam(result);
2182
2183         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
2184 }
2185
2186 /* Change user password with auth crap*/
2187
2188 void winbindd_pam_chng_pswd_auth_crap(struct winbindd_cli_state *state)
2189 {
2190         struct winbindd_domain *domain = NULL;
2191         const char *domain_name = NULL;
2192
2193         /* Ensure null termination */
2194         state->request.data.chng_pswd_auth_crap.user[
2195                 sizeof(state->request.data.chng_pswd_auth_crap.user)-1]=0;
2196         state->request.data.chng_pswd_auth_crap.domain[
2197                 sizeof(state->request.data.chng_pswd_auth_crap.domain)-1]=0;
2198         
2199         DEBUG(3, ("[%5lu]: pam change pswd auth crap domain: %s user: %s\n",
2200                   (unsigned long)state->pid,
2201                   state->request.data.chng_pswd_auth_crap.domain,
2202                   state->request.data.chng_pswd_auth_crap.user));
2203         
2204         if (*state->request.data.chng_pswd_auth_crap.domain != '\0') {
2205                 domain_name = state->request.data.chng_pswd_auth_crap.domain;
2206         } else if (lp_winbind_use_default_domain()) {
2207                 domain_name = lp_workgroup();
2208         }
2209
2210         if (domain_name != NULL)
2211                 domain = find_domain_from_name(domain_name);
2212
2213         if (domain != NULL) {
2214                 DEBUG(7, ("[%5lu]: pam auth crap changing pswd in domain: "
2215                           "%s\n", (unsigned long)state->pid,domain->name));
2216                 sendto_domain(state, domain);
2217                 return;
2218         }
2219
2220         set_auth_errors(&state->response, NT_STATUS_NO_SUCH_USER);
2221         DEBUG(5, ("CRAP change password  for %s\\%s returned %s (PAM: %d)\n",
2222                   state->request.data.chng_pswd_auth_crap.domain,
2223                   state->request.data.chng_pswd_auth_crap.user, 
2224                   state->response.data.auth.nt_status_string,
2225                   state->response.data.auth.pam_error));
2226         request_error(state);
2227         return;
2228 }
2229
2230 enum winbindd_result winbindd_dual_pam_chng_pswd_auth_crap(struct winbindd_domain *domainSt, struct winbindd_cli_state *state)
2231 {
2232         NTSTATUS result;
2233         DATA_BLOB new_nt_password;
2234         DATA_BLOB old_nt_hash_enc;
2235         DATA_BLOB new_lm_password;
2236         DATA_BLOB old_lm_hash_enc;
2237         fstring  domain,user;
2238         POLICY_HND dom_pol;
2239         struct winbindd_domain *contact_domain = domainSt;
2240         struct rpc_pipe_client *cli;
2241
2242         /* Ensure null termination */
2243         state->request.data.chng_pswd_auth_crap.user[
2244                 sizeof(state->request.data.chng_pswd_auth_crap.user)-1]=0;
2245         state->request.data.chng_pswd_auth_crap.domain[
2246                 sizeof(state->request.data.chng_pswd_auth_crap.domain)-1]=0;
2247         *domain = 0;
2248         *user = 0;
2249         
2250         DEBUG(3, ("[%5lu]: pam change pswd auth crap domain: %s user: %s\n",
2251                   (unsigned long)state->pid,
2252                   state->request.data.chng_pswd_auth_crap.domain,
2253                   state->request.data.chng_pswd_auth_crap.user));
2254
2255         if (lp_winbind_offline_logon()) {
2256                 DEBUG(0,("Refusing password change as winbind offline logons are enabled. "));
2257                 DEBUGADD(0,("Changing passwords here would risk inconsistent logons\n"));
2258                 result = NT_STATUS_ACCESS_DENIED;
2259                 goto done;
2260         }
2261
2262         if (*state->request.data.chng_pswd_auth_crap.domain) {
2263                 fstrcpy(domain,state->request.data.chng_pswd_auth_crap.domain);
2264         } else {
2265                 parse_domain_user(state->request.data.chng_pswd_auth_crap.user,
2266                                   domain, user);
2267
2268                 if(!*domain) {
2269                         DEBUG(3,("no domain specified with username (%s) - "
2270                                  "failing auth\n",
2271                                  state->request.data.chng_pswd_auth_crap.user));
2272                         result = NT_STATUS_NO_SUCH_USER;
2273                         goto done;
2274                 }
2275         }
2276
2277         if (!*domain && lp_winbind_use_default_domain()) {
2278                 fstrcpy(domain,(char *)lp_workgroup());
2279         }
2280
2281         if(!*user) {
2282                 fstrcpy(user, state->request.data.chng_pswd_auth_crap.user);
2283         }
2284
2285         DEBUG(3, ("[%5lu]: pam auth crap domain: %s user: %s\n",
2286                   (unsigned long)state->pid, domain, user));
2287         
2288         /* Change password */
2289         new_nt_password = data_blob_talloc(
2290                 state->mem_ctx,
2291                 state->request.data.chng_pswd_auth_crap.new_nt_pswd,
2292                 state->request.data.chng_pswd_auth_crap.new_nt_pswd_len);
2293
2294         old_nt_hash_enc = data_blob_talloc(
2295                 state->mem_ctx,
2296                 state->request.data.chng_pswd_auth_crap.old_nt_hash_enc,
2297                 state->request.data.chng_pswd_auth_crap.old_nt_hash_enc_len);
2298
2299         if(state->request.data.chng_pswd_auth_crap.new_lm_pswd_len > 0) {
2300                 new_lm_password = data_blob_talloc(
2301                         state->mem_ctx,
2302                         state->request.data.chng_pswd_auth_crap.new_lm_pswd,
2303                         state->request.data.chng_pswd_auth_crap.new_lm_pswd_len);
2304
2305                 old_lm_hash_enc = data_blob_talloc(
2306                         state->mem_ctx,
2307                         state->request.data.chng_pswd_auth_crap.old_lm_hash_enc,
2308                         state->request.data.chng_pswd_auth_crap.old_lm_hash_enc_len);
2309         } else {
2310                 new_lm_password.length = 0;
2311                 old_lm_hash_enc.length = 0;
2312         }
2313
2314         /* Get sam handle */
2315
2316         result = cm_connect_sam(contact_domain, state->mem_ctx, &cli, &dom_pol);
2317         if (!NT_STATUS_IS_OK(result)) {
2318                 DEBUG(1, ("could not get SAM handle on DC for %s\n", domain));
2319                 goto done;
2320         }
2321
2322         result = rpccli_samr_chng_pswd_auth_crap(
2323                 cli, state->mem_ctx, user, new_nt_password, old_nt_hash_enc,
2324                 new_lm_password, old_lm_hash_enc);
2325
2326  done:    
2327         state->response.data.auth.nt_status = NT_STATUS_V(result);
2328         fstrcpy(state->response.data.auth.nt_status_string, nt_errstr(result));
2329         fstrcpy(state->response.data.auth.error_string,
2330                 get_friendly_nt_error_msg(result));
2331         state->response.data.auth.pam_error = nt_status_to_pam(result);
2332
2333         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, 
2334               ("Password change for user [%s]\\[%s] returned %s (PAM: %d)\n", 
2335                domain, user,
2336                state->response.data.auth.nt_status_string,
2337                state->response.data.auth.pam_error));         
2338
2339         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
2340 }