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