winbindd: pass 'bool interactive' to winbind_dual_SamLogon()
[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
1446                 retry = false;
1447
1448                 result = cm_connect_netlogon(domain, &netlogon_pipe);
1449
1450                 if (NT_STATUS_EQUAL(result,
1451                                     NT_STATUS_CANT_ACCESS_DOMAIN_INFO)) {
1452                         /*
1453                          * This means we don't have a trust account.
1454                          */
1455                         *authoritative = 0;
1456                         result = NT_STATUS_NO_SUCH_USER;
1457                         break;
1458                 }
1459
1460                 if (!NT_STATUS_IS_OK(result)) {
1461                         DEBUG(3,("Could not open handle to NETLOGON pipe "
1462                                  "(error: %s, attempts: %d)\n",
1463                                   nt_errstr(result), netr_attempts));
1464
1465                         /* After the first retry always close the connection */
1466                         if (netr_attempts > 0) {
1467                                 DEBUG(3, ("This is again a problem for this "
1468                                           "particular call, forcing the close "
1469                                           "of this connection\n"));
1470                                 invalidate_cm_connection(domain);
1471                         }
1472
1473                         /* After the second retry failover to the next DC */
1474                         if (netr_attempts > 1) {
1475                                 /*
1476                                  * If the netlogon server is not reachable then
1477                                  * it is possible that the DC is rebuilding
1478                                  * sysvol and shutdown netlogon for that time.
1479                                  * We should failover to the next dc.
1480                                  */
1481                                 DEBUG(3, ("This is the third problem for this "
1482                                           "particular call, adding DC to the "
1483                                           "negative cache list: %s %s\n", domain->name, domain->dcname));
1484                                 add_failed_connection_entry(domain->name,
1485                                                             domain->dcname,
1486                                                             result);
1487                                 saf_delete(domain->name);
1488                         }
1489
1490                         /* Only allow 3 retries */
1491                         if (netr_attempts < 3) {
1492                                 DEBUG(3, ("The connection to netlogon "
1493                                           "failed, retrying\n"));
1494                                 netr_attempts++;
1495                                 retry = true;
1496                                 continue;
1497                         }
1498                         return result;
1499                 }
1500
1501                 logon_type_i = NetlogonInteractiveInformation;
1502                 logon_type_n = NetlogonNetworkInformation;
1503                 if (domain->domain_trust_attribs & LSA_TRUST_ATTRIBUTE_WITHIN_FOREST) {
1504                         logon_type_i = NetlogonInteractiveTransitiveInformation;
1505                         logon_type_n = NetlogonNetworkTransitiveInformation;
1506                 }
1507
1508                 if (domain->domain_trust_attribs & LSA_TRUST_ATTRIBUTE_FOREST_TRANSITIVE) {
1509                         logon_type_i = NetlogonInteractiveTransitiveInformation;
1510                         logon_type_n = NetlogonNetworkTransitiveInformation;
1511                 }
1512
1513                 if (domain->domain_trust_attribs & LSA_TRUST_ATTRIBUTE_NON_TRANSITIVE) {
1514                         logon_type_i = NetlogonInteractiveInformation;
1515                         logon_type_n = NetlogonNetworkInformation;
1516                 }
1517
1518                 if (domain->domain_trust_attribs & LSA_TRUST_ATTRIBUTE_QUARANTINED_DOMAIN) {
1519                         logon_type_i = NetlogonInteractiveInformation;
1520                         logon_type_n = NetlogonNetworkInformation;
1521                 }
1522
1523                 netr_attempts = 0;
1524                 if (domain->conn.netlogon_creds_ctx == NULL) {
1525                         DBG_NOTICE("No security credentials available for "
1526                                   "domain [%s]\n", domainname);
1527                         result = NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1528                 } else if (plaintext_given) {
1529                         result = rpccli_netlogon_password_logon(
1530                                 domain->conn.netlogon_creds_ctx,
1531                                 netlogon_pipe->binding_handle,
1532                                 mem_ctx,
1533                                 logon_parameters,
1534                                 domainname,
1535                                 username,
1536                                 password,
1537                                 workstation,
1538                                 logon_type_i,
1539                                 authoritative,
1540                                 flags,
1541                                 &validation_level,
1542                                 &validation);
1543                 } else if (interactive) {
1544                         result = rpccli_netlogon_interactive_logon(
1545                                 domain->conn.netlogon_creds_ctx,
1546                                 netlogon_pipe->binding_handle,
1547                                 mem_ctx,
1548                                 logon_parameters,
1549                                 username,
1550                                 domainname,
1551                                 workstation,
1552                                 lm_response,
1553                                 nt_response,
1554                                 logon_type_i,
1555                                 authoritative,
1556                                 flags,
1557                                 &validation_level,
1558                                 &validation);
1559                 } else {
1560                         result = rpccli_netlogon_network_logon(
1561                                 domain->conn.netlogon_creds_ctx,
1562                                 netlogon_pipe->binding_handle,
1563                                 mem_ctx,
1564                                 logon_parameters,
1565                                 username,
1566                                 domainname,
1567                                 workstation,
1568                                 chal,
1569                                 lm_response,
1570                                 nt_response,
1571                                 logon_type_n,
1572                                 authoritative,
1573                                 flags,
1574                                 &validation_level,
1575                                 &validation);
1576                 }
1577
1578                 /*
1579                  * we increment this after the "feature negotiation"
1580                  * for can_do_samlogon_ex and can_do_validation6
1581                  */
1582                 attempts += 1;
1583
1584                 /* We have to try a second time as cm_connect_netlogon
1585                    might not yet have noticed that the DC has killed
1586                    our connection. */
1587
1588                 if (!rpccli_is_connected(netlogon_pipe)) {
1589                         retry = true;
1590                         continue;
1591                 }
1592
1593                 /* if we get access denied, a possible cause was that we had
1594                    and open connection to the DC, but someone changed our
1595                    machine account password out from underneath us using 'net
1596                    rpc changetrustpw' */
1597
1598                 if ( NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED) ) {
1599                         DEBUG(1,("winbind_samlogon_retry_loop: sam_logon returned "
1600                                  "ACCESS_DENIED.  Maybe the DC has Restrict "
1601                                  "NTLM set or the trust account "
1602                                 "password was changed and we didn't know it. "
1603                                  "Killing connections to domain %s\n",
1604                                 domainname));
1605                         invalidate_cm_connection(domain);
1606                         retry = true;
1607                 }
1608
1609                 if (NT_STATUS_EQUAL(result, NT_STATUS_RPC_PROCNUM_OUT_OF_RANGE)) {
1610                         /*
1611                          * Got DCERPC_FAULT_OP_RNG_ERROR for SamLogon
1612                          * (no Ex). This happens against old Samba
1613                          * DCs, if LogonSamLogonEx() fails with an error
1614                          * e.g. NT_STATUS_NO_SUCH_USER or NT_STATUS_WRONG_PASSWORD.
1615                          *
1616                          * The server will log something like this:
1617                          * api_net_sam_logon_ex: Failed to marshall NET_R_SAM_LOGON_EX.
1618                          *
1619                          * This sets the whole connection into a fault_state mode
1620                          * and all following request get NT_STATUS_RPC_PROCNUM_OUT_OF_RANGE.
1621                          *
1622                          * This also happens to our retry with LogonSamLogonWithFlags()
1623                          * and LogonSamLogon().
1624                          *
1625                          * In order to recover from this situation, we need to
1626                          * drop the connection.
1627                          */
1628                         invalidate_cm_connection(domain);
1629                         result = NT_STATUS_LOGON_FAILURE;
1630                         break;
1631                 }
1632
1633         } while ( (attempts < 2) && retry );
1634
1635         if (NT_STATUS_EQUAL(result, NT_STATUS_IO_TIMEOUT)) {
1636                 DEBUG(3,("winbind_samlogon_retry_loop: sam_network_logon(ex) "
1637                                 "returned NT_STATUS_IO_TIMEOUT after the retry. "
1638                                 "Killing connections to domain %s\n",
1639                         domainname));
1640                 invalidate_cm_connection(domain);
1641         }
1642
1643         if (!NT_STATUS_IS_OK(result)) {
1644                 return result;
1645         }
1646
1647         *_validation_level = validation_level;
1648         *_validation = validation;
1649         return NT_STATUS_OK;
1650 }
1651
1652 static NTSTATUS winbindd_dual_pam_auth_samlogon(
1653         TALLOC_CTX *mem_ctx,
1654         struct winbindd_domain *domain,
1655         const char *user,
1656         const char *pass,
1657         uint32_t request_flags,
1658         uint16_t *_validation_level,
1659         union netr_Validation **_validation)
1660 {
1661
1662         uchar chal[8];
1663         DATA_BLOB lm_resp;
1664         DATA_BLOB nt_resp;
1665         unsigned char local_nt_response[24];
1666         fstring name_domain, name_user;
1667         NTSTATUS result;
1668         uint8_t authoritative = 0;
1669         uint32_t flags = 0;
1670         uint16_t validation_level;
1671         union netr_Validation *validation = NULL;
1672         struct netr_SamBaseInfo *base_info = NULL;
1673
1674         DEBUG(10,("winbindd_dual_pam_auth_samlogon\n"));
1675
1676         /* Parse domain and username */
1677
1678         parse_domain_user(user, name_domain, name_user);
1679
1680         /*
1681          * We check against domain->name instead of
1682          * name_domain, as find_auth_domain() ->
1683          * find_domain_from_name_noinit() already decided
1684          * that we are in a child for the correct domain.
1685          *
1686          * name_domain can also be lp_realm()
1687          * we need to check against domain->name.
1688          */
1689         if (strequal(domain->name, get_global_sam_name())) {
1690                 DATA_BLOB chal_blob = data_blob_const(chal, sizeof(chal));
1691                 struct netr_SamInfo3 *info3 = NULL;
1692
1693                 /* do password magic */
1694
1695                 generate_random_buffer(chal, sizeof(chal));
1696
1697                 if (lp_client_ntlmv2_auth()) {
1698                         DATA_BLOB server_chal;
1699                         DATA_BLOB names_blob;
1700                         server_chal = data_blob_const(chal, 8);
1701
1702                         /* note that the 'workgroup' here is for the local
1703                            machine.  The 'server name' must match the
1704                            'workstation' passed to the actual SamLogon call.
1705                         */
1706                         names_blob = NTLMv2_generate_names_blob(
1707                                 mem_ctx, lp_netbios_name(), lp_workgroup());
1708
1709                         if (!SMBNTLMv2encrypt(mem_ctx, name_user, name_domain,
1710                                               pass,
1711                                               &server_chal,
1712                                               &names_blob,
1713                                               &lm_resp, &nt_resp, NULL, NULL)) {
1714                                 data_blob_free(&names_blob);
1715                                 DEBUG(0, ("winbindd_pam_auth: SMBNTLMv2encrypt() failed!\n"));
1716                                 result = NT_STATUS_NO_MEMORY;
1717                                 goto done;
1718                         }
1719                         data_blob_free(&names_blob);
1720                 } else {
1721                         lm_resp = data_blob_null;
1722                         SMBNTencrypt(pass, chal, local_nt_response);
1723
1724                         nt_resp = data_blob_talloc(mem_ctx, local_nt_response,
1725                                                    sizeof(local_nt_response));
1726                 }
1727
1728                 result = winbindd_dual_auth_passdb(
1729                         talloc_tos(), 0, name_domain, name_user,
1730                         &chal_blob, &lm_resp, &nt_resp,
1731                         true, /* interactive */
1732                         &authoritative,
1733                         &info3);
1734
1735                 /*
1736                  * We need to try the remote NETLOGON server if this is
1737                  * not authoritative (for example on the RODC).
1738                  */
1739                 if (authoritative != 0) {
1740                         if (NT_STATUS_IS_OK(result)) {
1741                                 result = map_info3_to_validation(
1742                                                 mem_ctx,
1743                                                 info3,
1744                                                 &validation_level,
1745                                                 &validation);
1746                                 TALLOC_FREE(info3);
1747                                 if (!NT_STATUS_IS_OK(result)) {
1748                                         goto done;
1749                                 }
1750                         }
1751
1752                         goto done;
1753                 }
1754         }
1755
1756         /* check authentication loop */
1757
1758         result = winbind_samlogon_retry_loop(domain,
1759                                              mem_ctx,
1760                                              0,
1761                                              name_user,
1762                                              pass,
1763                                              name_domain,
1764                                              lp_netbios_name(),
1765                                              true, /* plaintext_given */
1766                                              NULL,
1767                                              data_blob_null, data_blob_null,
1768                                              true, /* interactive */
1769                                              &authoritative,
1770                                              &flags,
1771                                              &validation_level,
1772                                              &validation);
1773         if (!NT_STATUS_IS_OK(result)) {
1774                 goto done;
1775         }
1776
1777         /* handle the case where a NT4 DC does not fill in the acct_flags in
1778          * the samlogon reply info3. When accurate info3 is required by the
1779          * caller, we look up the account flags ourselves - gd */
1780
1781         switch (validation_level) {
1782         case 3:
1783                 base_info = &validation->sam3->base;
1784                 break;
1785         case 6:
1786                 base_info = &validation->sam6->base;
1787                 break;
1788         default:
1789                 DBG_ERR("Bad validation level %d", (int)validation_level);
1790                 result = NT_STATUS_INTERNAL_ERROR;
1791                 goto done;
1792         }
1793         if ((request_flags & WBFLAG_PAM_INFO3_TEXT) &&
1794             (base_info->acct_flags == 0))
1795         {
1796                 struct rpc_pipe_client *samr_pipe;
1797                 struct policy_handle samr_domain_handle, user_pol;
1798                 union samr_UserInfo *info = NULL;
1799                 NTSTATUS status_tmp, result_tmp;
1800                 uint32_t acct_flags;
1801                 struct dcerpc_binding_handle *b;
1802
1803                 status_tmp = cm_connect_sam(domain, mem_ctx, false,
1804                                             &samr_pipe, &samr_domain_handle);
1805
1806                 if (!NT_STATUS_IS_OK(status_tmp)) {
1807                         DEBUG(3, ("could not open handle to SAMR pipe: %s\n",
1808                                 nt_errstr(status_tmp)));
1809                         goto done;
1810                 }
1811
1812                 b = samr_pipe->binding_handle;
1813
1814                 status_tmp = dcerpc_samr_OpenUser(b, mem_ctx,
1815                                                   &samr_domain_handle,
1816                                                   MAXIMUM_ALLOWED_ACCESS,
1817                                                   base_info->rid,
1818                                                   &user_pol,
1819                                                   &result_tmp);
1820
1821                 if (!NT_STATUS_IS_OK(status_tmp)) {
1822                         DEBUG(3, ("could not open user handle on SAMR pipe: %s\n",
1823                                 nt_errstr(status_tmp)));
1824                         goto done;
1825                 }
1826                 if (!NT_STATUS_IS_OK(result_tmp)) {
1827                         DEBUG(3, ("could not open user handle on SAMR pipe: %s\n",
1828                                 nt_errstr(result_tmp)));
1829                         goto done;
1830                 }
1831
1832                 status_tmp = dcerpc_samr_QueryUserInfo(b, mem_ctx,
1833                                                        &user_pol,
1834                                                        16,
1835                                                        &info,
1836                                                        &result_tmp);
1837
1838                 if (any_nt_status_not_ok(status_tmp, result_tmp,
1839                                          &status_tmp)) {
1840                         DEBUG(3, ("could not query user info on SAMR pipe: %s\n",
1841                                 nt_errstr(status_tmp)));
1842                         dcerpc_samr_Close(b, mem_ctx, &user_pol, &result_tmp);
1843                         goto done;
1844                 }
1845
1846                 acct_flags = info->info16.acct_flags;
1847
1848                 if (acct_flags == 0) {
1849                         dcerpc_samr_Close(b, mem_ctx, &user_pol, &result_tmp);
1850                         goto done;
1851                 }
1852
1853                 base_info->acct_flags = acct_flags;
1854
1855                 DEBUG(10,("successfully retrieved acct_flags 0x%x\n", acct_flags));
1856
1857                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result_tmp);
1858         }
1859
1860 done:
1861         if (NT_STATUS_IS_OK(result)) {
1862                 *_validation_level = validation_level;
1863                 *_validation = validation;
1864         }
1865         return result;
1866 }
1867
1868 enum winbindd_result winbindd_dual_pam_auth(struct winbindd_domain *domain,
1869                                             struct winbindd_cli_state *state)
1870 {
1871         NTSTATUS result = NT_STATUS_LOGON_FAILURE;
1872         NTSTATUS krb5_result = NT_STATUS_OK;
1873         fstring name_domain, name_user;
1874         char *mapped_user;
1875         fstring domain_user;
1876         uint16_t validation_level = UINT16_MAX;
1877         union netr_Validation *validation = NULL;
1878         NTSTATUS name_map_status = NT_STATUS_UNSUCCESSFUL;
1879
1880         /* Ensure null termination */
1881         state->request->data.auth.user[sizeof(state->request->data.auth.user)-1]='\0';
1882
1883         /* Ensure null termination */
1884         state->request->data.auth.pass[sizeof(state->request->data.auth.pass)-1]='\0';
1885
1886         DEBUG(3, ("[%5lu]: dual pam auth %s\n", (unsigned long)state->pid,
1887                   state->request->data.auth.user));
1888
1889         /* Parse domain and username */
1890
1891         name_map_status = normalize_name_unmap(state->mem_ctx,
1892                                                state->request->data.auth.user,
1893                                                &mapped_user);
1894
1895         /* If the name normalization didnt' actually do anything,
1896            just use the original name */
1897
1898         if (!NT_STATUS_IS_OK(name_map_status) &&
1899             !NT_STATUS_EQUAL(name_map_status, NT_STATUS_FILE_RENAMED))
1900         {
1901                 mapped_user = state->request->data.auth.user;
1902         }
1903
1904         parse_domain_user(mapped_user, name_domain, name_user);
1905
1906         if ( mapped_user != state->request->data.auth.user ) {
1907                 fstr_sprintf( domain_user, "%s%c%s", name_domain,
1908                         *lp_winbind_separator(),
1909                         name_user );
1910                 strlcpy( state->request->data.auth.user, domain_user,
1911                              sizeof(state->request->data.auth.user));
1912         }
1913
1914         if (!domain->online) {
1915                 result = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1916                 if (domain->startup) {
1917                         /* Logons are very important to users. If we're offline and
1918                            we get a request within the first 30 seconds of startup,
1919                            try very hard to find a DC and go online. */
1920
1921                         DEBUG(10,("winbindd_dual_pam_auth: domain: %s offline and auth "
1922                                 "request in startup mode.\n", domain->name ));
1923
1924                         winbindd_flush_negative_conn_cache(domain);
1925                         result = init_dc_connection(domain, false);
1926                 }
1927         }
1928
1929         DEBUG(10,("winbindd_dual_pam_auth: domain: %s last was %s\n", domain->name, domain->online ? "online":"offline"));
1930
1931         /* Check for Kerberos authentication */
1932         if (domain->online && (state->request->flags & WBFLAG_PAM_KRB5)) {
1933                 struct netr_SamInfo3 *info3 = NULL;
1934
1935                 result = winbindd_dual_pam_auth_kerberos(domain, state, &info3);
1936                 /* save for later */
1937                 krb5_result = result;
1938
1939
1940                 if (NT_STATUS_IS_OK(result)) {
1941                         DEBUG(10,("winbindd_dual_pam_auth_kerberos succeeded\n"));
1942
1943                         result = map_info3_to_validation(state->mem_ctx,
1944                                                          info3,
1945                                                          &validation_level,
1946                                                          &validation);
1947                         TALLOC_FREE(info3);
1948                         if (!NT_STATUS_IS_OK(result)) {
1949                                 DBG_ERR("map_info3_to_validation failed\n");
1950                                 goto done;
1951                         }
1952                         goto process_result;
1953                 }
1954
1955                 DBG_DEBUG("winbindd_dual_pam_auth_kerberos failed: %s\n",
1956                           nt_errstr(result));
1957
1958                 if (NT_STATUS_EQUAL(result, NT_STATUS_NO_LOGON_SERVERS) ||
1959                     NT_STATUS_EQUAL(result, NT_STATUS_IO_TIMEOUT) ||
1960                     NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
1961                         DEBUG(10,("winbindd_dual_pam_auth_kerberos setting domain to offline\n"));
1962                         set_domain_offline( domain );
1963                         goto cached_logon;
1964                 }
1965
1966                 /* there are quite some NT_STATUS errors where there is no
1967                  * point in retrying with a samlogon, we explictly have to take
1968                  * care not to increase the bad logon counter on the DC */
1969
1970                 if (NT_STATUS_EQUAL(result, NT_STATUS_ACCOUNT_DISABLED) ||
1971                     NT_STATUS_EQUAL(result, NT_STATUS_ACCOUNT_EXPIRED) ||
1972                     NT_STATUS_EQUAL(result, NT_STATUS_ACCOUNT_LOCKED_OUT) ||
1973                     NT_STATUS_EQUAL(result, NT_STATUS_INVALID_LOGON_HOURS) ||
1974                     NT_STATUS_EQUAL(result, NT_STATUS_INVALID_WORKSTATION) ||
1975                     NT_STATUS_EQUAL(result, NT_STATUS_LOGON_FAILURE) ||
1976                     NT_STATUS_EQUAL(result, NT_STATUS_NO_SUCH_USER) ||
1977                     NT_STATUS_EQUAL(result, NT_STATUS_PASSWORD_EXPIRED) ||
1978                     NT_STATUS_EQUAL(result, NT_STATUS_PASSWORD_MUST_CHANGE) ||
1979                     NT_STATUS_EQUAL(result, NT_STATUS_WRONG_PASSWORD)) {
1980                         goto done;
1981                 }
1982
1983                 if (state->request->flags & WBFLAG_PAM_FALLBACK_AFTER_KRB5) {
1984                         DEBUG(3,("falling back to samlogon\n"));
1985                         goto sam_logon;
1986                 } else {
1987                         goto cached_logon;
1988                 }
1989         }
1990
1991 sam_logon:
1992         /* Check for Samlogon authentication */
1993         if (domain->online) {
1994                 struct netr_SamBaseInfo *base_info = NULL;
1995
1996                 result = winbindd_dual_pam_auth_samlogon(
1997                         state->mem_ctx, domain,
1998                         state->request->data.auth.user,
1999                         state->request->data.auth.pass,
2000                         state->request->flags,
2001                         &validation_level,
2002                         &validation);
2003
2004                 if (NT_STATUS_IS_OK(result)) {
2005                         DEBUG(10,("winbindd_dual_pam_auth_samlogon succeeded\n"));
2006
2007                         switch (validation_level) {
2008                         case 3:
2009                                 base_info = &validation->sam3->base;
2010                                 break;
2011                         case 6:
2012                                 base_info = &validation->sam6->base;
2013                                 break;
2014                         default:
2015                                 DBG_ERR("Bad validation level %d\n",
2016                                         validation_level);
2017                                 result = NT_STATUS_INTERNAL_ERROR;
2018                                 goto done;
2019                         }
2020
2021                         /* add the Krb5 err if we have one */
2022                         if ( NT_STATUS_EQUAL(krb5_result, NT_STATUS_TIME_DIFFERENCE_AT_DC ) ) {
2023                                 base_info->user_flags |= LOGON_KRB5_FAIL_CLOCK_SKEW;
2024                         }
2025
2026                         goto process_result;
2027                 }
2028
2029                 DEBUG(10,("winbindd_dual_pam_auth_samlogon failed: %s\n",
2030                           nt_errstr(result)));
2031
2032                 if (NT_STATUS_EQUAL(result, NT_STATUS_NO_LOGON_SERVERS) ||
2033                     NT_STATUS_EQUAL(result, NT_STATUS_IO_TIMEOUT) ||
2034                     NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND))
2035                 {
2036                         DEBUG(10,("winbindd_dual_pam_auth_samlogon setting domain to offline\n"));
2037                         set_domain_offline( domain );
2038                         goto cached_logon;
2039                 }
2040
2041                 if (domain->online) {
2042                         /* We're still online - fail. */
2043                         goto done;
2044                 }
2045         }
2046
2047 cached_logon:
2048         /* Check for Cached logons */
2049         if (!domain->online && (state->request->flags & WBFLAG_PAM_CACHED_LOGIN) &&
2050             lp_winbind_offline_logon()) {
2051                 struct netr_SamInfo3 *info3 = NULL;
2052
2053                 result = winbindd_dual_pam_auth_cached(domain, state, &info3);
2054
2055                 if (!NT_STATUS_IS_OK(result)) {
2056                         DEBUG(10,("winbindd_dual_pam_auth_cached failed: %s\n", nt_errstr(result)));
2057                         goto done;
2058                 }
2059                 DEBUG(10,("winbindd_dual_pam_auth_cached succeeded\n"));
2060
2061                 result = map_info3_to_validation(state->mem_ctx,
2062                                                  info3,
2063                                                  &validation_level,
2064                                                  &validation);
2065                 TALLOC_FREE(info3);
2066                 if (!NT_STATUS_IS_OK(result)) {
2067                         DBG_ERR("map_info3_to_validation failed\n");
2068                         goto done;
2069                 }
2070         }
2071
2072 process_result:
2073
2074         if (NT_STATUS_IS_OK(result)) {
2075                 struct dom_sid user_sid;
2076                 TALLOC_CTX *base_ctx = NULL;
2077                 struct netr_SamBaseInfo *base_info = NULL;
2078                 struct netr_SamInfo3 *info3 = NULL;
2079
2080                 switch (validation_level) {
2081                 case 3:
2082                         base_ctx = validation->sam3;
2083                         base_info = &validation->sam3->base;
2084                         break;
2085                 case 6:
2086                         base_ctx = validation->sam6;
2087                         base_info = &validation->sam6->base;
2088                         break;
2089                 default:
2090                         result = NT_STATUS_INTERNAL_ERROR;
2091                         goto done;
2092                 }
2093
2094                 sid_compose(&user_sid, base_info->domain_sid, base_info->rid);
2095
2096                 if (base_info->full_name.string == NULL) {
2097                         struct netr_SamInfo3 *cached_info3;
2098
2099                         cached_info3 = netsamlogon_cache_get(state->mem_ctx,
2100                                                              &user_sid);
2101                         if (cached_info3 != NULL &&
2102                             cached_info3->base.full_name.string != NULL) {
2103                                 base_info->full_name.string = talloc_strdup(
2104                                         base_ctx,
2105                                         cached_info3->base.full_name.string);
2106                                 if (base_info->full_name.string == NULL) {
2107                                         result = NT_STATUS_NO_MEMORY;
2108                                         goto done;
2109                                 }
2110                         } else {
2111
2112                                 /* this might fail so we don't check the return code */
2113                                 wcache_query_user_fullname(domain,
2114                                                 base_ctx,
2115                                                 &user_sid,
2116                                                 &base_info->full_name.string);
2117                         }
2118                 }
2119
2120                 result = map_validation_to_info3(talloc_tos(),
2121                                                  validation_level,
2122                                                  validation,
2123                                                  &info3);
2124                 if (!NT_STATUS_IS_OK(result)) {
2125                         goto done;
2126                 }
2127
2128                 wcache_invalidate_samlogon(find_domain_from_name(name_domain),
2129                                            &user_sid);
2130                 netsamlogon_cache_store(name_user, info3);
2131
2132                 /* save name_to_sid info as early as possible (only if
2133                    this is our primary domain so we don't invalidate
2134                    the cache entry by storing the seq_num for the wrong
2135                    domain). */
2136                 if ( domain->primary ) {
2137                         cache_name2sid(domain, name_domain, name_user,
2138                                        SID_NAME_USER, &user_sid);
2139                 }
2140
2141                 /* Check if the user is in the right group */
2142
2143                 result = check_info3_in_group(
2144                         info3,
2145                         state->request->data.auth.require_membership_of_sid);
2146                 if (!NT_STATUS_IS_OK(result)) {
2147                         DEBUG(3, ("User %s is not in the required group (%s), so plaintext authentication is rejected\n",
2148                                   state->request->data.auth.user,
2149                                   state->request->data.auth.require_membership_of_sid));
2150                         goto done;
2151                 }
2152
2153                 result = append_auth_data(state->mem_ctx, state->response,
2154                                           state->request->flags,
2155                                           validation_level,
2156                                           validation,
2157                                           name_domain, name_user);
2158                 if (!NT_STATUS_IS_OK(result)) {
2159                         goto done;
2160                 }
2161
2162                 if ((state->request->flags & WBFLAG_PAM_CACHED_LOGIN)
2163                     && lp_winbind_offline_logon()) {
2164
2165                         result = winbindd_store_creds(domain,
2166                                                       state->request->data.auth.user,
2167                                                       state->request->data.auth.pass,
2168                                                       info3);
2169                 }
2170
2171                 if (state->request->flags & WBFLAG_PAM_GET_PWD_POLICY) {
2172                         /*
2173                          * WBFLAG_PAM_GET_PWD_POLICY is not used within
2174                          * any Samba caller anymore.
2175                          *
2176                          * We just fake this based on the effective values
2177                          * for the user, for legacy callers.
2178                          */
2179                         fake_password_policy(state->response, &info3->base);
2180                 }
2181
2182                 result = NT_STATUS_OK;
2183         }
2184
2185 done:
2186         /* give us a more useful (more correct?) error code */
2187         if ((NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) ||
2188             (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)))) {
2189                 result = NT_STATUS_NO_LOGON_SERVERS;
2190         }
2191
2192         set_auth_errors(state->response, result);
2193
2194         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, ("Plain-text authentication for user %s returned %s (PAM: %d)\n",
2195               state->request->data.auth.user,
2196               state->response->data.auth.nt_status_string,
2197               state->response->data.auth.pam_error));
2198
2199         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
2200 }
2201
2202 NTSTATUS winbind_dual_SamLogon(struct winbindd_domain *domain,
2203                                TALLOC_CTX *mem_ctx,
2204                                bool interactive,
2205                                uint32_t logon_parameters,
2206                                const char *name_user,
2207                                const char *name_domain,
2208                                const char *workstation,
2209                                const uint8_t chal[8],
2210                                DATA_BLOB lm_response,
2211                                DATA_BLOB nt_response,
2212                                uint8_t *authoritative,
2213                                bool skip_sam,
2214                                uint32_t *flags,
2215                                uint16_t *_validation_level,
2216                                union netr_Validation **_validation)
2217 {
2218         uint16_t validation_level;
2219         union netr_Validation *validation = NULL;
2220         NTSTATUS result;
2221
2222         /*
2223          * We check against domain->name instead of
2224          * name_domain, as find_auth_domain() ->
2225          * find_domain_from_name_noinit() already decided
2226          * that we are in a child for the correct domain.
2227          *
2228          * name_domain can also be lp_realm()
2229          * we need to check against domain->name.
2230          */
2231         if (!skip_sam && strequal(domain->name, get_global_sam_name())) {
2232                 DATA_BLOB chal_blob = data_blob_const(
2233                         chal, 8);
2234                 struct netr_SamInfo3 *info3 = NULL;
2235
2236                 result = winbindd_dual_auth_passdb(
2237                         talloc_tos(),
2238                         logon_parameters,
2239                         name_domain, name_user,
2240                         &chal_blob, &lm_response, &nt_response,
2241                         interactive,
2242                         authoritative,
2243                         &info3);
2244                 if (NT_STATUS_IS_OK(result)) {
2245                         result = map_info3_to_validation(mem_ctx,
2246                                                          info3,
2247                                                          &validation_level,
2248                                                          &validation);
2249                         TALLOC_FREE(info3);
2250                         if (!NT_STATUS_IS_OK(result)) {
2251                                 goto done;
2252                         }
2253                 }
2254
2255                 /*
2256                  * We need to try the remote NETLOGON server if this is
2257                  * not authoritative.
2258                  */
2259                 if (*authoritative != 0) {
2260                         *flags = 0;
2261                         goto process_result;
2262                 }
2263         }
2264
2265         result = winbind_samlogon_retry_loop(domain,
2266                                              mem_ctx,
2267                                              logon_parameters,
2268                                              name_user,
2269                                              NULL, /* password */
2270                                              name_domain,
2271                                              /* Bug #3248 - found by Stefan Burkei. */
2272                                              workstation, /* We carefully set this above so use it... */
2273                                              false, /* plaintext_given */
2274                                              chal,
2275                                              lm_response,
2276                                              nt_response,
2277                                              interactive,
2278                                              authoritative,
2279                                              flags,
2280                                              &validation_level,
2281                                              &validation);
2282         if (!NT_STATUS_IS_OK(result)) {
2283                 goto done;
2284         }
2285
2286 process_result:
2287
2288         if (NT_STATUS_IS_OK(result)) {
2289                 struct dom_sid user_sid;
2290                 TALLOC_CTX *base_ctx = NULL;
2291                 struct netr_SamBaseInfo *base_info = NULL;
2292                 struct netr_SamInfo3 *info3 = NULL;
2293
2294                 switch (validation_level) {
2295                 case 3:
2296                         base_ctx = validation->sam3;
2297                         base_info = &validation->sam3->base;
2298                         break;
2299                 case 6:
2300                         base_ctx = validation->sam6;
2301                         base_info = &validation->sam6->base;
2302                         break;
2303                 default:
2304                         result = NT_STATUS_INTERNAL_ERROR;
2305                         goto done;
2306                 }
2307
2308                 sid_compose(&user_sid, base_info->domain_sid, base_info->rid);
2309
2310                 if (base_info->full_name.string == NULL) {
2311                         struct netr_SamInfo3 *cached_info3;
2312
2313                         cached_info3 = netsamlogon_cache_get(mem_ctx,
2314                                                              &user_sid);
2315                         if (cached_info3 != NULL &&
2316                             cached_info3->base.full_name.string != NULL)
2317                         {
2318                                 base_info->full_name.string = talloc_strdup(
2319                                         base_ctx,
2320                                         cached_info3->base.full_name.string);
2321                         } else {
2322
2323                                 /* this might fail so we don't check the return code */
2324                                 wcache_query_user_fullname(domain,
2325                                                 base_ctx,
2326                                                 &user_sid,
2327                                                 &base_info->full_name.string);
2328                         }
2329                 }
2330
2331                 result = map_validation_to_info3(talloc_tos(),
2332                                                  validation_level,
2333                                                  validation,
2334                                                  &info3);
2335                 if (!NT_STATUS_IS_OK(result)) {
2336                         goto done;
2337                 }
2338                 wcache_invalidate_samlogon(find_domain_from_name(name_domain),
2339                                            &user_sid);
2340                 netsamlogon_cache_store(name_user, info3);
2341                 TALLOC_FREE(info3);
2342         }
2343
2344 done:
2345
2346         /* give us a more useful (more correct?) error code */
2347         if ((NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) ||
2348             (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)))) {
2349                 result = NT_STATUS_NO_LOGON_SERVERS;
2350         }
2351
2352         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2,
2353               ("NTLM CRAP authentication for user [%s]\\[%s] returned %s\n",
2354                name_domain,
2355                name_user,
2356                nt_errstr(result)));
2357
2358         if (!NT_STATUS_IS_OK(result)) {
2359                 return result;
2360         }
2361
2362         *_validation_level = validation_level;
2363         *_validation = validation;
2364         return NT_STATUS_OK;
2365 }
2366
2367 enum winbindd_result winbindd_dual_pam_auth_crap(struct winbindd_domain *domain,
2368                                                  struct winbindd_cli_state *state)
2369 {
2370         NTSTATUS result;
2371         const char *name_user = NULL;
2372         const char *name_domain = NULL;
2373         const char *workstation;
2374         uint8_t authoritative = 0;
2375         uint32_t flags = 0;
2376         uint16_t validation_level;
2377         union netr_Validation *validation = NULL;
2378         DATA_BLOB lm_resp, nt_resp;
2379
2380         /* This is child-only, so no check for privileged access is needed
2381            anymore */
2382
2383         /* Ensure null termination */
2384         state->request->data.auth_crap.user[sizeof(state->request->data.auth_crap.user)-1]=0;
2385         state->request->data.auth_crap.domain[sizeof(state->request->data.auth_crap.domain)-1]=0;
2386
2387         name_user = state->request->data.auth_crap.user;
2388         name_domain = state->request->data.auth_crap.domain;
2389         workstation = state->request->data.auth_crap.workstation;
2390
2391         DEBUG(3, ("[%5lu]: pam auth crap domain: %s user: %s\n", (unsigned long)state->pid,
2392                   name_domain, name_user));
2393
2394         if (state->request->data.auth_crap.lm_resp_len > sizeof(state->request->data.auth_crap.lm_resp)
2395                 || state->request->data.auth_crap.nt_resp_len > sizeof(state->request->data.auth_crap.nt_resp)) {
2396                 if (!(state->request->flags & WBFLAG_BIG_NTLMV2_BLOB) ||
2397                      state->request->extra_len != state->request->data.auth_crap.nt_resp_len) {
2398                         DEBUG(0, ("winbindd_pam_auth_crap: invalid password length %u/%u\n",
2399                                   state->request->data.auth_crap.lm_resp_len,
2400                                   state->request->data.auth_crap.nt_resp_len));
2401                         result = NT_STATUS_INVALID_PARAMETER;
2402                         goto done;
2403                 }
2404         }
2405
2406         lm_resp = data_blob_talloc(state->mem_ctx, state->request->data.auth_crap.lm_resp,
2407                                         state->request->data.auth_crap.lm_resp_len);
2408
2409         if (state->request->flags & WBFLAG_BIG_NTLMV2_BLOB) {
2410                 nt_resp = data_blob_talloc(state->mem_ctx,
2411                                            state->request->extra_data.data,
2412                                            state->request->data.auth_crap.nt_resp_len);
2413         } else {
2414                 nt_resp = data_blob_talloc(state->mem_ctx,
2415                                            state->request->data.auth_crap.nt_resp,
2416                                            state->request->data.auth_crap.nt_resp_len);
2417         }
2418
2419         result = winbind_dual_SamLogon(domain,
2420                                        state->mem_ctx,
2421                                        false, /* interactive */
2422                                        state->request->data.auth_crap.logon_parameters,
2423                                        name_user,
2424                                        name_domain,
2425                                        /* Bug #3248 - found by Stefan Burkei. */
2426                                        workstation, /* We carefully set this above so use it... */
2427                                        state->request->data.auth_crap.chal,
2428                                        lm_resp,
2429                                        nt_resp,
2430                                        &authoritative,
2431                                        false,
2432                                        &flags,
2433                                        &validation_level,
2434                                        &validation);
2435         if (!NT_STATUS_IS_OK(result)) {
2436                 state->response->data.auth.authoritative = authoritative;
2437                 goto done;
2438         }
2439
2440         if (NT_STATUS_IS_OK(result)) {
2441                 struct netr_SamInfo3 *info3 = NULL;
2442
2443                 result = map_validation_to_info3(state->mem_ctx,
2444                                                  validation_level,
2445                                                  validation,
2446                                                  &info3);
2447                 if (!NT_STATUS_IS_OK(result)) {
2448                         goto done;
2449                 }
2450
2451                 /* Check if the user is in the right group */
2452                 result = check_info3_in_group(
2453                         info3,
2454                         state->request->data.auth_crap.require_membership_of_sid);
2455                 if (!NT_STATUS_IS_OK(result)) {
2456                         DEBUG(3, ("User %s is not in the required group (%s), so "
2457                                   "crap authentication is rejected\n",
2458                                   state->request->data.auth_crap.user,
2459                                   state->request->data.auth_crap.require_membership_of_sid));
2460                         goto done;
2461                 }
2462
2463                 result = append_auth_data(state->mem_ctx, state->response,
2464                                           state->request->flags,
2465                                           validation_level,
2466                                           validation,
2467                                           name_domain, name_user);
2468                 if (!NT_STATUS_IS_OK(result)) {
2469                         goto done;
2470                 }
2471         }
2472
2473 done:
2474
2475         if (state->request->flags & WBFLAG_PAM_NT_STATUS_SQUASH) {
2476                 result = nt_status_squash(result);
2477         }
2478
2479         set_auth_errors(state->response, result);
2480
2481         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
2482 }
2483
2484 enum winbindd_result winbindd_dual_pam_chauthtok(struct winbindd_domain *contact_domain,
2485                                                  struct winbindd_cli_state *state)
2486 {
2487         char *oldpass;
2488         char *newpass = NULL;
2489         struct policy_handle dom_pol;
2490         struct rpc_pipe_client *cli = NULL;
2491         bool got_info = false;
2492         struct samr_DomInfo1 *info = NULL;
2493         struct userPwdChangeFailureInformation *reject = NULL;
2494         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2495         fstring domain, user;
2496         struct dcerpc_binding_handle *b = NULL;
2497
2498         ZERO_STRUCT(dom_pol);
2499
2500         DEBUG(3, ("[%5lu]: dual pam chauthtok %s\n", (unsigned long)state->pid,
2501                   state->request->data.auth.user));
2502
2503         if (!parse_domain_user(state->request->data.chauthtok.user, domain, user)) {
2504                 goto done;
2505         }
2506
2507         /* Change password */
2508
2509         oldpass = state->request->data.chauthtok.oldpass;
2510         newpass = state->request->data.chauthtok.newpass;
2511
2512         /* Initialize reject reason */
2513         state->response->data.auth.reject_reason = Undefined;
2514
2515         /* Get sam handle */
2516
2517         result = cm_connect_sam(contact_domain, state->mem_ctx, true, &cli,
2518                                 &dom_pol);
2519         if (!NT_STATUS_IS_OK(result)) {
2520                 DEBUG(1, ("could not get SAM handle on DC for %s\n", domain));
2521                 goto done;
2522         }
2523
2524         b = cli->binding_handle;
2525
2526         result = rpccli_samr_chgpasswd_user3(cli, state->mem_ctx,
2527                                              user,
2528                                              newpass,
2529                                              oldpass,
2530                                              &info,
2531                                              &reject);
2532
2533         /* Windows 2003 returns NT_STATUS_PASSWORD_RESTRICTION */
2534
2535         if (NT_STATUS_EQUAL(result, NT_STATUS_PASSWORD_RESTRICTION) ) {
2536
2537                 fill_in_password_policy(state->response, info);
2538
2539                 state->response->data.auth.reject_reason =
2540                         reject->extendedFailureReason;
2541
2542                 got_info = true;
2543         }
2544
2545         /* atm the pidl generated rpccli_samr_ChangePasswordUser3 function will
2546          * return with NT_STATUS_BUFFER_TOO_SMALL for w2k dcs as w2k just
2547          * returns with 4byte error code (NT_STATUS_NOT_SUPPORTED) which is too
2548          * short to comply with the samr_ChangePasswordUser3 idl - gd */
2549
2550         /* only fallback when the chgpasswd_user3 call is not supported */
2551         if (NT_STATUS_EQUAL(result, NT_STATUS_RPC_PROCNUM_OUT_OF_RANGE) ||
2552             NT_STATUS_EQUAL(result, NT_STATUS_NOT_SUPPORTED) ||
2553             NT_STATUS_EQUAL(result, NT_STATUS_BUFFER_TOO_SMALL) ||
2554             NT_STATUS_EQUAL(result, NT_STATUS_NOT_IMPLEMENTED)) {
2555
2556                 DEBUG(10,("Password change with chgpasswd_user3 failed with: %s, retrying chgpasswd_user2\n",
2557                         nt_errstr(result)));
2558
2559                 result = rpccli_samr_chgpasswd_user2(cli, state->mem_ctx, user, newpass, oldpass);
2560
2561                 /* Windows 2000 returns NT_STATUS_ACCOUNT_RESTRICTION.
2562                    Map to the same status code as Windows 2003. */
2563
2564                 if ( NT_STATUS_EQUAL(NT_STATUS_ACCOUNT_RESTRICTION, result ) ) {
2565                         result = NT_STATUS_PASSWORD_RESTRICTION;
2566                 }
2567         }
2568
2569 done:
2570
2571         if (NT_STATUS_IS_OK(result)
2572             && (state->request->flags & WBFLAG_PAM_CACHED_LOGIN)
2573             && lp_winbind_offline_logon()) {
2574                 result = winbindd_update_creds_by_name(contact_domain, user,
2575                                                        newpass);
2576                 /* Again, this happens when we login from gdm or xdm
2577                  * and the password expires, *BUT* cached crendentials
2578                  * doesn't exist. winbindd_update_creds_by_name()
2579                  * returns NT_STATUS_NO_SUCH_USER.
2580                  * This is not a failure.
2581                  * --- BoYang
2582                  * */
2583                 if (NT_STATUS_EQUAL(result, NT_STATUS_NO_SUCH_USER)) {
2584                         result = NT_STATUS_OK;
2585                 }
2586
2587                 if (!NT_STATUS_IS_OK(result)) {
2588                         DEBUG(10, ("Failed to store creds: %s\n",
2589                                    nt_errstr(result)));
2590                         goto process_result;
2591                 }
2592         }
2593
2594         if (!NT_STATUS_IS_OK(result) && !got_info && contact_domain) {
2595
2596                 NTSTATUS policy_ret;
2597
2598                 policy_ret = fillup_password_policy(
2599                         contact_domain, state->response);
2600
2601                 /* failure of this is non critical, it will just provide no
2602                  * additional information to the client why the change has
2603                  * failed - Guenther */
2604
2605                 if (!NT_STATUS_IS_OK(policy_ret)) {
2606                         DEBUG(10,("Failed to get password policies: %s\n", nt_errstr(policy_ret)));
2607                         goto process_result;
2608                 }
2609         }
2610
2611 process_result:
2612
2613         if (strequal(contact_domain->name, get_global_sam_name())) {
2614                 /* FIXME: internal rpc pipe does not cache handles yet */
2615                 if (b) {
2616                         if (is_valid_policy_hnd(&dom_pol)) {
2617                                 NTSTATUS _result;
2618                                 dcerpc_samr_Close(b, state->mem_ctx, &dom_pol, &_result);
2619                         }
2620                         TALLOC_FREE(cli);
2621                 }
2622         }
2623
2624         set_auth_errors(state->response, result);
2625
2626         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2,
2627               ("Password change for user [%s]\\[%s] returned %s (PAM: %d)\n",
2628                domain,
2629                user,
2630                state->response->data.auth.nt_status_string,
2631                state->response->data.auth.pam_error));
2632
2633         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
2634 }
2635
2636 enum winbindd_result winbindd_dual_pam_logoff(struct winbindd_domain *domain,
2637                                               struct winbindd_cli_state *state)
2638 {
2639         NTSTATUS result = NT_STATUS_NOT_SUPPORTED;
2640
2641         DEBUG(3, ("[%5lu]: pam dual logoff %s\n", (unsigned long)state->pid,
2642                 state->request->data.logoff.user));
2643
2644         if (!(state->request->flags & WBFLAG_PAM_KRB5)) {
2645                 result = NT_STATUS_OK;
2646                 goto process_result;
2647         }
2648
2649         if (state->request->data.logoff.krb5ccname[0] == '\0') {
2650                 result = NT_STATUS_OK;
2651                 goto process_result;
2652         }
2653
2654 #ifdef HAVE_KRB5
2655
2656         if (state->request->data.logoff.uid == (uid_t)-1) {
2657                 DEBUG(0,("winbindd_pam_logoff: invalid uid\n"));
2658                 goto process_result;
2659         }
2660
2661         /* what we need here is to find the corresponding krb5 ccache name *we*
2662          * created for a given username and destroy it */
2663
2664         if (!ccache_entry_exists(state->request->data.logoff.user)) {
2665                 result = NT_STATUS_OK;
2666                 DEBUG(10,("winbindd_pam_logoff: no entry found.\n"));
2667                 goto process_result;
2668         }
2669
2670         if (!ccache_entry_identical(state->request->data.logoff.user,
2671                                         state->request->data.logoff.uid,
2672                                         state->request->data.logoff.krb5ccname)) {
2673                 DEBUG(0,("winbindd_pam_logoff: cached entry differs.\n"));
2674                 goto process_result;
2675         }
2676
2677         result = remove_ccache(state->request->data.logoff.user);
2678         if (!NT_STATUS_IS_OK(result)) {
2679                 DEBUG(0,("winbindd_pam_logoff: failed to remove ccache: %s\n",
2680                         nt_errstr(result)));
2681                 goto process_result;
2682         }
2683
2684         /*
2685          * Remove any mlock'ed memory creds in the child
2686          * we might be using for krb5 ticket renewal.
2687          */
2688
2689         winbindd_delete_memory_creds(state->request->data.logoff.user);
2690
2691 #else
2692         result = NT_STATUS_NOT_SUPPORTED;
2693 #endif
2694
2695 process_result:
2696
2697
2698         set_auth_errors(state->response, result);
2699
2700         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
2701 }
2702
2703 /* Change user password with auth crap*/
2704
2705 enum winbindd_result winbindd_dual_pam_chng_pswd_auth_crap(struct winbindd_domain *domainSt, struct winbindd_cli_state *state)
2706 {
2707         NTSTATUS result;
2708         DATA_BLOB new_nt_password;
2709         DATA_BLOB old_nt_hash_enc;
2710         DATA_BLOB new_lm_password;
2711         DATA_BLOB old_lm_hash_enc;
2712         fstring  domain,user;
2713         struct policy_handle dom_pol;
2714         struct winbindd_domain *contact_domain = domainSt;
2715         struct rpc_pipe_client *cli = NULL;
2716         struct dcerpc_binding_handle *b = NULL;
2717
2718         ZERO_STRUCT(dom_pol);
2719
2720         /* Ensure null termination */
2721         state->request->data.chng_pswd_auth_crap.user[
2722                 sizeof(state->request->data.chng_pswd_auth_crap.user)-1]=0;
2723         state->request->data.chng_pswd_auth_crap.domain[
2724                 sizeof(state->request->data.chng_pswd_auth_crap.domain)-1]=0;
2725         *domain = 0;
2726         *user = 0;
2727
2728         DEBUG(3, ("[%5lu]: pam change pswd auth crap domain: %s user: %s\n",
2729                   (unsigned long)state->pid,
2730                   state->request->data.chng_pswd_auth_crap.domain,
2731                   state->request->data.chng_pswd_auth_crap.user));
2732
2733         if (lp_winbind_offline_logon()) {
2734                 DEBUG(0,("Refusing password change as winbind offline logons are enabled. "));
2735                 DEBUGADD(0,("Changing passwords here would risk inconsistent logons\n"));
2736                 result = NT_STATUS_ACCESS_DENIED;
2737                 goto done;
2738         }
2739
2740         if (*state->request->data.chng_pswd_auth_crap.domain) {
2741                 fstrcpy(domain,state->request->data.chng_pswd_auth_crap.domain);
2742         } else {
2743                 parse_domain_user(state->request->data.chng_pswd_auth_crap.user,
2744                                   domain, user);
2745
2746                 if(!*domain) {
2747                         DEBUG(3,("no domain specified with username (%s) - "
2748                                  "failing auth\n",
2749                                  state->request->data.chng_pswd_auth_crap.user));
2750                         result = NT_STATUS_NO_SUCH_USER;
2751                         goto done;
2752                 }
2753         }
2754
2755         if (!*domain && lp_winbind_use_default_domain()) {
2756                 fstrcpy(domain,lp_workgroup());
2757         }
2758
2759         if(!*user) {
2760                 fstrcpy(user, state->request->data.chng_pswd_auth_crap.user);
2761         }
2762
2763         DEBUG(3, ("[%5lu]: pam auth crap domain: %s user: %s\n",
2764                   (unsigned long)state->pid, domain, user));
2765
2766         /* Change password */
2767         new_nt_password = data_blob_const(
2768                 state->request->data.chng_pswd_auth_crap.new_nt_pswd,
2769                 state->request->data.chng_pswd_auth_crap.new_nt_pswd_len);
2770
2771         old_nt_hash_enc = data_blob_const(
2772                 state->request->data.chng_pswd_auth_crap.old_nt_hash_enc,
2773                 state->request->data.chng_pswd_auth_crap.old_nt_hash_enc_len);
2774
2775         if(state->request->data.chng_pswd_auth_crap.new_lm_pswd_len > 0)        {
2776                 new_lm_password = data_blob_const(
2777                         state->request->data.chng_pswd_auth_crap.new_lm_pswd,
2778                         state->request->data.chng_pswd_auth_crap.new_lm_pswd_len);
2779
2780                 old_lm_hash_enc = data_blob_const(
2781                         state->request->data.chng_pswd_auth_crap.old_lm_hash_enc,
2782                         state->request->data.chng_pswd_auth_crap.old_lm_hash_enc_len);
2783         } else {
2784                 new_lm_password = data_blob_null;
2785                 old_lm_hash_enc = data_blob_null;
2786         }
2787
2788         /* Get sam handle */
2789
2790         result = cm_connect_sam(contact_domain, state->mem_ctx, true, &cli, &dom_pol);
2791         if (!NT_STATUS_IS_OK(result)) {
2792                 DEBUG(1, ("could not get SAM handle on DC for %s\n", domain));
2793                 goto done;
2794         }
2795
2796         b = cli->binding_handle;
2797
2798         result = rpccli_samr_chng_pswd_auth_crap(
2799                 cli, state->mem_ctx, user, new_nt_password, old_nt_hash_enc,
2800                 new_lm_password, old_lm_hash_enc);
2801
2802  done:
2803
2804         if (strequal(contact_domain->name, get_global_sam_name())) {
2805                 /* FIXME: internal rpc pipe does not cache handles yet */
2806                 if (b) {
2807                         if (is_valid_policy_hnd(&dom_pol)) {
2808                                 NTSTATUS _result;
2809                                 dcerpc_samr_Close(b, state->mem_ctx, &dom_pol, &_result);
2810                         }
2811                         TALLOC_FREE(cli);
2812                 }
2813         }
2814
2815         set_auth_errors(state->response, result);
2816
2817         DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2,
2818               ("Password change for user [%s]\\[%s] returned %s (PAM: %d)\n",
2819                domain, user,
2820                state->response->data.auth.nt_status_string,
2821                state->response->data.auth.pam_error));
2822
2823         return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR;
2824 }
2825
2826 #ifdef HAVE_KRB5
2827 static NTSTATUS extract_pac_vrfy_sigs(TALLOC_CTX *mem_ctx, DATA_BLOB pac_blob,
2828                                       struct PAC_LOGON_INFO **logon_info)
2829 {
2830         krb5_context krbctx = NULL;
2831         krb5_error_code k5ret;
2832         krb5_keytab keytab;
2833         krb5_kt_cursor cursor;
2834         krb5_keytab_entry entry;
2835         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2836
2837         ZERO_STRUCT(entry);
2838         ZERO_STRUCT(cursor);
2839
2840         k5ret = krb5_init_context(&krbctx);
2841         if (k5ret) {
2842                 DEBUG(1, ("Failed to initialize kerberos context: %s\n",
2843                           error_message(k5ret)));
2844                 status = krb5_to_nt_status(k5ret);
2845                 goto out;
2846         }
2847
2848         k5ret =  gse_krb5_get_server_keytab(krbctx, &keytab);
2849         if (k5ret) {
2850                 DEBUG(1, ("Failed to get keytab: %s\n",
2851                           error_message(k5ret)));
2852                 status = krb5_to_nt_status(k5ret);
2853                 goto out_free;
2854         }
2855
2856         k5ret = krb5_kt_start_seq_get(krbctx, keytab, &cursor);
2857         if (k5ret) {
2858                 DEBUG(1, ("Failed to start seq: %s\n",
2859                           error_message(k5ret)));
2860                 status = krb5_to_nt_status(k5ret);
2861                 goto out_keytab;
2862         }
2863
2864         k5ret = krb5_kt_next_entry(krbctx, keytab, &entry, &cursor);
2865         while (k5ret == 0) {
2866                 status = kerberos_pac_logon_info(mem_ctx, pac_blob,
2867                                                  krbctx, NULL,
2868                                                  KRB5_KT_KEY(&entry), NULL, 0,
2869                                                  logon_info);
2870                 if (NT_STATUS_IS_OK(status)) {
2871                         break;
2872                 }
2873                 k5ret = smb_krb5_kt_free_entry(krbctx, &entry);
2874                 k5ret = krb5_kt_next_entry(krbctx, keytab, &entry, &cursor);
2875         }
2876
2877         k5ret = krb5_kt_end_seq_get(krbctx, keytab, &cursor);
2878         if (k5ret) {
2879                 DEBUG(1, ("Failed to end seq: %s\n",
2880                           error_message(k5ret)));
2881         }
2882 out_keytab:
2883         k5ret = krb5_kt_close(krbctx, keytab);
2884         if (k5ret) {
2885                 DEBUG(1, ("Failed to close keytab: %s\n",
2886                           error_message(k5ret)));
2887         }
2888 out_free:
2889         krb5_free_context(krbctx);
2890 out:
2891         return status;
2892 }
2893
2894 NTSTATUS winbindd_pam_auth_pac_send(struct winbindd_cli_state *state,
2895                                     struct netr_SamInfo3 **info3)
2896 {
2897         struct winbindd_request *req = state->request;
2898         DATA_BLOB pac_blob;
2899         struct PAC_LOGON_INFO *logon_info = NULL;
2900         struct netr_SamInfo3 *info3_copy = NULL;
2901         NTSTATUS result;
2902
2903         pac_blob = data_blob_const(req->extra_data.data, req->extra_len);
2904         result = extract_pac_vrfy_sigs(state->mem_ctx, pac_blob, &logon_info);
2905         if (!NT_STATUS_IS_OK(result) &&
2906             !NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
2907                 DEBUG(1, ("Error during PAC signature verification: %s\n",
2908                           nt_errstr(result)));
2909                 return result;
2910         }
2911
2912         if (logon_info) {
2913                 /*
2914                  * Signature verification succeeded, we can
2915                  * trust the PAC and prime the netsamlogon
2916                  * and name2sid caches. DO NOT DO THIS
2917                  * in the signature verification failed
2918                  * code path.
2919                  */
2920                 struct winbindd_domain *domain = NULL;
2921
2922                 result = create_info3_from_pac_logon_info(state->mem_ctx,
2923                                                         logon_info,
2924                                                         &info3_copy);
2925                 if (!NT_STATUS_IS_OK(result)) {
2926                         return result;
2927                 }
2928                 netsamlogon_cache_store(NULL, info3_copy);
2929
2930                 /*
2931                  * We're in the parent here, so find the child
2932                  * pointer from the PAC domain name.
2933                  */
2934                 domain = find_lookup_domain_from_name(
2935                                 info3_copy->base.logon_domain.string);
2936                 if (domain && domain->primary ) {
2937                         struct dom_sid user_sid;
2938
2939                         sid_compose(&user_sid,
2940                                 info3_copy->base.domain_sid,
2941                                 info3_copy->base.rid);
2942
2943                         cache_name2sid_trusted(domain,
2944                                 info3_copy->base.logon_domain.string,
2945                                 info3_copy->base.account_name.string,
2946                                 SID_NAME_USER,
2947                                 &user_sid);
2948
2949                         DBG_INFO("PAC for user %s\\%s SID %s primed cache\n",
2950                                 info3_copy->base.logon_domain.string,
2951                                 info3_copy->base.account_name.string,
2952                                 sid_string_dbg(&user_sid));
2953                 }
2954
2955         } else {
2956                 /* Try without signature verification */
2957                 result = kerberos_pac_logon_info(state->mem_ctx, pac_blob, NULL,
2958                                                  NULL, NULL, NULL, 0,
2959                                                  &logon_info);
2960                 if (!NT_STATUS_IS_OK(result)) {
2961                         DEBUG(10, ("Could not extract PAC: %s\n",
2962                                    nt_errstr(result)));
2963                         return result;
2964                 }
2965                 if (logon_info) {
2966                         /*
2967                          * Don't strictly need to copy here,
2968                          * but it makes it explicit we're
2969                          * returning a copy talloc'ed off
2970                          * the state->mem_ctx.
2971                          */
2972                         result = copy_netr_SamInfo3(state->mem_ctx,
2973                                                     &logon_info->info3,
2974                                                     &info3_copy);
2975                         if (!NT_STATUS_IS_OK(result)) {
2976                                 return result;
2977                         }
2978                 }
2979         }
2980
2981         *info3 = info3_copy;
2982
2983         return NT_STATUS_OK;
2984 }
2985 #else /* HAVE_KRB5 */
2986 NTSTATUS winbindd_pam_auth_pac_send(struct winbindd_cli_state *state,
2987                                     struct netr_SamInfo3 **info3)
2988 {
2989         return NT_STATUS_NO_SUCH_USER;
2990 }
2991 #endif /* HAVE_KRB5 */