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