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