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