s3-netlogon: Add support to authenticate trusted domains.
[mat/samba.git] / source3 / rpc_server / netlogon / srv_netlog_nt.c
1 /*
2  *  Unix SMB/CIFS implementation.
3  *  RPC Pipe client / server routines
4  *  Copyright (C) Andrew Tridgell              1992-1997,
5  *  Copyright (C) Luke Kenneth Casson Leighton 1996-1997,
6  *  Copyright (C) Paul Ashton                       1997.
7  *  Copyright (C) Jeremy Allison               1998-2001.
8  *  Copyright (C) Andrew Bartlett                   2001.
9  *  Copyright (C) Guenther Deschner                 2008-2009.
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 /* This is the implementation of the netlogon pipe. */
26
27 #include "includes.h"
28 #include "system/passwd.h" /* uid_wrapper */
29 #include "ntdomain.h"
30 #include "../libcli/auth/schannel.h"
31 #include "../librpc/gen_ndr/srv_netlogon.h"
32 #include "../librpc/gen_ndr/ndr_samr_c.h"
33 #include "../librpc/gen_ndr/ndr_lsa_c.h"
34 #include "rpc_client/cli_lsarpc.h"
35 #include "rpc_client/init_lsa.h"
36 #include "rpc_server/rpc_ncacn_np.h"
37 #include "../libcli/security/security.h"
38 #include "../libcli/security/dom_sid.h"
39 #include "librpc/gen_ndr/ndr_drsblobs.h"
40 #include "lib/crypto/arcfour.h"
41 #include "lib/crypto/md4.h"
42 #include "nsswitch/libwbclient/wbclient.h"
43 #include "../libcli/registry/util_reg.h"
44 #include "passdb.h"
45 #include "auth.h"
46 #include "messages.h"
47 #include "../lib/tsocket/tsocket.h"
48 #include "lib/param/param.h"
49
50 extern userdom_struct current_user_info;
51
52 #undef DBGC_CLASS
53 #define DBGC_CLASS DBGC_RPC_SRV
54
55 struct netlogon_server_pipe_state {
56         struct netr_Credential client_challenge;
57         struct netr_Credential server_challenge;
58 };
59
60 /*************************************************************************
61  _netr_LogonControl
62  *************************************************************************/
63
64 WERROR _netr_LogonControl(struct pipes_struct *p,
65                           struct netr_LogonControl *r)
66 {
67         struct netr_LogonControl2Ex l;
68
69         switch (r->in.level) {
70         case 1:
71                 break;
72         case 2:
73                 return WERR_NOT_SUPPORTED;
74         default:
75                 return WERR_UNKNOWN_LEVEL;
76         }
77
78         l.in.logon_server       = r->in.logon_server;
79         l.in.function_code      = r->in.function_code;
80         l.in.level              = r->in.level;
81         l.in.data               = NULL;
82         l.out.query             = r->out.query;
83
84         return _netr_LogonControl2Ex(p, &l);
85 }
86
87 /*************************************************************************
88  _netr_LogonControl2
89  *************************************************************************/
90
91 WERROR _netr_LogonControl2(struct pipes_struct *p,
92                            struct netr_LogonControl2 *r)
93 {
94         struct netr_LogonControl2Ex l;
95
96         l.in.logon_server       = r->in.logon_server;
97         l.in.function_code      = r->in.function_code;
98         l.in.level              = r->in.level;
99         l.in.data               = r->in.data;
100         l.out.query             = r->out.query;
101
102         return _netr_LogonControl2Ex(p, &l);
103 }
104
105 /*************************************************************************
106  *************************************************************************/
107
108 static bool wb_change_trust_creds(const char *domain, WERROR *tc_status)
109 {
110         wbcErr result;
111         struct wbcAuthErrorInfo *error = NULL;
112
113         result = wbcChangeTrustCredentials(domain, &error);
114         switch (result) {
115         case WBC_ERR_WINBIND_NOT_AVAILABLE:
116                 return false;
117         case WBC_ERR_DOMAIN_NOT_FOUND:
118                 *tc_status = WERR_NO_SUCH_DOMAIN;
119                 return true;
120         case WBC_ERR_SUCCESS:
121                 *tc_status = WERR_OK;
122                 return true;
123         default:
124                 break;
125         }
126
127         if (error && error->nt_status != 0) {
128                 *tc_status = ntstatus_to_werror(NT_STATUS(error->nt_status));
129         } else {
130                 *tc_status = WERR_TRUST_FAILURE;
131         }
132         wbcFreeMemory(error);
133         return true;
134 }
135
136 /*************************************************************************
137  *************************************************************************/
138
139 static bool wb_check_trust_creds(const char *domain, WERROR *tc_status)
140 {
141         wbcErr result;
142         struct wbcAuthErrorInfo *error = NULL;
143
144         result = wbcCheckTrustCredentials(domain, &error);
145         switch (result) {
146         case WBC_ERR_WINBIND_NOT_AVAILABLE:
147                 return false;
148         case WBC_ERR_DOMAIN_NOT_FOUND:
149                 *tc_status = WERR_NO_SUCH_DOMAIN;
150                 return true;
151         case WBC_ERR_SUCCESS:
152                 *tc_status = WERR_OK;
153                 return true;
154         default:
155                 break;
156         }
157
158         if (error && error->nt_status != 0) {
159                 *tc_status = ntstatus_to_werror(NT_STATUS(error->nt_status));
160         } else {
161                 *tc_status = WERR_TRUST_FAILURE;
162         }
163         wbcFreeMemory(error);
164         return true;
165 }
166
167 /****************************************************************
168  _netr_LogonControl2Ex
169 ****************************************************************/
170
171 WERROR _netr_LogonControl2Ex(struct pipes_struct *p,
172                              struct netr_LogonControl2Ex *r)
173 {
174         uint32_t flags = 0x0;
175         WERROR pdc_connection_status = WERR_OK;
176         uint32_t logon_attempts = 0x0;
177         WERROR tc_status;
178         fstring dc_name2;
179         const char *dc_name = NULL;
180         struct sockaddr_storage dc_ss;
181         const char *domain = NULL;
182         struct netr_NETLOGON_INFO_1 *info1;
183         struct netr_NETLOGON_INFO_2 *info2;
184         struct netr_NETLOGON_INFO_3 *info3;
185         struct netr_NETLOGON_INFO_4 *info4;
186         const char *fn;
187         uint32_t acct_ctrl;
188
189         switch (p->opnum) {
190         case NDR_NETR_LOGONCONTROL:
191                 fn = "_netr_LogonControl";
192                 break;
193         case NDR_NETR_LOGONCONTROL2:
194                 fn = "_netr_LogonControl2";
195                 break;
196         case NDR_NETR_LOGONCONTROL2EX:
197                 fn = "_netr_LogonControl2Ex";
198                 break;
199         default:
200                 return WERR_INVALID_PARAM;
201         }
202
203         acct_ctrl = p->session_info->info->acct_flags;
204
205         switch (r->in.function_code) {
206         case NETLOGON_CONTROL_TC_VERIFY:
207         case NETLOGON_CONTROL_CHANGE_PASSWORD:
208         case NETLOGON_CONTROL_REDISCOVER:
209                 if ((geteuid() != sec_initial_uid()) &&
210                     !nt_token_check_domain_rid(p->session_info->security_token, DOMAIN_RID_ADMINS) &&
211                     !nt_token_check_sid(&global_sid_Builtin_Administrators, p->session_info->security_token) &&
212                     !(acct_ctrl & (ACB_WSTRUST | ACB_SVRTRUST))) {
213                         return WERR_ACCESS_DENIED;
214                 }
215                 break;
216         default:
217                 break;
218         }
219
220         tc_status = WERR_NO_SUCH_DOMAIN;
221
222         switch (r->in.function_code) {
223         case NETLOGON_CONTROL_QUERY:
224                 tc_status = WERR_OK;
225                 break;
226         case NETLOGON_CONTROL_REPLICATE:
227         case NETLOGON_CONTROL_SYNCHRONIZE:
228         case NETLOGON_CONTROL_PDC_REPLICATE:
229         case NETLOGON_CONTROL_BACKUP_CHANGE_LOG:
230         case NETLOGON_CONTROL_BREAKPOINT:
231                 if (acct_ctrl & ACB_NORMAL) {
232                         return WERR_NOT_SUPPORTED;
233                 } else if (acct_ctrl & (ACB_WSTRUST | ACB_SVRTRUST)) {
234                         return WERR_ACCESS_DENIED;
235                 } else {
236                         return WERR_ACCESS_DENIED;
237                 }
238         case NETLOGON_CONTROL_TRUNCATE_LOG:
239                 if (acct_ctrl & ACB_NORMAL) {
240                         break;
241                 } else if (acct_ctrl & (ACB_WSTRUST | ACB_SVRTRUST)) {
242                         return WERR_ACCESS_DENIED;
243                 } else {
244                         return WERR_ACCESS_DENIED;
245                 }
246
247         case NETLOGON_CONTROL_TRANSPORT_NOTIFY:
248         case NETLOGON_CONTROL_FORCE_DNS_REG:
249         case NETLOGON_CONTROL_QUERY_DNS_REG:
250                 return WERR_NOT_SUPPORTED;
251         case NETLOGON_CONTROL_FIND_USER:
252                 if (!r->in.data || !r->in.data->user) {
253                         return WERR_NOT_SUPPORTED;
254                 }
255                 break;
256         case NETLOGON_CONTROL_SET_DBFLAG:
257                 if (!r->in.data) {
258                         return WERR_NOT_SUPPORTED;
259                 }
260                 break;
261         case NETLOGON_CONTROL_TC_VERIFY:
262                 if (!r->in.data || !r->in.data->domain) {
263                         return WERR_NOT_SUPPORTED;
264                 }
265
266                 if (!wb_check_trust_creds(r->in.data->domain, &tc_status)) {
267                         return WERR_NOT_SUPPORTED;
268                 }
269                 break;
270         case NETLOGON_CONTROL_TC_QUERY:
271                 if (!r->in.data || !r->in.data->domain) {
272                         return WERR_NOT_SUPPORTED;
273                 }
274
275                 domain = r->in.data->domain;
276
277                 if (!is_trusted_domain(domain)) {
278                         break;
279                 }
280
281                 if (!get_dc_name(domain, NULL, dc_name2, &dc_ss)) {
282                         tc_status = WERR_NO_LOGON_SERVERS;
283                         break;
284                 }
285
286                 dc_name = talloc_asprintf(p->mem_ctx, "\\\\%s", dc_name2);
287                 if (!dc_name) {
288                         return WERR_NOMEM;
289                 }
290
291                 tc_status = WERR_OK;
292
293                 break;
294
295         case NETLOGON_CONTROL_REDISCOVER:
296                 if (!r->in.data || !r->in.data->domain) {
297                         return WERR_NOT_SUPPORTED;
298                 }
299
300                 domain = r->in.data->domain;
301
302                 if (!is_trusted_domain(domain)) {
303                         break;
304                 }
305
306                 if (!get_dc_name(domain, NULL, dc_name2, &dc_ss)) {
307                         tc_status = WERR_NO_LOGON_SERVERS;
308                         break;
309                 }
310
311                 dc_name = talloc_asprintf(p->mem_ctx, "\\\\%s", dc_name2);
312                 if (!dc_name) {
313                         return WERR_NOMEM;
314                 }
315
316                 tc_status = WERR_OK;
317
318                 break;
319
320         case NETLOGON_CONTROL_CHANGE_PASSWORD:
321                 if (!r->in.data || !r->in.data->domain) {
322                         return WERR_NOT_SUPPORTED;
323                 }
324
325                 if (!wb_change_trust_creds(r->in.data->domain, &tc_status)) {
326                         return WERR_NOT_SUPPORTED;
327                 }
328                 break;
329
330         default:
331                 /* no idea what this should be */
332                 DEBUG(0,("%s: unimplemented function level [%d]\n",
333                         fn, r->in.function_code));
334                 return WERR_UNKNOWN_LEVEL;
335         }
336
337         /* prepare the response */
338
339         switch (r->in.level) {
340         case 1:
341                 info1 = talloc_zero(p->mem_ctx, struct netr_NETLOGON_INFO_1);
342                 W_ERROR_HAVE_NO_MEMORY(info1);
343
344                 info1->flags                    = flags;
345                 info1->pdc_connection_status    = pdc_connection_status;
346
347                 r->out.query->info1 = info1;
348                 break;
349         case 2:
350                 info2 = talloc_zero(p->mem_ctx, struct netr_NETLOGON_INFO_2);
351                 W_ERROR_HAVE_NO_MEMORY(info2);
352
353                 info2->flags                    = flags;
354                 info2->pdc_connection_status    = pdc_connection_status;
355                 info2->trusted_dc_name          = dc_name;
356                 info2->tc_connection_status     = tc_status;
357
358                 r->out.query->info2 = info2;
359                 break;
360         case 3:
361                 info3 = talloc_zero(p->mem_ctx, struct netr_NETLOGON_INFO_3);
362                 W_ERROR_HAVE_NO_MEMORY(info3);
363
364                 info3->flags                    = flags;
365                 info3->logon_attempts           = logon_attempts;
366
367                 r->out.query->info3 = info3;
368                 break;
369         case 4:
370                 info4 = talloc_zero(p->mem_ctx, struct netr_NETLOGON_INFO_4);
371                 W_ERROR_HAVE_NO_MEMORY(info4);
372
373                 info4->trusted_dc_name          = dc_name;
374                 info4->trusted_domain_name      = r->in.data->domain;
375
376                 r->out.query->info4 = info4;
377                 break;
378         default:
379                 return WERR_UNKNOWN_LEVEL;
380         }
381
382         return WERR_OK;
383 }
384
385 /*************************************************************************
386  _netr_NetrEnumerateTrustedDomains
387  *************************************************************************/
388
389 NTSTATUS _netr_NetrEnumerateTrustedDomains(struct pipes_struct *p,
390                                            struct netr_NetrEnumerateTrustedDomains *r)
391 {
392         NTSTATUS status;
393         NTSTATUS result = NT_STATUS_OK;
394         DATA_BLOB blob;
395         int num_domains = 0;
396         const char **trusted_domains = NULL;
397         struct lsa_DomainList domain_list;
398         struct dcerpc_binding_handle *h = NULL;
399         struct policy_handle pol;
400         uint32_t enum_ctx = 0;
401         int i;
402         uint32_t max_size = (uint32_t)-1;
403
404         DEBUG(6,("_netr_NetrEnumerateTrustedDomains: %d\n", __LINE__));
405
406         status = rpcint_binding_handle(p->mem_ctx,
407                                        &ndr_table_lsarpc,
408                                        p->remote_address,
409                                        p->session_info,
410                                        p->msg_ctx,
411                                        &h);
412         if (!NT_STATUS_IS_OK(status)) {
413                 return status;
414         }
415
416         status = dcerpc_lsa_open_policy2(h,
417                                          p->mem_ctx,
418                                          NULL,
419                                          true,
420                                          LSA_POLICY_VIEW_LOCAL_INFORMATION,
421                                          &pol,
422                                          &result);
423         if (!NT_STATUS_IS_OK(status)) {
424                 goto out;
425         }
426         if (!NT_STATUS_IS_OK(result)) {
427                 status = result;
428                 goto out;
429         }
430
431         do {
432                 /* Lookup list of trusted domains */
433                 status = dcerpc_lsa_EnumTrustDom(h,
434                                                  p->mem_ctx,
435                                                  &pol,
436                                                  &enum_ctx,
437                                                  &domain_list,
438                                                  max_size,
439                                                  &result);
440                 if (!NT_STATUS_IS_OK(status)) {
441                         goto out;
442                 }
443                 if (!NT_STATUS_IS_OK(result) &&
444                     !NT_STATUS_EQUAL(result, NT_STATUS_NO_MORE_ENTRIES) &&
445                     !NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES)) {
446                         status = result;
447                         goto out;
448                 }
449
450                 for (i = 0; i < domain_list.count; i++) {
451                         if (!add_string_to_array(p->mem_ctx, domain_list.domains[i].name.string,
452                                                  &trusted_domains, &num_domains)) {
453                                 status = NT_STATUS_NO_MEMORY;
454                                 goto out;
455                         }
456                 }
457         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
458
459         if (num_domains > 0) {
460                 /* multi sz terminate */
461                 trusted_domains = talloc_realloc(p->mem_ctx, trusted_domains, const char *, num_domains + 1);
462                 if (trusted_domains == NULL) {
463                         status = NT_STATUS_NO_MEMORY;
464                         goto out;
465                 }
466
467                 trusted_domains[num_domains] = NULL;
468         }
469
470         if (!push_reg_multi_sz(trusted_domains, &blob, trusted_domains)) {
471                 TALLOC_FREE(trusted_domains);
472                 status = NT_STATUS_NO_MEMORY;
473                 goto out;
474         }
475
476         r->out.trusted_domains_blob->data = blob.data;
477         r->out.trusted_domains_blob->length = blob.length;
478
479         DEBUG(6,("_netr_NetrEnumerateTrustedDomains: %d\n", __LINE__));
480
481         status = NT_STATUS_OK;
482
483  out:
484         if (is_valid_policy_hnd(&pol)) {
485                 dcerpc_lsa_Close(h, p->mem_ctx, &pol, &result);
486         }
487
488         return status;
489 }
490
491 /*************************************************************************
492  *************************************************************************/
493
494 static NTSTATUS samr_find_machine_account(TALLOC_CTX *mem_ctx,
495                                           struct dcerpc_binding_handle *b,
496                                           const char *account_name,
497                                           uint32_t access_mask,
498                                           struct dom_sid2 **domain_sid_p,
499                                           uint32_t *user_rid_p,
500                                           struct policy_handle *user_handle)
501 {
502         NTSTATUS status;
503         NTSTATUS result = NT_STATUS_OK;
504         struct policy_handle connect_handle, domain_handle;
505         struct lsa_String domain_name;
506         struct dom_sid2 *domain_sid;
507         struct lsa_String names;
508         struct samr_Ids rids;
509         struct samr_Ids types;
510         uint32_t rid;
511
512         status = dcerpc_samr_Connect2(b, mem_ctx,
513                                       lp_netbios_name(),
514                                       SAMR_ACCESS_CONNECT_TO_SERVER |
515                                       SAMR_ACCESS_ENUM_DOMAINS |
516                                       SAMR_ACCESS_LOOKUP_DOMAIN,
517                                       &connect_handle,
518                                       &result);
519         if (!NT_STATUS_IS_OK(status)) {
520                 goto out;
521         }
522         if (!NT_STATUS_IS_OK(result)) {
523                 status = result;
524                 goto out;
525         }
526
527         init_lsa_String(&domain_name, get_global_sam_name());
528
529         status = dcerpc_samr_LookupDomain(b, mem_ctx,
530                                           &connect_handle,
531                                           &domain_name,
532                                           &domain_sid,
533                                           &result);
534         if (!NT_STATUS_IS_OK(status)) {
535                 goto out;
536         }
537         if (!NT_STATUS_IS_OK(result)) {
538                 status = result;
539                 goto out;
540         }
541
542         status = dcerpc_samr_OpenDomain(b, mem_ctx,
543                                         &connect_handle,
544                                         SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
545                                         domain_sid,
546                                         &domain_handle,
547                                         &result);
548         if (!NT_STATUS_IS_OK(status)) {
549                 goto out;
550         }
551         if (!NT_STATUS_IS_OK(result)) {
552                 status = result;
553                 goto out;
554         }
555
556         init_lsa_String(&names, account_name);
557
558         status = dcerpc_samr_LookupNames(b, mem_ctx,
559                                          &domain_handle,
560                                          1,
561                                          &names,
562                                          &rids,
563                                          &types,
564                                          &result);
565         if (!NT_STATUS_IS_OK(status)) {
566                 goto out;
567         }
568         if (!NT_STATUS_IS_OK(result)) {
569                 status = result;
570                 goto out;
571         }
572
573         if (rids.count != 1) {
574                 status = NT_STATUS_NO_SUCH_USER;
575                 goto out;
576         }
577         if (rids.count != types.count) {
578                 status = NT_STATUS_INVALID_PARAMETER;
579                 goto out;
580         }
581         if (types.ids[0] != SID_NAME_USER) {
582                 status = NT_STATUS_NO_SUCH_USER;
583                 goto out;
584         }
585
586         rid = rids.ids[0];
587
588         status = dcerpc_samr_OpenUser(b, mem_ctx,
589                                       &domain_handle,
590                                       access_mask,
591                                       rid,
592                                       user_handle,
593                                       &result);
594         if (!NT_STATUS_IS_OK(status)) {
595                 goto out;
596         }
597         if (!NT_STATUS_IS_OK(result)) {
598                 status = result;
599                 goto out;
600         }
601
602         if (user_rid_p) {
603                 *user_rid_p = rid;
604         }
605
606         if (domain_sid_p) {
607                 *domain_sid_p = domain_sid;
608         }
609
610  out:
611         if (is_valid_policy_hnd(&domain_handle)) {
612                 dcerpc_samr_Close(b, mem_ctx, &domain_handle, &result);
613         }
614         if (is_valid_policy_hnd(&connect_handle)) {
615                 dcerpc_samr_Close(b, mem_ctx, &connect_handle, &result);
616         }
617
618         return status;
619 }
620
621 /******************************************************************
622  gets a machine password entry.  checks access rights of the host.
623  ******************************************************************/
624
625 static NTSTATUS get_md4pw(struct samr_Password *md4pw, const char *mach_acct,
626                           enum netr_SchannelType sec_chan_type,
627                           struct dom_sid *sid,
628                           struct messaging_context *msg_ctx)
629 {
630         NTSTATUS status;
631         NTSTATUS result = NT_STATUS_OK;
632         TALLOC_CTX *mem_ctx;
633         struct dcerpc_binding_handle *h = NULL;
634         struct tsocket_address *local;
635         struct policy_handle user_handle;
636         uint32_t user_rid;
637         struct dom_sid *domain_sid;
638         uint32_t acct_ctrl;
639         union samr_UserInfo *info;
640         struct auth_session_info *session_info;
641         int rc;
642
643 #if 0
644
645     /*
646      * Currently this code is redundent as we already have a filter
647      * by hostname list. What this code really needs to do is to
648      * get a hosts allowed/hosts denied list from the SAM database
649      * on a per user basis, and make the access decision there.
650      * I will leave this code here for now as a reminder to implement
651      * this at a later date. JRA.
652      */
653
654         if (!allow_access(lp_domain_hostsdeny(), lp_domain_hostsallow(),
655                           p->client_id.name,
656                           p->client_id.addr)) {
657                 DEBUG(0,("get_md4pw: Workstation %s denied access to domain\n", mach_acct));
658                 return False;
659         }
660 #endif /* 0 */
661
662         mem_ctx = talloc_stackframe();
663         if (mem_ctx == NULL) {
664                 status = NT_STATUS_NO_MEMORY;
665                 goto out;
666         }
667
668         status = make_session_info_system(mem_ctx, &session_info);
669         if (!NT_STATUS_IS_OK(status)) {
670                 goto out;
671         }
672
673         ZERO_STRUCT(user_handle);
674
675         rc = tsocket_address_inet_from_strings(mem_ctx,
676                                                "ip",
677                                                "127.0.0.1",
678                                                0,
679                                                &local);
680         if (rc < 0) {
681                 status = NT_STATUS_NO_MEMORY;
682                 goto out;
683         }
684
685         status = rpcint_binding_handle(mem_ctx,
686                                        &ndr_table_samr,
687                                        local,
688                                        session_info,
689                                        msg_ctx,
690                                        &h);
691         if (!NT_STATUS_IS_OK(status)) {
692                 goto out;
693         }
694
695         become_root();
696         status = samr_find_machine_account(mem_ctx, h, mach_acct,
697                                            SEC_FLAG_MAXIMUM_ALLOWED,
698                                            &domain_sid, &user_rid,
699                                            &user_handle);
700         unbecome_root();
701         if (!NT_STATUS_IS_OK(status)) {
702                 goto out;
703         }
704
705         status = dcerpc_samr_QueryUserInfo2(h,
706                                             mem_ctx,
707                                             &user_handle,
708                                             UserControlInformation,
709                                             &info,
710                                             &result);
711         if (!NT_STATUS_IS_OK(status)) {
712                 goto out;
713         }
714         if (!NT_STATUS_IS_OK(result)) {
715                 status = result;
716                 goto out;
717         }
718
719         acct_ctrl = info->info16.acct_flags;
720
721         if (acct_ctrl & ACB_DISABLED) {
722                 DEBUG(0,("get_md4pw: Workstation %s: account is disabled\n", mach_acct));
723                 status = NT_STATUS_ACCOUNT_DISABLED;
724                 goto out;
725         }
726
727         if (!(acct_ctrl & ACB_SVRTRUST) &&
728             !(acct_ctrl & ACB_WSTRUST) &&
729             !(acct_ctrl & ACB_DOMTRUST))
730         {
731                 DEBUG(0,("get_md4pw: Workstation %s: account is not a trust account\n", mach_acct));
732                 status = NT_STATUS_NO_TRUST_SAM_ACCOUNT;
733                 goto out;
734         }
735
736         switch (sec_chan_type) {
737                 case SEC_CHAN_BDC:
738                         if (!(acct_ctrl & ACB_SVRTRUST)) {
739                                 DEBUG(0,("get_md4pw: Workstation %s: BDC secure channel requested "
740                                          "but not a server trust account\n", mach_acct));
741                                 status = NT_STATUS_NO_TRUST_SAM_ACCOUNT;
742                                 goto out;
743                         }
744                         break;
745                 case SEC_CHAN_WKSTA:
746                         if (!(acct_ctrl & ACB_WSTRUST)) {
747                                 DEBUG(0,("get_md4pw: Workstation %s: WORKSTATION secure channel requested "
748                                          "but not a workstation trust account\n", mach_acct));
749                                 status = NT_STATUS_NO_TRUST_SAM_ACCOUNT;
750                                 goto out;
751                         }
752                         break;
753                 case SEC_CHAN_DOMAIN:
754                         if (!(acct_ctrl & ACB_DOMTRUST)) {
755                                 DEBUG(0,("get_md4pw: Workstation %s: DOMAIN secure channel requested "
756                                          "but not a interdomain trust account\n", mach_acct));
757                                 status = NT_STATUS_NO_TRUST_SAM_ACCOUNT;
758                                 goto out;
759                         }
760                         break;
761                 default:
762                         break;
763         }
764
765         become_root();
766         status = dcerpc_samr_QueryUserInfo2(h,
767                                             mem_ctx,
768                                             &user_handle,
769                                             UserInternal1Information,
770                                             &info,
771                                             &result);
772         unbecome_root();
773         if (!NT_STATUS_IS_OK(status)) {
774                 goto out;
775         }
776         if (!NT_STATUS_IS_OK(result)) {
777                 status = result;
778                 goto out;
779         }
780
781         if (info->info18.nt_pwd_active == 0) {
782                 DEBUG(0,("get_md4pw: Workstation %s: account does not have a password\n", mach_acct));
783                 status = NT_STATUS_LOGON_FAILURE;
784                 goto out;
785         }
786
787         /* samr gives out nthash unencrypted (!) */
788         memcpy(md4pw->hash, info->info18.nt_pwd.hash, 16);
789
790         sid_compose(sid, domain_sid, user_rid);
791
792  out:
793         if (h && is_valid_policy_hnd(&user_handle)) {
794                 dcerpc_samr_Close(h, mem_ctx, &user_handle, &result);
795         }
796
797         talloc_free(mem_ctx);
798
799         return status;
800 }
801
802 /*************************************************************************
803  _netr_ServerReqChallenge
804  *************************************************************************/
805
806 NTSTATUS _netr_ServerReqChallenge(struct pipes_struct *p,
807                                   struct netr_ServerReqChallenge *r)
808 {
809         struct netlogon_server_pipe_state *pipe_state =
810                 talloc_get_type(p->private_data, struct netlogon_server_pipe_state);
811
812         if (pipe_state) {
813                 DEBUG(10,("_netr_ServerReqChallenge: new challenge requested. Clearing old state.\n"));
814                 talloc_free(pipe_state);
815                 p->private_data = NULL;
816         }
817
818         pipe_state = talloc(p, struct netlogon_server_pipe_state);
819         NT_STATUS_HAVE_NO_MEMORY(pipe_state);
820
821         pipe_state->client_challenge = *r->in.credentials;
822
823         generate_random_buffer(pipe_state->server_challenge.data,
824                                sizeof(pipe_state->server_challenge.data));
825
826         *r->out.return_credentials = pipe_state->server_challenge;
827
828         p->private_data = pipe_state;
829
830         return NT_STATUS_OK;
831 }
832
833 /*************************************************************************
834  _netr_ServerAuthenticate
835  Create the initial credentials.
836  *************************************************************************/
837
838 NTSTATUS _netr_ServerAuthenticate(struct pipes_struct *p,
839                                   struct netr_ServerAuthenticate *r)
840 {
841         struct netr_ServerAuthenticate3 a;
842         uint32_t negotiate_flags = 0;
843         uint32_t rid;
844
845         a.in.server_name                = r->in.server_name;
846         a.in.account_name               = r->in.account_name;
847         a.in.secure_channel_type        = r->in.secure_channel_type;
848         a.in.computer_name              = r->in.computer_name;
849         a.in.credentials                = r->in.credentials;
850         a.in.negotiate_flags            = &negotiate_flags;
851
852         a.out.return_credentials        = r->out.return_credentials;
853         a.out.rid                       = &rid;
854         a.out.negotiate_flags           = &negotiate_flags;
855
856         return _netr_ServerAuthenticate3(p, &a);
857
858 }
859
860 /*************************************************************************
861  _netr_ServerAuthenticate3
862  *************************************************************************/
863
864 NTSTATUS _netr_ServerAuthenticate3(struct pipes_struct *p,
865                                    struct netr_ServerAuthenticate3 *r)
866 {
867         NTSTATUS status;
868         uint32_t srv_flgs;
869         /* r->in.negotiate_flags is an aliased pointer to r->out.negotiate_flags,
870          * so use a copy to avoid destroying the client values. */
871         uint32_t in_neg_flags = *r->in.negotiate_flags;
872         const char *fn;
873         struct loadparm_context *lp_ctx;
874         struct dom_sid sid;
875         struct samr_Password mach_pwd;
876         struct netlogon_creds_CredentialState *creds;
877         struct netlogon_server_pipe_state *pipe_state =
878                 talloc_get_type(p->private_data, struct netlogon_server_pipe_state);
879
880         /* According to Microsoft (see bugid #6099)
881          * Windows 7 looks at the negotiate_flags
882          * returned in this structure *even if the
883          * call fails with access denied* ! So in order
884          * to allow Win7 to connect to a Samba NT style
885          * PDC we set the flags before we know if it's
886          * an error or not.
887          */
888
889         /* 0x000001ff */
890         srv_flgs = NETLOGON_NEG_ACCOUNT_LOCKOUT |
891                    NETLOGON_NEG_PERSISTENT_SAMREPL |
892                    NETLOGON_NEG_ARCFOUR |
893                    NETLOGON_NEG_PROMOTION_COUNT |
894                    NETLOGON_NEG_CHANGELOG_BDC |
895                    NETLOGON_NEG_FULL_SYNC_REPL |
896                    NETLOGON_NEG_MULTIPLE_SIDS |
897                    NETLOGON_NEG_REDO |
898                    NETLOGON_NEG_PASSWORD_CHANGE_REFUSAL |
899                    NETLOGON_NEG_PASSWORD_SET2;
900
901         /* Ensure we support strong (128-bit) keys. */
902         if (in_neg_flags & NETLOGON_NEG_STRONG_KEYS) {
903                 srv_flgs |= NETLOGON_NEG_STRONG_KEYS;
904         }
905
906         if (lp_server_schannel() != false) {
907                 srv_flgs |= NETLOGON_NEG_SCHANNEL;
908         }
909
910         /*
911          * Support authenticaten of trusted domains.
912          *
913          * These flags are the minimum required set which works with win2k3
914          * and win2k8.
915          */
916         if (pdb_capabilities() & PDB_CAP_TRUSTED_DOMAINS_EX) {
917                 srv_flgs |= NETLOGON_NEG_TRANSITIVE_TRUSTS |
918                             NETLOGON_NEG_DNS_DOMAIN_TRUSTS |
919                             NETLOGON_NEG_CROSS_FOREST_TRUSTS |
920                             NETLOGON_NEG_NEUTRALIZE_NT4_EMULATION;
921         }
922
923         switch (p->opnum) {
924                 case NDR_NETR_SERVERAUTHENTICATE:
925                         fn = "_netr_ServerAuthenticate";
926                         break;
927                 case NDR_NETR_SERVERAUTHENTICATE2:
928                         fn = "_netr_ServerAuthenticate2";
929                         break;
930                 case NDR_NETR_SERVERAUTHENTICATE3:
931                         fn = "_netr_ServerAuthenticate3";
932                         break;
933                 default:
934                         return NT_STATUS_INTERNAL_ERROR;
935         }
936
937         /* We use this as the key to store the creds: */
938         /* r->in.computer_name */
939
940         if (!pipe_state) {
941                 DEBUG(0,("%s: no challenge sent to client %s\n", fn,
942                         r->in.computer_name));
943                 status = NT_STATUS_ACCESS_DENIED;
944                 goto out;
945         }
946
947         if ( (lp_server_schannel() == true) &&
948              ((in_neg_flags & NETLOGON_NEG_SCHANNEL) == 0) ) {
949
950                 /* schannel must be used, but client did not offer it. */
951                 DEBUG(0,("%s: schannel required but client failed "
952                         "to offer it. Client was %s\n",
953                         fn, r->in.account_name));
954                 status = NT_STATUS_ACCESS_DENIED;
955                 goto out;
956         }
957
958         status = get_md4pw(&mach_pwd,
959                            r->in.account_name,
960                            r->in.secure_channel_type,
961                            &sid, p->msg_ctx);
962         if (!NT_STATUS_IS_OK(status)) {
963                 DEBUG(0,("%s: failed to get machine password for "
964                         "account %s: %s\n",
965                         fn, r->in.account_name, nt_errstr(status) ));
966                 /* always return NT_STATUS_ACCESS_DENIED */
967                 status = NT_STATUS_ACCESS_DENIED;
968                 goto out;
969         }
970
971         /* From the client / server challenges and md4 password, generate sess key */
972         /* Check client credentials are valid. */
973         creds = netlogon_creds_server_init(p->mem_ctx,
974                                            r->in.account_name,
975                                            r->in.computer_name,
976                                            r->in.secure_channel_type,
977                                            &pipe_state->client_challenge,
978                                            &pipe_state->server_challenge,
979                                            &mach_pwd,
980                                            r->in.credentials,
981                                            r->out.return_credentials,
982                                            srv_flgs);
983         if (!creds) {
984                 DEBUG(0,("%s: netlogon_creds_server_check failed. Rejecting auth "
985                         "request from client %s machine account %s\n",
986                         fn, r->in.computer_name,
987                         r->in.account_name));
988                 status = NT_STATUS_ACCESS_DENIED;
989                 goto out;
990         }
991
992         creds->sid = dom_sid_dup(creds, &sid);
993         if (!creds->sid) {
994                 status = NT_STATUS_NO_MEMORY;
995                 goto out;
996         }
997
998         lp_ctx = loadparm_init_s3(p->mem_ctx, loadparm_s3_context());
999         if (lp_ctx == NULL) {
1000                 DEBUG(10, ("loadparm_init_s3 failed\n"));
1001                 status = NT_STATUS_INTERNAL_ERROR;
1002                 goto out;
1003         }
1004
1005         /* Store off the state so we can continue after client disconnect. */
1006         become_root();
1007         status = schannel_save_creds_state(p->mem_ctx, lp_ctx, creds);
1008         unbecome_root();
1009
1010         talloc_unlink(p->mem_ctx, lp_ctx);
1011
1012         if (!NT_STATUS_IS_OK(status)) {
1013                 goto out;
1014         }
1015
1016         sid_peek_rid(&sid, r->out.rid);
1017
1018         status = NT_STATUS_OK;
1019
1020   out:
1021
1022         *r->out.negotiate_flags = srv_flgs;
1023         return status;
1024 }
1025
1026 /*************************************************************************
1027  _netr_ServerAuthenticate2
1028  *************************************************************************/
1029
1030 NTSTATUS _netr_ServerAuthenticate2(struct pipes_struct *p,
1031                                    struct netr_ServerAuthenticate2 *r)
1032 {
1033         struct netr_ServerAuthenticate3 a;
1034         uint32_t rid;
1035
1036         a.in.server_name                = r->in.server_name;
1037         a.in.account_name               = r->in.account_name;
1038         a.in.secure_channel_type        = r->in.secure_channel_type;
1039         a.in.computer_name              = r->in.computer_name;
1040         a.in.credentials                = r->in.credentials;
1041         a.in.negotiate_flags            = r->in.negotiate_flags;
1042
1043         a.out.return_credentials        = r->out.return_credentials;
1044         a.out.rid                       = &rid;
1045         a.out.negotiate_flags           = r->out.negotiate_flags;
1046
1047         return _netr_ServerAuthenticate3(p, &a);
1048 }
1049
1050 /*************************************************************************
1051  * If schannel is required for this call test that it actually is available.
1052  *************************************************************************/
1053 static NTSTATUS schannel_check_required(struct pipe_auth_data *auth_info,
1054                                         const char *computer_name,
1055                                         bool integrity, bool privacy)
1056 {
1057         if (auth_info && auth_info->auth_type == DCERPC_AUTH_TYPE_SCHANNEL) {
1058                 if (!privacy && !integrity) {
1059                         return NT_STATUS_OK;
1060                 }
1061
1062                 if ((!privacy && integrity) &&
1063                     auth_info->auth_level == DCERPC_AUTH_LEVEL_INTEGRITY) {
1064                         return NT_STATUS_OK;
1065                 }
1066
1067                 if ((privacy || integrity) &&
1068                     auth_info->auth_level == DCERPC_AUTH_LEVEL_PRIVACY) {
1069                         return NT_STATUS_OK;
1070                 }
1071         }
1072
1073         /* test didn't pass */
1074         DEBUG(0, ("schannel_check_required: [%s] is not using schannel\n",
1075                   computer_name));
1076
1077         return NT_STATUS_ACCESS_DENIED;
1078 }
1079
1080 /*************************************************************************
1081  *************************************************************************/
1082
1083 static NTSTATUS netr_creds_server_step_check(struct pipes_struct *p,
1084                                              TALLOC_CTX *mem_ctx,
1085                                              const char *computer_name,
1086                                              struct netr_Authenticator *received_authenticator,
1087                                              struct netr_Authenticator *return_authenticator,
1088                                              struct netlogon_creds_CredentialState **creds_out)
1089 {
1090         NTSTATUS status;
1091         bool schannel_global_required = (lp_server_schannel() == true) ? true:false;
1092         struct loadparm_context *lp_ctx;
1093
1094         if (schannel_global_required) {
1095                 status = schannel_check_required(&p->auth,
1096                                                  computer_name,
1097                                                  false, false);
1098                 if (!NT_STATUS_IS_OK(status)) {
1099                         return status;
1100                 }
1101         }
1102
1103         lp_ctx = loadparm_init_s3(mem_ctx, loadparm_s3_context());
1104         if (lp_ctx == NULL) {
1105                 DEBUG(0, ("loadparm_init_s3 failed\n"));
1106                 return NT_STATUS_INTERNAL_ERROR;
1107         }
1108
1109         status = schannel_check_creds_state(mem_ctx, lp_ctx,
1110                                             computer_name, received_authenticator,
1111                                             return_authenticator, creds_out);
1112         talloc_unlink(mem_ctx, lp_ctx);
1113         return status;
1114 }
1115
1116 /*************************************************************************
1117  *************************************************************************/
1118
1119 static NTSTATUS netr_set_machine_account_password(TALLOC_CTX *mem_ctx,
1120                                                   struct auth_session_info *session_info,
1121                                                   struct messaging_context *msg_ctx,
1122                                                   const char *account_name,
1123                                                   struct samr_Password *nt_hash)
1124 {
1125         NTSTATUS status;
1126         NTSTATUS result = NT_STATUS_OK;
1127         struct dcerpc_binding_handle *h = NULL;
1128         struct tsocket_address *local;
1129         struct policy_handle user_handle;
1130         uint32_t acct_ctrl;
1131         union samr_UserInfo *info;
1132         struct samr_UserInfo18 info18;
1133         DATA_BLOB in,out;
1134         int rc;
1135
1136         ZERO_STRUCT(user_handle);
1137
1138         rc = tsocket_address_inet_from_strings(mem_ctx,
1139                                                "ip",
1140                                                "127.0.0.1",
1141                                                0,
1142                                                &local);
1143         if (rc < 0) {
1144                 status = NT_STATUS_NO_MEMORY;
1145                 goto out;
1146         }
1147
1148         status = rpcint_binding_handle(mem_ctx,
1149                                        &ndr_table_samr,
1150                                        local,
1151                                        session_info,
1152                                        msg_ctx,
1153                                        &h);
1154         if (!NT_STATUS_IS_OK(status)) {
1155                 goto out;
1156         }
1157
1158         become_root();
1159         status = samr_find_machine_account(mem_ctx,
1160                                            h,
1161                                            account_name,
1162                                            SEC_FLAG_MAXIMUM_ALLOWED,
1163                                            NULL,
1164                                            NULL,
1165                                            &user_handle);
1166         unbecome_root();
1167         if (!NT_STATUS_IS_OK(status)) {
1168                 goto out;
1169         }
1170
1171         status = dcerpc_samr_QueryUserInfo2(h,
1172                                             mem_ctx,
1173                                             &user_handle,
1174                                             UserControlInformation,
1175                                             &info,
1176                                             &result);
1177         if (!NT_STATUS_IS_OK(status)) {
1178                 goto out;
1179         }
1180         if (!NT_STATUS_IS_OK(result)) {
1181                 status = result;
1182                 goto out;
1183         }
1184
1185         acct_ctrl = info->info16.acct_flags;
1186
1187         if (!(acct_ctrl & ACB_WSTRUST ||
1188               acct_ctrl & ACB_SVRTRUST ||
1189               acct_ctrl & ACB_DOMTRUST)) {
1190                 status = NT_STATUS_NO_SUCH_USER;
1191                 goto out;
1192         }
1193
1194         if (acct_ctrl & ACB_DISABLED) {
1195                 status = NT_STATUS_ACCOUNT_DISABLED;
1196                 goto out;
1197         }
1198
1199         ZERO_STRUCT(info18);
1200
1201         in = data_blob_const(nt_hash->hash, 16);
1202         out = data_blob_talloc_zero(mem_ctx, 16);
1203         sess_crypt_blob(&out, &in, &session_info->session_key, true);
1204         memcpy(info18.nt_pwd.hash, out.data, out.length);
1205
1206         info18.nt_pwd_active = true;
1207
1208         info->info18 = info18;
1209
1210         become_root();
1211         status = dcerpc_samr_SetUserInfo2(h,
1212                                           mem_ctx,
1213                                           &user_handle,
1214                                           UserInternal1Information,
1215                                           info,
1216                                           &result);
1217         unbecome_root();
1218         if (!NT_STATUS_IS_OK(status)) {
1219                 goto out;
1220         }
1221         if (!NT_STATUS_IS_OK(result)) {
1222                 status = result;
1223                 goto out;
1224         }
1225
1226  out:
1227         if (h && is_valid_policy_hnd(&user_handle)) {
1228                 dcerpc_samr_Close(h, mem_ctx, &user_handle, &result);
1229         }
1230
1231         return status;
1232 }
1233
1234 /*************************************************************************
1235  _netr_ServerPasswordSet
1236  *************************************************************************/
1237
1238 NTSTATUS _netr_ServerPasswordSet(struct pipes_struct *p,
1239                                  struct netr_ServerPasswordSet *r)
1240 {
1241         NTSTATUS status = NT_STATUS_OK;
1242         int i;
1243         struct netlogon_creds_CredentialState *creds;
1244
1245         DEBUG(5,("_netr_ServerPasswordSet: %d\n", __LINE__));
1246
1247         become_root();
1248         status = netr_creds_server_step_check(p, p->mem_ctx,
1249                                               r->in.computer_name,
1250                                               r->in.credential,
1251                                               r->out.return_authenticator,
1252                                               &creds);
1253         unbecome_root();
1254
1255         if (!NT_STATUS_IS_OK(status)) {
1256                 DEBUG(2,("_netr_ServerPasswordSet: netlogon_creds_server_step failed. Rejecting auth "
1257                         "request from client %s machine account %s\n",
1258                         r->in.computer_name, creds->computer_name));
1259                 TALLOC_FREE(creds);
1260                 return status;
1261         }
1262
1263         DEBUG(3,("_netr_ServerPasswordSet: Server Password Set by remote machine:[%s] on account [%s]\n",
1264                         r->in.computer_name, creds->computer_name));
1265
1266         netlogon_creds_des_decrypt(creds, r->in.new_password);
1267
1268         DEBUG(100,("_netr_ServerPasswordSet: new given value was :\n"));
1269         for(i = 0; i < sizeof(r->in.new_password->hash); i++)
1270                 DEBUG(100,("%02X ", r->in.new_password->hash[i]));
1271         DEBUG(100,("\n"));
1272
1273         status = netr_set_machine_account_password(p->mem_ctx,
1274                                                    p->session_info,
1275                                                    p->msg_ctx,
1276                                                    creds->account_name,
1277                                                    r->in.new_password);
1278         return status;
1279 }
1280
1281 /****************************************************************
1282  _netr_ServerPasswordSet2
1283 ****************************************************************/
1284
1285 NTSTATUS _netr_ServerPasswordSet2(struct pipes_struct *p,
1286                                   struct netr_ServerPasswordSet2 *r)
1287 {
1288         NTSTATUS status;
1289         struct netlogon_creds_CredentialState *creds = NULL;
1290         DATA_BLOB plaintext;
1291         struct samr_CryptPassword password_buf;
1292         struct samr_Password nt_hash;
1293
1294         become_root();
1295         status = netr_creds_server_step_check(p, p->mem_ctx,
1296                                               r->in.computer_name,
1297                                               r->in.credential,
1298                                               r->out.return_authenticator,
1299                                               &creds);
1300         unbecome_root();
1301
1302         if (!NT_STATUS_IS_OK(status)) {
1303                 const char *computer_name = "<unknown>";
1304
1305                 if (creds && creds->computer_name) {
1306                         computer_name = creds->computer_name;
1307                 }
1308                 DEBUG(2,("_netr_ServerPasswordSet2: netlogon_creds_server_step "
1309                         "failed. Rejecting auth request from client %s machine account %s\n",
1310                         r->in.computer_name, computer_name));
1311                 TALLOC_FREE(creds);
1312                 return status;
1313         }
1314
1315         memcpy(password_buf.data, r->in.new_password->data, 512);
1316         SIVAL(password_buf.data, 512, r->in.new_password->length);
1317         netlogon_creds_arcfour_crypt(creds, password_buf.data, 516);
1318
1319         if (!extract_pw_from_buffer(p->mem_ctx, password_buf.data, &plaintext)) {
1320                 TALLOC_FREE(creds);
1321                 return NT_STATUS_WRONG_PASSWORD;
1322         }
1323
1324         mdfour(nt_hash.hash, plaintext.data, plaintext.length);
1325
1326         status = netr_set_machine_account_password(p->mem_ctx,
1327                                                    p->session_info,
1328                                                    p->msg_ctx,
1329                                                    creds->account_name,
1330                                                    &nt_hash);
1331         TALLOC_FREE(creds);
1332         return status;
1333 }
1334
1335 /*************************************************************************
1336  _netr_LogonSamLogoff
1337  *************************************************************************/
1338
1339 NTSTATUS _netr_LogonSamLogoff(struct pipes_struct *p,
1340                               struct netr_LogonSamLogoff *r)
1341 {
1342         NTSTATUS status;
1343         struct netlogon_creds_CredentialState *creds;
1344
1345         become_root();
1346         status = netr_creds_server_step_check(p, p->mem_ctx,
1347                                               r->in.computer_name,
1348                                               r->in.credential,
1349                                               r->out.return_authenticator,
1350                                               &creds);
1351         unbecome_root();
1352
1353         return status;
1354 }
1355
1356 static NTSTATUS _netr_LogonSamLogon_check(const struct netr_LogonSamLogonEx *r)
1357 {
1358         switch (r->in.logon_level) {
1359         case NetlogonInteractiveInformation:
1360         case NetlogonServiceInformation:
1361         case NetlogonInteractiveTransitiveInformation:
1362         case NetlogonServiceTransitiveInformation:
1363                 if (r->in.logon->password == NULL) {
1364                         return NT_STATUS_INVALID_PARAMETER;
1365                 }
1366
1367                 switch (r->in.validation_level) {
1368                 case NetlogonValidationSamInfo:  /* 2 */
1369                 case NetlogonValidationSamInfo2: /* 3 */
1370                         break;
1371                 case NetlogonValidationSamInfo4: /* 6 */
1372                         if ((pdb_capabilities() & PDB_CAP_ADS) == 0) {
1373                                 DEBUG(10,("Not adding validation info level 6 "
1374                                    "without ADS passdb backend\n"));
1375                                 return NT_STATUS_INVALID_INFO_CLASS;
1376                         }
1377                         break;
1378                 default:
1379                         return NT_STATUS_INVALID_INFO_CLASS;
1380                 }
1381
1382                 break;
1383         case NetlogonNetworkInformation:
1384         case NetlogonNetworkTransitiveInformation:
1385                 if (r->in.logon->network == NULL) {
1386                         return NT_STATUS_INVALID_PARAMETER;
1387                 }
1388
1389                 switch (r->in.validation_level) {
1390                 case NetlogonValidationSamInfo:  /* 2 */
1391                 case NetlogonValidationSamInfo2: /* 3 */
1392                         break;
1393                 case NetlogonValidationSamInfo4: /* 6 */
1394                         if ((pdb_capabilities() & PDB_CAP_ADS) == 0) {
1395                                 DEBUG(10,("Not adding validation info level 6 "
1396                                    "without ADS passdb backend\n"));
1397                                 return NT_STATUS_INVALID_INFO_CLASS;
1398                         }
1399                         break;
1400                 default:
1401                         return NT_STATUS_INVALID_INFO_CLASS;
1402                 }
1403
1404                 break;
1405
1406         case NetlogonGenericInformation:
1407                 if (r->in.logon->generic == NULL) {
1408                         return NT_STATUS_INVALID_PARAMETER;
1409                 }
1410
1411                 /* we don't support this here */
1412                 return NT_STATUS_INVALID_PARAMETER;
1413 #if 0
1414                 switch (r->in.validation_level) {
1415                 /* TODO: case NetlogonValidationGenericInfo: 4 */
1416                 case NetlogonValidationGenericInfo2: /* 5 */
1417                         break;
1418                 default:
1419                         return NT_STATUS_INVALID_INFO_CLASS;
1420                 }
1421
1422                 break;
1423 #endif
1424         default:
1425                 return NT_STATUS_INVALID_PARAMETER;
1426         }
1427
1428         return NT_STATUS_OK;
1429 }
1430
1431 /*************************************************************************
1432  _netr_LogonSamLogon_base
1433  *************************************************************************/
1434
1435 static NTSTATUS _netr_LogonSamLogon_base(struct pipes_struct *p,
1436                                          struct netr_LogonSamLogonEx *r,
1437                                          struct netlogon_creds_CredentialState *creds)
1438 {
1439         NTSTATUS status = NT_STATUS_OK;
1440         union netr_LogonLevel *logon = r->in.logon;
1441         const char *nt_username, *nt_domain, *nt_workstation;
1442         struct auth_usersupplied_info *user_info = NULL;
1443         struct auth_serversupplied_info *server_info = NULL;
1444         struct auth_context *auth_context = NULL;
1445         uint8_t pipe_session_key[16];
1446         bool process_creds = true;
1447         const char *fn;
1448
1449         switch (p->opnum) {
1450                 case NDR_NETR_LOGONSAMLOGON:
1451                         process_creds = true;
1452                         fn = "_netr_LogonSamLogon";
1453                         break;
1454                 case NDR_NETR_LOGONSAMLOGONWITHFLAGS:
1455                         process_creds = true;
1456                         fn = "_netr_LogonSamLogonWithFlags";
1457                         break;
1458                 case NDR_NETR_LOGONSAMLOGONEX:
1459                         process_creds = false;
1460                         fn = "_netr_LogonSamLogonEx";
1461                         break;
1462                 default:
1463                         return NT_STATUS_INTERNAL_ERROR;
1464         }
1465
1466         *r->out.authoritative = true; /* authoritative response */
1467
1468         switch (r->in.validation_level) {
1469         case 2:
1470                 r->out.validation->sam2 = talloc_zero(p->mem_ctx, struct netr_SamInfo2);
1471                 if (!r->out.validation->sam2) {
1472                         return NT_STATUS_NO_MEMORY;
1473                 }
1474                 break;
1475         case 3:
1476                 r->out.validation->sam3 = talloc_zero(p->mem_ctx, struct netr_SamInfo3);
1477                 if (!r->out.validation->sam3) {
1478                         return NT_STATUS_NO_MEMORY;
1479                 }
1480                 break;
1481         case 6:
1482                 r->out.validation->sam6 = talloc_zero(p->mem_ctx, struct netr_SamInfo6);
1483                 if (!r->out.validation->sam6) {
1484                         return NT_STATUS_NO_MEMORY;
1485                 }
1486                 break;
1487         default:
1488                 DEBUG(0,("%s: bad validation_level value %d.\n",
1489                         fn, (int)r->in.validation_level));
1490                 return NT_STATUS_INVALID_INFO_CLASS;
1491         }
1492
1493         switch (r->in.logon_level) {
1494         case NetlogonInteractiveInformation:
1495         case NetlogonServiceInformation:
1496         case NetlogonInteractiveTransitiveInformation:
1497         case NetlogonServiceTransitiveInformation:
1498                 nt_username     = logon->password->identity_info.account_name.string ?
1499                                   logon->password->identity_info.account_name.string : "";
1500                 nt_domain       = logon->password->identity_info.domain_name.string ?
1501                                   logon->password->identity_info.domain_name.string : "";
1502                 nt_workstation  = logon->password->identity_info.workstation.string ?
1503                                   logon->password->identity_info.workstation.string : "";
1504
1505                 DEBUG(3,("SAM Logon (Interactive). Domain:[%s].  ", lp_workgroup()));
1506                 break;
1507         case NetlogonNetworkInformation:
1508         case NetlogonNetworkTransitiveInformation:
1509                 nt_username     = logon->network->identity_info.account_name.string ?
1510                                   logon->network->identity_info.account_name.string : "";
1511                 nt_domain       = logon->network->identity_info.domain_name.string ?
1512                                   logon->network->identity_info.domain_name.string : "";
1513                 nt_workstation  = logon->network->identity_info.workstation.string ?
1514                                   logon->network->identity_info.workstation.string : "";
1515
1516                 DEBUG(3,("SAM Logon (Network). Domain:[%s].  ", lp_workgroup()));
1517                 break;
1518         default:
1519                 DEBUG(2,("SAM Logon: unsupported switch value\n"));
1520                 return NT_STATUS_INVALID_INFO_CLASS;
1521         } /* end switch */
1522
1523         DEBUG(3,("User:[%s@%s] Requested Domain:[%s]\n", nt_username, nt_workstation, nt_domain));
1524         fstrcpy(current_user_info.smb_name, nt_username);
1525         sub_set_smb_name(nt_username);
1526
1527         DEBUG(5,("Attempting validation level %d for unmapped username %s.\n",
1528                 r->in.validation_level, nt_username));
1529
1530         status = NT_STATUS_OK;
1531
1532         switch (r->in.logon_level) {
1533         case NetlogonNetworkInformation:
1534         case NetlogonNetworkTransitiveInformation:
1535         {
1536                 const char *wksname = nt_workstation;
1537
1538                 status = make_auth_context_fixed(talloc_tos(), &auth_context,
1539                                                  logon->network->challenge);
1540                 if (!NT_STATUS_IS_OK(status)) {
1541                         return status;
1542                 }
1543
1544                 /* For a network logon, the workstation name comes in with two
1545                  * backslashes in the front. Strip them if they are there. */
1546
1547                 if (*wksname == '\\') wksname++;
1548                 if (*wksname == '\\') wksname++;
1549
1550                 /* Standard challenge/response authentication */
1551                 if (!make_user_info_netlogon_network(&user_info,
1552                                                      nt_username, nt_domain,
1553                                                      wksname,
1554                                                      p->remote_address,
1555                                                      logon->network->identity_info.parameter_control,
1556                                                      logon->network->lm.data,
1557                                                      logon->network->lm.length,
1558                                                      logon->network->nt.data,
1559                                                      logon->network->nt.length)) {
1560                         status = NT_STATUS_NO_MEMORY;
1561                 }
1562                 break;
1563         }
1564         case NetlogonInteractiveInformation:
1565         case NetlogonServiceInformation:
1566         case NetlogonInteractiveTransitiveInformation:
1567         case NetlogonServiceTransitiveInformation:
1568
1569                 /* 'Interactive' authentication, supplies the password in its
1570                    MD4 form, encrypted with the session key.  We will convert
1571                    this to challenge/response for the auth subsystem to chew
1572                    on */
1573         {
1574                 uint8_t chal[8];
1575
1576                 status = make_auth_context_subsystem(talloc_tos(),
1577                                                      &auth_context);
1578                 if (!NT_STATUS_IS_OK(status)) {
1579                         return status;
1580                 }
1581
1582                 auth_context->get_ntlm_challenge(auth_context, chal);
1583
1584                 if (!make_user_info_netlogon_interactive(&user_info,
1585                                                          nt_username, nt_domain,
1586                                                          nt_workstation,
1587                                                          p->remote_address,
1588                                                          logon->password->identity_info.parameter_control,
1589                                                          chal,
1590                                                          logon->password->lmpassword.hash,
1591                                                          logon->password->ntpassword.hash,
1592                                                          creds->session_key)) {
1593                         status = NT_STATUS_NO_MEMORY;
1594                 }
1595                 break;
1596         }
1597         default:
1598                 DEBUG(2,("SAM Logon: unsupported switch value\n"));
1599                 return NT_STATUS_INVALID_INFO_CLASS;
1600         } /* end switch */
1601
1602         if ( NT_STATUS_IS_OK(status) ) {
1603                 status = auth_context->check_ntlm_password(auth_context,
1604                         user_info, &server_info);
1605         }
1606
1607         TALLOC_FREE(auth_context);
1608         free_user_info(&user_info);
1609
1610         DEBUG(5,("%s: check_password returned status %s\n",
1611                   fn, nt_errstr(status)));
1612
1613         /* Check account and password */
1614
1615         if (!NT_STATUS_IS_OK(status)) {
1616                 /* If we don't know what this domain is, we need to
1617                    indicate that we are not authoritative.  This
1618                    allows the client to decide if it needs to try
1619                    a local user.  Fix by jpjanosi@us.ibm.com, #2976 */
1620                 if ( NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_USER)
1621                      && !strequal(nt_domain, get_global_sam_name())
1622                      && !is_trusted_domain(nt_domain) )
1623                         *r->out.authoritative = false; /* We are not authoritative */
1624
1625                 TALLOC_FREE(server_info);
1626                 return status;
1627         }
1628
1629         if (server_info->guest) {
1630                 /* We don't like guest domain logons... */
1631                 DEBUG(5,("%s: Attempted domain logon as GUEST "
1632                          "denied.\n", fn));
1633                 TALLOC_FREE(server_info);
1634                 return NT_STATUS_LOGON_FAILURE;
1635         }
1636
1637         /* This is the point at which, if the login was successful, that
1638            the SAM Local Security Authority should record that the user is
1639            logged in to the domain.  */
1640
1641         if (process_creds) {
1642                 /* Get the pipe session key from the creds. */
1643                 memcpy(pipe_session_key, creds->session_key, 16);
1644         } else {
1645                 struct schannel_state *schannel_auth;
1646                 /* Get the pipe session key from the schannel. */
1647                 if ((p->auth.auth_type != DCERPC_AUTH_TYPE_SCHANNEL)
1648                     || (p->auth.auth_ctx == NULL)) {
1649                         return NT_STATUS_INVALID_HANDLE;
1650                 }
1651
1652                 schannel_auth = talloc_get_type_abort(p->auth.auth_ctx,
1653                                                       struct schannel_state);
1654                 memcpy(pipe_session_key, schannel_auth->creds->session_key, 16);
1655         }
1656
1657         switch (r->in.validation_level) {
1658         case 2:
1659                 status = serverinfo_to_SamInfo2(server_info, pipe_session_key, 16,
1660                                                 r->out.validation->sam2);
1661                 break;
1662         case 3:
1663                 status = serverinfo_to_SamInfo3(server_info, pipe_session_key, 16,
1664                                                 r->out.validation->sam3);
1665                 break;
1666         case 6:
1667                 status = serverinfo_to_SamInfo6(server_info, pipe_session_key, 16,
1668                                                 r->out.validation->sam6);
1669                 break;
1670         }
1671
1672         TALLOC_FREE(server_info);
1673
1674         return status;
1675 }
1676
1677 /****************************************************************
1678  _netr_LogonSamLogonWithFlags
1679 ****************************************************************/
1680
1681 NTSTATUS _netr_LogonSamLogonWithFlags(struct pipes_struct *p,
1682                                       struct netr_LogonSamLogonWithFlags *r)
1683 {
1684         NTSTATUS status;
1685         struct netlogon_creds_CredentialState *creds;
1686         struct netr_LogonSamLogonEx r2;
1687         struct netr_Authenticator return_authenticator;
1688
1689         *r->out.authoritative = true;
1690
1691         r2.in.server_name       = r->in.server_name;
1692         r2.in.computer_name     = r->in.computer_name;
1693         r2.in.logon_level       = r->in.logon_level;
1694         r2.in.logon             = r->in.logon;
1695         r2.in.validation_level  = r->in.validation_level;
1696         r2.in.flags             = r->in.flags;
1697         r2.out.validation       = r->out.validation;
1698         r2.out.authoritative    = r->out.authoritative;
1699         r2.out.flags            = r->out.flags;
1700
1701         status = _netr_LogonSamLogon_check(&r2);
1702         if (!NT_STATUS_IS_OK(status)) {
1703                 return status;
1704         }
1705
1706         become_root();
1707         status = netr_creds_server_step_check(p, p->mem_ctx,
1708                                               r->in.computer_name,
1709                                               r->in.credential,
1710                                               &return_authenticator,
1711                                               &creds);
1712         unbecome_root();
1713         if (!NT_STATUS_IS_OK(status)) {
1714                 return status;
1715         }
1716
1717         status = _netr_LogonSamLogon_base(p, &r2, creds);
1718
1719         *r->out.return_authenticator = return_authenticator;
1720
1721         return status;
1722 }
1723
1724 /*************************************************************************
1725  _netr_LogonSamLogon
1726  *************************************************************************/
1727
1728 NTSTATUS _netr_LogonSamLogon(struct pipes_struct *p,
1729                              struct netr_LogonSamLogon *r)
1730 {
1731         NTSTATUS status;
1732         struct netr_LogonSamLogonWithFlags r2;
1733         uint32_t flags = 0;
1734
1735         r2.in.server_name               = r->in.server_name;
1736         r2.in.computer_name             = r->in.computer_name;
1737         r2.in.credential                = r->in.credential;
1738         r2.in.logon_level               = r->in.logon_level;
1739         r2.in.logon                     = r->in.logon;
1740         r2.in.validation_level          = r->in.validation_level;
1741         r2.in.return_authenticator      = r->in.return_authenticator;
1742         r2.in.flags                     = &flags;
1743         r2.out.validation               = r->out.validation;
1744         r2.out.authoritative            = r->out.authoritative;
1745         r2.out.flags                    = &flags;
1746         r2.out.return_authenticator     = r->out.return_authenticator;
1747
1748         status = _netr_LogonSamLogonWithFlags(p, &r2);
1749
1750         return status;
1751 }
1752
1753 /*************************************************************************
1754  _netr_LogonSamLogonEx
1755  - no credential chaining. Map into net sam logon.
1756  *************************************************************************/
1757
1758 NTSTATUS _netr_LogonSamLogonEx(struct pipes_struct *p,
1759                                struct netr_LogonSamLogonEx *r)
1760 {
1761         NTSTATUS status;
1762         struct netlogon_creds_CredentialState *creds = NULL;
1763         struct loadparm_context *lp_ctx;
1764
1765         *r->out.authoritative = true;
1766
1767         status = _netr_LogonSamLogon_check(r);
1768         if (!NT_STATUS_IS_OK(status)) {
1769                 return status;
1770         }
1771
1772         /* Only allow this if the pipe is protected. */
1773         if (p->auth.auth_type != DCERPC_AUTH_TYPE_SCHANNEL) {
1774                 DEBUG(0,("_netr_LogonSamLogonEx: client %s not using schannel for netlogon\n",
1775                         get_remote_machine_name() ));
1776                 return NT_STATUS_INVALID_PARAMETER;
1777         }
1778
1779         lp_ctx = loadparm_init_s3(p->mem_ctx, loadparm_s3_context());
1780         if (lp_ctx == NULL) {
1781                 DEBUG(0, ("loadparm_init_s3 failed\n"));
1782                 return NT_STATUS_INTERNAL_ERROR;
1783         }
1784
1785         become_root();
1786         status = schannel_get_creds_state(p->mem_ctx, lp_ctx,
1787                                           r->in.computer_name, &creds);
1788         unbecome_root();
1789         talloc_unlink(p->mem_ctx, lp_ctx);
1790
1791         if (!NT_STATUS_IS_OK(status)) {
1792                 return status;
1793         }
1794
1795         status = _netr_LogonSamLogon_base(p, r, creds);
1796         TALLOC_FREE(creds);
1797
1798         return status;
1799 }
1800
1801 /*************************************************************************
1802  _ds_enum_dom_trusts
1803  *************************************************************************/
1804 #if 0   /* JERRY -- not correct */
1805  NTSTATUS _ds_enum_dom_trusts(struct pipes_struct *p, DS_Q_ENUM_DOM_TRUSTS *q_u,
1806                              DS_R_ENUM_DOM_TRUSTS *r_u)
1807 {
1808         NTSTATUS status = NT_STATUS_OK;
1809
1810         /* TODO: According to MSDN, the can only be executed against a
1811            DC or domain member running Windows 2000 or later.  Need
1812            to test against a standalone 2k server and see what it
1813            does.  A windows 2000 DC includes its own domain in the
1814            list.  --jerry */
1815
1816         return status;
1817 }
1818 #endif  /* JERRY */
1819
1820
1821 /****************************************************************
1822 ****************************************************************/
1823
1824 WERROR _netr_LogonUasLogon(struct pipes_struct *p,
1825                            struct netr_LogonUasLogon *r)
1826 {
1827         p->rng_fault_state = true;
1828         return WERR_NOT_SUPPORTED;
1829 }
1830
1831 /****************************************************************
1832 ****************************************************************/
1833
1834 WERROR _netr_LogonUasLogoff(struct pipes_struct *p,
1835                             struct netr_LogonUasLogoff *r)
1836 {
1837         p->rng_fault_state = true;
1838         return WERR_NOT_SUPPORTED;
1839 }
1840
1841 /****************************************************************
1842 ****************************************************************/
1843
1844 NTSTATUS _netr_DatabaseDeltas(struct pipes_struct *p,
1845                               struct netr_DatabaseDeltas *r)
1846 {
1847         p->rng_fault_state = true;
1848         return NT_STATUS_NOT_IMPLEMENTED;
1849 }
1850
1851 /****************************************************************
1852 ****************************************************************/
1853
1854 NTSTATUS _netr_DatabaseSync(struct pipes_struct *p,
1855                             struct netr_DatabaseSync *r)
1856 {
1857         p->rng_fault_state = true;
1858         return NT_STATUS_NOT_IMPLEMENTED;
1859 }
1860
1861 /****************************************************************
1862 ****************************************************************/
1863
1864 NTSTATUS _netr_AccountDeltas(struct pipes_struct *p,
1865                              struct netr_AccountDeltas *r)
1866 {
1867         p->rng_fault_state = true;
1868         return NT_STATUS_NOT_IMPLEMENTED;
1869 }
1870
1871 /****************************************************************
1872 ****************************************************************/
1873
1874 NTSTATUS _netr_AccountSync(struct pipes_struct *p,
1875                            struct netr_AccountSync *r)
1876 {
1877         p->rng_fault_state = true;
1878         return NT_STATUS_NOT_IMPLEMENTED;
1879 }
1880
1881 /****************************************************************
1882 ****************************************************************/
1883
1884 static bool wb_getdcname(TALLOC_CTX *mem_ctx,
1885                          const char *domain,
1886                          const char **dcname,
1887                          uint32_t flags,
1888                          WERROR *werr)
1889 {
1890         wbcErr result;
1891         struct wbcDomainControllerInfo *dc_info = NULL;
1892
1893         result = wbcLookupDomainController(domain,
1894                                            flags,
1895                                            &dc_info);
1896         switch (result) {
1897         case WBC_ERR_SUCCESS:
1898                 break;
1899         case WBC_ERR_WINBIND_NOT_AVAILABLE:
1900                 return false;
1901         case WBC_ERR_DOMAIN_NOT_FOUND:
1902                 *werr = WERR_NO_SUCH_DOMAIN;
1903                 return true;
1904         default:
1905                 *werr = WERR_DOMAIN_CONTROLLER_NOT_FOUND;
1906                 return true;
1907         }
1908
1909         *dcname = talloc_strdup(mem_ctx, dc_info->dc_name);
1910         wbcFreeMemory(dc_info);
1911         if (!*dcname) {
1912                 *werr = WERR_NOMEM;
1913                 return false;
1914         }
1915
1916         *werr = WERR_OK;
1917
1918         return true;
1919 }
1920
1921 /****************************************************************
1922  _netr_GetDcName
1923 ****************************************************************/
1924
1925 WERROR _netr_GetDcName(struct pipes_struct *p,
1926                        struct netr_GetDcName *r)
1927 {
1928         NTSTATUS status;
1929         WERROR werr;
1930         uint32_t flags;
1931         struct netr_DsRGetDCNameInfo *info;
1932         bool ret;
1933
1934         ret = wb_getdcname(p->mem_ctx,
1935                            r->in.domainname,
1936                            r->out.dcname,
1937                            WBC_LOOKUP_DC_IS_FLAT_NAME |
1938                            WBC_LOOKUP_DC_RETURN_FLAT_NAME |
1939                            WBC_LOOKUP_DC_PDC_REQUIRED,
1940                            &werr);
1941         if (ret == true) {
1942                 return werr;
1943         }
1944
1945         flags = DS_PDC_REQUIRED | DS_IS_FLAT_NAME | DS_RETURN_FLAT_NAME;
1946
1947         status = dsgetdcname(p->mem_ctx,
1948                              p->msg_ctx,
1949                              r->in.domainname,
1950                              NULL,
1951                              NULL,
1952                              flags,
1953                              &info);
1954         if (!NT_STATUS_IS_OK(status)) {
1955                 return ntstatus_to_werror(status);
1956         }
1957
1958         *r->out.dcname = talloc_strdup(p->mem_ctx, info->dc_unc);
1959         talloc_free(info);
1960         if (!*r->out.dcname) {
1961                 return WERR_NOMEM;
1962         }
1963
1964         return WERR_OK;
1965 }
1966
1967 /****************************************************************
1968  _netr_GetAnyDCName
1969 ****************************************************************/
1970
1971 WERROR _netr_GetAnyDCName(struct pipes_struct *p,
1972                           struct netr_GetAnyDCName *r)
1973 {
1974         NTSTATUS status;
1975         WERROR werr;
1976         uint32_t flags;
1977         struct netr_DsRGetDCNameInfo *info;
1978         bool ret;
1979
1980         ret = wb_getdcname(p->mem_ctx,
1981                            r->in.domainname,
1982                            r->out.dcname,
1983                            WBC_LOOKUP_DC_IS_FLAT_NAME |
1984                            WBC_LOOKUP_DC_RETURN_FLAT_NAME,
1985                            &werr);
1986         if (ret == true) {
1987                 return werr;
1988         }
1989
1990         flags = DS_IS_FLAT_NAME | DS_RETURN_FLAT_NAME;
1991
1992         status = dsgetdcname(p->mem_ctx,
1993                              p->msg_ctx,
1994                              r->in.domainname,
1995                              NULL,
1996                              NULL,
1997                              flags,
1998                              &info);
1999         if (!NT_STATUS_IS_OK(status)) {
2000                 return ntstatus_to_werror(status);
2001         }
2002
2003         *r->out.dcname = talloc_strdup(p->mem_ctx, info->dc_unc);
2004         talloc_free(info);
2005         if (!*r->out.dcname) {
2006                 return WERR_NOMEM;
2007         }
2008
2009         return WERR_OK;
2010 }
2011
2012 /****************************************************************
2013 ****************************************************************/
2014
2015 NTSTATUS _netr_DatabaseSync2(struct pipes_struct *p,
2016                              struct netr_DatabaseSync2 *r)
2017 {
2018         p->rng_fault_state = true;
2019         return NT_STATUS_NOT_IMPLEMENTED;
2020 }
2021
2022 /****************************************************************
2023 ****************************************************************/
2024
2025 NTSTATUS _netr_DatabaseRedo(struct pipes_struct *p,
2026                             struct netr_DatabaseRedo *r)
2027 {
2028         p->rng_fault_state = true;
2029         return NT_STATUS_NOT_IMPLEMENTED;
2030 }
2031
2032 /****************************************************************
2033 ****************************************************************/
2034
2035 WERROR _netr_DsRGetDCName(struct pipes_struct *p,
2036                           struct netr_DsRGetDCName *r)
2037 {
2038         p->rng_fault_state = true;
2039         return WERR_NOT_SUPPORTED;
2040 }
2041
2042 /****************************************************************
2043 ****************************************************************/
2044
2045 NTSTATUS _netr_LogonGetCapabilities(struct pipes_struct *p,
2046                                     struct netr_LogonGetCapabilities *r)
2047 {
2048         struct netlogon_creds_CredentialState *creds;
2049         NTSTATUS status;
2050
2051         become_root();
2052         status = netr_creds_server_step_check(p, p->mem_ctx,
2053                                               r->in.computer_name,
2054                                               r->in.credential,
2055                                               r->out.return_authenticator,
2056                                               &creds);
2057         unbecome_root();
2058         if (!NT_STATUS_IS_OK(status)) {
2059                 return status;
2060         }
2061
2062         if (r->in.query_level != 1) {
2063                 return NT_STATUS_NOT_SUPPORTED;
2064         }
2065
2066         r->out.capabilities->server_capabilities = creds->negotiate_flags;
2067
2068         return NT_STATUS_OK;
2069 }
2070
2071 /****************************************************************
2072 ****************************************************************/
2073
2074 WERROR _netr_NETRLOGONSETSERVICEBITS(struct pipes_struct *p,
2075                                      struct netr_NETRLOGONSETSERVICEBITS *r)
2076 {
2077         p->rng_fault_state = true;
2078         return WERR_NOT_SUPPORTED;
2079 }
2080
2081 /****************************************************************
2082 ****************************************************************/
2083
2084 WERROR _netr_LogonGetTrustRid(struct pipes_struct *p,
2085                               struct netr_LogonGetTrustRid *r)
2086 {
2087         p->rng_fault_state = true;
2088         return WERR_NOT_SUPPORTED;
2089 }
2090
2091 /****************************************************************
2092 ****************************************************************/
2093
2094 WERROR _netr_NETRLOGONCOMPUTESERVERDIGEST(struct pipes_struct *p,
2095                                           struct netr_NETRLOGONCOMPUTESERVERDIGEST *r)
2096 {
2097         p->rng_fault_state = true;
2098         return WERR_NOT_SUPPORTED;
2099 }
2100
2101 /****************************************************************
2102 ****************************************************************/
2103
2104 WERROR _netr_NETRLOGONCOMPUTECLIENTDIGEST(struct pipes_struct *p,
2105                                           struct netr_NETRLOGONCOMPUTECLIENTDIGEST *r)
2106 {
2107         p->rng_fault_state = true;
2108         return WERR_NOT_SUPPORTED;
2109 }
2110
2111 /****************************************************************
2112 ****************************************************************/
2113
2114 WERROR _netr_DsRGetDCNameEx(struct pipes_struct *p,
2115                             struct netr_DsRGetDCNameEx *r)
2116 {
2117         p->rng_fault_state = true;
2118         return WERR_NOT_SUPPORTED;
2119 }
2120
2121 /****************************************************************
2122 ****************************************************************/
2123
2124 WERROR _netr_DsRGetSiteName(struct pipes_struct *p,
2125                             struct netr_DsRGetSiteName *r)
2126 {
2127         p->rng_fault_state = true;
2128         return WERR_NOT_SUPPORTED;
2129 }
2130
2131 /****************************************************************
2132 ****************************************************************/
2133
2134 NTSTATUS _netr_LogonGetDomainInfo(struct pipes_struct *p,
2135                                   struct netr_LogonGetDomainInfo *r)
2136 {
2137         p->rng_fault_state = true;
2138         return NT_STATUS_NOT_IMPLEMENTED;
2139 }
2140
2141 /****************************************************************
2142 ****************************************************************/
2143
2144 WERROR _netr_ServerPasswordGet(struct pipes_struct *p,
2145                                struct netr_ServerPasswordGet *r)
2146 {
2147         p->rng_fault_state = true;
2148         return WERR_NOT_SUPPORTED;
2149 }
2150
2151 /****************************************************************
2152 ****************************************************************/
2153
2154 WERROR _netr_NETRLOGONSENDTOSAM(struct pipes_struct *p,
2155                                 struct netr_NETRLOGONSENDTOSAM *r)
2156 {
2157         p->rng_fault_state = true;
2158         return WERR_NOT_SUPPORTED;
2159 }
2160
2161 /****************************************************************
2162 ****************************************************************/
2163
2164 WERROR _netr_DsRAddressToSitenamesW(struct pipes_struct *p,
2165                                     struct netr_DsRAddressToSitenamesW *r)
2166 {
2167         p->rng_fault_state = true;
2168         return WERR_NOT_SUPPORTED;
2169 }
2170
2171 /****************************************************************
2172 ****************************************************************/
2173
2174 WERROR _netr_DsRGetDCNameEx2(struct pipes_struct *p,
2175                              struct netr_DsRGetDCNameEx2 *r)
2176 {
2177         p->rng_fault_state = true;
2178         return WERR_NOT_SUPPORTED;
2179 }
2180
2181 /****************************************************************
2182 ****************************************************************/
2183
2184 WERROR _netr_NETRLOGONGETTIMESERVICEPARENTDOMAIN(struct pipes_struct *p,
2185                                                  struct netr_NETRLOGONGETTIMESERVICEPARENTDOMAIN *r)
2186 {
2187         p->rng_fault_state = true;
2188         return WERR_NOT_SUPPORTED;
2189 }
2190
2191 /****************************************************************
2192 ****************************************************************/
2193
2194 WERROR _netr_NetrEnumerateTrustedDomainsEx(struct pipes_struct *p,
2195                                            struct netr_NetrEnumerateTrustedDomainsEx *r)
2196 {
2197         p->rng_fault_state = true;
2198         return WERR_NOT_SUPPORTED;
2199 }
2200
2201 /****************************************************************
2202 ****************************************************************/
2203
2204 WERROR _netr_DsRAddressToSitenamesExW(struct pipes_struct *p,
2205                                       struct netr_DsRAddressToSitenamesExW *r)
2206 {
2207         p->rng_fault_state = true;
2208         return WERR_NOT_SUPPORTED;
2209 }
2210
2211 /****************************************************************
2212 ****************************************************************/
2213
2214 WERROR _netr_DsrGetDcSiteCoverageW(struct pipes_struct *p,
2215                                    struct netr_DsrGetDcSiteCoverageW *r)
2216 {
2217         p->rng_fault_state = true;
2218         return WERR_NOT_SUPPORTED;
2219 }
2220
2221 /****************************************************************
2222 ****************************************************************/
2223
2224 WERROR _netr_DsrEnumerateDomainTrusts(struct pipes_struct *p,
2225                                       struct netr_DsrEnumerateDomainTrusts *r)
2226 {
2227         p->rng_fault_state = true;
2228         return WERR_NOT_SUPPORTED;
2229 }
2230
2231 /****************************************************************
2232 ****************************************************************/
2233
2234 WERROR _netr_DsrDeregisterDNSHostRecords(struct pipes_struct *p,
2235                                          struct netr_DsrDeregisterDNSHostRecords *r)
2236 {
2237         p->rng_fault_state = true;
2238         return WERR_NOT_SUPPORTED;
2239 }
2240
2241 /****************************************************************
2242 ****************************************************************/
2243
2244 NTSTATUS _netr_ServerTrustPasswordsGet(struct pipes_struct *p,
2245                                        struct netr_ServerTrustPasswordsGet *r)
2246 {
2247         p->rng_fault_state = true;
2248         return NT_STATUS_NOT_IMPLEMENTED;
2249 }
2250
2251 /****************************************************************
2252 ****************************************************************/
2253
2254 WERROR _netr_DsRGetForestTrustInformation(struct pipes_struct *p,
2255                                           struct netr_DsRGetForestTrustInformation *r)
2256 {
2257         p->rng_fault_state = true;
2258         return WERR_NOT_SUPPORTED;
2259 }
2260
2261 /****************************************************************
2262 ****************************************************************/
2263
2264 static NTSTATUS fill_forest_trust_array(TALLOC_CTX *mem_ctx,
2265                                         struct lsa_ForestTrustInformation *info)
2266 {
2267         struct lsa_ForestTrustRecord *e;
2268         struct pdb_domain_info *dom_info;
2269         struct lsa_ForestTrustDomainInfo *domain_info;
2270
2271         dom_info = pdb_get_domain_info(mem_ctx);
2272         if (dom_info == NULL) {
2273                 return NT_STATUS_NO_MEMORY;
2274         }
2275
2276         info->count = 2;
2277         info->entries = talloc_array(info, struct lsa_ForestTrustRecord *, 2);
2278         if (info->entries == NULL) {
2279                 return NT_STATUS_NO_MEMORY;
2280         }
2281
2282         e = talloc(info, struct lsa_ForestTrustRecord);
2283         if (e == NULL) {
2284                 return NT_STATUS_NO_MEMORY;
2285         }
2286
2287         e->flags = 0;
2288         e->type = LSA_FOREST_TRUST_TOP_LEVEL_NAME;
2289         e->time = 0; /* so far always 0 in trces. */
2290         e->forest_trust_data.top_level_name.string = talloc_steal(info,
2291                                                                   dom_info->dns_forest);
2292
2293         info->entries[0] = e;
2294
2295         e = talloc(info, struct lsa_ForestTrustRecord);
2296         if (e == NULL) {
2297                 return NT_STATUS_NO_MEMORY;
2298         }
2299
2300         /* TODO: check if disabled and set flags accordingly */
2301         e->flags = 0;
2302         e->type = LSA_FOREST_TRUST_DOMAIN_INFO;
2303         e->time = 0; /* so far always 0 in traces. */
2304
2305         domain_info = &e->forest_trust_data.domain_info;
2306         domain_info->domain_sid = dom_sid_dup(info, &dom_info->sid);
2307
2308         domain_info->dns_domain_name.string = talloc_steal(info,
2309                                                            dom_info->dns_domain);
2310         domain_info->netbios_domain_name.string = talloc_steal(info,
2311                                                                dom_info->name);
2312
2313         info->entries[1] = e;
2314
2315         return NT_STATUS_OK;
2316 }
2317
2318 /****************************************************************
2319  _netr_GetForestTrustInformation
2320 ****************************************************************/
2321
2322 NTSTATUS _netr_GetForestTrustInformation(struct pipes_struct *p,
2323                                          struct netr_GetForestTrustInformation *r)
2324 {
2325         NTSTATUS status;
2326         struct netlogon_creds_CredentialState *creds;
2327         struct lsa_ForestTrustInformation *info, **info_ptr;
2328         struct loadparm_context *lp_ctx;
2329
2330         /* TODO: check server name */
2331
2332         lp_ctx = loadparm_init_s3(p->mem_ctx, loadparm_s3_context());
2333         if (lp_ctx == NULL) {
2334                 DEBUG(0, ("loadparm_init_s3 failed\n"));
2335                 return NT_STATUS_INTERNAL_ERROR;
2336         }
2337
2338         status = schannel_check_creds_state(p->mem_ctx, lp_ctx,
2339                                             r->in.computer_name,
2340                                             r->in.credential,
2341                                             r->out.return_authenticator,
2342                                             &creds);
2343         talloc_unlink(p->mem_ctx, lp_ctx);
2344         if (!NT_STATUS_IS_OK(status)) {
2345                 return status;
2346         }
2347
2348         if ((creds->secure_channel_type != SEC_CHAN_DNS_DOMAIN) &&
2349             (creds->secure_channel_type != SEC_CHAN_DOMAIN)) {
2350                 return NT_STATUS_NOT_IMPLEMENTED;
2351         }
2352
2353         info_ptr = talloc(p->mem_ctx, struct lsa_ForestTrustInformation *);
2354         if (!info_ptr) {
2355                 return NT_STATUS_NO_MEMORY;
2356         }
2357         info = talloc_zero(info_ptr, struct lsa_ForestTrustInformation);
2358         if (!info) {
2359                 return NT_STATUS_NO_MEMORY;
2360         }
2361
2362         status = fill_forest_trust_array(p->mem_ctx, info);
2363         if (!NT_STATUS_IS_OK(status)) {
2364                 return status;
2365         }
2366
2367         *info_ptr = info;
2368         r->out.forest_trust_info = info_ptr;
2369
2370         return NT_STATUS_OK;
2371 }
2372
2373 /****************************************************************
2374 ****************************************************************/
2375
2376 static NTSTATUS get_password_from_trustAuth(TALLOC_CTX *mem_ctx,
2377                                             const DATA_BLOB *trustAuth_blob,
2378                                             const DATA_BLOB *session_key,
2379                                             struct samr_Password *current_pw_enc,
2380                                             struct samr_Password *previous_pw_enc)
2381 {
2382         enum ndr_err_code ndr_err;
2383         struct trustAuthInOutBlob trustAuth;
2384
2385         ndr_err = ndr_pull_struct_blob_all(trustAuth_blob, mem_ctx, &trustAuth,
2386                                            (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
2387         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2388                 return NT_STATUS_UNSUCCESSFUL;
2389         }
2390
2391
2392         if (trustAuth.count != 0 && trustAuth.current.count != 0 &&
2393             trustAuth.current.array[0].AuthType == TRUST_AUTH_TYPE_CLEAR) {
2394                 mdfour(previous_pw_enc->hash,
2395                        trustAuth.current.array[0].AuthInfo.clear.password,
2396                        trustAuth.current.array[0].AuthInfo.clear.size);
2397         } else {
2398                 return NT_STATUS_UNSUCCESSFUL;
2399         }
2400
2401         arcfour_crypt_blob(current_pw_enc->hash, sizeof(current_pw_enc->hash),
2402                            session_key);
2403
2404         if (trustAuth.previous.count != 0 &&
2405             trustAuth.previous.array[0].AuthType == TRUST_AUTH_TYPE_CLEAR) {
2406                 mdfour(previous_pw_enc->hash,
2407                        trustAuth.previous.array[0].AuthInfo.clear.password,
2408                        trustAuth.previous.array[0].AuthInfo.clear.size);
2409         } else {
2410                 mdfour(previous_pw_enc->hash, NULL, 0);
2411         }
2412         arcfour_crypt_blob(previous_pw_enc->hash, sizeof(previous_pw_enc->hash),
2413                            session_key);
2414
2415         return NT_STATUS_OK;
2416 }
2417
2418 /****************************************************************
2419  _netr_ServerGetTrustInfo
2420 ****************************************************************/
2421
2422 NTSTATUS _netr_ServerGetTrustInfo(struct pipes_struct *p,
2423                                   struct netr_ServerGetTrustInfo *r)
2424 {
2425         NTSTATUS status;
2426         struct netlogon_creds_CredentialState *creds;
2427         char *account_name;
2428         size_t account_name_last;
2429         bool trusted;
2430         struct netr_TrustInfo *trust_info;
2431         struct pdb_trusted_domain *td;
2432         DATA_BLOB trustAuth_blob;
2433         struct samr_Password *new_owf_enc;
2434         struct samr_Password *old_owf_enc;
2435         DATA_BLOB session_key;
2436         struct loadparm_context *lp_ctx;
2437
2438         lp_ctx = loadparm_init_s3(p->mem_ctx, loadparm_s3_context());
2439         if (lp_ctx == NULL) {
2440                 DEBUG(0, ("loadparm_init_s3 failed\n"));
2441                 return NT_STATUS_INTERNAL_ERROR;
2442         }
2443
2444         /* TODO: check server name */
2445
2446         status = schannel_check_creds_state(p->mem_ctx, lp_ctx,
2447                                             r->in.computer_name,
2448                                             r->in.credential,
2449                                             r->out.return_authenticator,
2450                                             &creds);
2451         talloc_unlink(p->mem_ctx, lp_ctx);
2452         if (!NT_STATUS_IS_OK(status)) {
2453                 return status;
2454         }
2455
2456         account_name = talloc_strdup(p->mem_ctx, r->in.account_name);
2457         if (account_name == NULL) {
2458                 return NT_STATUS_NO_MEMORY;
2459         }
2460
2461         account_name_last = strlen(account_name);
2462         if (account_name_last == 0) {
2463                 return NT_STATUS_INVALID_PARAMETER;
2464         }
2465         account_name_last--;
2466         if (account_name[account_name_last] == '.') {
2467                 account_name[account_name_last] = '\0';
2468         }
2469
2470         if ((creds->secure_channel_type != SEC_CHAN_DNS_DOMAIN) &&
2471             (creds->secure_channel_type != SEC_CHAN_DOMAIN)) {
2472                 trusted = false;
2473         } else {
2474                 trusted = true;
2475         }
2476
2477
2478         if (trusted) {
2479                 account_name_last = strlen(account_name);
2480                 if (account_name_last == 0) {
2481                         return NT_STATUS_INVALID_PARAMETER;
2482                 }
2483                 account_name_last--;
2484                 if (account_name[account_name_last] == '$') {
2485                         account_name[account_name_last] = '\0';
2486                 }
2487
2488                 status = pdb_get_trusted_domain(p->mem_ctx, account_name, &td);
2489                 if (!NT_STATUS_IS_OK(status)) {
2490                         return status;
2491                 }
2492
2493                 if (r->out.trust_info != NULL) {
2494                         trust_info = talloc_zero(p->mem_ctx, struct netr_TrustInfo);
2495                         if (trust_info == NULL) {
2496                                 return NT_STATUS_NO_MEMORY;
2497                         }
2498                         trust_info->count = 1;
2499
2500                         trust_info->data = talloc_array(trust_info, uint32_t, 1);
2501                         if (trust_info->data == NULL) {
2502                                 return NT_STATUS_NO_MEMORY;
2503                         }
2504                         trust_info->data[0] = td->trust_attributes;
2505
2506                         *r->out.trust_info = trust_info;
2507                 }
2508
2509                 new_owf_enc = talloc_zero(p->mem_ctx, struct samr_Password);
2510                 old_owf_enc = talloc_zero(p->mem_ctx, struct samr_Password);
2511                 if (new_owf_enc == NULL || old_owf_enc == NULL) {
2512                         return NT_STATUS_NO_MEMORY;
2513                 }
2514
2515 /* TODO: which trustAuth shall we use if we have in/out trust or do they have to
2516  * be equal ? */
2517                 if (td->trust_direction & NETR_TRUST_FLAG_INBOUND) {
2518                         trustAuth_blob = td->trust_auth_incoming;
2519                 } else if (td->trust_direction & NETR_TRUST_FLAG_OUTBOUND) {
2520                         trustAuth_blob = td->trust_auth_outgoing;
2521                 }
2522
2523                 session_key.data = creds->session_key;
2524                 session_key.length = sizeof(creds->session_key);
2525                 status = get_password_from_trustAuth(p->mem_ctx, &trustAuth_blob,
2526                                                      &session_key,
2527                                                      new_owf_enc, old_owf_enc);
2528
2529                 if (!NT_STATUS_IS_OK(status)) {
2530                         return status;
2531                 }
2532
2533                 r->out.new_owf_password = new_owf_enc;
2534                 r->out.old_owf_password = old_owf_enc;
2535         } else {
2536 /* TODO: look for machine password */
2537                 r->out.new_owf_password = NULL;
2538                 r->out.old_owf_password = NULL;
2539
2540                 return NT_STATUS_NOT_IMPLEMENTED;
2541         }
2542
2543         return NT_STATUS_OK;
2544 }
2545
2546 /****************************************************************
2547 ****************************************************************/
2548
2549 NTSTATUS _netr_Unused47(struct pipes_struct *p,
2550                         struct netr_Unused47 *r)
2551 {
2552         p->rng_fault_state = true;
2553         return NT_STATUS_NOT_IMPLEMENTED;
2554 }
2555
2556 /****************************************************************
2557 ****************************************************************/
2558
2559 NTSTATUS _netr_DsrUpdateReadOnlyServerDnsRecords(struct pipes_struct *p,
2560                                                  struct netr_DsrUpdateReadOnlyServerDnsRecords *r)
2561 {
2562         p->rng_fault_state = true;
2563         return NT_STATUS_NOT_IMPLEMENTED;
2564 }