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