winbind: Fix CID 1427626 Uninitialized scalar variable
[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 #include "../libcli/auth/libcli_auth.h"
28 #include "../librpc/gen_ndr/ndr_samr_c.h"
29 #include "rpc_client/cli_pipe.h"
30 #include "rpc_client/cli_samr.h"
31 #include "../librpc/gen_ndr/ndr_netlogon.h"
32 #include "rpc_client/cli_netlogon.h"
33 #include "smb_krb5.h"
34 #include "../lib/crypto/arcfour.h"
35 #include "../libcli/security/security.h"
36 #include "ads.h"
37 #include "../librpc/gen_ndr/krb5pac.h"
38 #include "passdb/machine_sid.h"
39 #include "auth.h"
40 #include "../lib/tsocket/tsocket.h"
41 #include "auth/kerberos/pac_utils.h"
42 #include "auth/gensec/gensec.h"
43 #include "librpc/crypto/gse_krb5.h"
44 #include "lib/afs/afs_funcs.h"
45 #include "libsmb/samlogon_cache.h"
46 #include "rpc_client/util_netlogon.h"
47
48 #undef DBGC_CLASS
49 #define DBGC_CLASS DBGC_WINBIND
50
51 #define LOGON_KRB5_FAIL_CLOCK_SKEW      0x02000000
52
53 static NTSTATUS append_info3_as_txt(TALLOC_CTX *mem_ctx,
54                                     struct winbindd_response *resp,
55                                     uint16_t validation_level,
56                                     union netr_Validation *validation)
57 {
58         struct netr_SamInfo3 *info3 = NULL;
59         char *ex = NULL;
60         uint32_t i;
61         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
62         TALLOC_CTX *frame = talloc_stackframe();
63
64         status = map_validation_to_info3(frame,
65                                          validation_level,
66                                          validation,
67                                          &info3);
68         if (!NT_STATUS_IS_OK(status)) {
69                 goto out;
70         }
71
72         resp->data.auth.info3.logon_time =
73                 nt_time_to_unix(info3->base.logon_time);
74         resp->data.auth.info3.logoff_time =
75                 nt_time_to_unix(info3->base.logoff_time);
76         resp->data.auth.info3.kickoff_time =
77                 nt_time_to_unix(info3->base.kickoff_time);
78         resp->data.auth.info3.pass_last_set_time =
79                 nt_time_to_unix(info3->base.last_password_change);
80         resp->data.auth.info3.pass_can_change_time =
81                 nt_time_to_unix(info3->base.allow_password_change);
82         resp->data.auth.info3.pass_must_change_time =
83                 nt_time_to_unix(info3->base.force_password_change);
84
85         resp->data.auth.info3.logon_count = info3->base.logon_count;
86         resp->data.auth.info3.bad_pw_count = info3->base.bad_password_count;
87
88         resp->data.auth.info3.user_rid = info3->base.rid;
89         resp->data.auth.info3.group_rid = info3->base.primary_gid;
90         sid_to_fstring(resp->data.auth.info3.dom_sid, info3->base.domain_sid);
91
92         resp->data.auth.info3.num_groups = info3->base.groups.count;
93         resp->data.auth.info3.user_flgs = info3->base.user_flags;
94
95         resp->data.auth.info3.acct_flags = info3->base.acct_flags;
96         resp->data.auth.info3.num_other_sids = info3->sidcount;
97
98         fstrcpy(resp->data.auth.info3.user_name,
99                 info3->base.account_name.string);
100         fstrcpy(resp->data.auth.info3.full_name,
101                 info3->base.full_name.string);
102         fstrcpy(resp->data.auth.info3.logon_script,
103                 info3->base.logon_script.string);
104         fstrcpy(resp->data.auth.info3.profile_path,
105                 info3->base.profile_path.string);
106         fstrcpy(resp->data.auth.info3.home_dir,
107                 info3->base.home_directory.string);
108         fstrcpy(resp->data.auth.info3.dir_drive,
109                 info3->base.home_drive.string);
110
111         fstrcpy(resp->data.auth.info3.logon_srv,
112                 info3->base.logon_server.string);
113         fstrcpy(resp->data.auth.info3.logon_dom,
114                 info3->base.logon_domain.string);
115
116         resp->data.auth.validation_level = validation_level;
117         if (validation_level == 6) {
118                 fstrcpy(resp->data.auth.info6.dns_domainname,
119                         validation->sam6->dns_domainname.string);
120                 fstrcpy(resp->data.auth.info6.principal_name,
121                         validation->sam6->principal_name.string);
122         }
123
124         ex = talloc_strdup(frame, "");
125         if (ex == NULL) {
126                 status = NT_STATUS_NO_MEMORY;
127                 goto out;
128         }
129
130         for (i=0; i < info3->base.groups.count; i++) {
131                 ex = talloc_asprintf_append_buffer(ex, "0x%08X:0x%08X\n",
132                                                    info3->base.groups.rids[i].rid,
133                                                    info3->base.groups.rids[i].attributes);
134                 if (ex == NULL) {
135                         status = NT_STATUS_NO_MEMORY;
136                         goto out;
137                 }
138         }
139
140         for (i=0; i < info3->sidcount; i++) {
141                 char *sid;
142
143                 sid = dom_sid_string(frame, info3->sids[i].sid);
144                 if (sid == NULL) {
145                         status = NT_STATUS_NO_MEMORY;
146                         goto out;
147                 }
148
149                 ex = talloc_asprintf_append_buffer(ex, "%s:0x%08X\n",
150                                                    sid,
151                                                    info3->sids[i].attributes);
152                 if (ex == NULL) {
153                         status = NT_STATUS_NO_MEMORY;
154                         goto out;
155                 }
156         }
157
158         resp->length += talloc_get_size(ex);
159         resp->extra_data.data = talloc_move(mem_ctx, &ex);
160
161         status = NT_STATUS_OK;
162 out:
163         TALLOC_FREE(frame);
164         return status;
165 }
166
167 static NTSTATUS append_info3_as_ndr(TALLOC_CTX *mem_ctx,
168                                     struct winbindd_response *resp,
169                                     struct netr_SamInfo3 *info3)
170 {
171         DATA_BLOB blob;
172         enum ndr_err_code ndr_err;
173
174         ndr_err = ndr_push_struct_blob(&blob, mem_ctx, info3,
175                                        (ndr_push_flags_fn_t)ndr_push_netr_SamInfo3);
176         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
177                 DEBUG(0,("append_info3_as_ndr: failed to append\n"));
178                 return ndr_map_error2ntstatus(ndr_err);
179         }
180
181         resp->extra_data.data = blob.data;
182         resp->length += blob.length;
183
184         return NT_STATUS_OK;
185 }
186
187 static NTSTATUS append_unix_username(TALLOC_CTX *mem_ctx,
188                                      struct winbindd_response *resp,
189                                      const struct netr_SamInfo3 *info3,
190                                      const char *name_domain,
191                                      const char *name_user)
192 {
193         /* We've been asked to return the unix username, per
194            'winbind use default domain' settings and the like */
195
196         const char *nt_username, *nt_domain;
197
198         nt_domain = talloc_strdup(mem_ctx, info3->base.logon_domain.string);
199         if (!nt_domain) {
200                 /* If the server didn't give us one, just use the one
201                  * we sent them */
202                 nt_domain = name_domain;
203         }
204
205         nt_username = talloc_strdup(mem_ctx, info3->base.account_name.string);
206         if (!nt_username) {
207                 /* If the server didn't give us one, just use the one
208                  * we sent them */
209                 nt_username = name_user;
210         }
211
212         fill_domain_username(resp->data.auth.unix_username,
213                              nt_domain, nt_username, true);
214
215         DEBUG(5, ("Setting unix username to [%s]\n",
216                   resp->data.auth.unix_username));
217
218         return NT_STATUS_OK;
219 }
220
221 static NTSTATUS append_afs_token(TALLOC_CTX *mem_ctx,
222                                  struct winbindd_response *resp,
223                                  const struct netr_SamInfo3 *info3,
224                                  const char *name_domain,
225                                  const char *name_user)
226 {
227         char *afsname = NULL;
228         char *cell;
229         char *token;
230
231         afsname = talloc_strdup(mem_ctx, lp_afs_username_map());
232         if (afsname == NULL) {
233                 return NT_STATUS_NO_MEMORY;
234         }
235
236         afsname = talloc_string_sub(mem_ctx,
237                                     lp_afs_username_map(),
238                                     "%D", name_domain);
239         afsname = talloc_string_sub(mem_ctx, afsname,
240                                     "%u", name_user);
241         afsname = talloc_string_sub(mem_ctx, afsname,
242                                     "%U", name_user);
243
244         {
245                 struct dom_sid user_sid;
246                 fstring sidstr;
247
248                 sid_compose(&user_sid, info3->base.domain_sid,
249                             info3->base.rid);
250                 sid_to_fstring(sidstr, &user_sid);
251                 afsname = talloc_string_sub(mem_ctx, afsname,
252                                             "%s", sidstr);
253         }
254
255         if (afsname == NULL) {
256                 return NT_STATUS_NO_MEMORY;
257         }
258
259         if (!strlower_m(afsname)) {
260                 return NT_STATUS_INVALID_PARAMETER;
261         }
262
263         DEBUG(10, ("Generating token for user %s\n", afsname));
264
265         cell = strchr(afsname, '@');
266
267         if (cell == NULL) {
268                 return NT_STATUS_NO_MEMORY;
269         }
270
271         *cell = '\0';
272         cell += 1;
273
274         token = afs_createtoken_str(afsname, cell);
275         if (token == NULL) {
276                 return NT_STATUS_OK;
277         }
278         resp->extra_data.data = talloc_strdup(mem_ctx, token);
279         if (resp->extra_data.data == NULL) {
280                 return NT_STATUS_NO_MEMORY;
281         }
282         resp->length += strlen((const char *)resp->extra_data.data)+1;
283
284         return NT_STATUS_OK;
285 }
286
287 static NTSTATUS check_info3_in_group(struct netr_SamInfo3 *info3,
288                                      const char *group_sid)
289 /**
290  * Check whether a user belongs to a group or list of groups.
291  *
292  * @param mem_ctx talloc memory context.
293  * @param info3 user information, including group membership info.
294  * @param group_sid One or more groups , separated by commas.
295  *
296  * @return NT_STATUS_OK on success,
297  *    NT_STATUS_LOGON_FAILURE if the user does not belong,
298  *    or other NT_STATUS_IS_ERR(status) for other kinds of failure.
299  */
300 {
301         struct dom_sid *require_membership_of_sid;
302         uint32_t num_require_membership_of_sid;
303         char *req_sid;
304         const char *p;
305         struct dom_sid sid;
306         size_t i;
307         struct security_token *token;
308         TALLOC_CTX *frame = talloc_stackframe();
309         NTSTATUS status;
310
311         /* Parse the 'required group' SID */
312
313         if (!group_sid || !group_sid[0]) {
314                 /* NO sid supplied, all users may access */
315                 TALLOC_FREE(frame);
316                 return NT_STATUS_OK;
317         }
318
319         token = talloc_zero(talloc_tos(), struct security_token);
320         if (token == NULL) {
321                 DEBUG(0, ("talloc failed\n"));
322                 TALLOC_FREE(frame);
323                 return NT_STATUS_NO_MEMORY;
324         }
325
326         num_require_membership_of_sid = 0;
327         require_membership_of_sid = NULL;
328
329         p = group_sid;
330
331         while (next_token_talloc(talloc_tos(), &p, &req_sid, ",")) {
332                 if (!string_to_sid(&sid, req_sid)) {
333                         DEBUG(0, ("check_info3_in_group: could not parse %s "
334                                   "as a SID!", req_sid));
335                         TALLOC_FREE(frame);
336                         return NT_STATUS_INVALID_PARAMETER;
337                 }
338
339                 status = add_sid_to_array(talloc_tos(), &sid,
340                                           &require_membership_of_sid,
341                                           &num_require_membership_of_sid);
342                 if (!NT_STATUS_IS_OK(status)) {
343                         DEBUG(0, ("add_sid_to_array failed\n"));
344                         TALLOC_FREE(frame);
345                         return status;
346                 }
347         }
348
349         status = sid_array_from_info3(talloc_tos(), info3,
350                                       &token->sids,
351                                       &token->num_sids,
352                                       true);
353         if (!NT_STATUS_IS_OK(status)) {
354                 TALLOC_FREE(frame);
355                 return status;
356         }
357
358         if (!NT_STATUS_IS_OK(status = add_aliases(get_global_sam_sid(),
359                                                   token))
360             || !NT_STATUS_IS_OK(status = add_aliases(&global_sid_Builtin,
361                                                      token))) {
362                 DEBUG(3, ("could not add aliases: %s\n",
363                           nt_errstr(status)));
364                 TALLOC_FREE(frame);
365                 return status;
366         }
367
368         security_token_debug(DBGC_CLASS, 10, token);
369
370         for (i=0; i<num_require_membership_of_sid; i++) {
371                 DEBUG(10, ("Checking SID %s\n", sid_string_dbg(
372                                    &require_membership_of_sid[i])));
373                 if (nt_token_check_sid(&require_membership_of_sid[i],
374                                        token)) {
375                         DEBUG(10, ("Access ok\n"));
376                         TALLOC_FREE(frame);
377                         return NT_STATUS_OK;
378                 }
379         }
380
381         /* Do not distinguish this error from a wrong username/pw */
382
383         TALLOC_FREE(frame);
384         return NT_STATUS_LOGON_FAILURE;
385 }
386
387 struct winbindd_domain *find_auth_domain(uint8_t flags,
388                                          const char *domain_name)
389 {
390         struct winbindd_domain *domain;
391
392         if (IS_DC) {
393                 domain = find_domain_from_name_noinit(domain_name);
394                 if (domain == NULL) {
395                         DEBUG(3, ("Authentication for domain [%s] refused "
396                                   "as it is not a trusted domain\n",
397                                   domain_name));
398                 }
399                 return domain;
400         }
401
402         if (strequal(domain_name, get_global_sam_name())) {
403                 return find_domain_from_name_noinit(domain_name);
404         }
405
406         /* we can auth against trusted domains */
407         if (flags & WBFLAG_PAM_CONTACT_TRUSTDOM) {
408                 domain = find_domain_from_name_noinit(domain_name);
409                 if (domain == NULL) {
410                         DEBUG(3, ("Authentication for domain [%s] skipped "
411                                   "as it is not a trusted domain\n",
412                                   domain_name));
413                 } else {
414                         return domain;
415                 }
416         }
417
418         return find_our_domain();
419 }
420
421 static void fake_password_policy(struct winbindd_response *r,
422                                  const struct netr_SamBaseInfo *bi)
423 {
424         NTTIME min_password_age;
425         NTTIME max_password_age;
426
427         if (bi->allow_password_change > bi->last_password_change) {
428                 min_password_age = bi->allow_password_change -
429                                    bi->last_password_change;
430         } else {
431                 min_password_age = 0;
432         }
433
434         if (bi->force_password_change > bi->last_password_change) {
435                 max_password_age = bi->force_password_change -
436                                    bi->last_password_change;
437         } else {
438                 max_password_age = 0;
439         }
440
441         r->data.auth.policy.min_length_password = 0;
442         r->data.auth.policy.password_history = 0;
443         r->data.auth.policy.password_properties = 0;
444         r->data.auth.policy.expire =
445                 nt_time_to_unix_abs(&max_password_age);
446         r->data.auth.policy.min_passwordage =
447                 nt_time_to_unix_abs(&min_password_age);
448 }
449
450 static void fill_in_password_policy(struct winbindd_response *r,
451                                     const struct samr_DomInfo1 *p)
452 {
453         r->data.auth.policy.min_length_password =
454                 p->min_password_length;
455         r->data.auth.policy.password_history =
456                 p->password_history_length;
457         r->data.auth.policy.password_properties =
458                 p->password_properties;
459         r->data.auth.policy.expire      =
460                 nt_time_to_unix_abs((const NTTIME *)&(p->max_password_age));
461         r->data.auth.policy.min_passwordage =
462                 nt_time_to_unix_abs((const NTTIME *)&(p->min_password_age));
463 }
464
465 static NTSTATUS fillup_password_policy(struct winbindd_domain *domain,
466                                        struct winbindd_response *response)
467 {
468         TALLOC_CTX *frame = talloc_stackframe();
469         NTSTATUS status;
470         struct samr_DomInfo1 password_policy;
471
472         if ( !winbindd_can_contact_domain( domain ) ) {
473                 DEBUG(5,("fillup_password_policy: No inbound trust to "
474                          "contact domain %s\n", domain->name));
475                 status = NT_STATUS_NOT_SUPPORTED;
476                 goto done;
477         }
478
479         status = wb_cache_password_policy(domain, talloc_tos(),
480                                           &password_policy);
481         if (NT_STATUS_IS_ERR(status)) {
482                 goto done;
483         }
484
485         fill_in_password_policy(response, &password_policy);
486
487 done:
488         TALLOC_FREE(frame);
489         return NT_STATUS_OK;
490 }
491
492 static NTSTATUS get_max_bad_attempts_from_lockout_policy(struct winbindd_domain *domain,
493                                                          TALLOC_CTX *mem_ctx,
494                                                          uint16_t *lockout_threshold)
495 {
496         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
497         struct samr_DomInfo12 lockout_policy;
498
499         *lockout_threshold = 0;
500
501         status = wb_cache_lockout_policy(domain, mem_ctx, &lockout_policy);
502         if (NT_STATUS_IS_ERR(status)) {
503                 return status;
504         }
505
506         *lockout_threshold = lockout_policy.lockout_threshold;
507
508         return NT_STATUS_OK;
509 }
510
511 static NTSTATUS get_pwd_properties(struct winbindd_domain *domain,
512                                    TALLOC_CTX *mem_ctx,
513                                    uint32_t *password_properties)
514 {
515         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
516         struct samr_DomInfo1 password_policy;
517
518         *password_properties = 0;
519
520         status = wb_cache_password_policy(domain, mem_ctx, &password_policy);
521         if (NT_STATUS_IS_ERR(status)) {
522                 return status;
523         }
524
525         *password_properties = password_policy.password_properties;
526
527         return NT_STATUS_OK;
528 }
529
530 #ifdef HAVE_KRB5
531
532 static const char *generate_krb5_ccache(TALLOC_CTX *mem_ctx,
533                                         const char *type,
534                                         uid_t uid,
535                                         const char **user_ccache_file)
536 {
537         /* accept FILE and WRFILE as krb5_cc_type from the client and then
538          * build the full ccname string based on the user's uid here -
539          * Guenther*/
540
541         const char *gen_cc = NULL;
542
543         if (uid != -1) {
544                 if (strequal(type, "FILE")) {
545                         gen_cc = talloc_asprintf(
546                                 mem_ctx, "FILE:/tmp/krb5cc_%d", uid);
547                 }
548                 if (strequal(type, "WRFILE")) {
549                         gen_cc = talloc_asprintf(
550                                 mem_ctx, "WRFILE:/tmp/krb5cc_%d", uid);
551                 }
552                 if (strequal(type, "KEYRING")) {
553                         gen_cc = talloc_asprintf(
554                                 mem_ctx, "KEYRING:persistent:%d", uid);
555                 }
556
557                 if (strnequal(type, "FILE:/", 6) ||
558                     strnequal(type, "WRFILE:/", 8) ||
559                     strnequal(type, "DIR:/", 5)) {
560
561                         /* we allow only one "%u" substitution */
562
563                         char *p;
564
565                         p = strchr(type, '%');
566                         if (p != NULL) {
567
568                                 p++;
569
570                                 if (p != NULL && *p == 'u' && strchr(p, '%') == NULL) {
571                                         char uid_str[sizeof("18446744073709551615")];
572
573                                         snprintf(uid_str, sizeof(uid_str), "%u", uid);
574
575                                         gen_cc = talloc_string_sub2(mem_ctx,
576                                                         type,
577                                                         "%u",
578                                                         uid_str,
579                                                         /* remove_unsafe_characters */
580                                                         false,
581                                                         /* replace_once */
582                                                         true,
583                                                         /* allow_trailing_dollar */
584                                                         false);
585                                 }
586                         }
587                 }
588         }
589
590         *user_ccache_file = gen_cc;
591
592         if (gen_cc == NULL) {
593                 gen_cc = talloc_strdup(mem_ctx, "MEMORY:winbindd_pam_ccache");
594         }
595         if (gen_cc == NULL) {
596                 DEBUG(0,("out of memory\n"));
597                 return NULL;
598         }
599
600         DEBUG(10, ("using ccache: %s%s\n", gen_cc,
601                    (*user_ccache_file == NULL) ? " (internal)":""));
602
603         return gen_cc;
604 }
605
606 #endif
607
608 uid_t get_uid_from_request(struct winbindd_request *request)
609 {
610         uid_t uid;
611
612         uid = request->data.auth.uid;
613
614         if (uid == (uid_t)-1) {
615                 DEBUG(1,("invalid uid: '%u'\n", (unsigned int)uid));
616                 return -1;
617         }
618         return uid;
619 }
620
621 /**********************************************************************
622  Authenticate a user with a clear text password using Kerberos and fill up
623  ccache if required
624  **********************************************************************/
625
626 static NTSTATUS winbindd_raw_kerberos_login(TALLOC_CTX *mem_ctx,
627                                             struct winbindd_domain *domain,
628                                             const char *user,
629                                             const char *pass,
630                                             const char *krb5_cc_type,
631                                             uid_t uid,
632                                             struct netr_SamInfo3 **info3,
633                                             fstring krb5ccname)
634 {
635 #ifdef HAVE_KRB5
636         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
637         krb5_error_code krb5_ret;
638         const char *cc = NULL;
639         const char *principal_s = NULL;
640         const char *service = NULL;
641         char *realm = NULL;
642         fstring name_domain, name_user;
643         time_t ticket_lifetime = 0;
644         time_t renewal_until = 0;
645         ADS_STRUCT *ads;
646         time_t time_offset = 0;
647         const char *user_ccache_file;
648         struct PAC_LOGON_INFO *logon_info = NULL;
649         struct PAC_DATA *pac_data = NULL;
650         struct PAC_DATA_CTR *pac_data_ctr = NULL;
651         const char *local_service;
652         uint32_t i;
653         struct netr_SamInfo3 *info3_copy = NULL;
654
655         *info3 = NULL;
656
657         if (domain->alt_name == NULL) {
658                 return NT_STATUS_INVALID_PARAMETER;
659         }
660
661         /* 1st step:
662          * prepare a krb5_cc_cache string for the user */
663
664         if (uid == -1) {
665                 DEBUG(0,("no valid uid\n"));
666         }
667
668         cc = generate_krb5_ccache(mem_ctx,
669                                   krb5_cc_type,
670                                   uid,
671                                   &user_ccache_file);
672         if (cc == NULL) {
673                 return NT_STATUS_NO_MEMORY;
674         }
675
676
677         /* 2nd step:
678          * get kerberos properties */
679
680         if (domain->private_data) {
681                 ads = (ADS_STRUCT *)domain->private_data;
682                 time_offset = ads->auth.time_offset;
683         }
684
685
686         /* 3rd step:
687          * do kerberos auth and setup ccache as the user */
688
689         parse_domain_user(user, name_domain, name_user);
690
691         realm = talloc_strdup(mem_ctx, domain->alt_name);
692         if (realm == NULL) {
693                 return NT_STATUS_NO_MEMORY;
694         }
695
696         if (!strupper_m(realm)) {
697                 return NT_STATUS_INVALID_PARAMETER;
698         }
699
700         principal_s = talloc_asprintf(mem_ctx, "%s@%s", name_user, realm);
701         if (principal_s == NULL) {
702                 return NT_STATUS_NO_MEMORY;
703         }
704
705         service = talloc_asprintf(mem_ctx, "%s/%s@%s", KRB5_TGS_NAME, realm, realm);
706         if (service == NULL) {
707                 return NT_STATUS_NO_MEMORY;
708         }
709
710         local_service = talloc_asprintf(mem_ctx, "%s$@%s",
711                                         lp_netbios_name(), lp_realm());
712         if (local_service == NULL) {
713                 return NT_STATUS_NO_MEMORY;
714         }
715
716
717         /* if this is a user ccache, we need to act as the user to let the krb5
718          * library handle the chown, etc. */
719
720         /************************ ENTERING NON-ROOT **********************/
721
722         if (user_ccache_file != NULL) {
723                 set_effective_uid(uid);
724                 DEBUG(10,("winbindd_raw_kerberos_login: uid is %d\n", uid));
725         }
726
727         result = kerberos_return_pac(mem_ctx,
728                                      principal_s,
729                                      pass,
730                                      time_offset,
731                                      &ticket_lifetime,
732                                      &renewal_until,
733                                      cc,
734                                      true,
735                                      true,
736                                      WINBINDD_PAM_AUTH_KRB5_RENEW_TIME,
737                                      NULL,
738                                      local_service,
739                                      &pac_data_ctr);
740         if (user_ccache_file != NULL) {
741                 gain_root_privilege();
742         }
743
744         /************************ RETURNED TO ROOT **********************/
745
746         if (!NT_STATUS_IS_OK(result)) {
747                 goto failed;
748         }
749
750         if (pac_data_ctr == NULL) {
751                 goto failed;
752         }
753
754         pac_data = pac_data_ctr->pac_data;
755         if (pac_data == NULL) {
756                 goto failed;
757         }
758
759         for (i=0; i < pac_data->num_buffers; i++) {
760
761                 if (pac_data->buffers[i].type != PAC_TYPE_LOGON_INFO) {
762                         continue;
763                 }
764
765                 logon_info = pac_data->buffers[i].info->logon_info.info;
766                 if (!logon_info) {
767                         return NT_STATUS_INVALID_PARAMETER;
768                 }
769
770                 break;
771         }
772
773         if (logon_info == NULL) {
774                 DEBUG(10,("Missing logon_info in ticket of %s\n",
775                         principal_s));
776                 return NT_STATUS_INVALID_PARAMETER;
777         }
778
779         DEBUG(10,("winbindd_raw_kerberos_login: winbindd validated ticket of %s\n",
780                 principal_s));
781
782         result = create_info3_from_pac_logon_info(mem_ctx, logon_info, &info3_copy);
783         if (!NT_STATUS_IS_OK(result)) {
784                 goto failed;
785         }
786
787         /* if we had a user's ccache then return that string for the pam
788          * environment */
789
790         if (user_ccache_file != NULL) {
791
792                 fstrcpy(krb5ccname, user_ccache_file);
793
794                 result = add_ccache_to_list(principal_s,
795                                             cc,
796                                             service,
797                                             user,
798                                             pass,
799                                             realm,
800                                             uid,
801                                             time(NULL),
802                                             ticket_lifetime,
803                                             renewal_until,
804                                             false);
805
806                 if (!NT_STATUS_IS_OK(result)) {
807                         DEBUG(10,("winbindd_raw_kerberos_login: failed to add ccache to list: %s\n",
808                                 nt_errstr(result)));
809                 }
810         } else {
811
812                 /* need to delete the memory cred cache, it is not used anymore */
813
814                 krb5_ret = ads_kdestroy(cc);
815                 if (krb5_ret) {
816                         DEBUG(3,("winbindd_raw_kerberos_login: "
817                                  "could not destroy krb5 credential cache: "
818                                  "%s\n", error_message(krb5_ret)));
819                 }
820
821         }
822         *info3 = info3_copy;
823         return NT_STATUS_OK;
824
825 failed:
826         /*
827          * Do not delete an existing valid credential cache, if the user
828          * e.g. enters a wrong password
829          */
830         if ((strequal(krb5_cc_type, "FILE") || strequal(krb5_cc_type, "WRFILE"))
831             && user_ccache_file != NULL) {
832                 return result;
833         }
834
835         /* we could have created a new credential cache with a valid tgt in it
836          * but we werent able to get or verify the service ticket for this
837          * local host and therefor didn't get the PAC, we need to remove that
838          * cache entirely now */
839
840         krb5_ret = ads_kdestroy(cc);
841         if (krb5_ret) {
842                 DEBUG(3,("winbindd_raw_kerberos_login: "
843                          "could not destroy krb5 credential cache: "
844                          "%s\n", error_message(krb5_ret)));
845         }
846
847         if (!NT_STATUS_IS_OK(remove_ccache(user))) {
848                 DEBUG(3,("winbindd_raw_kerberos_login: "
849                           "could not remove ccache for user %s\n",
850                         user));
851         }
852
853         return result;
854 #else
855         return NT_STATUS_NOT_SUPPORTED;
856 #endif /* HAVE_KRB5 */
857 }
858
859 /****************************************************************
860 ****************************************************************/
861
862 bool check_request_flags(uint32_t flags)
863 {
864         uint32_t flags_edata = WBFLAG_PAM_AFS_TOKEN |
865                                WBFLAG_PAM_INFO3_TEXT |
866                                WBFLAG_PAM_INFO3_NDR;
867
868         if ( ( (flags & flags_edata) == WBFLAG_PAM_AFS_TOKEN) ||
869              ( (flags & flags_edata) == WBFLAG_PAM_INFO3_NDR) ||
870              ( (flags & flags_edata) == WBFLAG_PAM_INFO3_TEXT)||
871               !(flags & flags_edata) ) {
872                 return true;
873         }
874
875         DEBUG(1, ("check_request_flags: invalid request flags[0x%08X]\n",
876                   flags));
877
878         return false;
879 }
880
881 /****************************************************************
882 ****************************************************************/
883
884 NTSTATUS append_auth_data(TALLOC_CTX *mem_ctx,
885                           struct winbindd_response *resp,
886                           uint32_t request_flags,
887                           uint16_t validation_level,
888                           union netr_Validation *validation,
889                           const char *name_domain,
890                           const char *name_user)
891 {
892         struct netr_SamInfo3 *info3 = NULL;
893         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
894
895         result = map_validation_to_info3(talloc_tos(),
896                                          validation_level,
897                                          validation,
898                                          &info3);
899         if (!NT_STATUS_IS_OK(result)) {
900                 goto out;
901         }
902
903         if (request_flags & WBFLAG_PAM_USER_SESSION_KEY) {
904                 memcpy(resp->data.auth.user_session_key,
905                        info3->base.key.key,
906                        sizeof(resp->data.auth.user_session_key)
907                        /* 16 */);
908         }
909
910         if (request_flags & WBFLAG_PAM_LMKEY) {
911                 memcpy(resp->data.auth.first_8_lm_hash,
912                        info3->base.LMSessKey.key,
913                        sizeof(resp->data.auth.first_8_lm_hash)
914                        /* 8 */);
915         }
916
917         if (request_flags & WBFLAG_PAM_UNIX_NAME) {
918                 result = append_unix_username(mem_ctx, resp,
919                                               info3, name_domain, name_user);
920                 if (!NT_STATUS_IS_OK(result)) {
921                         DEBUG(10,("Failed to append Unix Username: %s\n",
922                                 nt_errstr(result)));
923                         goto out;
924                 }
925         }
926
927         /* currently, anything from here on potentially overwrites extra_data. */
928
929         if (request_flags & WBFLAG_PAM_INFO3_NDR) {
930                 result = append_info3_as_ndr(mem_ctx, resp, info3);
931                 if (!NT_STATUS_IS_OK(result)) {
932                         DEBUG(10,("Failed to append INFO3 (NDR): %s\n",
933                                 nt_errstr(result)));
934                         goto out;
935                 }
936         }
937
938         if (request_flags & WBFLAG_PAM_INFO3_TEXT) {
939                 result = append_info3_as_txt(mem_ctx, resp,
940                                              validation_level,
941                                              validation);
942                 if (!NT_STATUS_IS_OK(result)) {
943                         DEBUG(10,("Failed to append INFO3 (TXT): %s\n",
944                                 nt_errstr(result)));
945                         goto out;
946                 }
947         }
948
949         if (request_flags & WBFLAG_PAM_AFS_TOKEN) {
950                 result = append_afs_token(mem_ctx, resp,
951                                           info3, name_domain, name_user);
952                 if (!NT_STATUS_IS_OK(result)) {
953                         DEBUG(10,("Failed to append AFS token: %s\n",
954                                 nt_errstr(result)));
955                         goto out;
956                 }
957         }
958
959         result = NT_STATUS_OK;
960 out:
961         TALLOC_FREE(info3);
962         return result;
963 }
964
965 static NTSTATUS winbindd_dual_pam_auth_cached(struct winbindd_domain *domain,
966                                               struct winbindd_cli_state *state,
967                                               struct netr_SamInfo3 **info3)
968 {
969         NTSTATUS result = NT_STATUS_LOGON_FAILURE;
970         uint16_t max_allowed_bad_attempts;
971         fstring name_domain, name_user;
972         struct dom_sid sid;
973         enum lsa_SidType type;
974         uchar new_nt_pass[NT_HASH_LEN];
975         const uint8_t *cached_nt_pass;
976         const uint8_t *cached_salt;
977         struct netr_SamInfo3 *my_info3;
978         time_t kickoff_time, must_change_time;
979         bool password_good = false;
980 #ifdef HAVE_KRB5
981         struct winbindd_tdc_domain *tdc_domain = NULL;
982 #endif
983
984         *info3 = NULL;
985
986         ZERO_STRUCTP(info3);
987
988         DEBUG(10,("winbindd_dual_pam_auth_cached\n"));
989
990         /* Parse domain and username */
991
992         parse_domain_user(state->request->data.auth.user, name_domain, name_user);
993
994
995         if (!lookup_cached_name(name_domain,
996                                 name_user,
997                                 &sid,
998                                 &type)) {
999                 DEBUG(10,("winbindd_dual_pam_auth_cached: no such user in the cache\n"));
1000                 return NT_STATUS_NO_SUCH_USER;
1001         }
1002
1003         if (type != SID_NAME_USER) {
1004                 DEBUG(10,("winbindd_dual_pam_auth_cached: not a user (%s)\n", sid_type_lookup(type)));
1005                 return NT_STATUS_LOGON_FAILURE;
1006         }
1007
1008         result = winbindd_get_creds(domain,
1009                                     state->mem_ctx,
1010                                     &sid,
1011                                     &my_info3,
1012                                     &cached_nt_pass,
1013                                     &cached_salt);
1014         if (!NT_STATUS_IS_OK(result)) {
1015                 DEBUG(10,("winbindd_dual_pam_auth_cached: failed to get creds: %s\n", nt_errstr(result)));
1016                 return result;
1017         }
1018
1019         *info3 = my_info3;
1020
1021         E_md4hash(state->request->data.auth.pass, new_nt_pass);
1022
1023         dump_data_pw("new_nt_pass", new_nt_pass, NT_HASH_LEN);
1024         dump_data_pw("cached_nt_pass", cached_nt_pass, NT_HASH_LEN);
1025         if (cached_salt) {
1026                 dump_data_pw("cached_salt", cached_salt, NT_HASH_LEN);
1027         }
1028
1029         if (cached_salt) {
1030                 /* In this case we didn't store the nt_hash itself,
1031                    but the MD5 combination of salt + nt_hash. */
1032                 uchar salted_hash[NT_HASH_LEN];
1033                 E_md5hash(cached_salt, new_nt_pass, salted_hash);
1034
1035                 password_good = (memcmp(cached_nt_pass, salted_hash,
1036                                         NT_HASH_LEN) == 0);
1037         } else {
1038                 /* Old cached cred - direct store of nt_hash (bad bad bad !). */
1039                 password_good = (memcmp(cached_nt_pass, new_nt_pass,
1040                                         NT_HASH_LEN) == 0);
1041         }
1042
1043         if (password_good) {
1044
1045                 /* User *DOES* know the password, update logon_time and reset
1046                  * bad_pw_count */
1047
1048                 my_info3->base.user_flags |= NETLOGON_CACHED_ACCOUNT;
1049
1050                 if (my_info3->base.acct_flags & ACB_AUTOLOCK) {
1051                         return NT_STATUS_ACCOUNT_LOCKED_OUT;
1052                 }
1053
1054                 if (my_info3->base.acct_flags & ACB_DISABLED) {
1055                         return NT_STATUS_ACCOUNT_DISABLED;
1056                 }
1057
1058                 if (my_info3->base.acct_flags & ACB_WSTRUST) {
1059                         return NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT;
1060                 }
1061
1062                 if (my_info3->base.acct_flags & ACB_SVRTRUST) {
1063                         return NT_STATUS_NOLOGON_SERVER_TRUST_ACCOUNT;
1064                 }
1065
1066                 if (my_info3->base.acct_flags & ACB_DOMTRUST) {
1067                         return NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT;
1068                 }
1069
1070                 if (!(my_info3->base.acct_flags & ACB_NORMAL)) {
1071                         DEBUG(0,("winbindd_dual_pam_auth_cached: whats wrong with that one?: 0x%08x\n",
1072                                 my_info3->base.acct_flags));
1073                         return NT_STATUS_LOGON_FAILURE;
1074                 }
1075
1076                 kickoff_time = nt_time_to_unix(my_info3->base.kickoff_time);
1077                 if (kickoff_time != 0 && time(NULL) > kickoff_time) {
1078                         return NT_STATUS_ACCOUNT_EXPIRED;
1079                 }
1080
1081                 must_change_time = nt_time_to_unix(my_info3->base.force_password_change);
1082                 if (must_change_time != 0 && must_change_time < time(NULL)) {
1083                         /* we allow grace logons when the password has expired */
1084                         my_info3->base.user_flags |= NETLOGON_GRACE_LOGON;
1085                         /* return NT_STATUS_PASSWORD_EXPIRED; */
1086                         goto success;
1087                 }
1088
1089 #ifdef HAVE_KRB5
1090                 if ((state->request->flags & WBFLAG_PAM_KRB5) &&
1091                     ((tdc_domain = wcache_tdc_fetch_domain(state->mem_ctx, name_domain)) != NULL) &&
1092                     ((tdc_domain->trust_type & LSA_TRUST_TYPE_UPLEVEL) ||
1093                     /* used to cope with the case winbindd starting without network. */
1094                     !strequal(tdc_domain->domain_name, tdc_domain->dns_name))) {
1095
1096                         uid_t uid = -1;
1097                         const char *cc = NULL;
1098                         char *realm = NULL;
1099                         const char *principal_s = NULL;
1100                         const char *service = NULL;
1101                         const char *user_ccache_file;
1102
1103                         if (domain->alt_name == NULL) {
1104                                 return NT_STATUS_INVALID_PARAMETER;
1105                         }
1106
1107                         uid = get_uid_from_request(state->request);
1108                         if (uid == -1) {
1109                                 DEBUG(0,("winbindd_dual_pam_auth_cached: invalid uid\n"));
1110                                 return NT_STATUS_INVALID_PARAMETER;
1111                         }
1112
1113                         cc = generate_krb5_ccache(state->mem_ctx,
1114                                                 state->request->data.auth.krb5_cc_type,
1115                                                 state->request->data.auth.uid,
1116                                                 &user_ccache_file);
1117                         if (cc == NULL) {
1118                                 return NT_STATUS_NO_MEMORY;
1119                         }
1120
1121                         realm = talloc_strdup(state->mem_ctx, domain->alt_name);
1122                         if (realm == NULL) {
1123                                 return NT_STATUS_NO_MEMORY;
1124                         }
1125
1126                         if (!strupper_m(realm)) {
1127                                 return NT_STATUS_INVALID_PARAMETER;
1128                         }
1129
1130                         principal_s = talloc_asprintf(state->mem_ctx, "%s@%s", name_user, realm);
1131                         if (principal_s == NULL) {
1132                                 return NT_STATUS_NO_MEMORY;
1133                         }
1134
1135                         service = talloc_asprintf(state->mem_ctx, "%s/%s@%s", KRB5_TGS_NAME, realm, realm);
1136                         if (service == NULL) {
1137                                 return NT_STATUS_NO_MEMORY;
1138                         }
1139
1140                         if (user_ccache_file != NULL) {
1141
1142                                 fstrcpy(state->response->data.auth.krb5ccname,
1143                                         user_ccache_file);
1144
1145                                 result = add_ccache_to_list(principal_s,
1146                                                             cc,
1147                                                             service,
1148                                                             state->request->data.auth.user,
1149                                                             state->request->data.auth.pass,
1150                                                             realm,
1151                                                             uid,
1152                                                             time(NULL),
1153                                                             time(NULL) + lp_winbind_cache_time(),
1154                                                             time(NULL) + WINBINDD_PAM_AUTH_KRB5_RENEW_TIME,
1155                                                             true);
1156
1157                                 if (!NT_STATUS_IS_OK(result)) {
1158                                         DEBUG(10,("winbindd_dual_pam_auth_cached: failed "
1159                                                 "to add ccache to list: %s\n",
1160                                                 nt_errstr(result)));
1161                                 }
1162                         }
1163                 }
1164 #endif /* HAVE_KRB5 */
1165  success:
1166                 /* FIXME: we possibly should handle logon hours as well (does xp when
1167                  * offline?) see auth/auth_sam.c:sam_account_ok for details */
1168
1169                 unix_to_nt_time(&my_info3->base.logon_time, time(NULL));
1170                 my_info3->base.bad_password_count = 0;
1171
1172                 result = winbindd_update_creds_by_info3(domain,
1173                                                         state->request->data.auth.user,
1174                                                         state->request->data.auth.pass,
1175                                                         my_info3);
1176                 if (!NT_STATUS_IS_OK(result)) {
1177                         DEBUG(1,("winbindd_dual_pam_auth_cached: failed to update creds: %s\n",
1178                                 nt_errstr(result)));
1179                         return result;
1180                 }
1181
1182                 return NT_STATUS_OK;
1183
1184         }
1185
1186         /* User does *NOT* know the correct password, modify info3 accordingly, but only if online */
1187         if (domain->online == false) {
1188                 goto failed;
1189         }
1190
1191         /* failure of this is not critical */
1192         result = get_max_bad_attempts_from_lockout_policy(domain, state->mem_ctx, &max_allowed_bad_attempts);
1193         if (!NT_STATUS_IS_OK(result)) {
1194                 DEBUG(10,("winbindd_dual_pam_auth_cached: failed to get max_allowed_bad_attempts. "
1195                           "Won't be able to honour account lockout policies\n"));
1196         }
1197
1198         /* increase counter */
1199         my_info3->base.bad_password_count++;
1200
1201         if (max_allowed_bad_attempts == 0) {
1202                 goto failed;
1203         }
1204
1205         /* lockout user */
1206         if (my_info3->base.bad_password_count >= max_allowed_bad_attempts) {
1207
1208                 uint32_t password_properties;
1209
1210                 result = get_pwd_properties(domain, state->mem_ctx, &password_properties);
1211                 if (!NT_STATUS_IS_OK(result)) {
1212                         DEBUG(10,("winbindd_dual_pam_auth_cached: failed to get password properties.\n"));
1213                 }
1214
1215                 if ((my_info3->base.rid != DOMAIN_RID_ADMINISTRATOR) ||
1216                     (password_properties & DOMAIN_PASSWORD_LOCKOUT_ADMINS)) {
1217                         my_info3->base.acct_flags |= ACB_AUTOLOCK;
1218                 }
1219         }
1220
1221 failed:
1222         result = winbindd_update_creds_by_info3(domain,
1223                                                 state->request->data.auth.user,
1224                                                 NULL,
1225                                                 my_info3);
1226
1227         if (!NT_STATUS_IS_OK(result)) {
1228                 DEBUG(0,("winbindd_dual_pam_auth_cached: failed to update creds %s\n",
1229                         nt_errstr(result)));
1230         }
1231
1232         return NT_STATUS_LOGON_FAILURE;
1233 }
1234
1235 static NTSTATUS winbindd_dual_pam_auth_kerberos(struct winbindd_domain *domain,
1236                                                 struct winbindd_cli_state *state,
1237                                                 struct netr_SamInfo3 **info3)
1238 {
1239         struct winbindd_domain *contact_domain;
1240         fstring name_domain, name_user;
1241         NTSTATUS result;
1242
1243         DEBUG(10,("winbindd_dual_pam_auth_kerberos\n"));
1244
1245         /* Parse domain and username */
1246
1247         parse_domain_user(state->request->data.auth.user, name_domain, name_user);
1248
1249         /* what domain should we contact? */
1250
1251         if ( IS_DC ) {
1252                 if (!(contact_domain = find_domain_from_name(name_domain))) {
1253                         DEBUG(3, ("Authentication for domain for [%s] -> [%s]\\[%s] failed as %s is not a trusted domain\n",
1254                                   state->request->data.auth.user, name_domain, name_user, name_domain));
1255                         result = NT_STATUS_NO_SUCH_USER;
1256                         goto done;
1257                 }
1258
1259         } else {
1260                 if (is_myname(name_domain)) {
1261                         DEBUG(3, ("Authentication for domain %s (local domain to this server) not supported at this stage\n", name_domain));
1262                         result =  NT_STATUS_NO_SUCH_USER;
1263                         goto done;
1264                 }
1265
1266                 contact_domain = find_domain_from_name(name_domain);
1267                 if (contact_domain == NULL) {
1268                         DEBUG(3, ("Authentication for domain for [%s] -> [%s]\\[%s] failed as %s is not a trusted domain\n",
1269                                   state->request->data.auth.user, name_domain, name_user, name_domain));
1270
1271                         result =  NT_STATUS_NO_SUCH_USER;
1272                         goto done;
1273                 }
1274         }
1275
1276         if (contact_domain->initialized &&
1277             contact_domain->active_directory) {
1278                 goto try_login;
1279         }
1280
1281         if (!contact_domain->initialized) {
1282                 init_dc_connection(contact_domain, false);
1283         }
1284
1285         if (!contact_domain->active_directory) {
1286                 DEBUG(3,("krb5 auth requested but domain is not Active Directory\n"));
1287                 return NT_STATUS_INVALID_LOGON_TYPE;
1288         }
1289 try_login:
1290         result = winbindd_raw_kerberos_login(
1291                 state->mem_ctx, contact_domain,
1292                 state->request->data.auth.user,
1293                 state->request->data.auth.pass,
1294                 state->request->data.auth.krb5_cc_type,
1295                 get_uid_from_request(state->request),
1296                 info3, state->response->data.auth.krb5ccname);
1297 done:
1298         return result;
1299 }
1300
1301 static NTSTATUS winbindd_dual_auth_passdb(TALLOC_CTX *mem_ctx,
1302                                           uint32_t logon_parameters,
1303                                           const char *domain, const char *user,
1304                                           const DATA_BLOB *challenge,
1305                                           const DATA_BLOB *lm_resp,
1306                                           const DATA_BLOB *nt_resp,
1307                                           bool interactive,
1308                                           uint8_t *pauthoritative,
1309                                           struct netr_SamInfo3 **pinfo3)
1310 {
1311         struct auth_context *auth_context;
1312         struct auth_serversupplied_info *server_info;
1313         struct auth_usersupplied_info *user_info = NULL;
1314         struct tsocket_address *local;
1315         struct netr_SamInfo3 *info3;
1316         NTSTATUS status;
1317         bool ok;
1318         int rc;
1319         TALLOC_CTX *frame = talloc_stackframe();
1320
1321         /*
1322          * We are authoritative by default
1323          */
1324         *pauthoritative = 1;
1325
1326         rc = tsocket_address_inet_from_strings(frame,
1327                                                "ip",
1328                                                "127.0.0.1",
1329                                                0,
1330                                                &local);
1331         if (rc < 0) {
1332                 TALLOC_FREE(frame);
1333                 return NT_STATUS_NO_MEMORY;
1334         }
1335
1336         /*
1337          * TODO: We should get the service description passed in from
1338          * the winbind client, so we can have "smb2", "squid" or "samr" logged
1339          * here.
1340          */
1341         status = make_user_info(frame, &user_info, user, user, domain, domain,
1342                                 lp_netbios_name(), local, local,
1343                                 "winbind",
1344                                 lm_resp, nt_resp, NULL, NULL,
1345                                 NULL, AUTH_PASSWORD_RESPONSE);
1346         if (!NT_STATUS_IS_OK(status)) {
1347                 DEBUG(10, ("make_user_info failed: %s\n", nt_errstr(status)));
1348                 TALLOC_FREE(frame);
1349                 return status;
1350         }
1351
1352         user_info->logon_parameters = logon_parameters;
1353
1354         /* We don't want any more mapping of the username */
1355         user_info->mapped_state = True;
1356
1357         /* We don't want to come back to winbindd or to do PAM account checks */
1358         user_info->flags |= USER_INFO_INFO3_AND_NO_AUTHZ;
1359
1360         if (interactive) {
1361                 user_info->flags |= USER_INFO_INTERACTIVE_LOGON;
1362         }
1363
1364         status = make_auth3_context_for_winbind(frame, &auth_context);
1365         if (!NT_STATUS_IS_OK(status)) {
1366                 DBG_ERR("make_auth3_context_for_winbind failed: %s\n",
1367                         nt_errstr(status));
1368                 TALLOC_FREE(frame);
1369                 return status;
1370         }
1371
1372         ok = auth3_context_set_challenge(auth_context,
1373                                          challenge->data, "fixed");
1374         if (!ok) {
1375                 TALLOC_FREE(frame);
1376                 return NT_STATUS_NO_MEMORY;
1377         }
1378
1379         status = auth_check_ntlm_password(mem_ctx,
1380                                           auth_context,
1381                                           user_info,
1382                                           &server_info,
1383                                           pauthoritative);
1384         if (!NT_STATUS_IS_OK(status)) {
1385                 TALLOC_FREE(frame);
1386                 return status;
1387         }
1388
1389         info3 = talloc_zero(mem_ctx, struct netr_SamInfo3);
1390         if (info3 == NULL) {
1391                 TALLOC_FREE(frame);
1392                 return NT_STATUS_NO_MEMORY;
1393         }
1394
1395         status = serverinfo_to_SamInfo3(server_info, info3);
1396         if (!NT_STATUS_IS_OK(status)) {
1397                 TALLOC_FREE(frame);
1398                 TALLOC_FREE(info3);
1399                 DEBUG(0, ("serverinfo_to_SamInfo3 failed: %s\n",
1400                           nt_errstr(status)));
1401                 return status;
1402         }
1403
1404         *pinfo3 = info3;
1405         DEBUG(10, ("Authenticaticating user %s\\%s returned %s\n", domain,
1406                    user, nt_errstr(status)));
1407         TALLOC_FREE(frame);
1408         return status;
1409 }
1410
1411 static NTSTATUS winbind_samlogon_retry_loop(struct winbindd_domain *domain,
1412                                             TALLOC_CTX *mem_ctx,
1413                                             uint32_t logon_parameters,
1414                                             const char *username,
1415                                             const char *password,
1416                                             const char *domainname,
1417                                             const char *workstation,
1418                                             const uint8_t chal[8],
1419                                             DATA_BLOB lm_response,
1420                                             DATA_BLOB nt_response,
1421                                             bool interactive,
1422                                             uint8_t *authoritative,
1423                                             uint32_t *flags,
1424                                             uint16_t *_validation_level,
1425                                             union netr_Validation **_validation)
1426 {
1427         int attempts = 0;
1428         int netr_attempts = 0;
1429         bool retry = false;
1430         NTSTATUS result;
1431         uint16_t validation_level = UINT16_MAX;
1432         union netr_Validation *validation = NULL;
1433
1434         do {
1435                 struct rpc_pipe_client *netlogon_pipe;
1436
1437                 retry = false;
1438
1439                 result = cm_connect_netlogon(domain, &netlogon_pipe);
1440
1441                 if (NT_STATUS_EQUAL(result,
1442                                     NT_STATUS_CANT_ACCESS_DOMAIN_INFO)) {
1443                         /*
1444                          * This means we don't have a trust account.
1445                          */
1446                         *authoritative = 0;
1447                         result = NT_STATUS_NO_SUCH_USER;
1448                         break;
1449                 }
1450
1451                 if (!NT_STATUS_IS_OK(result)) {
1452                         DEBUG(3,("Could not open handle to NETLOGON pipe "
1453                                  "(error: %s, attempts: %d)\n",
1454                                   nt_errstr(result), netr_attempts));
1455
1456                         /* After the first retry always close the connection */
1457                         if (netr_attempts > 0) {
1458                                 DEBUG(3, ("This is again a problem for this "
1459                                           "particular call, forcing the close "
1460                                           "of this connection\n"));
1461                                 invalidate_cm_connection(domain);
1462                         }
1463
1464                         /* After the second retry failover to the next DC */
1465                         if (netr_attempts > 1) {
1466                                 /*
1467                                  * If the netlogon server is not reachable then
1468                                  * it is possible that the DC is rebuilding
1469                                  * sysvol and shutdown netlogon for that time.
1470                                  * We should failover to the next dc.
1471                                  */
1472                                 DEBUG(3, ("This is the third problem for this "
1473                                           "particular call, adding DC to the "
1474                                           "negative cache list: %s %s\n", domain->name, domain->dcname));
1475                                 add_failed_connection_entry(domain->name,
1476                                                             domain->dcname,
1477                                                             result);
1478                                 saf_delete(domain->name);
1479                         }
1480
1481                         /* Only allow 3 retries */
1482                         if (netr_attempts < 3) {
1483                                 DEBUG(3, ("The connection to netlogon "
1484                                           "failed, retrying\n"));
1485                                 netr_attempts++;
1486                                 retry = true;
1487                                 continue;
1488                         }
1489                         return result;
1490                 }
1491                 netr_attempts = 0;
1492                 if (domain->conn.netlogon_creds_ctx == NULL) {
1493                         DBG_NOTICE("No security credentials available for "
1494                                   "domain [%s]\n", domainname);
1495                         result = NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1496                 } else if (interactive) {
1497                         result = rpccli_netlogon_password_logon(
1498                                 domain->conn.netlogon_creds_ctx,
1499                                 netlogon_pipe->binding_handle,
1500                                 mem_ctx,
1501                                 logon_parameters,
1502                                 domainname,
1503                                 username,
1504                                 password,
1505                                 workstation,
1506                                 NetlogonInteractiveInformation,
1507                                 authoritative,
1508                                 flags,
1509                                 &validation_level,
1510                                 &validation);
1511                 } else {
1512                         result = rpccli_netlogon_network_logon(
1513                                 domain->conn.netlogon_creds_ctx,
1514                                 netlogon_pipe->binding_handle,
1515                                 mem_ctx,
1516                                 logon_parameters,
1517                                 username,
1518                                 domainname,
1519                                 workstation,
1520                                 chal,
1521                                 lm_response,
1522                                 nt_response,
1523                                 authoritative,
1524                                 flags,
1525                                 &validation_level,
1526                                 &validation);
1527                 }
1528
1529                 /*
1530                  * we increment this after the "feature negotiation"
1531                  * for can_do_samlogon_ex and can_do_validation6
1532                  */
1533                 attempts += 1;
1534
1535                 /* We have to try a second time as cm_connect_netlogon
1536                    might not yet have noticed that the DC has killed
1537                    our connection. */
1538
1539                 if (!rpccli_is_connected(netlogon_pipe)) {
1540                         retry = true;
1541                         continue;
1542                 }
1543
1544                 /* if we get access denied, a possible cause was that we had
1545                    and open connection to the DC, but someone changed our
1546                    machine account password out from underneath us using 'net
1547                    rpc changetrustpw' */
1548
1549                 if ( NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED) ) {
1550                         DEBUG(1,("winbind_samlogon_retry_loop: sam_logon returned "
1551                                  "ACCESS_DENIED.  Maybe the DC has Restrict "
1552                                  "NTLM set or the trust account "
1553                                 "password was changed and we didn't know it. "
1554                                  "Killing connections to domain %s\n",
1555                                 domainname));
1556                         invalidate_cm_connection(domain);
1557                         retry = true;
1558                 }
1559
1560                 if (NT_STATUS_EQUAL(result, NT_STATUS_RPC_PROCNUM_OUT_OF_RANGE)) {
1561                         /*
1562                          * Got DCERPC_FAULT_OP_RNG_ERROR for SamLogon
1563                          * (no Ex). This happens against old Samba
1564                          * DCs, if LogonSamLogonEx() fails with an error
1565                          * e.g. NT_STATUS_NO_SUCH_USER or NT_STATUS_WRONG_PASSWORD.
1566                          *
1567                          * The server will log something like this:
1568                          * api_net_sam_logon_ex: Failed to marshall NET_R_SAM_LOGON_EX.
1569                          *
1570                          * This sets the whole connection into a fault_state mode
1571                          * and all following request get NT_STATUS_RPC_PROCNUM_OUT_OF_RANGE.
1572                          *
1573                          * This also happens to our retry with LogonSamLogonWithFlags()
1574                          * and LogonSamLogon().
1575                          *
1576                          * In order to recover from this situation, we need to
1577                          * drop the connection.
1578                          */
1579                         invalidate_cm_connection(domain);
1580                         result = NT_STATUS_LOGON_FAILURE;
1581                         break;
1582                 }
1583
1584         } while ( (attempts < 2) && retry );
1585
1586         if (NT_STATUS_EQUAL(result, NT_STATUS_IO_TIMEOUT)) {
1587                 DEBUG(3,("winbind_samlogon_retry_loop: sam_network_logon(ex) "
1588                                 "returned NT_STATUS_IO_TIMEOUT after the retry. "
1589                                 "Killing connections to domain %s\n",
1590                         domainname));
1591                 invalidate_cm_connection(domain);
1592         }
1593
1594         if (!NT_STATUS_IS_OK(result)) {
1595                 return result;
1596         }
1597
1598         *_validation_level = validation_level;
1599         *_validation = validation;
1600         return NT_STATUS_OK;
1601 }
1602
1603 static NTSTATUS winbindd_dual_pam_auth_samlogon(
1604         TALLOC_CTX *mem_ctx,
1605         struct winbindd_domain *domain,
1606         const char *user,
1607         const char *pass,
1608         uint32_t request_flags,
1609         uint16_t *_validation_level,
1610         union netr_Validation **_validation)
1611 {
1612
1613         uchar chal[8];
1614         DATA_BLOB lm_resp;
1615         DATA_BLOB nt_resp;
1616         unsigned char local_nt_response[24];
1617         fstring name_domain, name_user;
1618         NTSTATUS result;
1619         uint8_t authoritative = 0;
1620         uint32_t flags = 0;
1621         uint16_t validation_level;
1622         union netr_Validation *validation = NULL;
1623         struct netr_SamBaseInfo *base_info = NULL;
1624
1625         DEBUG(10,("winbindd_dual_pam_auth_samlogon\n"));
1626
1627         /* Parse domain and username */
1628
1629         parse_domain_user(user, name_domain, name_user);
1630
1631         /*
1632          * We check against domain->name instead of
1633          * name_domain, as find_auth_domain() ->
1634          * find_domain_from_name_noinit() already decided
1635          * that we are in a child for the correct domain.
1636          *
1637          * name_domain can also be lp_realm()
1638          * we need to check against domain->name.
1639          */
1640         if (strequal(domain->name, get_global_sam_name())) {
1641                 DATA_BLOB chal_blob = data_blob_const(chal, sizeof(chal));
1642                 struct netr_SamInfo3 *info3 = NULL;
1643
1644                 /* do password magic */
1645
1646                 generate_random_buffer(chal, sizeof(chal));
1647
1648                 if (lp_client_ntlmv2_auth()) {
1649                         DATA_BLOB server_chal;
1650                         DATA_BLOB names_blob;
1651                         server_chal = data_blob_const(chal, 8);
1652
1653                         /* note that the 'workgroup' here is for the local
1654                            machine.  The 'server name' must match the
1655                            'workstation' passed to the actual SamLogon call.
1656                         */
1657                         names_blob = NTLMv2_generate_names_blob(
1658                                 mem_ctx, lp_netbios_name(), lp_workgroup());
1659
1660                         if (!SMBNTLMv2encrypt(mem_ctx, name_user, name_domain,
1661                                               pass,
1662                                               &server_chal,
1663                                               &names_blob,
1664                                               &lm_resp, &nt_resp, NULL, NULL)) {
1665                                 data_blob_free(&names_blob);
1666                                 DEBUG(0, ("winbindd_pam_auth: SMBNTLMv2encrypt() failed!\n"));
1667                                 result = NT_STATUS_NO_MEMORY;
1668                                 goto done;
1669                         }
1670                         data_blob_free(&names_blob);
1671                 } else {
1672                         lm_resp = data_blob_null;
1673                         SMBNTencrypt(pass, chal, local_nt_response);
1674
1675                         nt_resp = data_blob_talloc(mem_ctx, local_nt_response,
1676                                                    sizeof(local_nt_response));
1677                 }
1678
1679                 result = winbindd_dual_auth_passdb(
1680                         talloc_tos(), 0, name_domain, name_user,
1681                         &chal_blob, &lm_resp, &nt_resp,
1682                         true, /* interactive */
1683                         &authoritative,
1684                         &info3);
1685
1686                 /*
1687                  * We need to try the remote NETLOGON server if this is
1688                  * not authoritative (for example on the RODC).
1689                  */
1690                 if (authoritative != 0) {
1691                         if (NT_STATUS_IS_OK(result)) {
1692                                 result = map_info3_to_validation(
1693                                                 mem_ctx,
1694                                                 info3,
1695                                                 &validation_level,
1696                                                 &validation);
1697                                 TALLOC_FREE(info3);
1698                                 if (!NT_STATUS_IS_OK(result)) {
1699                                         goto done;
1700                                 }
1701                         }
1702
1703                         goto done;
1704                 }
1705         }
1706
1707         /* check authentication loop */
1708
1709         result = winbind_samlogon_retry_loop(domain,
1710                                              mem_ctx,
1711                                              0,
1712                                              name_user,
1713                                              pass,
1714                                              name_domain,
1715                                              lp_netbios_name(),
1716                                              NULL,
1717                                              data_blob_null, data_blob_null,
1718                                              true, /* interactive */
1719                                              &authoritative,
1720                                              &flags,
1721                                              &validation_level,
1722                                              &validation);
1723         if (!NT_STATUS_IS_OK(result)) {
1724                 goto done;
1725         }
1726
1727         /* handle the case where a NT4 DC does not fill in the acct_flags in
1728          * the samlogon reply info3. When accurate info3 is required by the
1729          * caller, we look up the account flags ourselves - gd */
1730
1731         switch (validation_level) {
1732         case 3:
1733                 base_info = &validation->sam3->base;
1734                 break;
1735         case 6:
1736                 base_info = &validation->sam6->base;
1737                 break;
1738         default:
1739                 DBG_ERR("Bad validation level %d", (int)validation_level);
1740                 result = NT_STATUS_INTERNAL_ERROR;
1741                 goto done;
1742         }
1743         if ((request_flags & WBFLAG_PAM_INFO3_TEXT) &&
1744             (base_info->acct_flags == 0))
1745         {
1746                 struct rpc_pipe_client *samr_pipe;
1747                 struct policy_handle samr_domain_handle, user_pol;
1748                 union samr_UserInfo *info = NULL;
1749                 NTSTATUS status_tmp, result_tmp;
1750                 uint32_t acct_flags;
1751                 struct dcerpc_binding_handle *b;
1752
1753                 status_tmp = cm_connect_sam(domain, mem_ctx, false,
1754                                             &samr_pipe, &samr_domain_handle);
1755
1756                 if (!NT_STATUS_IS_OK(status_tmp)) {
1757                         DEBUG(3, ("could not open handle to SAMR pipe: %s\n",
1758                                 nt_errstr(status_tmp)));
1759                         goto done;
1760                 }
1761
1762                 b = samr_pipe->binding_handle;
1763
1764                 status_tmp = dcerpc_samr_OpenUser(b, mem_ctx,
1765                                                   &samr_domain_handle,
1766                                                   MAXIMUM_ALLOWED_ACCESS,
1767                                                   base_info->rid,
1768                                                   &user_pol,
1769                                                   &result_tmp);
1770
1771                 if (!NT_STATUS_IS_OK(status_tmp)) {
1772                         DEBUG(3, ("could not open user handle on SAMR pipe: %s\n",
1773                                 nt_errstr(status_tmp)));
1774                         goto done;
1775                 }
1776                 if (!NT_STATUS_IS_OK(result_tmp)) {
1777                         DEBUG(3, ("could not open user handle on SAMR pipe: %s\n",
1778                                 nt_errstr(result_tmp)));
1779                         goto done;
1780                 }
1781
1782                 status_tmp = dcerpc_samr_QueryUserInfo(b, mem_ctx,
1783                                                        &user_pol,
1784                                                        16,
1785                                                        &info,
1786                                                        &result_tmp);
1787
1788                 if (any_nt_status_not_ok(status_tmp, result_tmp,
1789                                          &status_tmp)) {
1790                         DEBUG(3, ("could not query user info on SAMR pipe: %s\n",
1791                                 nt_errstr(status_tmp)));
1792                         dcerpc_samr_Close(b, mem_ctx, &user_pol, &result_tmp);
1793                         goto done;
1794                 }
1795
1796                 acct_flags = info->info16.acct_flags;
1797
1798                 if (acct_flags == 0) {
1799                         dcerpc_samr_Close(b, mem_ctx, &user_pol, &result_tmp);
1800                         goto done;
1801                 }
1802
1803                 base_info->acct_flags = acct_flags;
1804
1805                 DEBUG(10,("successfully retrieved acct_flags 0x%x\n", acct_flags));
1806
1807                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result_tmp);
1808         }
1809
1810 done:
1811         if (NT_STATUS_IS_OK(result)) {
1812                 *_validation_level = validation_level;
1813                 *_validation = validation;
1814         }
1815         return result;
1816 }
1817
1818 enum winbindd_result winbindd_dual_pam_auth(struct winbindd_domain *domain,
1819                                             struct winbindd_cli_state *state)
1820 {
1821         NTSTATUS result = NT_STATUS_LOGON_FAILURE;
1822         NTSTATUS krb5_result = NT_STATUS_OK;
1823         fstring name_domain, name_user;
1824         char *mapped_user;
1825         fstring domain_user;
1826         uint16_t validation_level = UINT16_MAX;
1827         union netr_Validation *validation = NULL;
1828         NTSTATUS name_map_status = NT_STATUS_UNSUCCESSFUL;
1829
1830         /* Ensure null termination */
1831         state->request->data.auth.user[sizeof(state->request->data.auth.user)-1]='\0';
1832
1833         /* Ensure null termination */
1834         state->request->data.auth.pass[sizeof(state->request->data.auth.pass)-1]='\0';
1835
1836         DEBUG(3, ("[%5lu]: dual pam auth %s\n", (unsigned long)state->pid,
1837                   state->request->data.auth.user));
1838
1839         /* Parse domain and username */
1840
1841         name_map_status = normalize_name_unmap(state->mem_ctx,
1842                                                state->request->data.auth.user,
1843                                                &mapped_user);
1844
1845         /* If the name normalization didnt' actually do anything,
1846            just use the original name */
1847
1848         if (!NT_STATUS_IS_OK(name_map_status) &&
1849             !NT_STATUS_EQUAL(name_map_status, NT_STATUS_FILE_RENAMED))
1850         {
1851                 mapped_user = state->request->data.auth.user;
1852         }
1853
1854         parse_domain_user(mapped_user, name_domain, name_user);
1855
1856         if ( mapped_user != state->request->data.auth.user ) {
1857                 fstr_sprintf( domain_user, "%s%c%s", name_domain,
1858                         *lp_winbind_separator(),
1859                         name_user );
1860                 strlcpy( state->request->data.auth.user, domain_user,
1861                              sizeof(state->request->data.auth.user));
1862         }
1863
1864         if (!domain->online) {
1865                 result = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1866                 if (domain->startup) {
1867                         /* Logons are very important to users. If we're offline and
1868                            we get a request within the first 30 seconds of startup,
1869                            try very hard to find a DC and go online. */
1870
1871                         DEBUG(10,("winbindd_dual_pam_auth: domain: %s offline and auth "
1872                                 "request in startup mode.\n", domain->name ));
1873
1874                         winbindd_flush_negative_conn_cache(domain);
1875                         result = init_dc_connection(domain, false);
1876                 }
1877         }
1878
1879         DEBUG(10,("winbindd_dual_pam_auth: domain: %s last was %s\n", domain->name, domain->online ? "online":"offline"));
1880
1881         /* Check for Kerberos authentication */
1882         if (domain->online && (state->request->flags & WBFLAG_PAM_KRB5)) {
1883                 struct netr_SamInfo3 *info3 = NULL;
1884
1885                 result = winbindd_dual_pam_auth_kerberos(domain, state, &info3);
1886                 /* save for later */
1887                 krb5_result = result;
1888
1889
1890                 if (NT_STATUS_IS_OK(result)) {
1891                         DEBUG(10,("winbindd_dual_pam_auth_kerberos succeeded\n"));
1892
1893                         result = map_info3_to_validation(state->mem_ctx,
1894                                                          info3,
1895                                                          &validation_level,
1896                                                          &validation);
1897                         TALLOC_FREE(info3);
1898                         if (!NT_STATUS_IS_OK(result)) {
1899                                 DBG_ERR("map_info3_to_validation failed\n");
1900                                 goto done;
1901                         }
1902                         goto process_result;
1903                 }
1904
1905                 DBG_DEBUG("winbindd_dual_pam_auth_kerberos failed: %s\n",
1906                           nt_errstr(result));
1907
1908                 if (NT_STATUS_EQUAL(result, NT_STATUS_NO_LOGON_SERVERS) ||
1909                     NT_STATUS_EQUAL(result, NT_STATUS_IO_TIMEOUT) ||
1910                     NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
1911                         DEBUG(10,("winbindd_dual_pam_auth_kerberos setting domain to offline\n"));
1912                         set_domain_offline( domain );
1913                         goto cached_logon;
1914                 }
1915
1916                 /* there are quite some NT_STATUS errors where there is no
1917                  * point in retrying with a samlogon, we explictly have to take
1918                  * care not to increase the bad logon counter on the DC */
1919
1920                 if (NT_STATUS_EQUAL(result, NT_STATUS_ACCOUNT_DISABLED) ||
1921                     NT_STATUS_EQUAL(result, NT_STATUS_ACCOUNT_EXPIRED) ||
1922                     NT_STATUS_EQUAL(result, NT_STATUS_ACCOUNT_LOCKED_OUT) ||
1923                     NT_STATUS_EQUAL(result, NT_STATUS_INVALID_LOGON_HOURS) ||
1924                     NT_STATUS_EQUAL(result, NT_STATUS_INVALID_WORKSTATION) ||
1925                     NT_STATUS_EQUAL(result, NT_STATUS_LOGON_FAILURE) ||
1926                     NT_STATUS_EQUAL(result, NT_STATUS_NO_SUCH_USER) ||
1927                     NT_STATUS_EQUAL(result, NT_STATUS_PASSWORD_EXPIRED) ||
1928                     NT_STATUS_EQUAL(result, NT_STATUS_PASSWORD_MUST_CHANGE) ||
1929                     NT_STATUS_EQUAL(result, NT_STATUS_WRONG_PASSWORD)) {
1930                         goto done;
1931                 }
1932
1933                 if (state->request->flags & WBFLAG_PAM_FALLBACK_AFTER_KRB5) {
1934                         DEBUG(3,("falling back to samlogon\n"));
1935                         goto sam_logon;
1936                 } else {
1937                         goto cached_logon;
1938                 }
1939         }
1940
1941 sam_logon:
1942         /* Check for Samlogon authentication */
1943         if (domain->online) {
1944                 struct netr_SamBaseInfo *base_info = NULL;
1945
1946                 result = winbindd_dual_pam_auth_samlogon(
1947                         state->mem_ctx, domain,
1948                         state->request->data.auth.user,
1949                         state->request->data.auth.pass,
1950                         state->request->flags,
1951                         &validation_level,
1952                         &validation);
1953
1954                 if (NT_STATUS_IS_OK(result)) {
1955                         DEBUG(10,("winbindd_dual_pam_auth_samlogon succeeded\n"));
1956
1957                         switch (validation_level) {
1958                         case 3:
1959                                 base_info = &validation->sam3->base;
1960                                 break;
1961                         case 6:
1962                                 base_info = &validation->sam6->base;
1963                                 break;
1964                         default:
1965                                 DBG_ERR("Bad validation level %d\n",
1966                                         validation_level);
1967                                 result = NT_STATUS_INTERNAL_ERROR;
1968                                 goto done;
1969                         }
1970
1971                         /* add the Krb5 err if we have one */
1972                         if ( NT_STATUS_EQUAL(krb5_result, NT_STATUS_TIME_DIFFERENCE_AT_DC ) ) {
1973                                 base_info->user_flags |= LOGON_KRB5_FAIL_CLOCK_SKEW;
1974                         }
1975
1976                         goto process_result;
1977                 }
1978
1979                 DEBUG(10,("winbindd_dual_pam_auth_samlogon failed: %s\n",
1980                           nt_errstr(result)));
1981
1982                 if (NT_STATUS_EQUAL(result, NT_STATUS_NO_LOGON_SERVERS) ||
1983                     NT_STATUS_EQUAL(result, NT_STATUS_IO_TIMEOUT) ||
1984                     NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND))
1985                 {
1986                         DEBUG(10,("winbindd_dual_pam_auth_samlogon setting domain to offline\n"));
1987                         set_domain_offline( domain );
1988                         goto cached_logon;
1989                 }
1990
1991                 if (domain->online) {
1992                         /* We're still online - fail. */
1993                         goto done;
1994                 }
1995         }
1996
1997 cached_logon:
1998         /* Check for Cached logons */
1999         if (!domain->online && (state->request->flags & WBFLAG_PAM_CACHED_LOGIN) &&
2000             lp_winbind_offline_logon()) {
2001                 struct netr_SamInfo3 *info3 = NULL;
2002
2003                 result = winbindd_dual_pam_auth_cached(domain, state, &info3);
2004
2005                 if (!NT_STATUS_IS_OK(result)) {
2006                         DEBUG(10,("winbindd_dual_pam_auth_cached failed: %s\n", nt_errstr(result)));
2007                         goto done;
2008                 }
2009                 DEBUG(10,("winbindd_dual_pam_auth_cached succeeded\n"));
2010
2011                 result = map_info3_to_validation(state->mem_ctx,
2012                                                  info3,
2013                                                  &validation_level,
2014                                                  &validation);
2015                 TALLOC_FREE(info3);
2016                 if (!NT_STATUS_IS_OK(result)) {
2017                         DBG_ERR("map_info3_to_validation failed\n");
2018                         goto done;
2019                 }
2020         }
2021
2022 process_result:
2023
2024         if (NT_STATUS_IS_OK(result)) {
2025                 struct dom_sid user_sid;
2026                 TALLOC_CTX *base_ctx = NULL;
2027                 struct netr_SamBaseInfo *base_info = NULL;
2028                 struct netr_SamInfo3 *info3 = NULL;
2029
2030                 switch (validation_level) {
2031                 case 3:
2032                         base_ctx = validation->sam3;
2033                         base_info = &validation->sam3->base;
2034                         break;
2035                 case 6:
2036                         base_ctx = validation->sam6;
2037                         base_info = &validation->sam6->base;
2038                         break;
2039                 default:
2040                         result = NT_STATUS_INTERNAL_ERROR;
2041                         goto done;
2042                 }
2043
2044                 sid_compose(&user_sid, base_info->domain_sid, base_info->rid);
2045
2046                 if (base_info->full_name.string == NULL) {
2047                         struct netr_SamInfo3 *cached_info3;
2048
2049                         cached_info3 = netsamlogon_cache_get(state->mem_ctx,
2050                                                              &user_sid);
2051                         if (cached_info3 != NULL &&
2052                             cached_info3->base.full_name.string != NULL) {
2053                                 base_info->full_name.string = talloc_strdup(
2054                                         base_ctx,
2055                                         cached_info3->base.full_name.string);
2056                                 if (base_info->full_name.string == NULL) {
2057                                         result = NT_STATUS_NO_MEMORY;
2058                                         goto done;
2059                                 }
2060                         } else {
2061
2062                                 /* this might fail so we don't check the return code */
2063                                 wcache_query_user_fullname(domain,
2064                                                 base_ctx,
2065                                                 &user_sid,
2066                                                 &base_info->full_name.string);
2067                         }
2068                 }
2069
2070                 result = map_validation_to_info3(talloc_tos(),
2071                                                  validation_level,
2072                                                  validation,
2073                                                  &info3);
2074                 if (!NT_STATUS_IS_OK(result)) {
2075                         goto done;
2076                 }
2077
2078                 wcache_invalidate_samlogon(find_domain_from_name(name_domain),
2079                                            &user_sid);
2080                 netsamlogon_cache_store(name_user, info3);
2081
2082                 /* save name_to_sid info as early as possible (only if
2083                    this is our primary domain so we don't invalidate
2084                    the cache entry by storing the seq_num for the wrong
2085                    domain). */
2086                 if ( domain->primary ) {
2087                         cache_name2sid(domain, name_domain, name_user,
2088                                        SID_NAME_USER, &user_sid);
2089                 }
2090
2091                 /* Check if the user is in the right group */
2092
2093                 result = check_info3_in_group(
2094                         info3,
2095                         state->request->data.auth.require_membership_of_sid);
2096                 if (!NT_STATUS_IS_OK(result)) {
2097                         DEBUG(3, ("User %s is not in the required group (%s), so plaintext authentication is rejected\n",
2098                                   state->request->data.auth.user,
2099                                   state->request->data.auth.require_membership_of_sid));
2100                         goto done;
2101                 }
2102
2103                 result = append_auth_data(state->mem_ctx, state->response,
2104                                           state->request->flags,
2105                                           validation_level,
2106                                           validation,
2107                                           name_domain, name_user);
2108                 if (!NT_STATUS_IS_OK(result)) {
2109                         goto done;
2110                 }
2111
2112                 if ((state->request->flags & WBFLAG_PAM_CACHED_LOGIN)
2113                     && lp_winbind_offline_logon()) {
2114
2115                         result = winbindd_store_creds(domain,
2116                                                       state->request->data.auth.user,
2117                                                       state->request->data.auth.pass,
2118                                                       info3);
2119                 }
2120
2121                 if (state->request->flags & WBFLAG_PAM_GET_PWD_POLICY) {
2122                         /*
2123                          * WBFLAG_PAM_GET_PWD_POLICY is not used within
2124                          * any Samba caller anymore.
2125                          *
2126                          * We just fake this based on the effective values
2127                          * for the user, for legacy callers.
2128                          */
2129                         fake_password_policy(state->response, &info3->base);
2130                 }
2131
2132                 result = NT_STATUS_OK;
2133         }
2134
2135 done:
2136         /* give us a more useful (more correct?) error code */
2137         if ((NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) ||
2138             (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)))) {
2139                 result = NT_STATUS_NO_LOGON_SERVERS;
2140         }
2141
2142         set_auth_errors(state->response, result);
2143
2144         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, ("Plain-text authentication for user %s returned %s (PAM: %d)\n",
2145               state->request->data.auth.user,
2146               state->response->data.auth.nt_status_string,
2147               state->response->data.auth.pam_error));
2148
2149         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
2150 }
2151
2152 NTSTATUS winbind_dual_SamLogon(struct winbindd_domain *domain,
2153                                TALLOC_CTX *mem_ctx,
2154                                uint32_t logon_parameters,
2155                                const char *name_user,
2156                                const char *name_domain,
2157                                const char *workstation,
2158                                const uint8_t chal[8],
2159                                DATA_BLOB lm_response,
2160                                DATA_BLOB nt_response,
2161                                uint8_t *authoritative,
2162                                bool skip_sam,
2163                                uint32_t *flags,
2164                                uint16_t *_validation_level,
2165                                union netr_Validation **_validation)
2166 {
2167         uint16_t validation_level;
2168         union netr_Validation *validation = NULL;
2169         NTSTATUS result;
2170
2171         /*
2172          * We check against domain->name instead of
2173          * name_domain, as find_auth_domain() ->
2174          * find_domain_from_name_noinit() already decided
2175          * that we are in a child for the correct domain.
2176          *
2177          * name_domain can also be lp_realm()
2178          * we need to check against domain->name.
2179          */
2180         if (!skip_sam && strequal(domain->name, get_global_sam_name())) {
2181                 DATA_BLOB chal_blob = data_blob_const(
2182                         chal, 8);
2183                 struct netr_SamInfo3 *info3 = NULL;
2184
2185                 result = winbindd_dual_auth_passdb(
2186                         talloc_tos(),
2187                         logon_parameters,
2188                         name_domain, name_user,
2189                         &chal_blob, &lm_response, &nt_response,
2190                         false, /* interactive */
2191                         authoritative,
2192                         &info3);
2193                 if (NT_STATUS_IS_OK(result)) {
2194                         result = map_info3_to_validation(mem_ctx,
2195                                                          info3,
2196                                                          &validation_level,
2197                                                          &validation);
2198                         TALLOC_FREE(info3);
2199                         if (!NT_STATUS_IS_OK(result)) {
2200                                 goto done;
2201                         }
2202                 }
2203
2204                 /*
2205                  * We need to try the remote NETLOGON server if this is
2206                  * not authoritative.
2207                  */
2208                 if (*authoritative != 0) {
2209                         *flags = 0;
2210                         goto process_result;
2211                 }
2212         }
2213
2214         result = winbind_samlogon_retry_loop(domain,
2215                                              mem_ctx,
2216                                              logon_parameters,
2217                                              name_user,
2218                                              NULL, /* password */
2219                                              name_domain,
2220                                              /* Bug #3248 - found by Stefan Burkei. */
2221                                              workstation, /* We carefully set this above so use it... */
2222                                              chal,
2223                                              lm_response,
2224                                              nt_response,
2225                                              false, /* interactive */
2226                                              authoritative,
2227                                              flags,
2228                                              &validation_level,
2229                                              &validation);
2230         if (!NT_STATUS_IS_OK(result)) {
2231                 goto done;
2232         }
2233
2234 process_result:
2235
2236         if (NT_STATUS_IS_OK(result)) {
2237                 struct dom_sid user_sid;
2238                 TALLOC_CTX *base_ctx = NULL;
2239                 struct netr_SamBaseInfo *base_info = NULL;
2240                 struct netr_SamInfo3 *info3 = NULL;
2241
2242                 switch (validation_level) {
2243                 case 3:
2244                         base_ctx = validation->sam3;
2245                         base_info = &validation->sam3->base;
2246                         break;
2247                 case 6:
2248                         base_ctx = validation->sam6;
2249                         base_info = &validation->sam6->base;
2250                         break;
2251                 default:
2252                         result = NT_STATUS_INTERNAL_ERROR;
2253                         goto done;
2254                 }
2255
2256                 sid_compose(&user_sid, base_info->domain_sid, base_info->rid);
2257
2258                 if (base_info->full_name.string == NULL) {
2259                         struct netr_SamInfo3 *cached_info3;
2260
2261                         cached_info3 = netsamlogon_cache_get(mem_ctx,
2262                                                              &user_sid);
2263                         if (cached_info3 != NULL &&
2264                             cached_info3->base.full_name.string != NULL)
2265                         {
2266                                 base_info->full_name.string = talloc_strdup(
2267                                         base_ctx,
2268                                         cached_info3->base.full_name.string);
2269                         } else {
2270
2271                                 /* this might fail so we don't check the return code */
2272                                 wcache_query_user_fullname(domain,
2273                                                 base_ctx,
2274                                                 &user_sid,
2275                                                 &base_info->full_name.string);
2276                         }
2277                 }
2278
2279                 result = map_validation_to_info3(talloc_tos(),
2280                                                  validation_level,
2281                                                  validation,
2282                                                  &info3);
2283                 if (!NT_STATUS_IS_OK(result)) {
2284                         goto done;
2285                 }
2286                 wcache_invalidate_samlogon(find_domain_from_name(name_domain),
2287                                            &user_sid);
2288                 netsamlogon_cache_store(name_user, info3);
2289                 TALLOC_FREE(info3);
2290         }
2291
2292 done:
2293
2294         /* give us a more useful (more correct?) error code */
2295         if ((NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) ||
2296             (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)))) {
2297                 result = NT_STATUS_NO_LOGON_SERVERS;
2298         }
2299
2300         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2,
2301               ("NTLM CRAP authentication for user [%s]\\[%s] returned %s\n",
2302                name_domain,
2303                name_user,
2304                nt_errstr(result)));
2305
2306         if (!NT_STATUS_IS_OK(result)) {
2307                 return result;
2308         }
2309
2310         *_validation_level = validation_level;
2311         *_validation = validation;
2312         return NT_STATUS_OK;
2313 }
2314
2315 enum winbindd_result winbindd_dual_pam_auth_crap(struct winbindd_domain *domain,
2316                                                  struct winbindd_cli_state *state)
2317 {
2318         NTSTATUS result;
2319         const char *name_user = NULL;
2320         const char *name_domain = NULL;
2321         const char *workstation;
2322         uint8_t authoritative = 0;
2323         uint32_t flags = 0;
2324         uint16_t validation_level;
2325         union netr_Validation *validation = NULL;
2326         DATA_BLOB lm_resp, nt_resp;
2327
2328         /* This is child-only, so no check for privileged access is needed
2329            anymore */
2330
2331         /* Ensure null termination */
2332         state->request->data.auth_crap.user[sizeof(state->request->data.auth_crap.user)-1]=0;
2333         state->request->data.auth_crap.domain[sizeof(state->request->data.auth_crap.domain)-1]=0;
2334
2335         name_user = state->request->data.auth_crap.user;
2336         name_domain = state->request->data.auth_crap.domain;
2337         workstation = state->request->data.auth_crap.workstation;
2338
2339         DEBUG(3, ("[%5lu]: pam auth crap domain: %s user: %s\n", (unsigned long)state->pid,
2340                   name_domain, name_user));
2341
2342         if (state->request->data.auth_crap.lm_resp_len > sizeof(state->request->data.auth_crap.lm_resp)
2343                 || state->request->data.auth_crap.nt_resp_len > sizeof(state->request->data.auth_crap.nt_resp)) {
2344                 if (!(state->request->flags & WBFLAG_BIG_NTLMV2_BLOB) ||
2345                      state->request->extra_len != state->request->data.auth_crap.nt_resp_len) {
2346                         DEBUG(0, ("winbindd_pam_auth_crap: invalid password length %u/%u\n",
2347                                   state->request->data.auth_crap.lm_resp_len,
2348                                   state->request->data.auth_crap.nt_resp_len));
2349                         result = NT_STATUS_INVALID_PARAMETER;
2350                         goto done;
2351                 }
2352         }
2353
2354         lm_resp = data_blob_talloc(state->mem_ctx, state->request->data.auth_crap.lm_resp,
2355                                         state->request->data.auth_crap.lm_resp_len);
2356
2357         if (state->request->flags & WBFLAG_BIG_NTLMV2_BLOB) {
2358                 nt_resp = data_blob_talloc(state->mem_ctx,
2359                                            state->request->extra_data.data,
2360                                            state->request->data.auth_crap.nt_resp_len);
2361         } else {
2362                 nt_resp = data_blob_talloc(state->mem_ctx,
2363                                            state->request->data.auth_crap.nt_resp,
2364                                            state->request->data.auth_crap.nt_resp_len);
2365         }
2366
2367         result = winbind_dual_SamLogon(domain,
2368                                        state->mem_ctx,
2369                                        state->request->data.auth_crap.logon_parameters,
2370                                        name_user,
2371                                        name_domain,
2372                                        /* Bug #3248 - found by Stefan Burkei. */
2373                                        workstation, /* We carefully set this above so use it... */
2374                                        state->request->data.auth_crap.chal,
2375                                        lm_resp,
2376                                        nt_resp,
2377                                        &authoritative,
2378                                        false,
2379                                        &flags,
2380                                        &validation_level,
2381                                        &validation);
2382         if (!NT_STATUS_IS_OK(result)) {
2383                 state->response->data.auth.authoritative = authoritative;
2384                 goto done;
2385         }
2386
2387         if (NT_STATUS_IS_OK(result)) {
2388                 struct netr_SamInfo3 *info3 = NULL;
2389
2390                 result = map_validation_to_info3(state->mem_ctx,
2391                                                  validation_level,
2392                                                  validation,
2393                                                  &info3);
2394                 if (!NT_STATUS_IS_OK(result)) {
2395                         goto done;
2396                 }
2397
2398                 /* Check if the user is in the right group */
2399                 result = check_info3_in_group(
2400                         info3,
2401                         state->request->data.auth_crap.require_membership_of_sid);
2402                 if (!NT_STATUS_IS_OK(result)) {
2403                         DEBUG(3, ("User %s is not in the required group (%s), so "
2404                                   "crap authentication is rejected\n",
2405                                   state->request->data.auth_crap.user,
2406                                   state->request->data.auth_crap.require_membership_of_sid));
2407                         goto done;
2408                 }
2409
2410                 result = append_auth_data(state->mem_ctx, state->response,
2411                                           state->request->flags,
2412                                           validation_level,
2413                                           validation,
2414                                           name_domain, name_user);
2415                 if (!NT_STATUS_IS_OK(result)) {
2416                         goto done;
2417                 }
2418         }
2419
2420 done:
2421
2422         if (state->request->flags & WBFLAG_PAM_NT_STATUS_SQUASH) {
2423                 result = nt_status_squash(result);
2424         }
2425
2426         set_auth_errors(state->response, result);
2427
2428         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
2429 }
2430
2431 enum winbindd_result winbindd_dual_pam_chauthtok(struct winbindd_domain *contact_domain,
2432                                                  struct winbindd_cli_state *state)
2433 {
2434         char *oldpass;
2435         char *newpass = NULL;
2436         struct policy_handle dom_pol;
2437         struct rpc_pipe_client *cli = NULL;
2438         bool got_info = false;
2439         struct samr_DomInfo1 *info = NULL;
2440         struct userPwdChangeFailureInformation *reject = NULL;
2441         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2442         fstring domain, user;
2443         struct dcerpc_binding_handle *b = NULL;
2444
2445         ZERO_STRUCT(dom_pol);
2446
2447         DEBUG(3, ("[%5lu]: dual pam chauthtok %s\n", (unsigned long)state->pid,
2448                   state->request->data.auth.user));
2449
2450         if (!parse_domain_user(state->request->data.chauthtok.user, domain, user)) {
2451                 goto done;
2452         }
2453
2454         /* Change password */
2455
2456         oldpass = state->request->data.chauthtok.oldpass;
2457         newpass = state->request->data.chauthtok.newpass;
2458
2459         /* Initialize reject reason */
2460         state->response->data.auth.reject_reason = Undefined;
2461
2462         /* Get sam handle */
2463
2464         result = cm_connect_sam(contact_domain, state->mem_ctx, true, &cli,
2465                                 &dom_pol);
2466         if (!NT_STATUS_IS_OK(result)) {
2467                 DEBUG(1, ("could not get SAM handle on DC for %s\n", domain));
2468                 goto done;
2469         }
2470
2471         b = cli->binding_handle;
2472
2473         result = rpccli_samr_chgpasswd_user3(cli, state->mem_ctx,
2474                                              user,
2475                                              newpass,
2476                                              oldpass,
2477                                              &info,
2478                                              &reject);
2479
2480         /* Windows 2003 returns NT_STATUS_PASSWORD_RESTRICTION */
2481
2482         if (NT_STATUS_EQUAL(result, NT_STATUS_PASSWORD_RESTRICTION) ) {
2483
2484                 fill_in_password_policy(state->response, info);
2485
2486                 state->response->data.auth.reject_reason =
2487                         reject->extendedFailureReason;
2488
2489                 got_info = true;
2490         }
2491
2492         /* atm the pidl generated rpccli_samr_ChangePasswordUser3 function will
2493          * return with NT_STATUS_BUFFER_TOO_SMALL for w2k dcs as w2k just
2494          * returns with 4byte error code (NT_STATUS_NOT_SUPPORTED) which is too
2495          * short to comply with the samr_ChangePasswordUser3 idl - gd */
2496
2497         /* only fallback when the chgpasswd_user3 call is not supported */
2498         if (NT_STATUS_EQUAL(result, NT_STATUS_RPC_PROCNUM_OUT_OF_RANGE) ||
2499             NT_STATUS_EQUAL(result, NT_STATUS_NOT_SUPPORTED) ||
2500             NT_STATUS_EQUAL(result, NT_STATUS_BUFFER_TOO_SMALL) ||
2501             NT_STATUS_EQUAL(result, NT_STATUS_NOT_IMPLEMENTED)) {
2502
2503                 DEBUG(10,("Password change with chgpasswd_user3 failed with: %s, retrying chgpasswd_user2\n",
2504                         nt_errstr(result)));
2505
2506                 result = rpccli_samr_chgpasswd_user2(cli, state->mem_ctx, user, newpass, oldpass);
2507
2508                 /* Windows 2000 returns NT_STATUS_ACCOUNT_RESTRICTION.
2509                    Map to the same status code as Windows 2003. */
2510
2511                 if ( NT_STATUS_EQUAL(NT_STATUS_ACCOUNT_RESTRICTION, result ) ) {
2512                         result = NT_STATUS_PASSWORD_RESTRICTION;
2513                 }
2514         }
2515
2516 done:
2517
2518         if (NT_STATUS_IS_OK(result)
2519             && (state->request->flags & WBFLAG_PAM_CACHED_LOGIN)
2520             && lp_winbind_offline_logon()) {
2521                 result = winbindd_update_creds_by_name(contact_domain, user,
2522                                                        newpass);
2523                 /* Again, this happens when we login from gdm or xdm
2524                  * and the password expires, *BUT* cached crendentials
2525                  * doesn't exist. winbindd_update_creds_by_name()
2526                  * returns NT_STATUS_NO_SUCH_USER.
2527                  * This is not a failure.
2528                  * --- BoYang
2529                  * */
2530                 if (NT_STATUS_EQUAL(result, NT_STATUS_NO_SUCH_USER)) {
2531                         result = NT_STATUS_OK;
2532                 }
2533
2534                 if (!NT_STATUS_IS_OK(result)) {
2535                         DEBUG(10, ("Failed to store creds: %s\n",
2536                                    nt_errstr(result)));
2537                         goto process_result;
2538                 }
2539         }
2540
2541         if (!NT_STATUS_IS_OK(result) && !got_info && contact_domain) {
2542
2543                 NTSTATUS policy_ret;
2544
2545                 policy_ret = fillup_password_policy(
2546                         contact_domain, state->response);
2547
2548                 /* failure of this is non critical, it will just provide no
2549                  * additional information to the client why the change has
2550                  * failed - Guenther */
2551
2552                 if (!NT_STATUS_IS_OK(policy_ret)) {
2553                         DEBUG(10,("Failed to get password policies: %s\n", nt_errstr(policy_ret)));
2554                         goto process_result;
2555                 }
2556         }
2557
2558 process_result:
2559
2560         if (strequal(contact_domain->name, get_global_sam_name())) {
2561                 /* FIXME: internal rpc pipe does not cache handles yet */
2562                 if (b) {
2563                         if (is_valid_policy_hnd(&dom_pol)) {
2564                                 NTSTATUS _result;
2565                                 dcerpc_samr_Close(b, state->mem_ctx, &dom_pol, &_result);
2566                         }
2567                         TALLOC_FREE(cli);
2568                 }
2569         }
2570
2571         set_auth_errors(state->response, result);
2572
2573         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2,
2574               ("Password change for user [%s]\\[%s] returned %s (PAM: %d)\n",
2575                domain,
2576                user,
2577                state->response->data.auth.nt_status_string,
2578                state->response->data.auth.pam_error));
2579
2580         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
2581 }
2582
2583 enum winbindd_result winbindd_dual_pam_logoff(struct winbindd_domain *domain,
2584                                               struct winbindd_cli_state *state)
2585 {
2586         NTSTATUS result = NT_STATUS_NOT_SUPPORTED;
2587
2588         DEBUG(3, ("[%5lu]: pam dual logoff %s\n", (unsigned long)state->pid,
2589                 state->request->data.logoff.user));
2590
2591         if (!(state->request->flags & WBFLAG_PAM_KRB5)) {
2592                 result = NT_STATUS_OK;
2593                 goto process_result;
2594         }
2595
2596         if (state->request->data.logoff.krb5ccname[0] == '\0') {
2597                 result = NT_STATUS_OK;
2598                 goto process_result;
2599         }
2600
2601 #ifdef HAVE_KRB5
2602
2603         if (state->request->data.logoff.uid == (uid_t)-1) {
2604                 DEBUG(0,("winbindd_pam_logoff: invalid uid\n"));
2605                 goto process_result;
2606         }
2607
2608         /* what we need here is to find the corresponding krb5 ccache name *we*
2609          * created for a given username and destroy it */
2610
2611         if (!ccache_entry_exists(state->request->data.logoff.user)) {
2612                 result = NT_STATUS_OK;
2613                 DEBUG(10,("winbindd_pam_logoff: no entry found.\n"));
2614                 goto process_result;
2615         }
2616
2617         if (!ccache_entry_identical(state->request->data.logoff.user,
2618                                         state->request->data.logoff.uid,
2619                                         state->request->data.logoff.krb5ccname)) {
2620                 DEBUG(0,("winbindd_pam_logoff: cached entry differs.\n"));
2621                 goto process_result;
2622         }
2623
2624         result = remove_ccache(state->request->data.logoff.user);
2625         if (!NT_STATUS_IS_OK(result)) {
2626                 DEBUG(0,("winbindd_pam_logoff: failed to remove ccache: %s\n",
2627                         nt_errstr(result)));
2628                 goto process_result;
2629         }
2630
2631         /*
2632          * Remove any mlock'ed memory creds in the child
2633          * we might be using for krb5 ticket renewal.
2634          */
2635
2636         winbindd_delete_memory_creds(state->request->data.logoff.user);
2637
2638 #else
2639         result = NT_STATUS_NOT_SUPPORTED;
2640 #endif
2641
2642 process_result:
2643
2644
2645         set_auth_errors(state->response, result);
2646
2647         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
2648 }
2649
2650 /* Change user password with auth crap*/
2651
2652 enum winbindd_result winbindd_dual_pam_chng_pswd_auth_crap(struct winbindd_domain *domainSt, struct winbindd_cli_state *state)
2653 {
2654         NTSTATUS result;
2655         DATA_BLOB new_nt_password;
2656         DATA_BLOB old_nt_hash_enc;
2657         DATA_BLOB new_lm_password;
2658         DATA_BLOB old_lm_hash_enc;
2659         fstring  domain,user;
2660         struct policy_handle dom_pol;
2661         struct winbindd_domain *contact_domain = domainSt;
2662         struct rpc_pipe_client *cli = NULL;
2663         struct dcerpc_binding_handle *b = NULL;
2664
2665         ZERO_STRUCT(dom_pol);
2666
2667         /* Ensure null termination */
2668         state->request->data.chng_pswd_auth_crap.user[
2669                 sizeof(state->request->data.chng_pswd_auth_crap.user)-1]=0;
2670         state->request->data.chng_pswd_auth_crap.domain[
2671                 sizeof(state->request->data.chng_pswd_auth_crap.domain)-1]=0;
2672         *domain = 0;
2673         *user = 0;
2674
2675         DEBUG(3, ("[%5lu]: pam change pswd auth crap domain: %s user: %s\n",
2676                   (unsigned long)state->pid,
2677                   state->request->data.chng_pswd_auth_crap.domain,
2678                   state->request->data.chng_pswd_auth_crap.user));
2679
2680         if (lp_winbind_offline_logon()) {
2681                 DEBUG(0,("Refusing password change as winbind offline logons are enabled. "));
2682                 DEBUGADD(0,("Changing passwords here would risk inconsistent logons\n"));
2683                 result = NT_STATUS_ACCESS_DENIED;
2684                 goto done;
2685         }
2686
2687         if (*state->request->data.chng_pswd_auth_crap.domain) {
2688                 fstrcpy(domain,state->request->data.chng_pswd_auth_crap.domain);
2689         } else {
2690                 parse_domain_user(state->request->data.chng_pswd_auth_crap.user,
2691                                   domain, user);
2692
2693                 if(!*domain) {
2694                         DEBUG(3,("no domain specified with username (%s) - "
2695                                  "failing auth\n",
2696                                  state->request->data.chng_pswd_auth_crap.user));
2697                         result = NT_STATUS_NO_SUCH_USER;
2698                         goto done;
2699                 }
2700         }
2701
2702         if (!*domain && lp_winbind_use_default_domain()) {
2703                 fstrcpy(domain,lp_workgroup());
2704         }
2705
2706         if(!*user) {
2707                 fstrcpy(user, state->request->data.chng_pswd_auth_crap.user);
2708         }
2709
2710         DEBUG(3, ("[%5lu]: pam auth crap domain: %s user: %s\n",
2711                   (unsigned long)state->pid, domain, user));
2712
2713         /* Change password */
2714         new_nt_password = data_blob_const(
2715                 state->request->data.chng_pswd_auth_crap.new_nt_pswd,
2716                 state->request->data.chng_pswd_auth_crap.new_nt_pswd_len);
2717
2718         old_nt_hash_enc = data_blob_const(
2719                 state->request->data.chng_pswd_auth_crap.old_nt_hash_enc,
2720                 state->request->data.chng_pswd_auth_crap.old_nt_hash_enc_len);
2721
2722         if(state->request->data.chng_pswd_auth_crap.new_lm_pswd_len > 0)        {
2723                 new_lm_password = data_blob_const(
2724                         state->request->data.chng_pswd_auth_crap.new_lm_pswd,
2725                         state->request->data.chng_pswd_auth_crap.new_lm_pswd_len);
2726
2727                 old_lm_hash_enc = data_blob_const(
2728                         state->request->data.chng_pswd_auth_crap.old_lm_hash_enc,
2729                         state->request->data.chng_pswd_auth_crap.old_lm_hash_enc_len);
2730         } else {
2731                 new_lm_password = data_blob_null;
2732                 old_lm_hash_enc = data_blob_null;
2733         }
2734
2735         /* Get sam handle */
2736
2737         result = cm_connect_sam(contact_domain, state->mem_ctx, true, &cli, &dom_pol);
2738         if (!NT_STATUS_IS_OK(result)) {
2739                 DEBUG(1, ("could not get SAM handle on DC for %s\n", domain));
2740                 goto done;
2741         }
2742
2743         b = cli->binding_handle;
2744
2745         result = rpccli_samr_chng_pswd_auth_crap(
2746                 cli, state->mem_ctx, user, new_nt_password, old_nt_hash_enc,
2747                 new_lm_password, old_lm_hash_enc);
2748
2749  done:
2750
2751         if (strequal(contact_domain->name, get_global_sam_name())) {
2752                 /* FIXME: internal rpc pipe does not cache handles yet */
2753                 if (b) {
2754                         if (is_valid_policy_hnd(&dom_pol)) {
2755                                 NTSTATUS _result;
2756                                 dcerpc_samr_Close(b, state->mem_ctx, &dom_pol, &_result);
2757                         }
2758                         TALLOC_FREE(cli);
2759                 }
2760         }
2761
2762         set_auth_errors(state->response, result);
2763
2764         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2,
2765               ("Password change for user [%s]\\[%s] returned %s (PAM: %d)\n",
2766                domain, user,
2767                state->response->data.auth.nt_status_string,
2768                state->response->data.auth.pam_error));
2769
2770         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
2771 }
2772
2773 #ifdef HAVE_KRB5
2774 static NTSTATUS extract_pac_vrfy_sigs(TALLOC_CTX *mem_ctx, DATA_BLOB pac_blob,
2775                                       struct PAC_LOGON_INFO **logon_info)
2776 {
2777         krb5_context krbctx = NULL;
2778         krb5_error_code k5ret;
2779         krb5_keytab keytab;
2780         krb5_kt_cursor cursor;
2781         krb5_keytab_entry entry;
2782         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2783
2784         ZERO_STRUCT(entry);
2785         ZERO_STRUCT(cursor);
2786
2787         k5ret = krb5_init_context(&krbctx);
2788         if (k5ret) {
2789                 DEBUG(1, ("Failed to initialize kerberos context: %s\n",
2790                           error_message(k5ret)));
2791                 status = krb5_to_nt_status(k5ret);
2792                 goto out;
2793         }
2794
2795         k5ret =  gse_krb5_get_server_keytab(krbctx, &keytab);
2796         if (k5ret) {
2797                 DEBUG(1, ("Failed to get keytab: %s\n",
2798                           error_message(k5ret)));
2799                 status = krb5_to_nt_status(k5ret);
2800                 goto out_free;
2801         }
2802
2803         k5ret = krb5_kt_start_seq_get(krbctx, keytab, &cursor);
2804         if (k5ret) {
2805                 DEBUG(1, ("Failed to start seq: %s\n",
2806                           error_message(k5ret)));
2807                 status = krb5_to_nt_status(k5ret);
2808                 goto out_keytab;
2809         }
2810
2811         k5ret = krb5_kt_next_entry(krbctx, keytab, &entry, &cursor);
2812         while (k5ret == 0) {
2813                 status = kerberos_pac_logon_info(mem_ctx, pac_blob,
2814                                                  krbctx, NULL,
2815                                                  KRB5_KT_KEY(&entry), NULL, 0,
2816                                                  logon_info);
2817                 if (NT_STATUS_IS_OK(status)) {
2818                         break;
2819                 }
2820                 k5ret = smb_krb5_kt_free_entry(krbctx, &entry);
2821                 k5ret = krb5_kt_next_entry(krbctx, keytab, &entry, &cursor);
2822         }
2823
2824         k5ret = krb5_kt_end_seq_get(krbctx, keytab, &cursor);
2825         if (k5ret) {
2826                 DEBUG(1, ("Failed to end seq: %s\n",
2827                           error_message(k5ret)));
2828         }
2829 out_keytab:
2830         k5ret = krb5_kt_close(krbctx, keytab);
2831         if (k5ret) {
2832                 DEBUG(1, ("Failed to close keytab: %s\n",
2833                           error_message(k5ret)));
2834         }
2835 out_free:
2836         krb5_free_context(krbctx);
2837 out:
2838         return status;
2839 }
2840
2841 NTSTATUS winbindd_pam_auth_pac_send(struct winbindd_cli_state *state,
2842                                     struct netr_SamInfo3 **info3)
2843 {
2844         struct winbindd_request *req = state->request;
2845         DATA_BLOB pac_blob;
2846         struct PAC_LOGON_INFO *logon_info = NULL;
2847         struct netr_SamInfo3 *info3_copy = NULL;
2848         NTSTATUS result;
2849
2850         pac_blob = data_blob_const(req->extra_data.data, req->extra_len);
2851         result = extract_pac_vrfy_sigs(state->mem_ctx, pac_blob, &logon_info);
2852         if (!NT_STATUS_IS_OK(result) &&
2853             !NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
2854                 DEBUG(1, ("Error during PAC signature verification: %s\n",
2855                           nt_errstr(result)));
2856                 return result;
2857         }
2858
2859         if (logon_info) {
2860                 /*
2861                  * Signature verification succeeded, we can
2862                  * trust the PAC and prime the netsamlogon
2863                  * and name2sid caches. DO NOT DO THIS
2864                  * in the signature verification failed
2865                  * code path.
2866                  */
2867                 struct winbindd_domain *domain = NULL;
2868
2869                 result = create_info3_from_pac_logon_info(state->mem_ctx,
2870                                                         logon_info,
2871                                                         &info3_copy);
2872                 if (!NT_STATUS_IS_OK(result)) {
2873                         return result;
2874                 }
2875                 netsamlogon_cache_store(NULL, info3_copy);
2876
2877                 /*
2878                  * We're in the parent here, so find the child
2879                  * pointer from the PAC domain name.
2880                  */
2881                 domain = find_lookup_domain_from_name(
2882                                 info3_copy->base.logon_domain.string);
2883                 if (domain && domain->primary ) {
2884                         struct dom_sid user_sid;
2885
2886                         sid_compose(&user_sid,
2887                                 info3_copy->base.domain_sid,
2888                                 info3_copy->base.rid);
2889
2890                         cache_name2sid_trusted(domain,
2891                                 info3_copy->base.logon_domain.string,
2892                                 info3_copy->base.account_name.string,
2893                                 SID_NAME_USER,
2894                                 &user_sid);
2895
2896                         DBG_INFO("PAC for user %s\\%s SID %s primed cache\n",
2897                                 info3_copy->base.logon_domain.string,
2898                                 info3_copy->base.account_name.string,
2899                                 sid_string_dbg(&user_sid));
2900                 }
2901
2902         } else {
2903                 /* Try without signature verification */
2904                 result = kerberos_pac_logon_info(state->mem_ctx, pac_blob, NULL,
2905                                                  NULL, NULL, NULL, 0,
2906                                                  &logon_info);
2907                 if (!NT_STATUS_IS_OK(result)) {
2908                         DEBUG(10, ("Could not extract PAC: %s\n",
2909                                    nt_errstr(result)));
2910                         return result;
2911                 }
2912                 if (logon_info) {
2913                         /*
2914                          * Don't strictly need to copy here,
2915                          * but it makes it explicit we're
2916                          * returning a copy talloc'ed off
2917                          * the state->mem_ctx.
2918                          */
2919                         result = copy_netr_SamInfo3(state->mem_ctx,
2920                                                     &logon_info->info3,
2921                                                     &info3_copy);
2922                         if (!NT_STATUS_IS_OK(result)) {
2923                                 return result;
2924                         }
2925                 }
2926         }
2927
2928         *info3 = info3_copy;
2929
2930         return NT_STATUS_OK;
2931 }
2932 #else /* HAVE_KRB5 */
2933 NTSTATUS winbindd_pam_auth_pac_send(struct winbindd_cli_state *state,
2934                                     struct netr_SamInfo3 **info3)
2935 {
2936         return NT_STATUS_NO_SUCH_USER;
2937 }
2938 #endif /* HAVE_KRB5 */