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