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