s3: Include uid_wrapper where it is missing.
[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;
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                 DEBUG(2,("_netr_ServerPasswordSet2: netlogon_creds_server_step "
1305                         "failed. Rejecting auth request from client %s machine account %s\n",
1306                         r->in.computer_name, creds->computer_name));
1307                 TALLOC_FREE(creds);
1308                 return status;
1309         }
1310
1311         memcpy(password_buf.data, r->in.new_password->data, 512);
1312         SIVAL(password_buf.data, 512, r->in.new_password->length);
1313         netlogon_creds_arcfour_crypt(creds, password_buf.data, 516);
1314
1315         if (!extract_pw_from_buffer(p->mem_ctx, password_buf.data, &plaintext)) {
1316                 return NT_STATUS_WRONG_PASSWORD;
1317         }
1318
1319         mdfour(nt_hash.hash, plaintext.data, plaintext.length);
1320
1321         status = netr_set_machine_account_password(p->mem_ctx,
1322                                                    p->session_info,
1323                                                    p->msg_ctx,
1324                                                    creds->account_name,
1325                                                    &nt_hash);
1326         return status;
1327 }
1328
1329 /*************************************************************************
1330  _netr_LogonSamLogoff
1331  *************************************************************************/
1332
1333 NTSTATUS _netr_LogonSamLogoff(struct pipes_struct *p,
1334                               struct netr_LogonSamLogoff *r)
1335 {
1336         NTSTATUS status;
1337         struct netlogon_creds_CredentialState *creds;
1338
1339         become_root();
1340         status = netr_creds_server_step_check(p, p->mem_ctx,
1341                                               r->in.computer_name,
1342                                               r->in.credential,
1343                                               r->out.return_authenticator,
1344                                               &creds);
1345         unbecome_root();
1346
1347         return status;
1348 }
1349
1350 static NTSTATUS _netr_LogonSamLogon_check(const struct netr_LogonSamLogonEx *r)
1351 {
1352         switch (r->in.logon_level) {
1353         case NetlogonInteractiveInformation:
1354         case NetlogonServiceInformation:
1355         case NetlogonInteractiveTransitiveInformation:
1356         case NetlogonServiceTransitiveInformation:
1357                 if (r->in.logon->password == NULL) {
1358                         return NT_STATUS_INVALID_PARAMETER;
1359                 }
1360
1361                 switch (r->in.validation_level) {
1362                 case NetlogonValidationSamInfo:  /* 2 */
1363                 case NetlogonValidationSamInfo2: /* 3 */
1364                         break;
1365                 case NetlogonValidationSamInfo4: /* 6 */
1366                         if ((pdb_capabilities() & PDB_CAP_ADS) == 0) {
1367                                 DEBUG(10,("Not adding validation info level 6 "
1368                                    "without ADS passdb backend\n"));
1369                                 return NT_STATUS_INVALID_INFO_CLASS;
1370                         }
1371                         break;
1372                 default:
1373                         return NT_STATUS_INVALID_INFO_CLASS;
1374                 }
1375
1376                 break;
1377         case NetlogonNetworkInformation:
1378         case NetlogonNetworkTransitiveInformation:
1379                 if (r->in.logon->network == NULL) {
1380                         return NT_STATUS_INVALID_PARAMETER;
1381                 }
1382
1383                 switch (r->in.validation_level) {
1384                 case NetlogonValidationSamInfo:  /* 2 */
1385                 case NetlogonValidationSamInfo2: /* 3 */
1386                         break;
1387                 case NetlogonValidationSamInfo4: /* 6 */
1388                         if ((pdb_capabilities() & PDB_CAP_ADS) == 0) {
1389                                 DEBUG(10,("Not adding validation info level 6 "
1390                                    "without ADS passdb backend\n"));
1391                                 return NT_STATUS_INVALID_INFO_CLASS;
1392                         }
1393                         break;
1394                 default:
1395                         return NT_STATUS_INVALID_INFO_CLASS;
1396                 }
1397
1398                 break;
1399
1400         case NetlogonGenericInformation:
1401                 if (r->in.logon->generic == NULL) {
1402                         return NT_STATUS_INVALID_PARAMETER;
1403                 }
1404
1405                 /* we don't support this here */
1406                 return NT_STATUS_INVALID_PARAMETER;
1407 #if 0
1408                 switch (r->in.validation_level) {
1409                 /* TODO: case NetlogonValidationGenericInfo: 4 */
1410                 case NetlogonValidationGenericInfo2: /* 5 */
1411                         break;
1412                 default:
1413                         return NT_STATUS_INVALID_INFO_CLASS;
1414                 }
1415
1416                 break;
1417 #endif
1418         default:
1419                 return NT_STATUS_INVALID_PARAMETER;
1420         }
1421
1422         return NT_STATUS_OK;
1423 }
1424
1425 /*************************************************************************
1426  _netr_LogonSamLogon_base
1427  *************************************************************************/
1428
1429 static NTSTATUS _netr_LogonSamLogon_base(struct pipes_struct *p,
1430                                          struct netr_LogonSamLogonEx *r,
1431                                          struct netlogon_creds_CredentialState *creds)
1432 {
1433         NTSTATUS status = NT_STATUS_OK;
1434         union netr_LogonLevel *logon = r->in.logon;
1435         const char *nt_username, *nt_domain, *nt_workstation;
1436         struct auth_usersupplied_info *user_info = NULL;
1437         struct auth_serversupplied_info *server_info = NULL;
1438         struct auth_context *auth_context = NULL;
1439         uint8_t pipe_session_key[16];
1440         bool process_creds = true;
1441         const char *fn;
1442
1443         switch (p->opnum) {
1444                 case NDR_NETR_LOGONSAMLOGON:
1445                         process_creds = true;
1446                         fn = "_netr_LogonSamLogon";
1447                         break;
1448                 case NDR_NETR_LOGONSAMLOGONWITHFLAGS:
1449                         process_creds = true;
1450                         fn = "_netr_LogonSamLogonWithFlags";
1451                         break;
1452                 case NDR_NETR_LOGONSAMLOGONEX:
1453                         process_creds = false;
1454                         fn = "_netr_LogonSamLogonEx";
1455                         break;
1456                 default:
1457                         return NT_STATUS_INTERNAL_ERROR;
1458         }
1459
1460         *r->out.authoritative = true; /* authoritative response */
1461
1462         switch (r->in.validation_level) {
1463         case 2:
1464                 r->out.validation->sam2 = talloc_zero(p->mem_ctx, struct netr_SamInfo2);
1465                 if (!r->out.validation->sam2) {
1466                         return NT_STATUS_NO_MEMORY;
1467                 }
1468                 break;
1469         case 3:
1470                 r->out.validation->sam3 = talloc_zero(p->mem_ctx, struct netr_SamInfo3);
1471                 if (!r->out.validation->sam3) {
1472                         return NT_STATUS_NO_MEMORY;
1473                 }
1474                 break;
1475         case 6:
1476                 r->out.validation->sam6 = talloc_zero(p->mem_ctx, struct netr_SamInfo6);
1477                 if (!r->out.validation->sam6) {
1478                         return NT_STATUS_NO_MEMORY;
1479                 }
1480                 break;
1481         default:
1482                 DEBUG(0,("%s: bad validation_level value %d.\n",
1483                         fn, (int)r->in.validation_level));
1484                 return NT_STATUS_INVALID_INFO_CLASS;
1485         }
1486
1487         switch (r->in.logon_level) {
1488         case NetlogonInteractiveInformation:
1489         case NetlogonServiceInformation:
1490         case NetlogonInteractiveTransitiveInformation:
1491         case NetlogonServiceTransitiveInformation:
1492                 nt_username     = logon->password->identity_info.account_name.string ?
1493                                   logon->password->identity_info.account_name.string : "";
1494                 nt_domain       = logon->password->identity_info.domain_name.string ?
1495                                   logon->password->identity_info.domain_name.string : "";
1496                 nt_workstation  = logon->password->identity_info.workstation.string ?
1497                                   logon->password->identity_info.workstation.string : "";
1498
1499                 DEBUG(3,("SAM Logon (Interactive). Domain:[%s].  ", lp_workgroup()));
1500                 break;
1501         case NetlogonNetworkInformation:
1502         case NetlogonNetworkTransitiveInformation:
1503                 nt_username     = logon->network->identity_info.account_name.string ?
1504                                   logon->network->identity_info.account_name.string : "";
1505                 nt_domain       = logon->network->identity_info.domain_name.string ?
1506                                   logon->network->identity_info.domain_name.string : "";
1507                 nt_workstation  = logon->network->identity_info.workstation.string ?
1508                                   logon->network->identity_info.workstation.string : "";
1509
1510                 DEBUG(3,("SAM Logon (Network). Domain:[%s].  ", lp_workgroup()));
1511                 break;
1512         default:
1513                 DEBUG(2,("SAM Logon: unsupported switch value\n"));
1514                 return NT_STATUS_INVALID_INFO_CLASS;
1515         } /* end switch */
1516
1517         DEBUG(3,("User:[%s@%s] Requested Domain:[%s]\n", nt_username, nt_workstation, nt_domain));
1518         fstrcpy(current_user_info.smb_name, nt_username);
1519         sub_set_smb_name(nt_username);
1520
1521         DEBUG(5,("Attempting validation level %d for unmapped username %s.\n",
1522                 r->in.validation_level, nt_username));
1523
1524         status = NT_STATUS_OK;
1525
1526         switch (r->in.logon_level) {
1527         case NetlogonNetworkInformation:
1528         case NetlogonNetworkTransitiveInformation:
1529         {
1530                 const char *wksname = nt_workstation;
1531
1532                 status = make_auth_context_fixed(talloc_tos(), &auth_context,
1533                                                  logon->network->challenge);
1534                 if (!NT_STATUS_IS_OK(status)) {
1535                         return status;
1536                 }
1537
1538                 /* For a network logon, the workstation name comes in with two
1539                  * backslashes in the front. Strip them if they are there. */
1540
1541                 if (*wksname == '\\') wksname++;
1542                 if (*wksname == '\\') wksname++;
1543
1544                 /* Standard challenge/response authentication */
1545                 if (!make_user_info_netlogon_network(&user_info,
1546                                                      nt_username, nt_domain,
1547                                                      wksname,
1548                                                      p->remote_address,
1549                                                      logon->network->identity_info.parameter_control,
1550                                                      logon->network->lm.data,
1551                                                      logon->network->lm.length,
1552                                                      logon->network->nt.data,
1553                                                      logon->network->nt.length)) {
1554                         status = NT_STATUS_NO_MEMORY;
1555                 }
1556                 break;
1557         }
1558         case NetlogonInteractiveInformation:
1559         case NetlogonServiceInformation:
1560         case NetlogonInteractiveTransitiveInformation:
1561         case NetlogonServiceTransitiveInformation:
1562
1563                 /* 'Interactive' authentication, supplies the password in its
1564                    MD4 form, encrypted with the session key.  We will convert
1565                    this to challenge/response for the auth subsystem to chew
1566                    on */
1567         {
1568                 uint8_t chal[8];
1569
1570                 status = make_auth_context_subsystem(talloc_tos(),
1571                                                      &auth_context);
1572                 if (!NT_STATUS_IS_OK(status)) {
1573                         return status;
1574                 }
1575
1576                 auth_context->get_ntlm_challenge(auth_context, chal);
1577
1578                 if (!make_user_info_netlogon_interactive(&user_info,
1579                                                          nt_username, nt_domain,
1580                                                          nt_workstation,
1581                                                          p->remote_address,
1582                                                          logon->password->identity_info.parameter_control,
1583                                                          chal,
1584                                                          logon->password->lmpassword.hash,
1585                                                          logon->password->ntpassword.hash,
1586                                                          creds->session_key)) {
1587                         status = NT_STATUS_NO_MEMORY;
1588                 }
1589                 break;
1590         }
1591         default:
1592                 DEBUG(2,("SAM Logon: unsupported switch value\n"));
1593                 return NT_STATUS_INVALID_INFO_CLASS;
1594         } /* end switch */
1595
1596         if ( NT_STATUS_IS_OK(status) ) {
1597                 status = auth_context->check_ntlm_password(auth_context,
1598                         user_info, &server_info);
1599         }
1600
1601         TALLOC_FREE(auth_context);
1602         free_user_info(&user_info);
1603
1604         DEBUG(5,("%s: check_password returned status %s\n",
1605                   fn, nt_errstr(status)));
1606
1607         /* Check account and password */
1608
1609         if (!NT_STATUS_IS_OK(status)) {
1610                 /* If we don't know what this domain is, we need to
1611                    indicate that we are not authoritative.  This
1612                    allows the client to decide if it needs to try
1613                    a local user.  Fix by jpjanosi@us.ibm.com, #2976 */
1614                 if ( NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_USER)
1615                      && !strequal(nt_domain, get_global_sam_name())
1616                      && !is_trusted_domain(nt_domain) )
1617                         *r->out.authoritative = false; /* We are not authoritative */
1618
1619                 TALLOC_FREE(server_info);
1620                 return status;
1621         }
1622
1623         if (server_info->guest) {
1624                 /* We don't like guest domain logons... */
1625                 DEBUG(5,("%s: Attempted domain logon as GUEST "
1626                          "denied.\n", fn));
1627                 TALLOC_FREE(server_info);
1628                 return NT_STATUS_LOGON_FAILURE;
1629         }
1630
1631         /* This is the point at which, if the login was successful, that
1632            the SAM Local Security Authority should record that the user is
1633            logged in to the domain.  */
1634
1635         if (process_creds) {
1636                 /* Get the pipe session key from the creds. */
1637                 memcpy(pipe_session_key, creds->session_key, 16);
1638         } else {
1639                 struct schannel_state *schannel_auth;
1640                 /* Get the pipe session key from the schannel. */
1641                 if ((p->auth.auth_type != DCERPC_AUTH_TYPE_SCHANNEL)
1642                     || (p->auth.auth_ctx == NULL)) {
1643                         return NT_STATUS_INVALID_HANDLE;
1644                 }
1645
1646                 schannel_auth = talloc_get_type_abort(p->auth.auth_ctx,
1647                                                       struct schannel_state);
1648                 memcpy(pipe_session_key, schannel_auth->creds->session_key, 16);
1649         }
1650
1651         switch (r->in.validation_level) {
1652         case 2:
1653                 status = serverinfo_to_SamInfo2(server_info, pipe_session_key, 16,
1654                                                 r->out.validation->sam2);
1655                 break;
1656         case 3:
1657                 status = serverinfo_to_SamInfo3(server_info, pipe_session_key, 16,
1658                                                 r->out.validation->sam3);
1659                 break;
1660         case 6:
1661                 status = serverinfo_to_SamInfo6(server_info, pipe_session_key, 16,
1662                                                 r->out.validation->sam6);
1663                 break;
1664         }
1665
1666         TALLOC_FREE(server_info);
1667
1668         return status;
1669 }
1670
1671 /****************************************************************
1672  _netr_LogonSamLogonWithFlags
1673 ****************************************************************/
1674
1675 NTSTATUS _netr_LogonSamLogonWithFlags(struct pipes_struct *p,
1676                                       struct netr_LogonSamLogonWithFlags *r)
1677 {
1678         NTSTATUS status;
1679         struct netlogon_creds_CredentialState *creds;
1680         struct netr_LogonSamLogonEx r2;
1681         struct netr_Authenticator return_authenticator;
1682
1683         *r->out.authoritative = true;
1684
1685         r2.in.server_name       = r->in.server_name;
1686         r2.in.computer_name     = r->in.computer_name;
1687         r2.in.logon_level       = r->in.logon_level;
1688         r2.in.logon             = r->in.logon;
1689         r2.in.validation_level  = r->in.validation_level;
1690         r2.in.flags             = r->in.flags;
1691         r2.out.validation       = r->out.validation;
1692         r2.out.authoritative    = r->out.authoritative;
1693         r2.out.flags            = r->out.flags;
1694
1695         status = _netr_LogonSamLogon_check(&r2);
1696         if (!NT_STATUS_IS_OK(status)) {
1697                 return status;
1698         }
1699
1700         become_root();
1701         status = netr_creds_server_step_check(p, p->mem_ctx,
1702                                               r->in.computer_name,
1703                                               r->in.credential,
1704                                               &return_authenticator,
1705                                               &creds);
1706         unbecome_root();
1707         if (!NT_STATUS_IS_OK(status)) {
1708                 return status;
1709         }
1710
1711         status = _netr_LogonSamLogon_base(p, &r2, creds);
1712
1713         *r->out.return_authenticator = return_authenticator;
1714
1715         return status;
1716 }
1717
1718 /*************************************************************************
1719  _netr_LogonSamLogon
1720  *************************************************************************/
1721
1722 NTSTATUS _netr_LogonSamLogon(struct pipes_struct *p,
1723                              struct netr_LogonSamLogon *r)
1724 {
1725         NTSTATUS status;
1726         struct netr_LogonSamLogonWithFlags r2;
1727         uint32_t flags = 0;
1728
1729         r2.in.server_name               = r->in.server_name;
1730         r2.in.computer_name             = r->in.computer_name;
1731         r2.in.credential                = r->in.credential;
1732         r2.in.logon_level               = r->in.logon_level;
1733         r2.in.logon                     = r->in.logon;
1734         r2.in.validation_level          = r->in.validation_level;
1735         r2.in.return_authenticator      = r->in.return_authenticator;
1736         r2.in.flags                     = &flags;
1737         r2.out.validation               = r->out.validation;
1738         r2.out.authoritative            = r->out.authoritative;
1739         r2.out.flags                    = &flags;
1740         r2.out.return_authenticator     = r->out.return_authenticator;
1741
1742         status = _netr_LogonSamLogonWithFlags(p, &r2);
1743
1744         return status;
1745 }
1746
1747 /*************************************************************************
1748  _netr_LogonSamLogonEx
1749  - no credential chaining. Map into net sam logon.
1750  *************************************************************************/
1751
1752 NTSTATUS _netr_LogonSamLogonEx(struct pipes_struct *p,
1753                                struct netr_LogonSamLogonEx *r)
1754 {
1755         NTSTATUS status;
1756         struct netlogon_creds_CredentialState *creds = NULL;
1757         struct loadparm_context *lp_ctx;
1758
1759         *r->out.authoritative = true;
1760
1761         status = _netr_LogonSamLogon_check(r);
1762         if (!NT_STATUS_IS_OK(status)) {
1763                 return status;
1764         }
1765
1766         /* Only allow this if the pipe is protected. */
1767         if (p->auth.auth_type != DCERPC_AUTH_TYPE_SCHANNEL) {
1768                 DEBUG(0,("_netr_LogonSamLogonEx: client %s not using schannel for netlogon\n",
1769                         get_remote_machine_name() ));
1770                 return NT_STATUS_INVALID_PARAMETER;
1771         }
1772
1773         lp_ctx = loadparm_init_s3(p->mem_ctx, loadparm_s3_context());
1774         if (lp_ctx == NULL) {
1775                 DEBUG(0, ("loadparm_init_s3 failed\n"));
1776                 return NT_STATUS_INTERNAL_ERROR;
1777         }
1778
1779         become_root();
1780         status = schannel_get_creds_state(p->mem_ctx, lp_ctx,
1781                                           r->in.computer_name, &creds);
1782         unbecome_root();
1783         talloc_unlink(p->mem_ctx, lp_ctx);
1784
1785         if (!NT_STATUS_IS_OK(status)) {
1786                 return status;
1787         }
1788
1789         status = _netr_LogonSamLogon_base(p, r, creds);
1790         TALLOC_FREE(creds);
1791
1792         return status;
1793 }
1794
1795 /*************************************************************************
1796  _ds_enum_dom_trusts
1797  *************************************************************************/
1798 #if 0   /* JERRY -- not correct */
1799  NTSTATUS _ds_enum_dom_trusts(struct pipes_struct *p, DS_Q_ENUM_DOM_TRUSTS *q_u,
1800                              DS_R_ENUM_DOM_TRUSTS *r_u)
1801 {
1802         NTSTATUS status = NT_STATUS_OK;
1803
1804         /* TODO: According to MSDN, the can only be executed against a
1805            DC or domain member running Windows 2000 or later.  Need
1806            to test against a standalone 2k server and see what it
1807            does.  A windows 2000 DC includes its own domain in the
1808            list.  --jerry */
1809
1810         return status;
1811 }
1812 #endif  /* JERRY */
1813
1814
1815 /****************************************************************
1816 ****************************************************************/
1817
1818 WERROR _netr_LogonUasLogon(struct pipes_struct *p,
1819                            struct netr_LogonUasLogon *r)
1820 {
1821         p->rng_fault_state = true;
1822         return WERR_NOT_SUPPORTED;
1823 }
1824
1825 /****************************************************************
1826 ****************************************************************/
1827
1828 WERROR _netr_LogonUasLogoff(struct pipes_struct *p,
1829                             struct netr_LogonUasLogoff *r)
1830 {
1831         p->rng_fault_state = true;
1832         return WERR_NOT_SUPPORTED;
1833 }
1834
1835 /****************************************************************
1836 ****************************************************************/
1837
1838 NTSTATUS _netr_DatabaseDeltas(struct pipes_struct *p,
1839                               struct netr_DatabaseDeltas *r)
1840 {
1841         p->rng_fault_state = true;
1842         return NT_STATUS_NOT_IMPLEMENTED;
1843 }
1844
1845 /****************************************************************
1846 ****************************************************************/
1847
1848 NTSTATUS _netr_DatabaseSync(struct pipes_struct *p,
1849                             struct netr_DatabaseSync *r)
1850 {
1851         p->rng_fault_state = true;
1852         return NT_STATUS_NOT_IMPLEMENTED;
1853 }
1854
1855 /****************************************************************
1856 ****************************************************************/
1857
1858 NTSTATUS _netr_AccountDeltas(struct pipes_struct *p,
1859                              struct netr_AccountDeltas *r)
1860 {
1861         p->rng_fault_state = true;
1862         return NT_STATUS_NOT_IMPLEMENTED;
1863 }
1864
1865 /****************************************************************
1866 ****************************************************************/
1867
1868 NTSTATUS _netr_AccountSync(struct pipes_struct *p,
1869                            struct netr_AccountSync *r)
1870 {
1871         p->rng_fault_state = true;
1872         return NT_STATUS_NOT_IMPLEMENTED;
1873 }
1874
1875 /****************************************************************
1876 ****************************************************************/
1877
1878 static bool wb_getdcname(TALLOC_CTX *mem_ctx,
1879                          const char *domain,
1880                          const char **dcname,
1881                          uint32_t flags,
1882                          WERROR *werr)
1883 {
1884         wbcErr result;
1885         struct wbcDomainControllerInfo *dc_info = NULL;
1886
1887         result = wbcLookupDomainController(domain,
1888                                            flags,
1889                                            &dc_info);
1890         switch (result) {
1891         case WBC_ERR_SUCCESS:
1892                 break;
1893         case WBC_ERR_WINBIND_NOT_AVAILABLE:
1894                 return false;
1895         case WBC_ERR_DOMAIN_NOT_FOUND:
1896                 *werr = WERR_NO_SUCH_DOMAIN;
1897                 return true;
1898         default:
1899                 *werr = WERR_DOMAIN_CONTROLLER_NOT_FOUND;
1900                 return true;
1901         }
1902
1903         *dcname = talloc_strdup(mem_ctx, dc_info->dc_name);
1904         wbcFreeMemory(dc_info);
1905         if (!*dcname) {
1906                 *werr = WERR_NOMEM;
1907                 return false;
1908         }
1909
1910         *werr = WERR_OK;
1911
1912         return true;
1913 }
1914
1915 /****************************************************************
1916  _netr_GetDcName
1917 ****************************************************************/
1918
1919 WERROR _netr_GetDcName(struct pipes_struct *p,
1920                        struct netr_GetDcName *r)
1921 {
1922         NTSTATUS status;
1923         WERROR werr;
1924         uint32_t flags;
1925         struct netr_DsRGetDCNameInfo *info;
1926         bool ret;
1927
1928         ret = wb_getdcname(p->mem_ctx,
1929                            r->in.domainname,
1930                            r->out.dcname,
1931                            WBC_LOOKUP_DC_IS_FLAT_NAME |
1932                            WBC_LOOKUP_DC_RETURN_FLAT_NAME |
1933                            WBC_LOOKUP_DC_PDC_REQUIRED,
1934                            &werr);
1935         if (ret == true) {
1936                 return werr;
1937         }
1938
1939         flags = DS_PDC_REQUIRED | DS_IS_FLAT_NAME | DS_RETURN_FLAT_NAME;
1940
1941         status = dsgetdcname(p->mem_ctx,
1942                              p->msg_ctx,
1943                              r->in.domainname,
1944                              NULL,
1945                              NULL,
1946                              flags,
1947                              &info);
1948         if (!NT_STATUS_IS_OK(status)) {
1949                 return ntstatus_to_werror(status);
1950         }
1951
1952         *r->out.dcname = talloc_strdup(p->mem_ctx, info->dc_unc);
1953         talloc_free(info);
1954         if (!*r->out.dcname) {
1955                 return WERR_NOMEM;
1956         }
1957
1958         return WERR_OK;
1959 }
1960
1961 /****************************************************************
1962  _netr_GetAnyDCName
1963 ****************************************************************/
1964
1965 WERROR _netr_GetAnyDCName(struct pipes_struct *p,
1966                           struct netr_GetAnyDCName *r)
1967 {
1968         NTSTATUS status;
1969         WERROR werr;
1970         uint32_t flags;
1971         struct netr_DsRGetDCNameInfo *info;
1972         bool ret;
1973
1974         ret = wb_getdcname(p->mem_ctx,
1975                            r->in.domainname,
1976                            r->out.dcname,
1977                            WBC_LOOKUP_DC_IS_FLAT_NAME |
1978                            WBC_LOOKUP_DC_RETURN_FLAT_NAME,
1979                            &werr);
1980         if (ret == true) {
1981                 return werr;
1982         }
1983
1984         flags = DS_IS_FLAT_NAME | DS_RETURN_FLAT_NAME;
1985
1986         status = dsgetdcname(p->mem_ctx,
1987                              p->msg_ctx,
1988                              r->in.domainname,
1989                              NULL,
1990                              NULL,
1991                              flags,
1992                              &info);
1993         if (!NT_STATUS_IS_OK(status)) {
1994                 return ntstatus_to_werror(status);
1995         }
1996
1997         *r->out.dcname = talloc_strdup(p->mem_ctx, info->dc_unc);
1998         talloc_free(info);
1999         if (!*r->out.dcname) {
2000                 return WERR_NOMEM;
2001         }
2002
2003         return WERR_OK;
2004 }
2005
2006 /****************************************************************
2007 ****************************************************************/
2008
2009 NTSTATUS _netr_DatabaseSync2(struct pipes_struct *p,
2010                              struct netr_DatabaseSync2 *r)
2011 {
2012         p->rng_fault_state = true;
2013         return NT_STATUS_NOT_IMPLEMENTED;
2014 }
2015
2016 /****************************************************************
2017 ****************************************************************/
2018
2019 NTSTATUS _netr_DatabaseRedo(struct pipes_struct *p,
2020                             struct netr_DatabaseRedo *r)
2021 {
2022         p->rng_fault_state = true;
2023         return NT_STATUS_NOT_IMPLEMENTED;
2024 }
2025
2026 /****************************************************************
2027 ****************************************************************/
2028
2029 WERROR _netr_DsRGetDCName(struct pipes_struct *p,
2030                           struct netr_DsRGetDCName *r)
2031 {
2032         p->rng_fault_state = true;
2033         return WERR_NOT_SUPPORTED;
2034 }
2035
2036 /****************************************************************
2037 ****************************************************************/
2038
2039 NTSTATUS _netr_LogonGetCapabilities(struct pipes_struct *p,
2040                                     struct netr_LogonGetCapabilities *r)
2041 {
2042         return NT_STATUS_NOT_IMPLEMENTED;
2043 }
2044
2045 /****************************************************************
2046 ****************************************************************/
2047
2048 WERROR _netr_NETRLOGONSETSERVICEBITS(struct pipes_struct *p,
2049                                      struct netr_NETRLOGONSETSERVICEBITS *r)
2050 {
2051         p->rng_fault_state = true;
2052         return WERR_NOT_SUPPORTED;
2053 }
2054
2055 /****************************************************************
2056 ****************************************************************/
2057
2058 WERROR _netr_LogonGetTrustRid(struct pipes_struct *p,
2059                               struct netr_LogonGetTrustRid *r)
2060 {
2061         p->rng_fault_state = true;
2062         return WERR_NOT_SUPPORTED;
2063 }
2064
2065 /****************************************************************
2066 ****************************************************************/
2067
2068 WERROR _netr_NETRLOGONCOMPUTESERVERDIGEST(struct pipes_struct *p,
2069                                           struct netr_NETRLOGONCOMPUTESERVERDIGEST *r)
2070 {
2071         p->rng_fault_state = true;
2072         return WERR_NOT_SUPPORTED;
2073 }
2074
2075 /****************************************************************
2076 ****************************************************************/
2077
2078 WERROR _netr_NETRLOGONCOMPUTECLIENTDIGEST(struct pipes_struct *p,
2079                                           struct netr_NETRLOGONCOMPUTECLIENTDIGEST *r)
2080 {
2081         p->rng_fault_state = true;
2082         return WERR_NOT_SUPPORTED;
2083 }
2084
2085 /****************************************************************
2086 ****************************************************************/
2087
2088 WERROR _netr_DsRGetDCNameEx(struct pipes_struct *p,
2089                             struct netr_DsRGetDCNameEx *r)
2090 {
2091         p->rng_fault_state = true;
2092         return WERR_NOT_SUPPORTED;
2093 }
2094
2095 /****************************************************************
2096 ****************************************************************/
2097
2098 WERROR _netr_DsRGetSiteName(struct pipes_struct *p,
2099                             struct netr_DsRGetSiteName *r)
2100 {
2101         p->rng_fault_state = true;
2102         return WERR_NOT_SUPPORTED;
2103 }
2104
2105 /****************************************************************
2106 ****************************************************************/
2107
2108 NTSTATUS _netr_LogonGetDomainInfo(struct pipes_struct *p,
2109                                   struct netr_LogonGetDomainInfo *r)
2110 {
2111         p->rng_fault_state = true;
2112         return NT_STATUS_NOT_IMPLEMENTED;
2113 }
2114
2115 /****************************************************************
2116 ****************************************************************/
2117
2118 WERROR _netr_ServerPasswordGet(struct pipes_struct *p,
2119                                struct netr_ServerPasswordGet *r)
2120 {
2121         p->rng_fault_state = true;
2122         return WERR_NOT_SUPPORTED;
2123 }
2124
2125 /****************************************************************
2126 ****************************************************************/
2127
2128 WERROR _netr_NETRLOGONSENDTOSAM(struct pipes_struct *p,
2129                                 struct netr_NETRLOGONSENDTOSAM *r)
2130 {
2131         p->rng_fault_state = true;
2132         return WERR_NOT_SUPPORTED;
2133 }
2134
2135 /****************************************************************
2136 ****************************************************************/
2137
2138 WERROR _netr_DsRAddressToSitenamesW(struct pipes_struct *p,
2139                                     struct netr_DsRAddressToSitenamesW *r)
2140 {
2141         p->rng_fault_state = true;
2142         return WERR_NOT_SUPPORTED;
2143 }
2144
2145 /****************************************************************
2146 ****************************************************************/
2147
2148 WERROR _netr_DsRGetDCNameEx2(struct pipes_struct *p,
2149                              struct netr_DsRGetDCNameEx2 *r)
2150 {
2151         p->rng_fault_state = true;
2152         return WERR_NOT_SUPPORTED;
2153 }
2154
2155 /****************************************************************
2156 ****************************************************************/
2157
2158 WERROR _netr_NETRLOGONGETTIMESERVICEPARENTDOMAIN(struct pipes_struct *p,
2159                                                  struct netr_NETRLOGONGETTIMESERVICEPARENTDOMAIN *r)
2160 {
2161         p->rng_fault_state = true;
2162         return WERR_NOT_SUPPORTED;
2163 }
2164
2165 /****************************************************************
2166 ****************************************************************/
2167
2168 WERROR _netr_NetrEnumerateTrustedDomainsEx(struct pipes_struct *p,
2169                                            struct netr_NetrEnumerateTrustedDomainsEx *r)
2170 {
2171         p->rng_fault_state = true;
2172         return WERR_NOT_SUPPORTED;
2173 }
2174
2175 /****************************************************************
2176 ****************************************************************/
2177
2178 WERROR _netr_DsRAddressToSitenamesExW(struct pipes_struct *p,
2179                                       struct netr_DsRAddressToSitenamesExW *r)
2180 {
2181         p->rng_fault_state = true;
2182         return WERR_NOT_SUPPORTED;
2183 }
2184
2185 /****************************************************************
2186 ****************************************************************/
2187
2188 WERROR _netr_DsrGetDcSiteCoverageW(struct pipes_struct *p,
2189                                    struct netr_DsrGetDcSiteCoverageW *r)
2190 {
2191         p->rng_fault_state = true;
2192         return WERR_NOT_SUPPORTED;
2193 }
2194
2195 /****************************************************************
2196 ****************************************************************/
2197
2198 WERROR _netr_DsrEnumerateDomainTrusts(struct pipes_struct *p,
2199                                       struct netr_DsrEnumerateDomainTrusts *r)
2200 {
2201         p->rng_fault_state = true;
2202         return WERR_NOT_SUPPORTED;
2203 }
2204
2205 /****************************************************************
2206 ****************************************************************/
2207
2208 WERROR _netr_DsrDeregisterDNSHostRecords(struct pipes_struct *p,
2209                                          struct netr_DsrDeregisterDNSHostRecords *r)
2210 {
2211         p->rng_fault_state = true;
2212         return WERR_NOT_SUPPORTED;
2213 }
2214
2215 /****************************************************************
2216 ****************************************************************/
2217
2218 NTSTATUS _netr_ServerTrustPasswordsGet(struct pipes_struct *p,
2219                                        struct netr_ServerTrustPasswordsGet *r)
2220 {
2221         p->rng_fault_state = true;
2222         return NT_STATUS_NOT_IMPLEMENTED;
2223 }
2224
2225 /****************************************************************
2226 ****************************************************************/
2227
2228 WERROR _netr_DsRGetForestTrustInformation(struct pipes_struct *p,
2229                                           struct netr_DsRGetForestTrustInformation *r)
2230 {
2231         p->rng_fault_state = true;
2232         return WERR_NOT_SUPPORTED;
2233 }
2234
2235 /****************************************************************
2236 ****************************************************************/
2237
2238 static NTSTATUS fill_forest_trust_array(TALLOC_CTX *mem_ctx,
2239                                         struct lsa_ForestTrustInformation *info)
2240 {
2241         struct lsa_ForestTrustRecord *e;
2242         struct pdb_domain_info *dom_info;
2243         struct lsa_ForestTrustDomainInfo *domain_info;
2244
2245         dom_info = pdb_get_domain_info(mem_ctx);
2246         if (dom_info == NULL) {
2247                 return NT_STATUS_NO_MEMORY;
2248         }
2249
2250         info->count = 2;
2251         info->entries = talloc_array(info, struct lsa_ForestTrustRecord *, 2);
2252         if (info->entries == NULL) {
2253                 return NT_STATUS_NO_MEMORY;
2254         }
2255
2256         e = talloc(info, struct lsa_ForestTrustRecord);
2257         if (e == NULL) {
2258                 return NT_STATUS_NO_MEMORY;
2259         }
2260
2261         e->flags = 0;
2262         e->type = LSA_FOREST_TRUST_TOP_LEVEL_NAME;
2263         e->time = 0; /* so far always 0 in trces. */
2264         e->forest_trust_data.top_level_name.string = talloc_steal(info,
2265                                                                   dom_info->dns_forest);
2266
2267         info->entries[0] = e;
2268
2269         e = talloc(info, struct lsa_ForestTrustRecord);
2270         if (e == NULL) {
2271                 return NT_STATUS_NO_MEMORY;
2272         }
2273
2274         /* TODO: check if disabled and set flags accordingly */
2275         e->flags = 0;
2276         e->type = LSA_FOREST_TRUST_DOMAIN_INFO;
2277         e->time = 0; /* so far always 0 in traces. */
2278
2279         domain_info = &e->forest_trust_data.domain_info;
2280         domain_info->domain_sid = dom_sid_dup(info, &dom_info->sid);
2281
2282         domain_info->dns_domain_name.string = talloc_steal(info,
2283                                                            dom_info->dns_domain);
2284         domain_info->netbios_domain_name.string = talloc_steal(info,
2285                                                                dom_info->name);
2286
2287         info->entries[1] = e;
2288
2289         return NT_STATUS_OK;
2290 }
2291
2292 /****************************************************************
2293  _netr_GetForestTrustInformation
2294 ****************************************************************/
2295
2296 NTSTATUS _netr_GetForestTrustInformation(struct pipes_struct *p,
2297                                          struct netr_GetForestTrustInformation *r)
2298 {
2299         NTSTATUS status;
2300         struct netlogon_creds_CredentialState *creds;
2301         struct lsa_ForestTrustInformation *info, **info_ptr;
2302         struct loadparm_context *lp_ctx;
2303
2304         /* TODO: check server name */
2305
2306         lp_ctx = loadparm_init_s3(p->mem_ctx, loadparm_s3_context());
2307         if (lp_ctx == NULL) {
2308                 DEBUG(0, ("loadparm_init_s3 failed\n"));
2309                 return NT_STATUS_INTERNAL_ERROR;
2310         }
2311
2312         status = schannel_check_creds_state(p->mem_ctx, lp_ctx,
2313                                             r->in.computer_name,
2314                                             r->in.credential,
2315                                             r->out.return_authenticator,
2316                                             &creds);
2317         talloc_unlink(p->mem_ctx, lp_ctx);
2318         if (!NT_STATUS_IS_OK(status)) {
2319                 return status;
2320         }
2321
2322         if ((creds->secure_channel_type != SEC_CHAN_DNS_DOMAIN) &&
2323             (creds->secure_channel_type != SEC_CHAN_DOMAIN)) {
2324                 return NT_STATUS_NOT_IMPLEMENTED;
2325         }
2326
2327         info_ptr = talloc(p->mem_ctx, struct lsa_ForestTrustInformation *);
2328         if (!info_ptr) {
2329                 return NT_STATUS_NO_MEMORY;
2330         }
2331         info = talloc_zero(info_ptr, struct lsa_ForestTrustInformation);
2332         if (!info) {
2333                 return NT_STATUS_NO_MEMORY;
2334         }
2335
2336         status = fill_forest_trust_array(p->mem_ctx, info);
2337         if (!NT_STATUS_IS_OK(status)) {
2338                 return status;
2339         }
2340
2341         *info_ptr = info;
2342         r->out.forest_trust_info = info_ptr;
2343
2344         return NT_STATUS_OK;
2345 }
2346
2347 /****************************************************************
2348 ****************************************************************/
2349
2350 static NTSTATUS get_password_from_trustAuth(TALLOC_CTX *mem_ctx,
2351                                             const DATA_BLOB *trustAuth_blob,
2352                                             const DATA_BLOB *session_key,
2353                                             struct samr_Password *current_pw_enc,
2354                                             struct samr_Password *previous_pw_enc)
2355 {
2356         enum ndr_err_code ndr_err;
2357         struct trustAuthInOutBlob trustAuth;
2358
2359         ndr_err = ndr_pull_struct_blob_all(trustAuth_blob, mem_ctx, &trustAuth,
2360                                            (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
2361         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2362                 return NT_STATUS_UNSUCCESSFUL;
2363         }
2364
2365
2366         if (trustAuth.count != 0 && trustAuth.current.count != 0 &&
2367             trustAuth.current.array[0].AuthType == TRUST_AUTH_TYPE_CLEAR) {
2368                 mdfour(previous_pw_enc->hash,
2369                        trustAuth.current.array[0].AuthInfo.clear.password,
2370                        trustAuth.current.array[0].AuthInfo.clear.size);
2371         } else {
2372                 return NT_STATUS_UNSUCCESSFUL;
2373         }
2374
2375         arcfour_crypt_blob(current_pw_enc->hash, sizeof(current_pw_enc->hash),
2376                            session_key);
2377
2378         if (trustAuth.previous.count != 0 &&
2379             trustAuth.previous.array[0].AuthType == TRUST_AUTH_TYPE_CLEAR) {
2380                 mdfour(previous_pw_enc->hash,
2381                        trustAuth.previous.array[0].AuthInfo.clear.password,
2382                        trustAuth.previous.array[0].AuthInfo.clear.size);
2383         } else {
2384                 mdfour(previous_pw_enc->hash, NULL, 0);
2385         }
2386         arcfour_crypt_blob(previous_pw_enc->hash, sizeof(previous_pw_enc->hash),
2387                            session_key);
2388
2389         return NT_STATUS_OK;
2390 }
2391
2392 /****************************************************************
2393  _netr_ServerGetTrustInfo
2394 ****************************************************************/
2395
2396 NTSTATUS _netr_ServerGetTrustInfo(struct pipes_struct *p,
2397                                   struct netr_ServerGetTrustInfo *r)
2398 {
2399         NTSTATUS status;
2400         struct netlogon_creds_CredentialState *creds;
2401         char *account_name;
2402         size_t account_name_last;
2403         bool trusted;
2404         struct netr_TrustInfo *trust_info;
2405         struct pdb_trusted_domain *td;
2406         DATA_BLOB trustAuth_blob;
2407         struct samr_Password *new_owf_enc;
2408         struct samr_Password *old_owf_enc;
2409         DATA_BLOB session_key;
2410         struct loadparm_context *lp_ctx;
2411
2412         lp_ctx = loadparm_init_s3(p->mem_ctx, loadparm_s3_context());
2413         if (lp_ctx == NULL) {
2414                 DEBUG(0, ("loadparm_init_s3 failed\n"));
2415                 return NT_STATUS_INTERNAL_ERROR;
2416         }
2417
2418         /* TODO: check server name */
2419
2420         status = schannel_check_creds_state(p->mem_ctx, lp_ctx,
2421                                             r->in.computer_name,
2422                                             r->in.credential,
2423                                             r->out.return_authenticator,
2424                                             &creds);
2425         talloc_unlink(p->mem_ctx, lp_ctx);
2426         if (!NT_STATUS_IS_OK(status)) {
2427                 return status;
2428         }
2429
2430         account_name = talloc_strdup(p->mem_ctx, r->in.account_name);
2431         if (account_name == NULL) {
2432                 return NT_STATUS_NO_MEMORY;
2433         }
2434
2435         account_name_last = strlen(account_name);
2436         if (account_name_last == 0) {
2437                 return NT_STATUS_INVALID_PARAMETER;
2438         }
2439         account_name_last--;
2440         if (account_name[account_name_last] == '.') {
2441                 account_name[account_name_last] = '\0';
2442         }
2443
2444         if ((creds->secure_channel_type != SEC_CHAN_DNS_DOMAIN) &&
2445             (creds->secure_channel_type != SEC_CHAN_DOMAIN)) {
2446                 trusted = false;
2447         } else {
2448                 trusted = true;
2449         }
2450
2451
2452         if (trusted) {
2453                 account_name_last = strlen(account_name);
2454                 if (account_name_last == 0) {
2455                         return NT_STATUS_INVALID_PARAMETER;
2456                 }
2457                 account_name_last--;
2458                 if (account_name[account_name_last] == '$') {
2459                         account_name[account_name_last] = '\0';
2460                 }
2461
2462                 status = pdb_get_trusted_domain(p->mem_ctx, account_name, &td);
2463                 if (!NT_STATUS_IS_OK(status)) {
2464                         return status;
2465                 }
2466
2467                 if (r->out.trust_info != NULL) {
2468                         trust_info = talloc_zero(p->mem_ctx, struct netr_TrustInfo);
2469                         if (trust_info == NULL) {
2470                                 return NT_STATUS_NO_MEMORY;
2471                         }
2472                         trust_info->count = 1;
2473
2474                         trust_info->data = talloc_array(trust_info, uint32_t, 1);
2475                         if (trust_info->data == NULL) {
2476                                 return NT_STATUS_NO_MEMORY;
2477                         }
2478                         trust_info->data[0] = td->trust_attributes;
2479
2480                         *r->out.trust_info = trust_info;
2481                 }
2482
2483                 new_owf_enc = talloc_zero(p->mem_ctx, struct samr_Password);
2484                 old_owf_enc = talloc_zero(p->mem_ctx, struct samr_Password);
2485                 if (new_owf_enc == NULL || old_owf_enc == NULL) {
2486                         return NT_STATUS_NO_MEMORY;
2487                 }
2488
2489 /* TODO: which trustAuth shall we use if we have in/out trust or do they have to
2490  * be equal ? */
2491                 if (td->trust_direction & NETR_TRUST_FLAG_INBOUND) {
2492                         trustAuth_blob = td->trust_auth_incoming;
2493                 } else if (td->trust_direction & NETR_TRUST_FLAG_OUTBOUND) {
2494                         trustAuth_blob = td->trust_auth_outgoing;
2495                 }
2496
2497                 session_key.data = creds->session_key;
2498                 session_key.length = sizeof(creds->session_key);
2499                 status = get_password_from_trustAuth(p->mem_ctx, &trustAuth_blob,
2500                                                      &session_key,
2501                                                      new_owf_enc, old_owf_enc);
2502
2503                 if (!NT_STATUS_IS_OK(status)) {
2504                         return status;
2505                 }
2506
2507                 r->out.new_owf_password = new_owf_enc;
2508                 r->out.old_owf_password = old_owf_enc;
2509         } else {
2510 /* TODO: look for machine password */
2511                 r->out.new_owf_password = NULL;
2512                 r->out.old_owf_password = NULL;
2513
2514                 return NT_STATUS_NOT_IMPLEMENTED;
2515         }
2516
2517         return NT_STATUS_OK;
2518 }
2519
2520 /****************************************************************
2521 ****************************************************************/
2522
2523 NTSTATUS _netr_Unused47(struct pipes_struct *p,
2524                         struct netr_Unused47 *r)
2525 {
2526         p->rng_fault_state = true;
2527         return NT_STATUS_NOT_IMPLEMENTED;
2528 }
2529
2530 /****************************************************************
2531 ****************************************************************/
2532
2533 NTSTATUS _netr_DsrUpdateReadOnlyServerDnsRecords(struct pipes_struct *p,
2534                                                  struct netr_DsrUpdateReadOnlyServerDnsRecords *r)
2535 {
2536         p->rng_fault_state = true;
2537         return NT_STATUS_NOT_IMPLEMENTED;
2538 }