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