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