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