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