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