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