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