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