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