Fix bug #8562 - talloc: double free error.
[samba.git] / source3 / rpc_server / netlogon / srv_netlog_nt.c
1 /*
2  *  Unix SMB/CIFS implementation.
3  *  RPC Pipe client / server routines
4  *  Copyright (C) Andrew Tridgell              1992-1997,
5  *  Copyright (C) Luke Kenneth Casson Leighton 1996-1997,
6  *  Copyright (C) Paul Ashton                       1997.
7  *  Copyright (C) Jeremy Allison               1998-2001.
8  *  Copyright (C) Andrew Bartlett                   2001.
9  *  Copyright (C) Guenther Deschner                 2008-2009.
10  *
11  *  This program is free software; you can redistribute it and/or modify
12  *  it under the terms of the GNU General Public License as published by
13  *  the Free Software Foundation; either version 3 of the License, or
14  *  (at your option) any later version.
15  *
16  *  This program is distributed in the hope that it will be useful,
17  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
18  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  *  GNU General Public License for more details.
20  *
21  *  You should have received a copy of the GNU General Public License
22  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
23  */
24
25 /* This is the implementation of the netlogon pipe. */
26
27 #include "includes.h"
28 #include "system/passwd.h" /* uid_wrapper */
29 #include "ntdomain.h"
30 #include "../libcli/auth/schannel.h"
31 #include "../librpc/gen_ndr/srv_netlogon.h"
32 #include "../librpc/gen_ndr/ndr_samr_c.h"
33 #include "../librpc/gen_ndr/ndr_lsa_c.h"
34 #include "rpc_client/cli_lsarpc.h"
35 #include "rpc_client/init_lsa.h"
36 #include "rpc_server/rpc_ncacn_np.h"
37 #include "../libcli/security/security.h"
38 #include "../libcli/security/dom_sid.h"
39 #include "librpc/gen_ndr/ndr_drsblobs.h"
40 #include "lib/crypto/arcfour.h"
41 #include "lib/crypto/md4.h"
42 #include "nsswitch/libwbclient/wbclient.h"
43 #include "../libcli/registry/util_reg.h"
44 #include "passdb.h"
45 #include "auth.h"
46 #include "messages.h"
47 #include "../lib/tsocket/tsocket.h"
48 #include "lib/param/param.h"
49
50 extern userdom_struct current_user_info;
51
52 #undef DBGC_CLASS
53 #define DBGC_CLASS DBGC_RPC_SRV
54
55 struct netlogon_server_pipe_state {
56         struct netr_Credential client_challenge;
57         struct netr_Credential server_challenge;
58 };
59
60 /*************************************************************************
61  _netr_LogonControl
62  *************************************************************************/
63
64 WERROR _netr_LogonControl(struct pipes_struct *p,
65                           struct netr_LogonControl *r)
66 {
67         struct netr_LogonControl2Ex l;
68
69         switch (r->in.level) {
70         case 1:
71                 break;
72         case 2:
73                 return WERR_NOT_SUPPORTED;
74         default:
75                 return WERR_UNKNOWN_LEVEL;
76         }
77
78         l.in.logon_server       = r->in.logon_server;
79         l.in.function_code      = r->in.function_code;
80         l.in.level              = r->in.level;
81         l.in.data               = NULL;
82         l.out.query             = r->out.query;
83
84         return _netr_LogonControl2Ex(p, &l);
85 }
86
87 /****************************************************************************
88 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->info->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->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->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->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->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->remote_address,
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                                       lp_netbios_name(),
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         struct tsocket_address *local;
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_session_info *session_info;
655         int rc;
656
657 #if 0
658
659     /*
660      * Currently this code is redundent as we already have a filter
661      * by hostname list. What this code really needs to do is to
662      * get a hosts allowed/hosts denied list from the SAM database
663      * on a per user basis, and make the access decision there.
664      * I will leave this code here for now as a reminder to implement
665      * this at a later date. JRA.
666      */
667
668         if (!allow_access(lp_domain_hostsdeny(), lp_domain_hostsallow(),
669                           p->client_id.name,
670                           p->client_id.addr)) {
671                 DEBUG(0,("get_md4pw: Workstation %s denied access to domain\n", mach_acct));
672                 return False;
673         }
674 #endif /* 0 */
675
676         mem_ctx = talloc_stackframe();
677         if (mem_ctx == NULL) {
678                 status = NT_STATUS_NO_MEMORY;
679                 goto out;
680         }
681
682         status = make_session_info_system(mem_ctx, &session_info);
683         if (!NT_STATUS_IS_OK(status)) {
684                 goto out;
685         }
686
687         ZERO_STRUCT(user_handle);
688
689         rc = tsocket_address_inet_from_strings(mem_ctx,
690                                                "ip",
691                                                "127.0.0.1",
692                                                0,
693                                                &local);
694         if (rc < 0) {
695                 status = NT_STATUS_NO_MEMORY;
696                 goto out;
697         }
698
699         status = rpcint_binding_handle(mem_ctx,
700                                        &ndr_table_samr,
701                                        local,
702                                        session_info,
703                                        msg_ctx,
704                                        &h);
705         if (!NT_STATUS_IS_OK(status)) {
706                 goto out;
707         }
708
709         become_root();
710         status = samr_find_machine_account(mem_ctx, h, mach_acct,
711                                            SEC_FLAG_MAXIMUM_ALLOWED,
712                                            &domain_sid, &user_rid,
713                                            &user_handle);
714         unbecome_root();
715         if (!NT_STATUS_IS_OK(status)) {
716                 goto out;
717         }
718
719         status = dcerpc_samr_QueryUserInfo2(h,
720                                             mem_ctx,
721                                             &user_handle,
722                                             UserControlInformation,
723                                             &info,
724                                             &result);
725         if (!NT_STATUS_IS_OK(status)) {
726                 goto out;
727         }
728         if (!NT_STATUS_IS_OK(result)) {
729                 status = result;
730                 goto out;
731         }
732
733         acct_ctrl = info->info16.acct_flags;
734
735         if (acct_ctrl & ACB_DISABLED) {
736                 DEBUG(0,("get_md4pw: Workstation %s: account is disabled\n", mach_acct));
737                 status = NT_STATUS_ACCOUNT_DISABLED;
738                 goto out;
739         }
740
741         if (!(acct_ctrl & ACB_SVRTRUST) &&
742             !(acct_ctrl & ACB_WSTRUST) &&
743             !(acct_ctrl & ACB_DOMTRUST))
744         {
745                 DEBUG(0,("get_md4pw: Workstation %s: account is not a trust account\n", mach_acct));
746                 status = NT_STATUS_NO_TRUST_SAM_ACCOUNT;
747                 goto out;
748         }
749
750         switch (sec_chan_type) {
751                 case SEC_CHAN_BDC:
752                         if (!(acct_ctrl & ACB_SVRTRUST)) {
753                                 DEBUG(0,("get_md4pw: Workstation %s: BDC secure channel requested "
754                                          "but not a server trust account\n", mach_acct));
755                                 status = NT_STATUS_NO_TRUST_SAM_ACCOUNT;
756                                 goto out;
757                         }
758                         break;
759                 case SEC_CHAN_WKSTA:
760                         if (!(acct_ctrl & ACB_WSTRUST)) {
761                                 DEBUG(0,("get_md4pw: Workstation %s: WORKSTATION secure channel requested "
762                                          "but not a workstation trust account\n", mach_acct));
763                                 status = NT_STATUS_NO_TRUST_SAM_ACCOUNT;
764                                 goto out;
765                         }
766                         break;
767                 case SEC_CHAN_DOMAIN:
768                         if (!(acct_ctrl & ACB_DOMTRUST)) {
769                                 DEBUG(0,("get_md4pw: Workstation %s: DOMAIN secure channel requested "
770                                          "but not a interdomain trust account\n", mach_acct));
771                                 status = NT_STATUS_NO_TRUST_SAM_ACCOUNT;
772                                 goto out;
773                         }
774                         break;
775                 default:
776                         break;
777         }
778
779         become_root();
780         status = dcerpc_samr_QueryUserInfo2(h,
781                                             mem_ctx,
782                                             &user_handle,
783                                             UserInternal1Information,
784                                             &info,
785                                             &result);
786         unbecome_root();
787         if (!NT_STATUS_IS_OK(status)) {
788                 goto out;
789         }
790         if (!NT_STATUS_IS_OK(result)) {
791                 status = result;
792                 goto out;
793         }
794
795         if (info->info18.nt_pwd_active == 0) {
796                 DEBUG(0,("get_md4pw: Workstation %s: account does not have a password\n", mach_acct));
797                 status = NT_STATUS_LOGON_FAILURE;
798                 goto out;
799         }
800
801         /* samr gives out nthash unencrypted (!) */
802         memcpy(md4pw->hash, info->info18.nt_pwd.hash, 16);
803
804         sid_compose(sid, domain_sid, user_rid);
805
806  out:
807         if (h && is_valid_policy_hnd(&user_handle)) {
808                 dcerpc_samr_Close(h, mem_ctx, &user_handle, &result);
809         }
810
811         talloc_free(mem_ctx);
812
813         return status;
814 }
815
816 /*************************************************************************
817  _netr_ServerReqChallenge
818  *************************************************************************/
819
820 NTSTATUS _netr_ServerReqChallenge(struct pipes_struct *p,
821                                   struct netr_ServerReqChallenge *r)
822 {
823         struct netlogon_server_pipe_state *pipe_state =
824                 talloc_get_type(p->private_data, struct netlogon_server_pipe_state);
825
826         if (pipe_state) {
827                 DEBUG(10,("_netr_ServerReqChallenge: new challenge requested. Clearing old state.\n"));
828                 talloc_free(pipe_state);
829                 p->private_data = NULL;
830         }
831
832         pipe_state = talloc(p, struct netlogon_server_pipe_state);
833         NT_STATUS_HAVE_NO_MEMORY(pipe_state);
834
835         pipe_state->client_challenge = *r->in.credentials;
836
837         generate_random_buffer(pipe_state->server_challenge.data,
838                                sizeof(pipe_state->server_challenge.data));
839
840         *r->out.return_credentials = pipe_state->server_challenge;
841
842         p->private_data = pipe_state;
843
844         return NT_STATUS_OK;
845 }
846
847 /*************************************************************************
848  _netr_ServerAuthenticate
849  Create the initial credentials.
850  *************************************************************************/
851
852 NTSTATUS _netr_ServerAuthenticate(struct pipes_struct *p,
853                                   struct netr_ServerAuthenticate *r)
854 {
855         struct netr_ServerAuthenticate3 a;
856         uint32_t negotiate_flags = 0;
857         uint32_t rid;
858
859         a.in.server_name                = r->in.server_name;
860         a.in.account_name               = r->in.account_name;
861         a.in.secure_channel_type        = r->in.secure_channel_type;
862         a.in.computer_name              = r->in.computer_name;
863         a.in.credentials                = r->in.credentials;
864         a.in.negotiate_flags            = &negotiate_flags;
865
866         a.out.return_credentials        = r->out.return_credentials;
867         a.out.rid                       = &rid;
868         a.out.negotiate_flags           = &negotiate_flags;
869
870         return _netr_ServerAuthenticate3(p, &a);
871
872 }
873
874 /*************************************************************************
875  _netr_ServerAuthenticate3
876  *************************************************************************/
877
878 NTSTATUS _netr_ServerAuthenticate3(struct pipes_struct *p,
879                                    struct netr_ServerAuthenticate3 *r)
880 {
881         NTSTATUS status;
882         uint32_t srv_flgs;
883         /* r->in.negotiate_flags is an aliased pointer to r->out.negotiate_flags,
884          * so use a copy to avoid destroying the client values. */
885         uint32_t in_neg_flags = *r->in.negotiate_flags;
886         const char *fn;
887         struct loadparm_context *lp_ctx;
888         struct dom_sid sid;
889         struct samr_Password mach_pwd;
890         struct netlogon_creds_CredentialState *creds;
891         struct netlogon_server_pipe_state *pipe_state =
892                 talloc_get_type(p->private_data, struct netlogon_server_pipe_state);
893
894         /* According to Microsoft (see bugid #6099)
895          * Windows 7 looks at the negotiate_flags
896          * returned in this structure *even if the
897          * call fails with access denied* ! So in order
898          * to allow Win7 to connect to a Samba NT style
899          * PDC we set the flags before we know if it's
900          * an error or not.
901          */
902
903         /* 0x000001ff */
904         srv_flgs = NETLOGON_NEG_ACCOUNT_LOCKOUT |
905                    NETLOGON_NEG_PERSISTENT_SAMREPL |
906                    NETLOGON_NEG_ARCFOUR |
907                    NETLOGON_NEG_PROMOTION_COUNT |
908                    NETLOGON_NEG_CHANGELOG_BDC |
909                    NETLOGON_NEG_FULL_SYNC_REPL |
910                    NETLOGON_NEG_MULTIPLE_SIDS |
911                    NETLOGON_NEG_REDO |
912                    NETLOGON_NEG_PASSWORD_CHANGE_REFUSAL |
913                    NETLOGON_NEG_PASSWORD_SET2;
914
915         /* Ensure we support strong (128-bit) keys. */
916         if (in_neg_flags & NETLOGON_NEG_STRONG_KEYS) {
917                 srv_flgs |= NETLOGON_NEG_STRONG_KEYS;
918         }
919
920         if (lp_server_schannel() != false) {
921                 srv_flgs |= NETLOGON_NEG_SCHANNEL;
922         }
923
924         switch (p->opnum) {
925                 case NDR_NETR_SERVERAUTHENTICATE:
926                         fn = "_netr_ServerAuthenticate";
927                         break;
928                 case NDR_NETR_SERVERAUTHENTICATE2:
929                         fn = "_netr_ServerAuthenticate2";
930                         break;
931                 case NDR_NETR_SERVERAUTHENTICATE3:
932                         fn = "_netr_ServerAuthenticate3";
933                         break;
934                 default:
935                         return NT_STATUS_INTERNAL_ERROR;
936         }
937
938         /* We use this as the key to store the creds: */
939         /* r->in.computer_name */
940
941         if (!pipe_state) {
942                 DEBUG(0,("%s: no challenge sent to client %s\n", fn,
943                         r->in.computer_name));
944                 status = NT_STATUS_ACCESS_DENIED;
945                 goto out;
946         }
947
948         if ( (lp_server_schannel() == true) &&
949              ((in_neg_flags & NETLOGON_NEG_SCHANNEL) == 0) ) {
950
951                 /* schannel must be used, but client did not offer it. */
952                 DEBUG(0,("%s: schannel required but client failed "
953                         "to offer it. Client was %s\n",
954                         fn, r->in.account_name));
955                 status = NT_STATUS_ACCESS_DENIED;
956                 goto out;
957         }
958
959         status = get_md4pw(&mach_pwd,
960                            r->in.account_name,
961                            r->in.secure_channel_type,
962                            &sid, p->msg_ctx);
963         if (!NT_STATUS_IS_OK(status)) {
964                 DEBUG(0,("%s: failed to get machine password for "
965                         "account %s: %s\n",
966                         fn, r->in.account_name, nt_errstr(status) ));
967                 /* always return NT_STATUS_ACCESS_DENIED */
968                 status = NT_STATUS_ACCESS_DENIED;
969                 goto out;
970         }
971
972         /* From the client / server challenges and md4 password, generate sess key */
973         /* Check client credentials are valid. */
974         creds = netlogon_creds_server_init(p->mem_ctx,
975                                            r->in.account_name,
976                                            r->in.computer_name,
977                                            r->in.secure_channel_type,
978                                            &pipe_state->client_challenge,
979                                            &pipe_state->server_challenge,
980                                            &mach_pwd,
981                                            r->in.credentials,
982                                            r->out.return_credentials,
983                                            *r->in.negotiate_flags);
984         if (!creds) {
985                 DEBUG(0,("%s: netlogon_creds_server_check failed. Rejecting auth "
986                         "request from client %s machine account %s\n",
987                         fn, r->in.computer_name,
988                         r->in.account_name));
989                 status = NT_STATUS_ACCESS_DENIED;
990                 goto out;
991         }
992
993         creds->sid = dom_sid_dup(creds, &sid);
994         if (!creds->sid) {
995                 status = NT_STATUS_NO_MEMORY;
996                 goto out;
997         }
998
999         lp_ctx = loadparm_init_s3(p->mem_ctx, loadparm_s3_context());
1000         if (lp_ctx == NULL) {
1001                 DEBUG(10, ("loadparm_init_s3 failed\n"));
1002                 status = NT_STATUS_INTERNAL_ERROR;
1003                 goto out;
1004         }
1005
1006         /* Store off the state so we can continue after client disconnect. */
1007         become_root();
1008         status = schannel_save_creds_state(p->mem_ctx, lp_ctx, creds);
1009         unbecome_root();
1010
1011         talloc_unlink(p->mem_ctx, lp_ctx);
1012
1013         if (!NT_STATUS_IS_OK(status)) {
1014                 goto out;
1015         }
1016
1017         sid_peek_rid(&sid, r->out.rid);
1018
1019         status = NT_STATUS_OK;
1020
1021   out:
1022
1023         *r->out.negotiate_flags = srv_flgs;
1024         return status;
1025 }
1026
1027 /*************************************************************************
1028  _netr_ServerAuthenticate2
1029  *************************************************************************/
1030
1031 NTSTATUS _netr_ServerAuthenticate2(struct pipes_struct *p,
1032                                    struct netr_ServerAuthenticate2 *r)
1033 {
1034         struct netr_ServerAuthenticate3 a;
1035         uint32_t rid;
1036
1037         a.in.server_name                = r->in.server_name;
1038         a.in.account_name               = r->in.account_name;
1039         a.in.secure_channel_type        = r->in.secure_channel_type;
1040         a.in.computer_name              = r->in.computer_name;
1041         a.in.credentials                = r->in.credentials;
1042         a.in.negotiate_flags            = r->in.negotiate_flags;
1043
1044         a.out.return_credentials        = r->out.return_credentials;
1045         a.out.rid                       = &rid;
1046         a.out.negotiate_flags           = r->out.negotiate_flags;
1047
1048         return _netr_ServerAuthenticate3(p, &a);
1049 }
1050
1051 /*************************************************************************
1052  * If schannel is required for this call test that it actually is available.
1053  *************************************************************************/
1054 static NTSTATUS schannel_check_required(struct pipe_auth_data *auth_info,
1055                                         const char *computer_name,
1056                                         bool integrity, bool privacy)
1057 {
1058         if (auth_info && auth_info->auth_type == DCERPC_AUTH_TYPE_SCHANNEL) {
1059                 if (!privacy && !integrity) {
1060                         return NT_STATUS_OK;
1061                 }
1062
1063                 if ((!privacy && integrity) &&
1064                     auth_info->auth_level == DCERPC_AUTH_LEVEL_INTEGRITY) {
1065                         return NT_STATUS_OK;
1066                 }
1067
1068                 if ((privacy || integrity) &&
1069                     auth_info->auth_level == DCERPC_AUTH_LEVEL_PRIVACY) {
1070                         return NT_STATUS_OK;
1071                 }
1072         }
1073
1074         /* test didn't pass */
1075         DEBUG(0, ("schannel_check_required: [%s] is not using schannel\n",
1076                   computer_name));
1077
1078         return NT_STATUS_ACCESS_DENIED;
1079 }
1080
1081 /*************************************************************************
1082  *************************************************************************/
1083
1084 static NTSTATUS netr_creds_server_step_check(struct pipes_struct *p,
1085                                              TALLOC_CTX *mem_ctx,
1086                                              const char *computer_name,
1087                                              struct netr_Authenticator *received_authenticator,
1088                                              struct netr_Authenticator *return_authenticator,
1089                                              struct netlogon_creds_CredentialState **creds_out)
1090 {
1091         NTSTATUS status;
1092         bool schannel_global_required = (lp_server_schannel() == true) ? true:false;
1093         struct loadparm_context *lp_ctx;
1094
1095         if (schannel_global_required) {
1096                 status = schannel_check_required(&p->auth,
1097                                                  computer_name,
1098                                                  false, false);
1099                 if (!NT_STATUS_IS_OK(status)) {
1100                         return status;
1101                 }
1102         }
1103
1104         lp_ctx = loadparm_init_s3(mem_ctx, loadparm_s3_context());
1105         if (lp_ctx == NULL) {
1106                 DEBUG(0, ("loadparm_init_s3 failed\n"));
1107                 return NT_STATUS_INTERNAL_ERROR;
1108         }
1109
1110         status = schannel_check_creds_state(mem_ctx, lp_ctx,
1111                                             computer_name, received_authenticator,
1112                                             return_authenticator, creds_out);
1113         talloc_unlink(mem_ctx, lp_ctx);
1114         return status;
1115 }
1116
1117 /*************************************************************************
1118  *************************************************************************/
1119
1120 static NTSTATUS netr_set_machine_account_password(TALLOC_CTX *mem_ctx,
1121                                                   struct auth_session_info *session_info,
1122                                                   struct messaging_context *msg_ctx,
1123                                                   const char *account_name,
1124                                                   struct samr_Password *nt_hash)
1125 {
1126         NTSTATUS status;
1127         NTSTATUS result = NT_STATUS_OK;
1128         struct dcerpc_binding_handle *h = NULL;
1129         struct tsocket_address *local;
1130         struct policy_handle user_handle;
1131         uint32_t acct_ctrl;
1132         union samr_UserInfo *info;
1133         struct samr_UserInfo18 info18;
1134         DATA_BLOB in,out;
1135         int rc;
1136
1137         ZERO_STRUCT(user_handle);
1138
1139         rc = tsocket_address_inet_from_strings(mem_ctx,
1140                                                "ip",
1141                                                "127.0.0.1",
1142                                                0,
1143                                                &local);
1144         if (rc < 0) {
1145                 status = NT_STATUS_NO_MEMORY;
1146                 goto out;
1147         }
1148
1149         status = rpcint_binding_handle(mem_ctx,
1150                                        &ndr_table_samr,
1151                                        local,
1152                                        session_info,
1153                                        msg_ctx,
1154                                        &h);
1155         if (!NT_STATUS_IS_OK(status)) {
1156                 goto out;
1157         }
1158
1159         become_root();
1160         status = samr_find_machine_account(mem_ctx,
1161                                            h,
1162                                            account_name,
1163                                            SEC_FLAG_MAXIMUM_ALLOWED,
1164                                            NULL,
1165                                            NULL,
1166                                            &user_handle);
1167         unbecome_root();
1168         if (!NT_STATUS_IS_OK(status)) {
1169                 goto out;
1170         }
1171
1172         status = dcerpc_samr_QueryUserInfo2(h,
1173                                             mem_ctx,
1174                                             &user_handle,
1175                                             UserControlInformation,
1176                                             &info,
1177                                             &result);
1178         if (!NT_STATUS_IS_OK(status)) {
1179                 goto out;
1180         }
1181         if (!NT_STATUS_IS_OK(result)) {
1182                 status = result;
1183                 goto out;
1184         }
1185
1186         acct_ctrl = info->info16.acct_flags;
1187
1188         if (!(acct_ctrl & ACB_WSTRUST ||
1189               acct_ctrl & ACB_SVRTRUST ||
1190               acct_ctrl & ACB_DOMTRUST)) {
1191                 status = NT_STATUS_NO_SUCH_USER;
1192                 goto out;
1193         }
1194
1195         if (acct_ctrl & ACB_DISABLED) {
1196                 status = NT_STATUS_ACCOUNT_DISABLED;
1197                 goto out;
1198         }
1199
1200         ZERO_STRUCT(info18);
1201
1202         in = data_blob_const(nt_hash->hash, 16);
1203         out = data_blob_talloc_zero(mem_ctx, 16);
1204         sess_crypt_blob(&out, &in, &session_info->session_key, true);
1205         memcpy(info18.nt_pwd.hash, out.data, out.length);
1206
1207         info18.nt_pwd_active = true;
1208
1209         info->info18 = info18;
1210
1211         become_root();
1212         status = dcerpc_samr_SetUserInfo2(h,
1213                                           mem_ctx,
1214                                           &user_handle,
1215                                           UserInternal1Information,
1216                                           info,
1217                                           &result);
1218         unbecome_root();
1219         if (!NT_STATUS_IS_OK(status)) {
1220                 goto out;
1221         }
1222         if (!NT_STATUS_IS_OK(result)) {
1223                 status = result;
1224                 goto out;
1225         }
1226
1227  out:
1228         if (h && is_valid_policy_hnd(&user_handle)) {
1229                 dcerpc_samr_Close(h, mem_ctx, &user_handle, &result);
1230         }
1231
1232         return status;
1233 }
1234
1235 /*************************************************************************
1236  _netr_ServerPasswordSet
1237  *************************************************************************/
1238
1239 NTSTATUS _netr_ServerPasswordSet(struct pipes_struct *p,
1240                                  struct netr_ServerPasswordSet *r)
1241 {
1242         NTSTATUS status = NT_STATUS_OK;
1243         int i;
1244         struct netlogon_creds_CredentialState *creds;
1245
1246         DEBUG(5,("_netr_ServerPasswordSet: %d\n", __LINE__));
1247
1248         become_root();
1249         status = netr_creds_server_step_check(p, p->mem_ctx,
1250                                               r->in.computer_name,
1251                                               r->in.credential,
1252                                               r->out.return_authenticator,
1253                                               &creds);
1254         unbecome_root();
1255
1256         if (!NT_STATUS_IS_OK(status)) {
1257                 DEBUG(2,("_netr_ServerPasswordSet: netlogon_creds_server_step failed. Rejecting auth "
1258                         "request from client %s machine account %s\n",
1259                         r->in.computer_name, creds->computer_name));
1260                 TALLOC_FREE(creds);
1261                 return status;
1262         }
1263
1264         DEBUG(3,("_netr_ServerPasswordSet: Server Password Set by remote machine:[%s] on account [%s]\n",
1265                         r->in.computer_name, creds->computer_name));
1266
1267         netlogon_creds_des_decrypt(creds, r->in.new_password);
1268
1269         DEBUG(100,("_netr_ServerPasswordSet: new given value was :\n"));
1270         for(i = 0; i < sizeof(r->in.new_password->hash); i++)
1271                 DEBUG(100,("%02X ", r->in.new_password->hash[i]));
1272         DEBUG(100,("\n"));
1273
1274         status = netr_set_machine_account_password(p->mem_ctx,
1275                                                    p->session_info,
1276                                                    p->msg_ctx,
1277                                                    creds->account_name,
1278                                                    r->in.new_password);
1279         return status;
1280 }
1281
1282 /****************************************************************
1283  _netr_ServerPasswordSet2
1284 ****************************************************************/
1285
1286 NTSTATUS _netr_ServerPasswordSet2(struct pipes_struct *p,
1287                                   struct netr_ServerPasswordSet2 *r)
1288 {
1289         NTSTATUS status;
1290         struct netlogon_creds_CredentialState *creds = NULL;
1291         DATA_BLOB plaintext;
1292         struct samr_CryptPassword password_buf;
1293         struct samr_Password nt_hash;
1294
1295         become_root();
1296         status = netr_creds_server_step_check(p, p->mem_ctx,
1297                                               r->in.computer_name,
1298                                               r->in.credential,
1299                                               r->out.return_authenticator,
1300                                               &creds);
1301         unbecome_root();
1302
1303         if (!NT_STATUS_IS_OK(status)) {
1304                 const char *computer_name = "<unknown>";
1305
1306                 if (creds && creds->computer_name) {
1307                         computer_name = creds->computer_name;
1308                 }
1309                 DEBUG(2,("_netr_ServerPasswordSet2: netlogon_creds_server_step "
1310                         "failed. Rejecting auth request from client %s machine account %s\n",
1311                         r->in.computer_name, computer_name));
1312                 TALLOC_FREE(creds);
1313                 return status;
1314         }
1315
1316         memcpy(password_buf.data, r->in.new_password->data, 512);
1317         SIVAL(password_buf.data, 512, r->in.new_password->length);
1318         netlogon_creds_arcfour_crypt(creds, password_buf.data, 516);
1319
1320         if (!extract_pw_from_buffer(p->mem_ctx, password_buf.data, &plaintext)) {
1321                 TALLOC_FREE(creds);
1322                 return NT_STATUS_WRONG_PASSWORD;
1323         }
1324
1325         mdfour(nt_hash.hash, plaintext.data, plaintext.length);
1326
1327         status = netr_set_machine_account_password(p->mem_ctx,
1328                                                    p->session_info,
1329                                                    p->msg_ctx,
1330                                                    creds->account_name,
1331                                                    &nt_hash);
1332         TALLOC_FREE(creds);
1333         return status;
1334 }
1335
1336 /*************************************************************************
1337  _netr_LogonSamLogoff
1338  *************************************************************************/
1339
1340 NTSTATUS _netr_LogonSamLogoff(struct pipes_struct *p,
1341                               struct netr_LogonSamLogoff *r)
1342 {
1343         NTSTATUS status;
1344         struct netlogon_creds_CredentialState *creds;
1345
1346         become_root();
1347         status = netr_creds_server_step_check(p, p->mem_ctx,
1348                                               r->in.computer_name,
1349                                               r->in.credential,
1350                                               r->out.return_authenticator,
1351                                               &creds);
1352         unbecome_root();
1353
1354         return status;
1355 }
1356
1357 static NTSTATUS _netr_LogonSamLogon_check(const struct netr_LogonSamLogonEx *r)
1358 {
1359         switch (r->in.logon_level) {
1360         case NetlogonInteractiveInformation:
1361         case NetlogonServiceInformation:
1362         case NetlogonInteractiveTransitiveInformation:
1363         case NetlogonServiceTransitiveInformation:
1364                 if (r->in.logon->password == NULL) {
1365                         return NT_STATUS_INVALID_PARAMETER;
1366                 }
1367
1368                 switch (r->in.validation_level) {
1369                 case NetlogonValidationSamInfo:  /* 2 */
1370                 case NetlogonValidationSamInfo2: /* 3 */
1371                         break;
1372                 case NetlogonValidationSamInfo4: /* 6 */
1373                         if ((pdb_capabilities() & PDB_CAP_ADS) == 0) {
1374                                 DEBUG(10,("Not adding validation info level 6 "
1375                                    "without ADS passdb backend\n"));
1376                                 return NT_STATUS_INVALID_INFO_CLASS;
1377                         }
1378                         break;
1379                 default:
1380                         return NT_STATUS_INVALID_INFO_CLASS;
1381                 }
1382
1383                 break;
1384         case NetlogonNetworkInformation:
1385         case NetlogonNetworkTransitiveInformation:
1386                 if (r->in.logon->network == NULL) {
1387                         return NT_STATUS_INVALID_PARAMETER;
1388                 }
1389
1390                 switch (r->in.validation_level) {
1391                 case NetlogonValidationSamInfo:  /* 2 */
1392                 case NetlogonValidationSamInfo2: /* 3 */
1393                         break;
1394                 case NetlogonValidationSamInfo4: /* 6 */
1395                         if ((pdb_capabilities() & PDB_CAP_ADS) == 0) {
1396                                 DEBUG(10,("Not adding validation info level 6 "
1397                                    "without ADS passdb backend\n"));
1398                                 return NT_STATUS_INVALID_INFO_CLASS;
1399                         }
1400                         break;
1401                 default:
1402                         return NT_STATUS_INVALID_INFO_CLASS;
1403                 }
1404
1405                 break;
1406
1407         case NetlogonGenericInformation:
1408                 if (r->in.logon->generic == NULL) {
1409                         return NT_STATUS_INVALID_PARAMETER;
1410                 }
1411
1412                 /* we don't support this here */
1413                 return NT_STATUS_INVALID_PARAMETER;
1414 #if 0
1415                 switch (r->in.validation_level) {
1416                 /* TODO: case NetlogonValidationGenericInfo: 4 */
1417                 case NetlogonValidationGenericInfo2: /* 5 */
1418                         break;
1419                 default:
1420                         return NT_STATUS_INVALID_INFO_CLASS;
1421                 }
1422
1423                 break;
1424 #endif
1425         default:
1426                 return NT_STATUS_INVALID_PARAMETER;
1427         }
1428
1429         return NT_STATUS_OK;
1430 }
1431
1432 /*************************************************************************
1433  _netr_LogonSamLogon_base
1434  *************************************************************************/
1435
1436 static NTSTATUS _netr_LogonSamLogon_base(struct pipes_struct *p,
1437                                          struct netr_LogonSamLogonEx *r,
1438                                          struct netlogon_creds_CredentialState *creds)
1439 {
1440         NTSTATUS status = NT_STATUS_OK;
1441         union netr_LogonLevel *logon = r->in.logon;
1442         const char *nt_username, *nt_domain, *nt_workstation;
1443         struct auth_usersupplied_info *user_info = NULL;
1444         struct auth_serversupplied_info *server_info = NULL;
1445         struct auth_context *auth_context = NULL;
1446         uint8_t pipe_session_key[16];
1447         bool process_creds = true;
1448         const char *fn;
1449
1450         switch (p->opnum) {
1451                 case NDR_NETR_LOGONSAMLOGON:
1452                         process_creds = true;
1453                         fn = "_netr_LogonSamLogon";
1454                         break;
1455                 case NDR_NETR_LOGONSAMLOGONWITHFLAGS:
1456                         process_creds = true;
1457                         fn = "_netr_LogonSamLogonWithFlags";
1458                         break;
1459                 case NDR_NETR_LOGONSAMLOGONEX:
1460                         process_creds = false;
1461                         fn = "_netr_LogonSamLogonEx";
1462                         break;
1463                 default:
1464                         return NT_STATUS_INTERNAL_ERROR;
1465         }
1466
1467         *r->out.authoritative = true; /* authoritative response */
1468
1469         switch (r->in.validation_level) {
1470         case 2:
1471                 r->out.validation->sam2 = talloc_zero(p->mem_ctx, struct netr_SamInfo2);
1472                 if (!r->out.validation->sam2) {
1473                         return NT_STATUS_NO_MEMORY;
1474                 }
1475                 break;
1476         case 3:
1477                 r->out.validation->sam3 = talloc_zero(p->mem_ctx, struct netr_SamInfo3);
1478                 if (!r->out.validation->sam3) {
1479                         return NT_STATUS_NO_MEMORY;
1480                 }
1481                 break;
1482         case 6:
1483                 r->out.validation->sam6 = talloc_zero(p->mem_ctx, struct netr_SamInfo6);
1484                 if (!r->out.validation->sam6) {
1485                         return NT_STATUS_NO_MEMORY;
1486                 }
1487                 break;
1488         default:
1489                 DEBUG(0,("%s: bad validation_level value %d.\n",
1490                         fn, (int)r->in.validation_level));
1491                 return NT_STATUS_INVALID_INFO_CLASS;
1492         }
1493
1494         switch (r->in.logon_level) {
1495         case NetlogonInteractiveInformation:
1496         case NetlogonServiceInformation:
1497         case NetlogonInteractiveTransitiveInformation:
1498         case NetlogonServiceTransitiveInformation:
1499                 nt_username     = logon->password->identity_info.account_name.string ?
1500                                   logon->password->identity_info.account_name.string : "";
1501                 nt_domain       = logon->password->identity_info.domain_name.string ?
1502                                   logon->password->identity_info.domain_name.string : "";
1503                 nt_workstation  = logon->password->identity_info.workstation.string ?
1504                                   logon->password->identity_info.workstation.string : "";
1505
1506                 DEBUG(3,("SAM Logon (Interactive). Domain:[%s].  ", lp_workgroup()));
1507                 break;
1508         case NetlogonNetworkInformation:
1509         case NetlogonNetworkTransitiveInformation:
1510                 nt_username     = logon->network->identity_info.account_name.string ?
1511                                   logon->network->identity_info.account_name.string : "";
1512                 nt_domain       = logon->network->identity_info.domain_name.string ?
1513                                   logon->network->identity_info.domain_name.string : "";
1514                 nt_workstation  = logon->network->identity_info.workstation.string ?
1515                                   logon->network->identity_info.workstation.string : "";
1516
1517                 DEBUG(3,("SAM Logon (Network). Domain:[%s].  ", lp_workgroup()));
1518                 break;
1519         default:
1520                 DEBUG(2,("SAM Logon: unsupported switch value\n"));
1521                 return NT_STATUS_INVALID_INFO_CLASS;
1522         } /* end switch */
1523
1524         DEBUG(3,("User:[%s@%s] Requested Domain:[%s]\n", nt_username, nt_workstation, nt_domain));
1525         fstrcpy(current_user_info.smb_name, nt_username);
1526         sub_set_smb_name(nt_username);
1527
1528         DEBUG(5,("Attempting validation level %d for unmapped username %s.\n",
1529                 r->in.validation_level, nt_username));
1530
1531         status = NT_STATUS_OK;
1532
1533         switch (r->in.logon_level) {
1534         case NetlogonNetworkInformation:
1535         case NetlogonNetworkTransitiveInformation:
1536         {
1537                 const char *wksname = nt_workstation;
1538
1539                 status = make_auth_context_fixed(talloc_tos(), &auth_context,
1540                                                  logon->network->challenge);
1541                 if (!NT_STATUS_IS_OK(status)) {
1542                         return status;
1543                 }
1544
1545                 /* For a network logon, the workstation name comes in with two
1546                  * backslashes in the front. Strip them if they are there. */
1547
1548                 if (*wksname == '\\') wksname++;
1549                 if (*wksname == '\\') wksname++;
1550
1551                 /* Standard challenge/response authentication */
1552                 if (!make_user_info_netlogon_network(&user_info,
1553                                                      nt_username, nt_domain,
1554                                                      wksname,
1555                                                      p->remote_address,
1556                                                      logon->network->identity_info.parameter_control,
1557                                                      logon->network->lm.data,
1558                                                      logon->network->lm.length,
1559                                                      logon->network->nt.data,
1560                                                      logon->network->nt.length)) {
1561                         status = NT_STATUS_NO_MEMORY;
1562                 }
1563                 break;
1564         }
1565         case NetlogonInteractiveInformation:
1566         case NetlogonServiceInformation:
1567         case NetlogonInteractiveTransitiveInformation:
1568         case NetlogonServiceTransitiveInformation:
1569
1570                 /* 'Interactive' authentication, supplies the password in its
1571                    MD4 form, encrypted with the session key.  We will convert
1572                    this to challenge/response for the auth subsystem to chew
1573                    on */
1574         {
1575                 uint8_t chal[8];
1576
1577                 status = make_auth_context_subsystem(talloc_tos(),
1578                                                      &auth_context);
1579                 if (!NT_STATUS_IS_OK(status)) {
1580                         return status;
1581                 }
1582
1583                 auth_context->get_ntlm_challenge(auth_context, chal);
1584
1585                 if (!make_user_info_netlogon_interactive(&user_info,
1586                                                          nt_username, nt_domain,
1587                                                          nt_workstation,
1588                                                          p->remote_address,
1589                                                          logon->password->identity_info.parameter_control,
1590                                                          chal,
1591                                                          logon->password->lmpassword.hash,
1592                                                          logon->password->ntpassword.hash,
1593                                                          creds->session_key)) {
1594                         status = NT_STATUS_NO_MEMORY;
1595                 }
1596                 break;
1597         }
1598         default:
1599                 DEBUG(2,("SAM Logon: unsupported switch value\n"));
1600                 return NT_STATUS_INVALID_INFO_CLASS;
1601         } /* end switch */
1602
1603         if ( NT_STATUS_IS_OK(status) ) {
1604                 status = auth_context->check_ntlm_password(auth_context,
1605                         user_info, &server_info);
1606         }
1607
1608         TALLOC_FREE(auth_context);
1609         free_user_info(&user_info);
1610
1611         DEBUG(5,("%s: check_password returned status %s\n",
1612                   fn, nt_errstr(status)));
1613
1614         /* Check account and password */
1615
1616         if (!NT_STATUS_IS_OK(status)) {
1617                 /* If we don't know what this domain is, we need to
1618                    indicate that we are not authoritative.  This
1619                    allows the client to decide if it needs to try
1620                    a local user.  Fix by jpjanosi@us.ibm.com, #2976 */
1621                 if ( NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_USER)
1622                      && !strequal(nt_domain, get_global_sam_name())
1623                      && !is_trusted_domain(nt_domain) )
1624                         *r->out.authoritative = false; /* We are not authoritative */
1625
1626                 TALLOC_FREE(server_info);
1627                 return status;
1628         }
1629
1630         if (server_info->guest) {
1631                 /* We don't like guest domain logons... */
1632                 DEBUG(5,("%s: Attempted domain logon as GUEST "
1633                          "denied.\n", fn));
1634                 TALLOC_FREE(server_info);
1635                 return NT_STATUS_LOGON_FAILURE;
1636         }
1637
1638         /* This is the point at which, if the login was successful, that
1639            the SAM Local Security Authority should record that the user is
1640            logged in to the domain.  */
1641
1642         if (process_creds) {
1643                 /* Get the pipe session key from the creds. */
1644                 memcpy(pipe_session_key, creds->session_key, 16);
1645         } else {
1646                 struct schannel_state *schannel_auth;
1647                 /* Get the pipe session key from the schannel. */
1648                 if ((p->auth.auth_type != DCERPC_AUTH_TYPE_SCHANNEL)
1649                     || (p->auth.auth_ctx == NULL)) {
1650                         return NT_STATUS_INVALID_HANDLE;
1651                 }
1652
1653                 schannel_auth = talloc_get_type_abort(p->auth.auth_ctx,
1654                                                       struct schannel_state);
1655                 memcpy(pipe_session_key, schannel_auth->creds->session_key, 16);
1656         }
1657
1658         switch (r->in.validation_level) {
1659         case 2:
1660                 status = serverinfo_to_SamInfo2(server_info, pipe_session_key, 16,
1661                                                 r->out.validation->sam2);
1662                 break;
1663         case 3:
1664                 status = serverinfo_to_SamInfo3(server_info, pipe_session_key, 16,
1665                                                 r->out.validation->sam3);
1666                 break;
1667         case 6:
1668                 status = serverinfo_to_SamInfo6(server_info, pipe_session_key, 16,
1669                                                 r->out.validation->sam6);
1670                 break;
1671         }
1672
1673         TALLOC_FREE(server_info);
1674
1675         return status;
1676 }
1677
1678 /****************************************************************
1679  _netr_LogonSamLogonWithFlags
1680 ****************************************************************/
1681
1682 NTSTATUS _netr_LogonSamLogonWithFlags(struct pipes_struct *p,
1683                                       struct netr_LogonSamLogonWithFlags *r)
1684 {
1685         NTSTATUS status;
1686         struct netlogon_creds_CredentialState *creds;
1687         struct netr_LogonSamLogonEx r2;
1688         struct netr_Authenticator return_authenticator;
1689
1690         *r->out.authoritative = true;
1691
1692         r2.in.server_name       = r->in.server_name;
1693         r2.in.computer_name     = r->in.computer_name;
1694         r2.in.logon_level       = r->in.logon_level;
1695         r2.in.logon             = r->in.logon;
1696         r2.in.validation_level  = r->in.validation_level;
1697         r2.in.flags             = r->in.flags;
1698         r2.out.validation       = r->out.validation;
1699         r2.out.authoritative    = r->out.authoritative;
1700         r2.out.flags            = r->out.flags;
1701
1702         status = _netr_LogonSamLogon_check(&r2);
1703         if (!NT_STATUS_IS_OK(status)) {
1704                 return status;
1705         }
1706
1707         become_root();
1708         status = netr_creds_server_step_check(p, p->mem_ctx,
1709                                               r->in.computer_name,
1710                                               r->in.credential,
1711                                               &return_authenticator,
1712                                               &creds);
1713         unbecome_root();
1714         if (!NT_STATUS_IS_OK(status)) {
1715                 return status;
1716         }
1717
1718         status = _netr_LogonSamLogon_base(p, &r2, creds);
1719
1720         *r->out.return_authenticator = return_authenticator;
1721
1722         return status;
1723 }
1724
1725 /*************************************************************************
1726  _netr_LogonSamLogon
1727  *************************************************************************/
1728
1729 NTSTATUS _netr_LogonSamLogon(struct pipes_struct *p,
1730                              struct netr_LogonSamLogon *r)
1731 {
1732         NTSTATUS status;
1733         struct netr_LogonSamLogonWithFlags r2;
1734         uint32_t flags = 0;
1735
1736         r2.in.server_name               = r->in.server_name;
1737         r2.in.computer_name             = r->in.computer_name;
1738         r2.in.credential                = r->in.credential;
1739         r2.in.logon_level               = r->in.logon_level;
1740         r2.in.logon                     = r->in.logon;
1741         r2.in.validation_level          = r->in.validation_level;
1742         r2.in.return_authenticator      = r->in.return_authenticator;
1743         r2.in.flags                     = &flags;
1744         r2.out.validation               = r->out.validation;
1745         r2.out.authoritative            = r->out.authoritative;
1746         r2.out.flags                    = &flags;
1747         r2.out.return_authenticator     = r->out.return_authenticator;
1748
1749         status = _netr_LogonSamLogonWithFlags(p, &r2);
1750
1751         return status;
1752 }
1753
1754 /*************************************************************************
1755  _netr_LogonSamLogonEx
1756  - no credential chaining. Map into net sam logon.
1757  *************************************************************************/
1758
1759 NTSTATUS _netr_LogonSamLogonEx(struct pipes_struct *p,
1760                                struct netr_LogonSamLogonEx *r)
1761 {
1762         NTSTATUS status;
1763         struct netlogon_creds_CredentialState *creds = NULL;
1764         struct loadparm_context *lp_ctx;
1765
1766         *r->out.authoritative = true;
1767
1768         status = _netr_LogonSamLogon_check(r);
1769         if (!NT_STATUS_IS_OK(status)) {
1770                 return status;
1771         }
1772
1773         /* Only allow this if the pipe is protected. */
1774         if (p->auth.auth_type != DCERPC_AUTH_TYPE_SCHANNEL) {
1775                 DEBUG(0,("_netr_LogonSamLogonEx: client %s not using schannel for netlogon\n",
1776                         get_remote_machine_name() ));
1777                 return NT_STATUS_INVALID_PARAMETER;
1778         }
1779
1780         lp_ctx = loadparm_init_s3(p->mem_ctx, loadparm_s3_context());
1781         if (lp_ctx == NULL) {
1782                 DEBUG(0, ("loadparm_init_s3 failed\n"));
1783                 return NT_STATUS_INTERNAL_ERROR;
1784         }
1785
1786         become_root();
1787         status = schannel_get_creds_state(p->mem_ctx, lp_ctx,
1788                                           r->in.computer_name, &creds);
1789         unbecome_root();
1790         talloc_unlink(p->mem_ctx, lp_ctx);
1791
1792         if (!NT_STATUS_IS_OK(status)) {
1793                 return status;
1794         }
1795
1796         status = _netr_LogonSamLogon_base(p, r, creds);
1797         TALLOC_FREE(creds);
1798
1799         return status;
1800 }
1801
1802 /*************************************************************************
1803  _ds_enum_dom_trusts
1804  *************************************************************************/
1805 #if 0   /* JERRY -- not correct */
1806  NTSTATUS _ds_enum_dom_trusts(struct pipes_struct *p, DS_Q_ENUM_DOM_TRUSTS *q_u,
1807                              DS_R_ENUM_DOM_TRUSTS *r_u)
1808 {
1809         NTSTATUS status = NT_STATUS_OK;
1810
1811         /* TODO: According to MSDN, the can only be executed against a
1812            DC or domain member running Windows 2000 or later.  Need
1813            to test against a standalone 2k server and see what it
1814            does.  A windows 2000 DC includes its own domain in the
1815            list.  --jerry */
1816
1817         return status;
1818 }
1819 #endif  /* JERRY */
1820
1821
1822 /****************************************************************
1823 ****************************************************************/
1824
1825 WERROR _netr_LogonUasLogon(struct pipes_struct *p,
1826                            struct netr_LogonUasLogon *r)
1827 {
1828         p->rng_fault_state = true;
1829         return WERR_NOT_SUPPORTED;
1830 }
1831
1832 /****************************************************************
1833 ****************************************************************/
1834
1835 WERROR _netr_LogonUasLogoff(struct pipes_struct *p,
1836                             struct netr_LogonUasLogoff *r)
1837 {
1838         p->rng_fault_state = true;
1839         return WERR_NOT_SUPPORTED;
1840 }
1841
1842 /****************************************************************
1843 ****************************************************************/
1844
1845 NTSTATUS _netr_DatabaseDeltas(struct pipes_struct *p,
1846                               struct netr_DatabaseDeltas *r)
1847 {
1848         p->rng_fault_state = true;
1849         return NT_STATUS_NOT_IMPLEMENTED;
1850 }
1851
1852 /****************************************************************
1853 ****************************************************************/
1854
1855 NTSTATUS _netr_DatabaseSync(struct pipes_struct *p,
1856                             struct netr_DatabaseSync *r)
1857 {
1858         p->rng_fault_state = true;
1859         return NT_STATUS_NOT_IMPLEMENTED;
1860 }
1861
1862 /****************************************************************
1863 ****************************************************************/
1864
1865 NTSTATUS _netr_AccountDeltas(struct pipes_struct *p,
1866                              struct netr_AccountDeltas *r)
1867 {
1868         p->rng_fault_state = true;
1869         return NT_STATUS_NOT_IMPLEMENTED;
1870 }
1871
1872 /****************************************************************
1873 ****************************************************************/
1874
1875 NTSTATUS _netr_AccountSync(struct pipes_struct *p,
1876                            struct netr_AccountSync *r)
1877 {
1878         p->rng_fault_state = true;
1879         return NT_STATUS_NOT_IMPLEMENTED;
1880 }
1881
1882 /****************************************************************
1883 ****************************************************************/
1884
1885 static bool wb_getdcname(TALLOC_CTX *mem_ctx,
1886                          const char *domain,
1887                          const char **dcname,
1888                          uint32_t flags,
1889                          WERROR *werr)
1890 {
1891         wbcErr result;
1892         struct wbcDomainControllerInfo *dc_info = NULL;
1893
1894         result = wbcLookupDomainController(domain,
1895                                            flags,
1896                                            &dc_info);
1897         switch (result) {
1898         case WBC_ERR_SUCCESS:
1899                 break;
1900         case WBC_ERR_WINBIND_NOT_AVAILABLE:
1901                 return false;
1902         case WBC_ERR_DOMAIN_NOT_FOUND:
1903                 *werr = WERR_NO_SUCH_DOMAIN;
1904                 return true;
1905         default:
1906                 *werr = WERR_DOMAIN_CONTROLLER_NOT_FOUND;
1907                 return true;
1908         }
1909
1910         *dcname = talloc_strdup(mem_ctx, dc_info->dc_name);
1911         wbcFreeMemory(dc_info);
1912         if (!*dcname) {
1913                 *werr = WERR_NOMEM;
1914                 return false;
1915         }
1916
1917         *werr = WERR_OK;
1918
1919         return true;
1920 }
1921
1922 /****************************************************************
1923  _netr_GetDcName
1924 ****************************************************************/
1925
1926 WERROR _netr_GetDcName(struct pipes_struct *p,
1927                        struct netr_GetDcName *r)
1928 {
1929         NTSTATUS status;
1930         WERROR werr;
1931         uint32_t flags;
1932         struct netr_DsRGetDCNameInfo *info;
1933         bool ret;
1934
1935         ret = wb_getdcname(p->mem_ctx,
1936                            r->in.domainname,
1937                            r->out.dcname,
1938                            WBC_LOOKUP_DC_IS_FLAT_NAME |
1939                            WBC_LOOKUP_DC_RETURN_FLAT_NAME |
1940                            WBC_LOOKUP_DC_PDC_REQUIRED,
1941                            &werr);
1942         if (ret == true) {
1943                 return werr;
1944         }
1945
1946         flags = DS_PDC_REQUIRED | DS_IS_FLAT_NAME | DS_RETURN_FLAT_NAME;
1947
1948         status = dsgetdcname(p->mem_ctx,
1949                              p->msg_ctx,
1950                              r->in.domainname,
1951                              NULL,
1952                              NULL,
1953                              flags,
1954                              &info);
1955         if (!NT_STATUS_IS_OK(status)) {
1956                 return ntstatus_to_werror(status);
1957         }
1958
1959         *r->out.dcname = talloc_strdup(p->mem_ctx, info->dc_unc);
1960         talloc_free(info);
1961         if (!*r->out.dcname) {
1962                 return WERR_NOMEM;
1963         }
1964
1965         return WERR_OK;
1966 }
1967
1968 /****************************************************************
1969  _netr_GetAnyDCName
1970 ****************************************************************/
1971
1972 WERROR _netr_GetAnyDCName(struct pipes_struct *p,
1973                           struct netr_GetAnyDCName *r)
1974 {
1975         NTSTATUS status;
1976         WERROR werr;
1977         uint32_t flags;
1978         struct netr_DsRGetDCNameInfo *info;
1979         bool ret;
1980
1981         ret = wb_getdcname(p->mem_ctx,
1982                            r->in.domainname,
1983                            r->out.dcname,
1984                            WBC_LOOKUP_DC_IS_FLAT_NAME |
1985                            WBC_LOOKUP_DC_RETURN_FLAT_NAME,
1986                            &werr);
1987         if (ret == true) {
1988                 return werr;
1989         }
1990
1991         flags = DS_IS_FLAT_NAME | DS_RETURN_FLAT_NAME;
1992
1993         status = dsgetdcname(p->mem_ctx,
1994                              p->msg_ctx,
1995                              r->in.domainname,
1996                              NULL,
1997                              NULL,
1998                              flags,
1999                              &info);
2000         if (!NT_STATUS_IS_OK(status)) {
2001                 return ntstatus_to_werror(status);
2002         }
2003
2004         *r->out.dcname = talloc_strdup(p->mem_ctx, info->dc_unc);
2005         talloc_free(info);
2006         if (!*r->out.dcname) {
2007                 return WERR_NOMEM;
2008         }
2009
2010         return WERR_OK;
2011 }
2012
2013 /****************************************************************
2014 ****************************************************************/
2015
2016 NTSTATUS _netr_DatabaseSync2(struct pipes_struct *p,
2017                              struct netr_DatabaseSync2 *r)
2018 {
2019         p->rng_fault_state = true;
2020         return NT_STATUS_NOT_IMPLEMENTED;
2021 }
2022
2023 /****************************************************************
2024 ****************************************************************/
2025
2026 NTSTATUS _netr_DatabaseRedo(struct pipes_struct *p,
2027                             struct netr_DatabaseRedo *r)
2028 {
2029         p->rng_fault_state = true;
2030         return NT_STATUS_NOT_IMPLEMENTED;
2031 }
2032
2033 /****************************************************************
2034 ****************************************************************/
2035
2036 WERROR _netr_DsRGetDCName(struct pipes_struct *p,
2037                           struct netr_DsRGetDCName *r)
2038 {
2039         p->rng_fault_state = true;
2040         return WERR_NOT_SUPPORTED;
2041 }
2042
2043 /****************************************************************
2044 ****************************************************************/
2045
2046 NTSTATUS _netr_LogonGetCapabilities(struct pipes_struct *p,
2047                                     struct netr_LogonGetCapabilities *r)
2048 {
2049         return NT_STATUS_NOT_IMPLEMENTED;
2050 }
2051
2052 /****************************************************************
2053 ****************************************************************/
2054
2055 WERROR _netr_NETRLOGONSETSERVICEBITS(struct pipes_struct *p,
2056                                      struct netr_NETRLOGONSETSERVICEBITS *r)
2057 {
2058         p->rng_fault_state = true;
2059         return WERR_NOT_SUPPORTED;
2060 }
2061
2062 /****************************************************************
2063 ****************************************************************/
2064
2065 WERROR _netr_LogonGetTrustRid(struct pipes_struct *p,
2066                               struct netr_LogonGetTrustRid *r)
2067 {
2068         p->rng_fault_state = true;
2069         return WERR_NOT_SUPPORTED;
2070 }
2071
2072 /****************************************************************
2073 ****************************************************************/
2074
2075 WERROR _netr_NETRLOGONCOMPUTESERVERDIGEST(struct pipes_struct *p,
2076                                           struct netr_NETRLOGONCOMPUTESERVERDIGEST *r)
2077 {
2078         p->rng_fault_state = true;
2079         return WERR_NOT_SUPPORTED;
2080 }
2081
2082 /****************************************************************
2083 ****************************************************************/
2084
2085 WERROR _netr_NETRLOGONCOMPUTECLIENTDIGEST(struct pipes_struct *p,
2086                                           struct netr_NETRLOGONCOMPUTECLIENTDIGEST *r)
2087 {
2088         p->rng_fault_state = true;
2089         return WERR_NOT_SUPPORTED;
2090 }
2091
2092 /****************************************************************
2093 ****************************************************************/
2094
2095 WERROR _netr_DsRGetDCNameEx(struct pipes_struct *p,
2096                             struct netr_DsRGetDCNameEx *r)
2097 {
2098         p->rng_fault_state = true;
2099         return WERR_NOT_SUPPORTED;
2100 }
2101
2102 /****************************************************************
2103 ****************************************************************/
2104
2105 WERROR _netr_DsRGetSiteName(struct pipes_struct *p,
2106                             struct netr_DsRGetSiteName *r)
2107 {
2108         p->rng_fault_state = true;
2109         return WERR_NOT_SUPPORTED;
2110 }
2111
2112 /****************************************************************
2113 ****************************************************************/
2114
2115 NTSTATUS _netr_LogonGetDomainInfo(struct pipes_struct *p,
2116                                   struct netr_LogonGetDomainInfo *r)
2117 {
2118         p->rng_fault_state = true;
2119         return NT_STATUS_NOT_IMPLEMENTED;
2120 }
2121
2122 /****************************************************************
2123 ****************************************************************/
2124
2125 WERROR _netr_ServerPasswordGet(struct pipes_struct *p,
2126                                struct netr_ServerPasswordGet *r)
2127 {
2128         p->rng_fault_state = true;
2129         return WERR_NOT_SUPPORTED;
2130 }
2131
2132 /****************************************************************
2133 ****************************************************************/
2134
2135 WERROR _netr_NETRLOGONSENDTOSAM(struct pipes_struct *p,
2136                                 struct netr_NETRLOGONSENDTOSAM *r)
2137 {
2138         p->rng_fault_state = true;
2139         return WERR_NOT_SUPPORTED;
2140 }
2141
2142 /****************************************************************
2143 ****************************************************************/
2144
2145 WERROR _netr_DsRAddressToSitenamesW(struct pipes_struct *p,
2146                                     struct netr_DsRAddressToSitenamesW *r)
2147 {
2148         p->rng_fault_state = true;
2149         return WERR_NOT_SUPPORTED;
2150 }
2151
2152 /****************************************************************
2153 ****************************************************************/
2154
2155 WERROR _netr_DsRGetDCNameEx2(struct pipes_struct *p,
2156                              struct netr_DsRGetDCNameEx2 *r)
2157 {
2158         p->rng_fault_state = true;
2159         return WERR_NOT_SUPPORTED;
2160 }
2161
2162 /****************************************************************
2163 ****************************************************************/
2164
2165 WERROR _netr_NETRLOGONGETTIMESERVICEPARENTDOMAIN(struct pipes_struct *p,
2166                                                  struct netr_NETRLOGONGETTIMESERVICEPARENTDOMAIN *r)
2167 {
2168         p->rng_fault_state = true;
2169         return WERR_NOT_SUPPORTED;
2170 }
2171
2172 /****************************************************************
2173 ****************************************************************/
2174
2175 WERROR _netr_NetrEnumerateTrustedDomainsEx(struct pipes_struct *p,
2176                                            struct netr_NetrEnumerateTrustedDomainsEx *r)
2177 {
2178         p->rng_fault_state = true;
2179         return WERR_NOT_SUPPORTED;
2180 }
2181
2182 /****************************************************************
2183 ****************************************************************/
2184
2185 WERROR _netr_DsRAddressToSitenamesExW(struct pipes_struct *p,
2186                                       struct netr_DsRAddressToSitenamesExW *r)
2187 {
2188         p->rng_fault_state = true;
2189         return WERR_NOT_SUPPORTED;
2190 }
2191
2192 /****************************************************************
2193 ****************************************************************/
2194
2195 WERROR _netr_DsrGetDcSiteCoverageW(struct pipes_struct *p,
2196                                    struct netr_DsrGetDcSiteCoverageW *r)
2197 {
2198         p->rng_fault_state = true;
2199         return WERR_NOT_SUPPORTED;
2200 }
2201
2202 /****************************************************************
2203 ****************************************************************/
2204
2205 WERROR _netr_DsrEnumerateDomainTrusts(struct pipes_struct *p,
2206                                       struct netr_DsrEnumerateDomainTrusts *r)
2207 {
2208         p->rng_fault_state = true;
2209         return WERR_NOT_SUPPORTED;
2210 }
2211
2212 /****************************************************************
2213 ****************************************************************/
2214
2215 WERROR _netr_DsrDeregisterDNSHostRecords(struct pipes_struct *p,
2216                                          struct netr_DsrDeregisterDNSHostRecords *r)
2217 {
2218         p->rng_fault_state = true;
2219         return WERR_NOT_SUPPORTED;
2220 }
2221
2222 /****************************************************************
2223 ****************************************************************/
2224
2225 NTSTATUS _netr_ServerTrustPasswordsGet(struct pipes_struct *p,
2226                                        struct netr_ServerTrustPasswordsGet *r)
2227 {
2228         p->rng_fault_state = true;
2229         return NT_STATUS_NOT_IMPLEMENTED;
2230 }
2231
2232 /****************************************************************
2233 ****************************************************************/
2234
2235 WERROR _netr_DsRGetForestTrustInformation(struct pipes_struct *p,
2236                                           struct netr_DsRGetForestTrustInformation *r)
2237 {
2238         p->rng_fault_state = true;
2239         return WERR_NOT_SUPPORTED;
2240 }
2241
2242 /****************************************************************
2243 ****************************************************************/
2244
2245 static NTSTATUS fill_forest_trust_array(TALLOC_CTX *mem_ctx,
2246                                         struct lsa_ForestTrustInformation *info)
2247 {
2248         struct lsa_ForestTrustRecord *e;
2249         struct pdb_domain_info *dom_info;
2250         struct lsa_ForestTrustDomainInfo *domain_info;
2251
2252         dom_info = pdb_get_domain_info(mem_ctx);
2253         if (dom_info == NULL) {
2254                 return NT_STATUS_NO_MEMORY;
2255         }
2256
2257         info->count = 2;
2258         info->entries = talloc_array(info, struct lsa_ForestTrustRecord *, 2);
2259         if (info->entries == NULL) {
2260                 return NT_STATUS_NO_MEMORY;
2261         }
2262
2263         e = talloc(info, struct lsa_ForestTrustRecord);
2264         if (e == NULL) {
2265                 return NT_STATUS_NO_MEMORY;
2266         }
2267
2268         e->flags = 0;
2269         e->type = LSA_FOREST_TRUST_TOP_LEVEL_NAME;
2270         e->time = 0; /* so far always 0 in trces. */
2271         e->forest_trust_data.top_level_name.string = talloc_steal(info,
2272                                                                   dom_info->dns_forest);
2273
2274         info->entries[0] = e;
2275
2276         e = talloc(info, struct lsa_ForestTrustRecord);
2277         if (e == NULL) {
2278                 return NT_STATUS_NO_MEMORY;
2279         }
2280
2281         /* TODO: check if disabled and set flags accordingly */
2282         e->flags = 0;
2283         e->type = LSA_FOREST_TRUST_DOMAIN_INFO;
2284         e->time = 0; /* so far always 0 in traces. */
2285
2286         domain_info = &e->forest_trust_data.domain_info;
2287         domain_info->domain_sid = dom_sid_dup(info, &dom_info->sid);
2288
2289         domain_info->dns_domain_name.string = talloc_steal(info,
2290                                                            dom_info->dns_domain);
2291         domain_info->netbios_domain_name.string = talloc_steal(info,
2292                                                                dom_info->name);
2293
2294         info->entries[1] = e;
2295
2296         return NT_STATUS_OK;
2297 }
2298
2299 /****************************************************************
2300  _netr_GetForestTrustInformation
2301 ****************************************************************/
2302
2303 NTSTATUS _netr_GetForestTrustInformation(struct pipes_struct *p,
2304                                          struct netr_GetForestTrustInformation *r)
2305 {
2306         NTSTATUS status;
2307         struct netlogon_creds_CredentialState *creds;
2308         struct lsa_ForestTrustInformation *info, **info_ptr;
2309         struct loadparm_context *lp_ctx;
2310
2311         /* TODO: check server name */
2312
2313         lp_ctx = loadparm_init_s3(p->mem_ctx, loadparm_s3_context());
2314         if (lp_ctx == NULL) {
2315                 DEBUG(0, ("loadparm_init_s3 failed\n"));
2316                 return NT_STATUS_INTERNAL_ERROR;
2317         }
2318
2319         status = schannel_check_creds_state(p->mem_ctx, lp_ctx,
2320                                             r->in.computer_name,
2321                                             r->in.credential,
2322                                             r->out.return_authenticator,
2323                                             &creds);
2324         talloc_unlink(p->mem_ctx, lp_ctx);
2325         if (!NT_STATUS_IS_OK(status)) {
2326                 return status;
2327         }
2328
2329         if ((creds->secure_channel_type != SEC_CHAN_DNS_DOMAIN) &&
2330             (creds->secure_channel_type != SEC_CHAN_DOMAIN)) {
2331                 return NT_STATUS_NOT_IMPLEMENTED;
2332         }
2333
2334         info_ptr = talloc(p->mem_ctx, struct lsa_ForestTrustInformation *);
2335         if (!info_ptr) {
2336                 return NT_STATUS_NO_MEMORY;
2337         }
2338         info = talloc_zero(info_ptr, struct lsa_ForestTrustInformation);
2339         if (!info) {
2340                 return NT_STATUS_NO_MEMORY;
2341         }
2342
2343         status = fill_forest_trust_array(p->mem_ctx, info);
2344         if (!NT_STATUS_IS_OK(status)) {
2345                 return status;
2346         }
2347
2348         *info_ptr = info;
2349         r->out.forest_trust_info = info_ptr;
2350
2351         return NT_STATUS_OK;
2352 }
2353
2354 /****************************************************************
2355 ****************************************************************/
2356
2357 static NTSTATUS get_password_from_trustAuth(TALLOC_CTX *mem_ctx,
2358                                             const DATA_BLOB *trustAuth_blob,
2359                                             const DATA_BLOB *session_key,
2360                                             struct samr_Password *current_pw_enc,
2361                                             struct samr_Password *previous_pw_enc)
2362 {
2363         enum ndr_err_code ndr_err;
2364         struct trustAuthInOutBlob trustAuth;
2365
2366         ndr_err = ndr_pull_struct_blob_all(trustAuth_blob, mem_ctx, &trustAuth,
2367                                            (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
2368         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2369                 return NT_STATUS_UNSUCCESSFUL;
2370         }
2371
2372
2373         if (trustAuth.count != 0 && trustAuth.current.count != 0 &&
2374             trustAuth.current.array[0].AuthType == TRUST_AUTH_TYPE_CLEAR) {
2375                 mdfour(previous_pw_enc->hash,
2376                        trustAuth.current.array[0].AuthInfo.clear.password,
2377                        trustAuth.current.array[0].AuthInfo.clear.size);
2378         } else {
2379                 return NT_STATUS_UNSUCCESSFUL;
2380         }
2381
2382         arcfour_crypt_blob(current_pw_enc->hash, sizeof(current_pw_enc->hash),
2383                            session_key);
2384
2385         if (trustAuth.previous.count != 0 &&
2386             trustAuth.previous.array[0].AuthType == TRUST_AUTH_TYPE_CLEAR) {
2387                 mdfour(previous_pw_enc->hash,
2388                        trustAuth.previous.array[0].AuthInfo.clear.password,
2389                        trustAuth.previous.array[0].AuthInfo.clear.size);
2390         } else {
2391                 mdfour(previous_pw_enc->hash, NULL, 0);
2392         }
2393         arcfour_crypt_blob(previous_pw_enc->hash, sizeof(previous_pw_enc->hash),
2394                            session_key);
2395
2396         return NT_STATUS_OK;
2397 }
2398
2399 /****************************************************************
2400  _netr_ServerGetTrustInfo
2401 ****************************************************************/
2402
2403 NTSTATUS _netr_ServerGetTrustInfo(struct pipes_struct *p,
2404                                   struct netr_ServerGetTrustInfo *r)
2405 {
2406         NTSTATUS status;
2407         struct netlogon_creds_CredentialState *creds;
2408         char *account_name;
2409         size_t account_name_last;
2410         bool trusted;
2411         struct netr_TrustInfo *trust_info;
2412         struct pdb_trusted_domain *td;
2413         DATA_BLOB trustAuth_blob;
2414         struct samr_Password *new_owf_enc;
2415         struct samr_Password *old_owf_enc;
2416         DATA_BLOB session_key;
2417         struct loadparm_context *lp_ctx;
2418
2419         lp_ctx = loadparm_init_s3(p->mem_ctx, loadparm_s3_context());
2420         if (lp_ctx == NULL) {
2421                 DEBUG(0, ("loadparm_init_s3 failed\n"));
2422                 return NT_STATUS_INTERNAL_ERROR;
2423         }
2424
2425         /* TODO: check server name */
2426
2427         status = schannel_check_creds_state(p->mem_ctx, lp_ctx,
2428                                             r->in.computer_name,
2429                                             r->in.credential,
2430                                             r->out.return_authenticator,
2431                                             &creds);
2432         talloc_unlink(p->mem_ctx, lp_ctx);
2433         if (!NT_STATUS_IS_OK(status)) {
2434                 return status;
2435         }
2436
2437         account_name = talloc_strdup(p->mem_ctx, r->in.account_name);
2438         if (account_name == NULL) {
2439                 return NT_STATUS_NO_MEMORY;
2440         }
2441
2442         account_name_last = strlen(account_name);
2443         if (account_name_last == 0) {
2444                 return NT_STATUS_INVALID_PARAMETER;
2445         }
2446         account_name_last--;
2447         if (account_name[account_name_last] == '.') {
2448                 account_name[account_name_last] = '\0';
2449         }
2450
2451         if ((creds->secure_channel_type != SEC_CHAN_DNS_DOMAIN) &&
2452             (creds->secure_channel_type != SEC_CHAN_DOMAIN)) {
2453                 trusted = false;
2454         } else {
2455                 trusted = true;
2456         }
2457
2458
2459         if (trusted) {
2460                 account_name_last = strlen(account_name);
2461                 if (account_name_last == 0) {
2462                         return NT_STATUS_INVALID_PARAMETER;
2463                 }
2464                 account_name_last--;
2465                 if (account_name[account_name_last] == '$') {
2466                         account_name[account_name_last] = '\0';
2467                 }
2468
2469                 status = pdb_get_trusted_domain(p->mem_ctx, account_name, &td);
2470                 if (!NT_STATUS_IS_OK(status)) {
2471                         return status;
2472                 }
2473
2474                 if (r->out.trust_info != NULL) {
2475                         trust_info = talloc_zero(p->mem_ctx, struct netr_TrustInfo);
2476                         if (trust_info == NULL) {
2477                                 return NT_STATUS_NO_MEMORY;
2478                         }
2479                         trust_info->count = 1;
2480
2481                         trust_info->data = talloc_array(trust_info, uint32_t, 1);
2482                         if (trust_info->data == NULL) {
2483                                 return NT_STATUS_NO_MEMORY;
2484                         }
2485                         trust_info->data[0] = td->trust_attributes;
2486
2487                         *r->out.trust_info = trust_info;
2488                 }
2489
2490                 new_owf_enc = talloc_zero(p->mem_ctx, struct samr_Password);
2491                 old_owf_enc = talloc_zero(p->mem_ctx, struct samr_Password);
2492                 if (new_owf_enc == NULL || old_owf_enc == NULL) {
2493                         return NT_STATUS_NO_MEMORY;
2494                 }
2495
2496 /* TODO: which trustAuth shall we use if we have in/out trust or do they have to
2497  * be equal ? */
2498                 if (td->trust_direction & NETR_TRUST_FLAG_INBOUND) {
2499                         trustAuth_blob = td->trust_auth_incoming;
2500                 } else if (td->trust_direction & NETR_TRUST_FLAG_OUTBOUND) {
2501                         trustAuth_blob = td->trust_auth_outgoing;
2502                 }
2503
2504                 session_key.data = creds->session_key;
2505                 session_key.length = sizeof(creds->session_key);
2506                 status = get_password_from_trustAuth(p->mem_ctx, &trustAuth_blob,
2507                                                      &session_key,
2508                                                      new_owf_enc, old_owf_enc);
2509
2510                 if (!NT_STATUS_IS_OK(status)) {
2511                         return status;
2512                 }
2513
2514                 r->out.new_owf_password = new_owf_enc;
2515                 r->out.old_owf_password = old_owf_enc;
2516         } else {
2517 /* TODO: look for machine password */
2518                 r->out.new_owf_password = NULL;
2519                 r->out.old_owf_password = NULL;
2520
2521                 return NT_STATUS_NOT_IMPLEMENTED;
2522         }
2523
2524         return NT_STATUS_OK;
2525 }
2526
2527 /****************************************************************
2528 ****************************************************************/
2529
2530 NTSTATUS _netr_Unused47(struct pipes_struct *p,
2531                         struct netr_Unused47 *r)
2532 {
2533         p->rng_fault_state = true;
2534         return NT_STATUS_NOT_IMPLEMENTED;
2535 }
2536
2537 /****************************************************************
2538 ****************************************************************/
2539
2540 NTSTATUS _netr_DsrUpdateReadOnlyServerDnsRecords(struct pipes_struct *p,
2541                                                  struct netr_DsrUpdateReadOnlyServerDnsRecords *r)
2542 {
2543         p->rng_fault_state = true;
2544         return NT_STATUS_NOT_IMPLEMENTED;
2545 }