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