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