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