Windows 2008 (Longhorn) auth2 flag fixes.
[Samba/nascimento.git] / source3 / winbindd / winbindd_cm.c
blobdbc664da8c76fee5e0b982d6eeb25f95a911bccd
1 /*
2 Unix SMB/CIFS implementation.
4 Winbind daemon connection manager
6 Copyright (C) Tim Potter 2001
7 Copyright (C) Andrew Bartlett 2002
8 Copyright (C) Gerald (Jerry) Carter 2003-2005.
9 Copyright (C) Volker Lendecke 2004-2005
10 Copyright (C) Jeremy Allison 2006
12 This program is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation; either version 3 of the License, or
15 (at your option) any later version.
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License for more details.
22 You should have received a copy of the GNU General Public License
23 along with this program. If not, see <http://www.gnu.org/licenses/>.
27 We need to manage connections to domain controllers without having to
28 mess up the main winbindd code with other issues. The aim of the
29 connection manager is to:
31 - make connections to domain controllers and cache them
32 - re-establish connections when networks or servers go down
33 - centralise the policy on connection timeouts, domain controller
34 selection etc
35 - manage re-entrancy for when winbindd becomes able to handle
36 multiple outstanding rpc requests
38 Why not have connection management as part of the rpc layer like tng?
39 Good question. This code may morph into libsmb/rpc_cache.c or something
40 like that but at the moment it's simply staying as part of winbind. I
41 think the TNG architecture of forcing every user of the rpc layer to use
42 the connection caching system is a bad idea. It should be an optional
43 method of using the routines.
45 The TNG design is quite good but I disagree with some aspects of the
46 implementation. -tpot
51 TODO:
53 - I'm pretty annoyed by all the make_nmb_name() stuff. It should be
54 moved down into another function.
56 - Take care when destroying cli_structs as they can be shared between
57 various sam handles.
61 #include "includes.h"
62 #include "winbindd.h"
64 #undef DBGC_CLASS
65 #define DBGC_CLASS DBGC_WINBIND
67 struct dc_name_ip {
68 fstring name;
69 struct sockaddr_storage ss;
72 extern struct winbindd_methods reconnect_methods;
73 extern bool override_logfile;
75 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain);
76 static void set_dc_type_and_flags( struct winbindd_domain *domain );
77 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
78 struct dc_name_ip **dcs, int *num_dcs);
80 /****************************************************************
81 Child failed to find DC's. Reschedule check.
82 ****************************************************************/
84 static void msg_failed_to_go_online(struct messaging_context *msg,
85 void *private_data,
86 uint32_t msg_type,
87 struct server_id server_id,
88 DATA_BLOB *data)
90 struct winbindd_domain *domain;
91 const char *domainname = (const char *)data->data;
93 if (data->data == NULL || data->length == 0) {
94 return;
97 DEBUG(5,("msg_fail_to_go_online: received for domain %s.\n", domainname));
99 for (domain = domain_list(); domain; domain = domain->next) {
100 if (domain->internal) {
101 continue;
104 if (strequal(domain->name, domainname)) {
105 if (domain->online) {
106 /* We're already online, ignore. */
107 DEBUG(5,("msg_fail_to_go_online: domain %s "
108 "already online.\n", domainname));
109 continue;
112 /* Reschedule the online check. */
113 set_domain_offline(domain);
114 break;
119 /****************************************************************
120 Actually cause a reconnect from a message.
121 ****************************************************************/
123 static void msg_try_to_go_online(struct messaging_context *msg,
124 void *private_data,
125 uint32_t msg_type,
126 struct server_id server_id,
127 DATA_BLOB *data)
129 struct winbindd_domain *domain;
130 const char *domainname = (const char *)data->data;
132 if (data->data == NULL || data->length == 0) {
133 return;
136 DEBUG(5,("msg_try_to_go_online: received for domain %s.\n", domainname));
138 for (domain = domain_list(); domain; domain = domain->next) {
139 if (domain->internal) {
140 continue;
143 if (strequal(domain->name, domainname)) {
145 if (domain->online) {
146 /* We're already online, ignore. */
147 DEBUG(5,("msg_try_to_go_online: domain %s "
148 "already online.\n", domainname));
149 continue;
152 /* This call takes care of setting the online
153 flag to true if we connected, or re-adding
154 the offline handler if false. Bypasses online
155 check so always does network calls. */
157 init_dc_connection_network(domain);
158 break;
163 /****************************************************************
164 Fork a child to try and contact a DC. Do this as contacting a
165 DC requires blocking lookups and we don't want to block our
166 parent.
167 ****************************************************************/
169 static bool fork_child_dc_connect(struct winbindd_domain *domain)
171 struct dc_name_ip *dcs = NULL;
172 int num_dcs = 0;
173 TALLOC_CTX *mem_ctx = NULL;
174 pid_t child_pid;
175 pid_t parent_pid = sys_getpid();
177 /* Stop zombies */
178 CatchChild();
180 child_pid = sys_fork();
182 if (child_pid == -1) {
183 DEBUG(0, ("fork_child_dc_connect: Could not fork: %s\n", strerror(errno)));
184 return False;
187 if (child_pid != 0) {
188 /* Parent */
189 messaging_register(winbind_messaging_context(), NULL,
190 MSG_WINBIND_TRY_TO_GO_ONLINE,
191 msg_try_to_go_online);
192 messaging_register(winbind_messaging_context(), NULL,
193 MSG_WINBIND_FAILED_TO_GO_ONLINE,
194 msg_failed_to_go_online);
195 return True;
198 /* Child. */
200 /* Leave messages blocked - we will never process one. */
202 /* tdb needs special fork handling */
203 if (tdb_reopen_all(1) == -1) {
204 DEBUG(0,("tdb_reopen_all failed.\n"));
205 _exit(0);
208 close_conns_after_fork();
210 if (!override_logfile) {
211 char *logfile;
212 if (asprintf(&logfile, "%s/log.winbindd-dc-connect", get_dyn_LOGFILEBASE()) > 0) {
213 lp_set_logfile(logfile);
214 SAFE_FREE(logfile);
215 reopen_logs();
219 mem_ctx = talloc_init("fork_child_dc_connect");
220 if (!mem_ctx) {
221 DEBUG(0,("talloc_init failed.\n"));
222 _exit(0);
225 if ((!get_dcs(mem_ctx, domain, &dcs, &num_dcs)) || (num_dcs == 0)) {
226 /* Still offline ? Can't find DC's. */
227 messaging_send_buf(winbind_messaging_context(),
228 pid_to_procid(parent_pid),
229 MSG_WINBIND_FAILED_TO_GO_ONLINE,
230 (uint8 *)domain->name,
231 strlen(domain->name)+1);
232 _exit(0);
235 /* We got a DC. Send a message to our parent to get it to
236 try and do the same. */
238 messaging_send_buf(winbind_messaging_context(),
239 pid_to_procid(parent_pid),
240 MSG_WINBIND_TRY_TO_GO_ONLINE,
241 (uint8 *)domain->name,
242 strlen(domain->name)+1);
243 _exit(0);
246 /****************************************************************
247 Handler triggered if we're offline to try and detect a DC.
248 ****************************************************************/
250 static void check_domain_online_handler(struct event_context *ctx,
251 struct timed_event *te,
252 const struct timeval *now,
253 void *private_data)
255 struct winbindd_domain *domain =
256 (struct winbindd_domain *)private_data;
258 DEBUG(10,("check_domain_online_handler: called for domain "
259 "%s (online = %s)\n", domain->name,
260 domain->online ? "True" : "False" ));
262 TALLOC_FREE(domain->check_online_event);
264 /* Are we still in "startup" mode ? */
266 if (domain->startup && (now->tv_sec > domain->startup_time + 30)) {
267 /* No longer in "startup" mode. */
268 DEBUG(10,("check_domain_online_handler: domain %s no longer in 'startup' mode.\n",
269 domain->name ));
270 domain->startup = False;
273 /* We've been told to stay offline, so stay
274 that way. */
276 if (get_global_winbindd_state_offline()) {
277 DEBUG(10,("check_domain_online_handler: domain %s remaining globally offline\n",
278 domain->name ));
279 return;
282 /* Fork a child to test if it can contact a DC.
283 If it can then send ourselves a message to
284 cause a reconnect. */
286 fork_child_dc_connect(domain);
289 /****************************************************************
290 If we're still offline setup the timeout check.
291 ****************************************************************/
293 static void calc_new_online_timeout_check(struct winbindd_domain *domain)
295 int wbc = lp_winbind_cache_time();
297 if (domain->startup) {
298 domain->check_online_timeout = 10;
299 } else if (domain->check_online_timeout < wbc) {
300 domain->check_online_timeout = wbc;
304 /****************************************************************
305 Set domain offline and also add handler to put us back online
306 if we detect a DC.
307 ****************************************************************/
309 void set_domain_offline(struct winbindd_domain *domain)
311 DEBUG(10,("set_domain_offline: called for domain %s\n",
312 domain->name ));
314 TALLOC_FREE(domain->check_online_event);
316 if (domain->internal) {
317 DEBUG(3,("set_domain_offline: domain %s is internal - logic error.\n",
318 domain->name ));
319 return;
322 domain->online = False;
324 /* Offline domains are always initialized. They're
325 re-initialized when they go back online. */
327 domain->initialized = True;
329 /* We only add the timeout handler that checks and
330 allows us to go back online when we've not
331 been told to remain offline. */
333 if (get_global_winbindd_state_offline()) {
334 DEBUG(10,("set_domain_offline: domain %s remaining globally offline\n",
335 domain->name ));
336 return;
339 /* If we're in statup mode, check again in 10 seconds, not in
340 lp_winbind_cache_time() seconds (which is 5 mins by default). */
342 calc_new_online_timeout_check(domain);
344 domain->check_online_event = event_add_timed(winbind_event_context(),
345 NULL,
346 timeval_current_ofs(domain->check_online_timeout,0),
347 "check_domain_online_handler",
348 check_domain_online_handler,
349 domain);
351 /* The above *has* to succeed for winbindd to work. */
352 if (!domain->check_online_event) {
353 smb_panic("set_domain_offline: failed to add online handler");
356 DEBUG(10,("set_domain_offline: added event handler for domain %s\n",
357 domain->name ));
359 /* Send an offline message to the idmap child when our
360 primary domain goes offline */
362 if ( domain->primary ) {
363 struct winbindd_child *idmap = idmap_child();
365 if ( idmap->pid != 0 ) {
366 messaging_send_buf(winbind_messaging_context(),
367 pid_to_procid(idmap->pid),
368 MSG_WINBIND_OFFLINE,
369 (uint8 *)domain->name,
370 strlen(domain->name)+1);
374 return;
377 /****************************************************************
378 Set domain online - if allowed.
379 ****************************************************************/
381 static void set_domain_online(struct winbindd_domain *domain)
383 struct timeval now;
385 DEBUG(10,("set_domain_online: called for domain %s\n",
386 domain->name ));
388 if (domain->internal) {
389 DEBUG(3,("set_domain_online: domain %s is internal - logic error.\n",
390 domain->name ));
391 return;
394 if (get_global_winbindd_state_offline()) {
395 DEBUG(10,("set_domain_online: domain %s remaining globally offline\n",
396 domain->name ));
397 return;
400 winbindd_set_locator_kdc_envs(domain);
402 /* If we are waiting to get a krb5 ticket, trigger immediately. */
403 GetTimeOfDay(&now);
404 set_event_dispatch_time(winbind_event_context(),
405 "krb5_ticket_gain_handler", now);
407 /* Ok, we're out of any startup mode now... */
408 domain->startup = False;
410 if (domain->online == False) {
411 /* We were offline - now we're online. We default to
412 using the MS-RPC backend if we started offline,
413 and if we're going online for the first time we
414 should really re-initialize the backends and the
415 checks to see if we're talking to an AD or NT domain.
418 domain->initialized = False;
420 /* 'reconnect_methods' is the MS-RPC backend. */
421 if (domain->backend == &reconnect_methods) {
422 domain->backend = NULL;
426 /* Ensure we have no online timeout checks. */
427 domain->check_online_timeout = 0;
428 TALLOC_FREE(domain->check_online_event);
430 /* Ensure we ignore any pending child messages. */
431 messaging_deregister(winbind_messaging_context(),
432 MSG_WINBIND_TRY_TO_GO_ONLINE, NULL);
433 messaging_deregister(winbind_messaging_context(),
434 MSG_WINBIND_FAILED_TO_GO_ONLINE, NULL);
436 domain->online = True;
438 /* Send an online message to the idmap child when our
439 primary domain comes online */
441 if ( domain->primary ) {
442 struct winbindd_child *idmap = idmap_child();
444 if ( idmap->pid != 0 ) {
445 messaging_send_buf(winbind_messaging_context(),
446 pid_to_procid(idmap->pid),
447 MSG_WINBIND_ONLINE,
448 (uint8 *)domain->name,
449 strlen(domain->name)+1);
453 return;
456 /****************************************************************
457 Requested to set a domain online.
458 ****************************************************************/
460 void set_domain_online_request(struct winbindd_domain *domain)
462 struct timeval tev;
464 DEBUG(10,("set_domain_online_request: called for domain %s\n",
465 domain->name ));
467 if (get_global_winbindd_state_offline()) {
468 DEBUG(10,("set_domain_online_request: domain %s remaining globally offline\n",
469 domain->name ));
470 return;
473 /* We've been told it's safe to go online and
474 try and connect to a DC. But I don't believe it
475 because network manager seems to lie.
476 Wait at least 5 seconds. Heuristics suck... */
478 if (!domain->check_online_event) {
479 /* If we've come from being globally offline we
480 don't have a check online event handler set.
481 We need to add one now we're trying to go
482 back online. */
484 DEBUG(10,("set_domain_online_request: domain %s was globally offline.\n",
485 domain->name ));
487 domain->check_online_event = event_add_timed(winbind_event_context(),
488 NULL,
489 timeval_current_ofs(5, 0),
490 "check_domain_online_handler",
491 check_domain_online_handler,
492 domain);
494 /* The above *has* to succeed for winbindd to work. */
495 if (!domain->check_online_event) {
496 smb_panic("set_domain_online_request: failed to add online handler");
500 GetTimeOfDay(&tev);
502 /* Go into "startup" mode again. */
503 domain->startup_time = tev.tv_sec;
504 domain->startup = True;
506 tev.tv_sec += 5;
508 set_event_dispatch_time(winbind_event_context(), "check_domain_online_handler", tev);
511 /****************************************************************
512 Add -ve connection cache entries for domain and realm.
513 ****************************************************************/
515 void winbind_add_failed_connection_entry(const struct winbindd_domain *domain,
516 const char *server,
517 NTSTATUS result)
519 add_failed_connection_entry(domain->name, server, result);
520 /* If this was the saf name for the last thing we talked to,
521 remove it. */
522 saf_delete(domain->name);
523 if (*domain->alt_name) {
524 add_failed_connection_entry(domain->alt_name, server, result);
525 saf_delete(domain->alt_name);
527 winbindd_unset_locator_kdc_env(domain);
530 /* Choose between anonymous or authenticated connections. We need to use
531 an authenticated connection if DCs have the RestrictAnonymous registry
532 entry set > 0, or the "Additional restrictions for anonymous
533 connections" set in the win2k Local Security Policy.
535 Caller to free() result in domain, username, password
538 static void cm_get_ipc_userpass(char **username, char **domain, char **password)
540 *username = (char *)secrets_fetch(SECRETS_AUTH_USER, NULL);
541 *domain = (char *)secrets_fetch(SECRETS_AUTH_DOMAIN, NULL);
542 *password = (char *)secrets_fetch(SECRETS_AUTH_PASSWORD, NULL);
544 if (*username && **username) {
546 if (!*domain || !**domain)
547 *domain = smb_xstrdup(lp_workgroup());
549 if (!*password || !**password)
550 *password = smb_xstrdup("");
552 DEBUG(3, ("cm_get_ipc_userpass: Retrieved auth-user from secrets.tdb [%s\\%s]\n",
553 *domain, *username));
555 } else {
556 DEBUG(3, ("cm_get_ipc_userpass: No auth-user defined\n"));
557 *username = smb_xstrdup("");
558 *domain = smb_xstrdup("");
559 *password = smb_xstrdup("");
563 static bool get_dc_name_via_netlogon(struct winbindd_domain *domain,
564 fstring dcname,
565 struct sockaddr_storage *dc_ss)
567 struct winbindd_domain *our_domain = NULL;
568 struct rpc_pipe_client *netlogon_pipe = NULL;
569 NTSTATUS result;
570 WERROR werr;
571 TALLOC_CTX *mem_ctx;
572 unsigned int orig_timeout;
573 char *tmp = NULL;
574 char *p;
576 /* Hmmmm. We can only open one connection to the NETLOGON pipe at the
577 * moment.... */
579 if (IS_DC) {
580 return False;
583 if (domain->primary) {
584 return False;
587 our_domain = find_our_domain();
589 if ((mem_ctx = talloc_init("get_dc_name_via_netlogon")) == NULL) {
590 return False;
593 result = cm_connect_netlogon(our_domain, &netlogon_pipe);
594 if (!NT_STATUS_IS_OK(result)) {
595 talloc_destroy(mem_ctx);
596 return False;
599 /* This call can take a long time - allow the server to time out.
600 35 seconds should do it. */
602 orig_timeout = cli_set_timeout(netlogon_pipe->cli, 35000);
604 if (our_domain->active_directory) {
605 struct DS_DOMAIN_CONTROLLER_INFO *domain_info = NULL;
607 werr = rpccli_netlogon_dsr_getdcname(netlogon_pipe,
608 mem_ctx,
609 our_domain->dcname,
610 domain->name,
611 NULL,
612 NULL,
613 DS_RETURN_DNS_NAME,
614 &domain_info);
615 if (W_ERROR_IS_OK(werr)) {
616 tmp = talloc_strdup(
617 mem_ctx, domain_info->domain_controller_name);
618 if (tmp == NULL) {
619 DEBUG(0, ("talloc_strdup failed\n"));
620 talloc_destroy(mem_ctx);
621 return false;
623 if (strlen(domain->alt_name) == 0) {
624 fstrcpy(domain->alt_name,
625 domain_info->domain_name);
627 if (strlen(domain->forest_name) == 0) {
628 fstrcpy(domain->forest_name,
629 domain_info->dns_forest_name);
632 } else {
634 werr = rpccli_netlogon_getanydcname(netlogon_pipe,
635 mem_ctx,
636 our_domain->dcname,
637 domain->name,
638 &tmp);
641 /* And restore our original timeout. */
642 cli_set_timeout(netlogon_pipe->cli, orig_timeout);
644 if (!W_ERROR_IS_OK(werr)) {
645 DEBUG(10, ("rpccli_netlogon_getanydcname failed: %s\n",
646 dos_errstr(werr)));
647 talloc_destroy(mem_ctx);
648 return False;
651 /* cli_netlogon_getanydcname gives us a name with \\ */
652 p = tmp;
653 if (*p == '\\') {
654 p+=1;
656 if (*p == '\\') {
657 p+=1;
660 fstrcpy(dcname, p);
662 talloc_destroy(mem_ctx);
664 DEBUG(10, ("rpccli_netlogon_getanydcname returned %s\n", dcname));
666 if (!resolve_name(dcname, dc_ss, 0x20)) {
667 return False;
670 return True;
674 * Helper function to assemble trust password and account name
676 static NTSTATUS get_trust_creds(const struct winbindd_domain *domain,
677 char **machine_password,
678 char **machine_account,
679 char **machine_krb5_principal)
681 const char *account_name;
683 if (!get_trust_pw_clear(domain->name, machine_password,
684 &account_name, NULL))
686 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
689 if ((machine_account != NULL) &&
690 (asprintf(machine_account, "%s$", account_name) == -1))
692 return NT_STATUS_NO_MEMORY;
695 /* this is at least correct when domain is our domain,
696 * which is the only case, when this is currently used: */
697 if (machine_krb5_principal != NULL)
699 if (asprintf(machine_krb5_principal, "%s$@%s",
700 account_name, domain->alt_name) == -1)
702 return NT_STATUS_NO_MEMORY;
705 strupper_m(*machine_krb5_principal);
708 return NT_STATUS_OK;
711 /************************************************************************
712 Given a fd with a just-connected TCP connection to a DC, open a connection
713 to the pipe.
714 ************************************************************************/
716 static NTSTATUS cm_prepare_connection(const struct winbindd_domain *domain,
717 const int sockfd,
718 const char *controller,
719 struct cli_state **cli,
720 bool *retry)
722 char *machine_password = NULL;
723 char *machine_krb5_principal = NULL;
724 char *machine_account = NULL;
725 char *ipc_username = NULL;
726 char *ipc_domain = NULL;
727 char *ipc_password = NULL;
729 bool got_mutex;
731 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
733 struct sockaddr peeraddr;
734 socklen_t peeraddr_len;
736 struct sockaddr_in *peeraddr_in = (struct sockaddr_in *)&peeraddr;
738 DEBUG(10,("cm_prepare_connection: connecting to DC %s for domain %s\n",
739 controller, domain->name ));
741 *retry = True;
743 got_mutex = secrets_named_mutex(controller,
744 WINBIND_SERVER_MUTEX_WAIT_TIME);
746 if (!got_mutex) {
747 DEBUG(0,("cm_prepare_connection: mutex grab failed for %s\n",
748 controller));
749 result = NT_STATUS_POSSIBLE_DEADLOCK;
750 goto done;
753 if ((*cli = cli_initialise()) == NULL) {
754 DEBUG(1, ("Could not cli_initialize\n"));
755 result = NT_STATUS_NO_MEMORY;
756 goto done;
759 (*cli)->timeout = 10000; /* 10 seconds */
760 (*cli)->fd = sockfd;
761 fstrcpy((*cli)->desthost, controller);
762 (*cli)->use_kerberos = True;
764 peeraddr_len = sizeof(peeraddr);
766 if ((getpeername((*cli)->fd, &peeraddr, &peeraddr_len) != 0) ||
767 (peeraddr_len != sizeof(struct sockaddr_in)) ||
768 (peeraddr_in->sin_family != PF_INET))
770 DEBUG(0,("cm_prepare_connection: %s\n", strerror(errno)));
771 result = NT_STATUS_UNSUCCESSFUL;
772 goto done;
775 if (ntohs(peeraddr_in->sin_port) == 139) {
776 struct nmb_name calling;
777 struct nmb_name called;
779 make_nmb_name(&calling, global_myname(), 0x0);
780 make_nmb_name(&called, "*SMBSERVER", 0x20);
782 if (!cli_session_request(*cli, &calling, &called)) {
783 DEBUG(8, ("cli_session_request failed for %s\n",
784 controller));
785 result = NT_STATUS_UNSUCCESSFUL;
786 goto done;
790 cli_setup_signing_state(*cli, Undefined);
792 if (!cli_negprot(*cli)) {
793 DEBUG(1, ("cli_negprot failed\n"));
794 result = NT_STATUS_UNSUCCESSFUL;
795 goto done;
798 if (!is_trusted_domain_situation(domain->name) &&
799 (*cli)->protocol >= PROTOCOL_NT1 &&
800 (*cli)->capabilities & CAP_EXTENDED_SECURITY)
802 ADS_STATUS ads_status;
804 result = get_trust_creds(domain, &machine_password,
805 &machine_account,
806 &machine_krb5_principal);
807 if (!NT_STATUS_IS_OK(result)) {
808 goto done;
811 if (lp_security() == SEC_ADS) {
813 /* Try a krb5 session */
815 (*cli)->use_kerberos = True;
816 DEBUG(5, ("connecting to %s from %s with kerberos principal "
817 "[%s]\n", controller, global_myname(),
818 machine_krb5_principal));
820 winbindd_set_locator_kdc_envs(domain);
822 ads_status = cli_session_setup_spnego(*cli,
823 machine_krb5_principal,
824 machine_password,
825 domain->name);
827 if (!ADS_ERR_OK(ads_status)) {
828 DEBUG(4,("failed kerberos session setup with %s\n",
829 ads_errstr(ads_status)));
832 result = ads_ntstatus(ads_status);
833 if (NT_STATUS_IS_OK(result)) {
834 /* Ensure creds are stored for NTLMSSP authenticated pipe access. */
835 cli_init_creds(*cli, machine_account, domain->name, machine_password);
836 goto session_setup_done;
840 /* Fall back to non-kerberos session setup using NTLMSSP SPNEGO with the machine account. */
841 (*cli)->use_kerberos = False;
843 DEBUG(5, ("connecting to %s from %s with username "
844 "[%s]\\[%s]\n", controller, global_myname(),
845 domain->name, machine_account));
847 ads_status = cli_session_setup_spnego(*cli,
848 machine_account,
849 machine_password,
850 domain->name);
851 if (!ADS_ERR_OK(ads_status)) {
852 DEBUG(4, ("authenticated session setup failed with %s\n",
853 ads_errstr(ads_status)));
856 result = ads_ntstatus(ads_status);
857 if (NT_STATUS_IS_OK(result)) {
858 /* Ensure creds are stored for NTLMSSP authenticated pipe access. */
859 cli_init_creds(*cli, machine_account, domain->name, machine_password);
860 goto session_setup_done;
864 /* Fall back to non-kerberos session setup with auth_user */
866 (*cli)->use_kerberos = False;
868 cm_get_ipc_userpass(&ipc_username, &ipc_domain, &ipc_password);
870 if ((((*cli)->sec_mode & NEGOTIATE_SECURITY_CHALLENGE_RESPONSE) != 0) &&
871 (strlen(ipc_username) > 0)) {
873 /* Only try authenticated if we have a username */
875 DEBUG(5, ("connecting to %s from %s with username "
876 "[%s]\\[%s]\n", controller, global_myname(),
877 ipc_domain, ipc_username));
879 if (NT_STATUS_IS_OK(cli_session_setup(
880 *cli, ipc_username,
881 ipc_password, strlen(ipc_password)+1,
882 ipc_password, strlen(ipc_password)+1,
883 ipc_domain))) {
884 /* Successful logon with given username. */
885 cli_init_creds(*cli, ipc_username, ipc_domain, ipc_password);
886 goto session_setup_done;
887 } else {
888 DEBUG(4, ("authenticated session setup with user %s\\%s failed.\n",
889 ipc_domain, ipc_username ));
893 /* Fall back to anonymous connection, this might fail later */
895 if (NT_STATUS_IS_OK(cli_session_setup(*cli, "", NULL, 0,
896 NULL, 0, ""))) {
897 DEBUG(5, ("Connected anonymously\n"));
898 cli_init_creds(*cli, "", "", "");
899 goto session_setup_done;
902 result = cli_nt_error(*cli);
904 if (NT_STATUS_IS_OK(result))
905 result = NT_STATUS_UNSUCCESSFUL;
907 /* We can't session setup */
909 goto done;
911 session_setup_done:
913 /* cache the server name for later connections */
915 saf_store( domain->name, (*cli)->desthost );
916 if (domain->alt_name && (*cli)->use_kerberos) {
917 saf_store( domain->alt_name, (*cli)->desthost );
920 winbindd_set_locator_kdc_envs(domain);
922 if (!cli_send_tconX(*cli, "IPC$", "IPC", "", 0)) {
924 result = cli_nt_error(*cli);
926 DEBUG(1,("failed tcon_X with %s\n", nt_errstr(result)));
928 if (NT_STATUS_IS_OK(result))
929 result = NT_STATUS_UNSUCCESSFUL;
931 goto done;
934 secrets_named_mutex_release(controller);
935 got_mutex = False;
936 *retry = False;
938 /* set the domain if empty; needed for schannel connections */
939 if ( !*(*cli)->domain ) {
940 fstrcpy( (*cli)->domain, domain->name );
943 result = NT_STATUS_OK;
945 done:
946 if (got_mutex) {
947 secrets_named_mutex_release(controller);
950 SAFE_FREE(machine_account);
951 SAFE_FREE(machine_password);
952 SAFE_FREE(machine_krb5_principal);
953 SAFE_FREE(ipc_username);
954 SAFE_FREE(ipc_domain);
955 SAFE_FREE(ipc_password);
957 if (!NT_STATUS_IS_OK(result)) {
958 winbind_add_failed_connection_entry(domain, controller, result);
959 if ((*cli) != NULL) {
960 cli_shutdown(*cli);
961 *cli = NULL;
965 return result;
968 static bool add_one_dc_unique(TALLOC_CTX *mem_ctx, const char *domain_name,
969 const char *dcname, struct sockaddr_storage *pss,
970 struct dc_name_ip **dcs, int *num)
972 if (!NT_STATUS_IS_OK(check_negative_conn_cache(domain_name, dcname))) {
973 DEBUG(10, ("DC %s was in the negative conn cache\n", dcname));
974 return False;
977 *dcs = TALLOC_REALLOC_ARRAY(mem_ctx, *dcs, struct dc_name_ip, (*num)+1);
979 if (*dcs == NULL)
980 return False;
982 fstrcpy((*dcs)[*num].name, dcname);
983 (*dcs)[*num].ss = *pss;
984 *num += 1;
985 return True;
988 static bool add_sockaddr_to_array(TALLOC_CTX *mem_ctx,
989 struct sockaddr_storage *pss, uint16 port,
990 struct sockaddr_storage **addrs, int *num)
992 *addrs = TALLOC_REALLOC_ARRAY(mem_ctx, *addrs, struct sockaddr_storage, (*num)+1);
994 if (*addrs == NULL) {
995 *num = 0;
996 return False;
999 (*addrs)[*num] = *pss;
1000 set_sockaddr_port(&(*addrs)[*num], port);
1002 *num += 1;
1003 return True;
1006 static void mailslot_name(struct in_addr dc_ip, fstring name)
1008 fstr_sprintf(name, "\\MAILSLOT\\NET\\GETDC%X", dc_ip.s_addr);
1011 static bool send_getdc_request(struct sockaddr_storage *dc_ss,
1012 const char *domain_name,
1013 const DOM_SID *sid)
1015 char outbuf[1024];
1016 struct in_addr dc_ip;
1017 char *p;
1018 fstring my_acct_name;
1019 fstring my_mailslot;
1020 size_t sid_size;
1022 if (dc_ss->ss_family != AF_INET) {
1023 return false;
1026 dc_ip = ((struct sockaddr_in *)dc_ss)->sin_addr;
1027 mailslot_name(dc_ip, my_mailslot);
1029 memset(outbuf, '\0', sizeof(outbuf));
1031 p = outbuf;
1033 SCVAL(p, 0, SAMLOGON);
1034 p++;
1036 SCVAL(p, 0, 0); /* Count pointer ... */
1037 p++;
1039 SIVAL(p, 0, 0); /* The sender's token ... */
1040 p += 2;
1042 p += dos_PutUniCode(p, global_myname(),
1043 sizeof(outbuf) - PTR_DIFF(p, outbuf), True);
1044 fstr_sprintf(my_acct_name, "%s$", global_myname());
1045 p += dos_PutUniCode(p, my_acct_name,
1046 sizeof(outbuf) - PTR_DIFF(p, outbuf), True);
1048 if (strlen(my_mailslot)+1 > sizeof(outbuf) - PTR_DIFF(p, outbuf)) {
1049 return false;
1052 memcpy(p, my_mailslot, strlen(my_mailslot)+1);
1053 p += strlen(my_mailslot)+1;
1055 if (sizeof(outbuf) - PTR_DIFF(p, outbuf) < 8) {
1056 return false;
1059 SIVAL(p, 0, 0x80);
1060 p+=4;
1062 sid_size = ndr_size_dom_sid(sid, 0);
1064 SIVAL(p, 0, sid_size);
1065 p+=4;
1067 p = ALIGN4(p, outbuf);
1068 if (PTR_DIFF(p, outbuf) > sizeof(outbuf)) {
1069 return false;
1072 if (sid_size + 8 > sizeof(outbuf) - PTR_DIFF(p, outbuf)) {
1073 return false;
1075 sid_linearize(p, sizeof(outbuf) - PTR_DIFF(p, outbuf), sid);
1077 p += sid_size;
1079 SIVAL(p, 0, 1);
1080 SSVAL(p, 4, 0xffff);
1081 SSVAL(p, 6, 0xffff);
1082 p+=8;
1084 return cli_send_mailslot(winbind_messaging_context(),
1085 False, "\\MAILSLOT\\NET\\NTLOGON", 0,
1086 outbuf, PTR_DIFF(p, outbuf),
1087 global_myname(), 0, domain_name, 0x1c,
1088 dc_ss);
1091 static bool receive_getdc_response(struct sockaddr_storage *dc_ss,
1092 const char *domain_name,
1093 fstring dc_name)
1095 struct packet_struct *packet;
1096 fstring my_mailslot;
1097 char *buf, *p;
1098 fstring dcname, user, domain;
1099 int len;
1100 struct in_addr dc_ip;
1102 if (dc_ss->ss_family != AF_INET) {
1103 return false;
1105 dc_ip = ((struct sockaddr_in *)dc_ss)->sin_addr;
1106 mailslot_name(dc_ip, my_mailslot);
1108 packet = receive_unexpected(DGRAM_PACKET, 0, my_mailslot);
1110 if (packet == NULL) {
1111 DEBUG(5, ("Did not receive packet for %s\n", my_mailslot));
1112 return False;
1115 DEBUG(5, ("Received packet for %s\n", my_mailslot));
1117 buf = packet->packet.dgram.data;
1118 len = packet->packet.dgram.datasize;
1120 if (len < 70) {
1121 /* 70 is a completely arbitrary value to make sure
1122 the SVAL below does not read uninitialized memory */
1123 DEBUG(3, ("GetDC got short response\n"));
1124 return False;
1127 /* This should be (buf-4)+SVAL(buf-4, smb_vwv12)... */
1128 p = buf+SVAL(buf, smb_vwv10);
1130 if (CVAL(p,0) != SAMLOGON_R) {
1131 DEBUG(8, ("GetDC got invalid response type %d\n", CVAL(p, 0)));
1132 return False;
1135 p+=2;
1136 pull_ucs2(buf, dcname, p, sizeof(dcname), PTR_DIFF(buf+len, p),
1137 STR_TERMINATE|STR_NOALIGN);
1138 p = skip_unibuf(p, PTR_DIFF(buf+len, p));
1139 pull_ucs2(buf, user, p, sizeof(dcname), PTR_DIFF(buf+len, p),
1140 STR_TERMINATE|STR_NOALIGN);
1141 p = skip_unibuf(p, PTR_DIFF(buf+len, p));
1142 pull_ucs2(buf, domain, p, sizeof(dcname), PTR_DIFF(buf+len, p),
1143 STR_TERMINATE|STR_NOALIGN);
1144 p = skip_unibuf(p, PTR_DIFF(buf+len, p));
1146 if (!strequal(domain, domain_name)) {
1147 DEBUG(3, ("GetDC: Expected domain %s, got %s\n",
1148 domain_name, domain));
1149 return False;
1152 p = dcname;
1153 if (*p == '\\') p += 1;
1154 if (*p == '\\') p += 1;
1156 fstrcpy(dc_name, p);
1158 DEBUG(10, ("GetDC gave name %s for domain %s\n",
1159 dc_name, domain));
1161 return True;
1164 /*******************************************************************
1165 convert an ip to a name
1166 *******************************************************************/
1168 static bool dcip_to_name(const struct winbindd_domain *domain,
1169 struct sockaddr_storage *pss,
1170 fstring name )
1172 struct ip_service ip_list;
1174 ip_list.ss = *pss;
1175 ip_list.port = 0;
1177 #ifdef WITH_ADS
1178 /* For active directory servers, try to get the ldap server name.
1179 None of these failures should be considered critical for now */
1181 if (lp_security() == SEC_ADS) {
1182 ADS_STRUCT *ads;
1183 char addr[INET6_ADDRSTRLEN];
1185 print_sockaddr(addr, sizeof(addr), pss);
1187 ads = ads_init(domain->alt_name, domain->name, NULL);
1188 ads->auth.flags |= ADS_AUTH_NO_BIND;
1190 if (ads_try_connect(ads, addr)) {
1191 /* We got a cldap packet. */
1192 fstrcpy(name, ads->config.ldap_server_name);
1193 namecache_store(name, 0x20, 1, &ip_list);
1195 DEBUG(10,("dcip_to_name: flags = 0x%x\n", (unsigned int)ads->config.flags));
1197 if (domain->primary && (ads->config.flags & ADS_KDC)) {
1198 if (ads_closest_dc(ads)) {
1199 char *sitename = sitename_fetch(ads->config.realm);
1201 /* We're going to use this KDC for this realm/domain.
1202 If we are using sites, then force the krb5 libs
1203 to use this KDC. */
1205 create_local_private_krb5_conf_for_domain(domain->alt_name,
1206 domain->name,
1207 sitename,
1208 pss);
1210 SAFE_FREE(sitename);
1211 } else {
1212 /* use an off site KDC */
1213 create_local_private_krb5_conf_for_domain(domain->alt_name,
1214 domain->name,
1215 NULL,
1216 pss);
1218 winbindd_set_locator_kdc_envs(domain);
1220 /* Ensure we contact this DC also. */
1221 saf_store( domain->name, name);
1222 saf_store( domain->alt_name, name);
1225 ads_destroy( &ads );
1226 return True;
1229 ads_destroy( &ads );
1231 #endif
1233 /* try GETDC requests next */
1235 if (send_getdc_request(pss, domain->name, &domain->sid)) {
1236 int i;
1237 smb_msleep(100);
1238 for (i=0; i<5; i++) {
1239 if (receive_getdc_response(pss, domain->name, name)) {
1240 namecache_store(name, 0x20, 1, &ip_list);
1241 return True;
1243 smb_msleep(500);
1247 /* try node status request */
1249 if ( name_status_find(domain->name, 0x1c, 0x20, pss, name) ) {
1250 namecache_store(name, 0x20, 1, &ip_list);
1251 return True;
1253 return False;
1256 /*******************************************************************
1257 Retreive a list of IP address for domain controllers. Fill in
1258 the dcs[] with results.
1259 *******************************************************************/
1261 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
1262 struct dc_name_ip **dcs, int *num_dcs)
1264 fstring dcname;
1265 struct sockaddr_storage ss;
1266 struct ip_service *ip_list = NULL;
1267 int iplist_size = 0;
1268 int i;
1269 bool is_our_domain;
1270 enum security_types sec = (enum security_types)lp_security();
1272 is_our_domain = strequal(domain->name, lp_workgroup());
1274 if ( !is_our_domain
1275 && get_dc_name_via_netlogon(domain, dcname, &ss)
1276 && add_one_dc_unique(mem_ctx, domain->name, dcname, &ss, dcs, num_dcs) )
1278 char addr[INET6_ADDRSTRLEN];
1279 print_sockaddr(addr, sizeof(addr), &ss);
1280 DEBUG(10, ("Retrieved DC %s at %s via netlogon\n",
1281 dcname, addr));
1282 return True;
1285 if (sec == SEC_ADS) {
1286 char *sitename = NULL;
1288 /* We need to make sure we know the local site before
1289 doing any DNS queries, as this will restrict the
1290 get_sorted_dc_list() call below to only fetching
1291 DNS records for the correct site. */
1293 /* Find any DC to get the site record.
1294 We deliberately don't care about the
1295 return here. */
1297 get_dc_name(domain->name, domain->alt_name, dcname, &ss);
1299 sitename = sitename_fetch(domain->alt_name);
1300 if (sitename) {
1302 /* Do the site-specific AD dns lookup first. */
1303 get_sorted_dc_list(domain->alt_name, sitename, &ip_list, &iplist_size, True);
1305 for ( i=0; i<iplist_size; i++ ) {
1306 char addr[INET6_ADDRSTRLEN];
1307 print_sockaddr(addr, sizeof(addr),
1308 &ip_list[i].ss);
1309 add_one_dc_unique(mem_ctx,
1310 domain->name,
1311 addr,
1312 &ip_list[i].ss,
1313 dcs,
1314 num_dcs);
1317 SAFE_FREE(ip_list);
1318 SAFE_FREE(sitename);
1319 iplist_size = 0;
1322 /* Now we add DCs from the main AD dns lookup. */
1323 get_sorted_dc_list(domain->alt_name, NULL, &ip_list, &iplist_size, True);
1325 for ( i=0; i<iplist_size; i++ ) {
1326 char addr[INET6_ADDRSTRLEN];
1327 print_sockaddr(addr, sizeof(addr),
1328 &ip_list[i].ss);
1329 add_one_dc_unique(mem_ctx,
1330 domain->name,
1331 addr,
1332 &ip_list[i].ss,
1333 dcs,
1334 num_dcs);
1338 /* try standard netbios queries if no ADS */
1340 if (iplist_size==0) {
1341 get_sorted_dc_list(domain->name, NULL, &ip_list, &iplist_size, False);
1344 /* FIXME!! this is where we should re-insert the GETDC requests --jerry */
1346 /* now add to the dc array. We'll wait until the last minute
1347 to look up the name of the DC. But we fill in the char* for
1348 the ip now in to make the failed connection cache work */
1350 for ( i=0; i<iplist_size; i++ ) {
1351 char addr[INET6_ADDRSTRLEN];
1352 print_sockaddr(addr, sizeof(addr),
1353 &ip_list[i].ss);
1354 add_one_dc_unique(mem_ctx, domain->name, addr,
1355 &ip_list[i].ss, dcs, num_dcs);
1358 SAFE_FREE( ip_list );
1360 return True;
1363 static bool find_new_dc(TALLOC_CTX *mem_ctx,
1364 struct winbindd_domain *domain,
1365 fstring dcname, struct sockaddr_storage *pss, int *fd)
1367 struct dc_name_ip *dcs = NULL;
1368 int num_dcs = 0;
1370 const char **dcnames = NULL;
1371 int num_dcnames = 0;
1373 struct sockaddr_storage *addrs = NULL;
1374 int num_addrs = 0;
1376 int i, fd_index;
1378 again:
1379 if (!get_dcs(mem_ctx, domain, &dcs, &num_dcs) || (num_dcs == 0))
1380 return False;
1382 for (i=0; i<num_dcs; i++) {
1384 if (!add_string_to_array(mem_ctx, dcs[i].name,
1385 &dcnames, &num_dcnames)) {
1386 return False;
1388 if (!add_sockaddr_to_array(mem_ctx, &dcs[i].ss, 445,
1389 &addrs, &num_addrs)) {
1390 return False;
1393 if (!add_string_to_array(mem_ctx, dcs[i].name,
1394 &dcnames, &num_dcnames)) {
1395 return False;
1397 if (!add_sockaddr_to_array(mem_ctx, &dcs[i].ss, 139,
1398 &addrs, &num_addrs)) {
1399 return False;
1403 if ((num_dcnames == 0) || (num_dcnames != num_addrs))
1404 return False;
1406 if ((addrs == NULL) || (dcnames == NULL))
1407 return False;
1409 /* 5 second timeout. */
1410 if (!open_any_socket_out(addrs, num_addrs, 5000, &fd_index, fd) ) {
1411 for (i=0; i<num_dcs; i++) {
1412 char ab[INET6_ADDRSTRLEN];
1413 print_sockaddr(ab, sizeof(ab), &dcs[i].ss);
1414 DEBUG(10, ("find_new_dc: open_any_socket_out failed for "
1415 "domain %s address %s. Error was %s\n",
1416 domain->name, ab, strerror(errno) ));
1417 winbind_add_failed_connection_entry(domain,
1418 dcs[i].name, NT_STATUS_UNSUCCESSFUL);
1420 return False;
1423 *pss = addrs[fd_index];
1425 if (*dcnames[fd_index] != '\0' && !is_ipaddress(dcnames[fd_index])) {
1426 /* Ok, we've got a name for the DC */
1427 fstrcpy(dcname, dcnames[fd_index]);
1428 return True;
1431 /* Try to figure out the name */
1432 if (dcip_to_name(domain, pss, dcname)) {
1433 return True;
1436 /* We can not continue without the DC's name */
1437 winbind_add_failed_connection_entry(domain, dcs[fd_index].name,
1438 NT_STATUS_UNSUCCESSFUL);
1439 goto again;
1442 static NTSTATUS cm_open_connection(struct winbindd_domain *domain,
1443 struct winbindd_cm_conn *new_conn)
1445 TALLOC_CTX *mem_ctx;
1446 NTSTATUS result;
1447 char *saf_servername = saf_fetch( domain->name );
1448 int retries;
1450 if ((mem_ctx = talloc_init("cm_open_connection")) == NULL) {
1451 SAFE_FREE(saf_servername);
1452 set_domain_offline(domain);
1453 return NT_STATUS_NO_MEMORY;
1456 /* we have to check the server affinity cache here since
1457 later we selecte a DC based on response time and not preference */
1459 /* Check the negative connection cache
1460 before talking to it. It going down may have
1461 triggered the reconnection. */
1463 if ( saf_servername && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, saf_servername))) {
1465 DEBUG(10,("cm_open_connection: saf_servername is '%s' for domain %s\n",
1466 saf_servername, domain->name ));
1468 /* convert an ip address to a name */
1469 if (is_ipaddress( saf_servername ) ) {
1470 fstring saf_name;
1471 struct sockaddr_storage ss;
1473 if (!interpret_string_addr(&ss, saf_servername,
1474 AI_NUMERICHOST)) {
1475 return NT_STATUS_UNSUCCESSFUL;
1477 if (dcip_to_name( domain, &ss, saf_name )) {
1478 fstrcpy( domain->dcname, saf_name );
1479 } else {
1480 winbind_add_failed_connection_entry(
1481 domain, saf_servername,
1482 NT_STATUS_UNSUCCESSFUL);
1484 } else {
1485 fstrcpy( domain->dcname, saf_servername );
1488 SAFE_FREE( saf_servername );
1491 for (retries = 0; retries < 3; retries++) {
1492 int fd = -1;
1493 bool retry = False;
1495 result = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1497 DEBUG(10,("cm_open_connection: dcname is '%s' for domain %s\n",
1498 domain->dcname, domain->name ));
1500 if (*domain->dcname
1501 && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, domain->dcname))
1502 && (resolve_name(domain->dcname, &domain->dcaddr, 0x20)))
1504 struct sockaddr_storage *addrs = NULL;
1505 int num_addrs = 0;
1506 int dummy = 0;
1508 if (!add_sockaddr_to_array(mem_ctx, &domain->dcaddr, 445, &addrs, &num_addrs)) {
1509 set_domain_offline(domain);
1510 talloc_destroy(mem_ctx);
1511 return NT_STATUS_NO_MEMORY;
1513 if (!add_sockaddr_to_array(mem_ctx, &domain->dcaddr, 139, &addrs, &num_addrs)) {
1514 set_domain_offline(domain);
1515 talloc_destroy(mem_ctx);
1516 return NT_STATUS_NO_MEMORY;
1519 /* 5 second timeout. */
1520 if (!open_any_socket_out(addrs, num_addrs, 5000, &dummy, &fd)) {
1521 fd = -1;
1525 if ((fd == -1)
1526 && !find_new_dc(mem_ctx, domain, domain->dcname, &domain->dcaddr, &fd))
1528 /* This is the one place where we will
1529 set the global winbindd offline state
1530 to true, if a "WINBINDD_OFFLINE" entry
1531 is found in the winbindd cache. */
1532 set_global_winbindd_state_offline();
1533 break;
1536 new_conn->cli = NULL;
1538 result = cm_prepare_connection(domain, fd, domain->dcname,
1539 &new_conn->cli, &retry);
1541 if (!retry)
1542 break;
1545 if (NT_STATUS_IS_OK(result)) {
1547 winbindd_set_locator_kdc_envs(domain);
1549 if (domain->online == False) {
1550 /* We're changing state from offline to online. */
1551 set_global_winbindd_state_online();
1553 set_domain_online(domain);
1554 } else {
1555 /* Ensure we setup the retry handler. */
1556 set_domain_offline(domain);
1559 talloc_destroy(mem_ctx);
1560 return result;
1563 /* Close down all open pipes on a connection. */
1565 void invalidate_cm_connection(struct winbindd_cm_conn *conn)
1567 /* We're closing down a possibly dead
1568 connection. Don't have impossibly long (10s) timeouts. */
1570 if (conn->cli) {
1571 cli_set_timeout(conn->cli, 1000); /* 1 second. */
1574 if (conn->samr_pipe != NULL) {
1575 if (!cli_rpc_pipe_close(conn->samr_pipe)) {
1576 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1577 if (conn->cli) {
1578 cli_set_timeout(conn->cli, 500);
1581 conn->samr_pipe = NULL;
1584 if (conn->lsa_pipe != NULL) {
1585 if (!cli_rpc_pipe_close(conn->lsa_pipe)) {
1586 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1587 if (conn->cli) {
1588 cli_set_timeout(conn->cli, 500);
1591 conn->lsa_pipe = NULL;
1594 if (conn->netlogon_pipe != NULL) {
1595 if (!cli_rpc_pipe_close(conn->netlogon_pipe)) {
1596 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1597 if (conn->cli) {
1598 cli_set_timeout(conn->cli, 500);
1601 conn->netlogon_pipe = NULL;
1604 if (conn->cli) {
1605 cli_shutdown(conn->cli);
1608 conn->cli = NULL;
1611 void close_conns_after_fork(void)
1613 struct winbindd_domain *domain;
1615 for (domain = domain_list(); domain; domain = domain->next) {
1616 if (domain->conn.cli == NULL)
1617 continue;
1619 if (domain->conn.cli->fd == -1)
1620 continue;
1622 close(domain->conn.cli->fd);
1623 domain->conn.cli->fd = -1;
1627 static bool connection_ok(struct winbindd_domain *domain)
1629 if (domain->conn.cli == NULL) {
1630 DEBUG(8, ("connection_ok: Connection to %s for domain %s has NULL "
1631 "cli!\n", domain->dcname, domain->name));
1632 return False;
1635 if (!domain->conn.cli->initialised) {
1636 DEBUG(3, ("connection_ok: Connection to %s for domain %s was never "
1637 "initialised!\n", domain->dcname, domain->name));
1638 return False;
1641 if (domain->conn.cli->fd == -1) {
1642 DEBUG(3, ("connection_ok: Connection to %s for domain %s has died or was "
1643 "never started (fd == -1)\n",
1644 domain->dcname, domain->name));
1645 return False;
1648 if (domain->online == False) {
1649 DEBUG(3, ("connection_ok: Domain %s is offline\n", domain->name));
1650 return False;
1653 return True;
1656 /* Initialize a new connection up to the RPC BIND.
1657 Bypass online status check so always does network calls. */
1659 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain)
1661 NTSTATUS result;
1663 /* Internal connections never use the network. */
1664 if (domain->internal) {
1665 domain->initialized = True;
1666 return NT_STATUS_OK;
1669 if (connection_ok(domain)) {
1670 if (!domain->initialized) {
1671 set_dc_type_and_flags(domain);
1673 return NT_STATUS_OK;
1676 invalidate_cm_connection(&domain->conn);
1678 result = cm_open_connection(domain, &domain->conn);
1680 if (NT_STATUS_IS_OK(result) && !domain->initialized) {
1681 set_dc_type_and_flags(domain);
1684 return result;
1687 NTSTATUS init_dc_connection(struct winbindd_domain *domain)
1689 if (domain->initialized && !domain->online) {
1690 /* We check for online status elsewhere. */
1691 return NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1694 return init_dc_connection_network(domain);
1697 /******************************************************************************
1698 Set the trust flags (direction and forest location) for a domain
1699 ******************************************************************************/
1701 static bool set_dc_type_and_flags_trustinfo( struct winbindd_domain *domain )
1703 struct winbindd_domain *our_domain;
1704 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
1705 struct ds_domain_trust *domains = NULL;
1706 int count = 0;
1707 int i;
1708 uint32 flags = (DS_DOMAIN_IN_FOREST |
1709 DS_DOMAIN_DIRECT_OUTBOUND |
1710 DS_DOMAIN_DIRECT_INBOUND);
1711 struct rpc_pipe_client *cli;
1712 TALLOC_CTX *mem_ctx = NULL;
1714 DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s\n", domain->name ));
1716 /* Our primary domain doesn't need to worry about trust flags.
1717 Force it to go through the network setup */
1718 if ( domain->primary ) {
1719 return False;
1722 our_domain = find_our_domain();
1724 if ( !connection_ok(our_domain) ) {
1725 DEBUG(3,("set_dc_type_and_flags_trustinfo: No connection to our domain!\n"));
1726 return False;
1729 /* This won't work unless our domain is AD */
1731 if ( !our_domain->active_directory ) {
1732 return False;
1735 /* Use DsEnumerateDomainTrusts to get us the trust direction
1736 and type */
1738 result = cm_connect_netlogon(our_domain, &cli);
1740 if (!NT_STATUS_IS_OK(result)) {
1741 DEBUG(5, ("set_dc_type_and_flags_trustinfo: Could not open "
1742 "a connection to %s for PIPE_NETLOGON (%s)\n",
1743 domain->name, nt_errstr(result)));
1744 return False;
1747 if ( (mem_ctx = talloc_init("set_dc_type_and_flags_trustinfo")) == NULL ) {
1748 DEBUG(0,("set_dc_type_and_flags_trustinfo: talloc_init() failed!\n"));
1749 return False;
1752 result = rpccli_ds_enum_domain_trusts(cli, mem_ctx,
1753 cli->cli->desthost,
1754 flags, &domains,
1755 (unsigned int *)&count);
1757 /* Now find the domain name and get the flags */
1759 for ( i=0; i<count; i++ ) {
1760 if ( strequal( domain->name, domains[i].netbios_domain ) ) {
1761 domain->domain_flags = domains[i].flags;
1762 domain->domain_type = domains[i].trust_type;
1763 domain->domain_trust_attribs = domains[i].trust_attributes;
1765 if ( domain->domain_type == DS_DOMAIN_TRUST_TYPE_UPLEVEL )
1766 domain->active_directory = True;
1768 /* This flag is only set if the domain is *our*
1769 primary domain and the primary domain is in
1770 native mode */
1772 domain->native_mode = (domain->domain_flags & DS_DOMAIN_NATIVE_MODE);
1774 DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s is %sin "
1775 "native mode.\n", domain->name,
1776 domain->native_mode ? "" : "NOT "));
1778 DEBUG(5,("set_dc_type_and_flags_trustinfo: domain %s is %s"
1779 "running active directory.\n", domain->name,
1780 domain->active_directory ? "" : "NOT "));
1783 domain->initialized = True;
1785 if ( !winbindd_can_contact_domain( domain) )
1786 domain->internal = True;
1788 break;
1792 talloc_destroy( mem_ctx );
1794 return domain->initialized;
1797 /******************************************************************************
1798 We can 'sense' certain things about the DC by it's replies to certain
1799 questions.
1801 This tells us if this particular remote server is Active Directory, and if it
1802 is native mode.
1803 ******************************************************************************/
1805 static void set_dc_type_and_flags_connect( struct winbindd_domain *domain )
1807 NTSTATUS result;
1808 DS_DOMINFO_CTR ctr;
1809 TALLOC_CTX *mem_ctx = NULL;
1810 struct rpc_pipe_client *cli;
1811 POLICY_HND pol;
1813 const char *domain_name = NULL;
1814 const char *dns_name = NULL;
1815 const char *forest_name = NULL;
1816 DOM_SID *dom_sid = NULL;
1818 ZERO_STRUCT( ctr );
1820 if (!connection_ok(domain)) {
1821 return;
1824 mem_ctx = talloc_init("set_dc_type_and_flags on domain %s\n",
1825 domain->name);
1826 if (!mem_ctx) {
1827 DEBUG(1, ("set_dc_type_and_flags_connect: talloc_init() failed\n"));
1828 return;
1831 DEBUG(5, ("set_dc_type_and_flags_connect: domain %s\n", domain->name ));
1833 cli = cli_rpc_pipe_open_noauth(domain->conn.cli, PI_LSARPC_DS,
1834 &result);
1836 if (cli == NULL) {
1837 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
1838 "PI_LSARPC_DS on domain %s: (%s)\n",
1839 domain->name, nt_errstr(result)));
1841 /* if this is just a non-AD domain we need to continue
1842 * identifying so that we can in the end return with
1843 * domain->initialized = True - gd */
1845 goto no_lsarpc_ds;
1848 result = rpccli_ds_getprimarydominfo(cli, mem_ctx,
1849 DsRolePrimaryDomainInfoBasic,
1850 &ctr);
1851 cli_rpc_pipe_close(cli);
1853 if (!NT_STATUS_IS_OK(result)) {
1854 DEBUG(5, ("set_dc_type_and_flags_connect: rpccli_ds_getprimarydominfo "
1855 "on domain %s failed: (%s)\n",
1856 domain->name, nt_errstr(result)));
1858 /* older samba3 DCs will return DCERPC_FAULT_OP_RNG_ERROR for
1859 * every opcode on the LSARPC_DS pipe, continue with
1860 * no_lsarpc_ds mode here as well to get domain->initialized
1861 * set - gd */
1863 if (NT_STATUS_V(result) == DCERPC_FAULT_OP_RNG_ERROR) {
1864 goto no_lsarpc_ds;
1867 TALLOC_FREE(mem_ctx);
1868 return;
1871 if ((ctr.basic->flags & DSROLE_PRIMARY_DS_RUNNING) &&
1872 !(ctr.basic->flags & DSROLE_PRIMARY_DS_MIXED_MODE)) {
1873 domain->native_mode = True;
1874 } else {
1875 domain->native_mode = False;
1878 no_lsarpc_ds:
1879 cli = cli_rpc_pipe_open_noauth(domain->conn.cli, PI_LSARPC, &result);
1881 if (cli == NULL) {
1882 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
1883 "PI_LSARPC on domain %s: (%s)\n",
1884 domain->name, nt_errstr(result)));
1885 cli_rpc_pipe_close(cli);
1886 TALLOC_FREE(mem_ctx);
1887 return;
1890 result = rpccli_lsa_open_policy2(cli, mem_ctx, True,
1891 SEC_RIGHTS_MAXIMUM_ALLOWED, &pol);
1893 if (NT_STATUS_IS_OK(result)) {
1894 /* This particular query is exactly what Win2k clients use
1895 to determine that the DC is active directory */
1896 result = rpccli_lsa_query_info_policy2(cli, mem_ctx, &pol,
1897 12, &domain_name,
1898 &dns_name, &forest_name,
1899 NULL, &dom_sid);
1902 if (NT_STATUS_IS_OK(result)) {
1903 domain->active_directory = True;
1905 if (domain_name)
1906 fstrcpy(domain->name, domain_name);
1908 if (dns_name)
1909 fstrcpy(domain->alt_name, dns_name);
1911 /* See if we can set some domain trust flags about
1912 ourself */
1914 if ( forest_name ) {
1915 fstrcpy(domain->forest_name, forest_name);
1917 if (strequal(domain->forest_name, domain->alt_name)) {
1918 domain->domain_flags = DS_DOMAIN_TREE_ROOT;
1922 if (dom_sid)
1923 sid_copy(&domain->sid, dom_sid);
1924 } else {
1925 domain->active_directory = False;
1927 result = rpccli_lsa_open_policy(cli, mem_ctx, True,
1928 SEC_RIGHTS_MAXIMUM_ALLOWED,
1929 &pol);
1931 if (!NT_STATUS_IS_OK(result))
1932 goto done;
1934 result = rpccli_lsa_query_info_policy(cli, mem_ctx,
1935 &pol, 5, &domain_name,
1936 &dom_sid);
1938 if (NT_STATUS_IS_OK(result)) {
1939 if (domain_name)
1940 fstrcpy(domain->name, domain_name);
1942 if (dom_sid)
1943 sid_copy(&domain->sid, dom_sid);
1946 done:
1948 DEBUG(5, ("set_dc_type_and_flags_connect: domain %s is %sin native mode.\n",
1949 domain->name, domain->native_mode ? "" : "NOT "));
1951 DEBUG(5,("set_dc_type_and_flags_connect: domain %s is %srunning active directory.\n",
1952 domain->name, domain->active_directory ? "" : "NOT "));
1954 cli_rpc_pipe_close(cli);
1956 TALLOC_FREE(mem_ctx);
1958 domain->initialized = True;
1961 /**********************************************************************
1962 Set the domain_flags (trust attributes, domain operating modes, etc...
1963 ***********************************************************************/
1965 static void set_dc_type_and_flags( struct winbindd_domain *domain )
1967 /* we always have to contact our primary domain */
1969 if ( domain->primary ) {
1970 DEBUG(10,("set_dc_type_and_flags: setting up flags for "
1971 "primary domain\n"));
1972 set_dc_type_and_flags_connect( domain );
1973 return;
1976 /* Use our DC to get the information if possible */
1978 if ( !set_dc_type_and_flags_trustinfo( domain ) ) {
1979 /* Otherwise, fallback to contacting the
1980 domain directly */
1981 set_dc_type_and_flags_connect( domain );
1984 return;
1989 /**********************************************************************
1990 ***********************************************************************/
1992 static bool cm_get_schannel_dcinfo(struct winbindd_domain *domain,
1993 struct dcinfo **ppdc)
1995 NTSTATUS result;
1996 struct rpc_pipe_client *netlogon_pipe;
1998 if (lp_client_schannel() == False) {
1999 return False;
2002 result = cm_connect_netlogon(domain, &netlogon_pipe);
2003 if (!NT_STATUS_IS_OK(result)) {
2004 return False;
2007 /* Return a pointer to the struct dcinfo from the
2008 netlogon pipe. */
2010 *ppdc = domain->conn.netlogon_pipe->dc;
2011 return True;
2014 NTSTATUS cm_connect_sam(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2015 struct rpc_pipe_client **cli, POLICY_HND *sam_handle)
2017 struct winbindd_cm_conn *conn;
2018 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2019 fstring conn_pwd;
2020 struct dcinfo *p_dcinfo;
2021 char *machine_password = NULL;
2022 char *machine_account = NULL;
2023 char *domain_name = NULL;
2025 result = init_dc_connection(domain);
2026 if (!NT_STATUS_IS_OK(result)) {
2027 return result;
2030 conn = &domain->conn;
2032 if (conn->samr_pipe != NULL) {
2033 goto done;
2037 * No SAMR pipe yet. Attempt to get an NTLMSSP SPNEGO authenticated
2038 * sign and sealed pipe using the machine account password by
2039 * preference. If we can't - try schannel, if that fails, try
2040 * anonymous.
2043 pwd_get_cleartext(&conn->cli->pwd, conn_pwd);
2044 if ((conn->cli->user_name[0] == '\0') ||
2045 (conn->cli->domain[0] == '\0') ||
2046 (conn_pwd[0] == '\0'))
2048 result = get_trust_creds(domain, &machine_password,
2049 &machine_account, NULL);
2050 if (!NT_STATUS_IS_OK(result)) {
2051 DEBUG(10, ("cm_connect_sam: No no user available for "
2052 "domain %s, trying schannel\n", conn->cli->domain));
2053 goto schannel;
2055 domain_name = domain->name;
2056 } else {
2057 machine_password = SMB_STRDUP(conn_pwd);
2058 machine_account = SMB_STRDUP(conn->cli->user_name);
2059 domain_name = conn->cli->domain;
2062 if (!machine_password || !machine_account) {
2063 result = NT_STATUS_NO_MEMORY;
2064 goto done;
2067 /* We have an authenticated connection. Use a NTLMSSP SPNEGO
2068 authenticated SAMR pipe with sign & seal. */
2069 conn->samr_pipe =
2070 cli_rpc_pipe_open_spnego_ntlmssp(conn->cli, PI_SAMR,
2071 PIPE_AUTH_LEVEL_PRIVACY,
2072 domain_name,
2073 machine_account,
2074 machine_password, &result);
2076 if (conn->samr_pipe == NULL) {
2077 DEBUG(10,("cm_connect_sam: failed to connect to SAMR "
2078 "pipe for domain %s using NTLMSSP "
2079 "authenticated pipe: user %s\\%s. Error was "
2080 "%s\n", domain->name, domain_name,
2081 machine_account, nt_errstr(result)));
2082 goto schannel;
2085 DEBUG(10,("cm_connect_sam: connected to SAMR pipe for "
2086 "domain %s using NTLMSSP authenticated "
2087 "pipe: user %s\\%s\n", domain->name,
2088 domain_name, machine_account));
2090 result = rpccli_samr_connect(conn->samr_pipe, mem_ctx,
2091 SEC_RIGHTS_MAXIMUM_ALLOWED,
2092 &conn->sam_connect_handle);
2093 if (NT_STATUS_IS_OK(result)) {
2094 goto open_domain;
2096 DEBUG(10,("cm_connect_sam: ntlmssp-sealed rpccli_samr_connect "
2097 "failed for domain %s, error was %s. Trying schannel\n",
2098 domain->name, nt_errstr(result) ));
2099 cli_rpc_pipe_close(conn->samr_pipe);
2101 schannel:
2103 /* Fall back to schannel if it's a W2K pre-SP1 box. */
2105 if (!cm_get_schannel_dcinfo(domain, &p_dcinfo)) {
2106 /* If this call fails - conn->cli can now be NULL ! */
2107 DEBUG(10, ("cm_connect_sam: Could not get schannel auth info "
2108 "for domain %s, trying anon\n", domain->name));
2109 goto anonymous;
2111 conn->samr_pipe = cli_rpc_pipe_open_schannel_with_key
2112 (conn->cli, PI_SAMR, PIPE_AUTH_LEVEL_PRIVACY,
2113 domain->name, p_dcinfo, &result);
2115 if (conn->samr_pipe == NULL) {
2116 DEBUG(10,("cm_connect_sam: failed to connect to SAMR pipe for "
2117 "domain %s using schannel. Error was %s\n",
2118 domain->name, nt_errstr(result) ));
2119 goto anonymous;
2121 DEBUG(10,("cm_connect_sam: connected to SAMR pipe for domain %s using "
2122 "schannel.\n", domain->name ));
2124 result = rpccli_samr_connect(conn->samr_pipe, mem_ctx,
2125 SEC_RIGHTS_MAXIMUM_ALLOWED,
2126 &conn->sam_connect_handle);
2127 if (NT_STATUS_IS_OK(result)) {
2128 goto open_domain;
2130 DEBUG(10,("cm_connect_sam: schannel-sealed rpccli_samr_connect failed "
2131 "for domain %s, error was %s. Trying anonymous\n",
2132 domain->name, nt_errstr(result) ));
2133 cli_rpc_pipe_close(conn->samr_pipe);
2135 anonymous:
2137 /* Finally fall back to anonymous. */
2138 conn->samr_pipe = cli_rpc_pipe_open_noauth(conn->cli, PI_SAMR,
2139 &result);
2141 if (conn->samr_pipe == NULL) {
2142 result = NT_STATUS_PIPE_NOT_AVAILABLE;
2143 goto done;
2146 result = rpccli_samr_connect(conn->samr_pipe, mem_ctx,
2147 SEC_RIGHTS_MAXIMUM_ALLOWED,
2148 &conn->sam_connect_handle);
2149 if (!NT_STATUS_IS_OK(result)) {
2150 DEBUG(10,("cm_connect_sam: rpccli_samr_connect failed "
2151 "for domain %s Error was %s\n",
2152 domain->name, nt_errstr(result) ));
2153 goto done;
2156 open_domain:
2157 result = rpccli_samr_open_domain(conn->samr_pipe,
2158 mem_ctx,
2159 &conn->sam_connect_handle,
2160 SEC_RIGHTS_MAXIMUM_ALLOWED,
2161 &domain->sid,
2162 &conn->sam_domain_handle);
2164 done:
2166 if (!NT_STATUS_IS_OK(result)) {
2167 invalidate_cm_connection(conn);
2168 return result;
2171 *cli = conn->samr_pipe;
2172 *sam_handle = conn->sam_domain_handle;
2173 SAFE_FREE(machine_password);
2174 SAFE_FREE(machine_account);
2175 return result;
2178 NTSTATUS cm_connect_lsa(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2179 struct rpc_pipe_client **cli, POLICY_HND *lsa_policy)
2181 struct winbindd_cm_conn *conn;
2182 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2183 fstring conn_pwd;
2184 struct dcinfo *p_dcinfo;
2186 result = init_dc_connection(domain);
2187 if (!NT_STATUS_IS_OK(result))
2188 return result;
2190 conn = &domain->conn;
2192 if (conn->lsa_pipe != NULL) {
2193 goto done;
2196 pwd_get_cleartext(&conn->cli->pwd, conn_pwd);
2197 if ((conn->cli->user_name[0] == '\0') ||
2198 (conn->cli->domain[0] == '\0') ||
2199 (conn_pwd[0] == '\0')) {
2200 DEBUG(10, ("cm_connect_lsa: No no user available for "
2201 "domain %s, trying schannel\n", conn->cli->domain));
2202 goto schannel;
2205 /* We have an authenticated connection. Use a NTLMSSP SPNEGO
2206 * authenticated LSA pipe with sign & seal. */
2207 conn->lsa_pipe = cli_rpc_pipe_open_spnego_ntlmssp
2208 (conn->cli, PI_LSARPC, PIPE_AUTH_LEVEL_PRIVACY,
2209 conn->cli->domain, conn->cli->user_name, conn_pwd, &result);
2211 if (conn->lsa_pipe == NULL) {
2212 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
2213 "domain %s using NTLMSSP authenticated pipe: user "
2214 "%s\\%s. Error was %s. Trying schannel.\n",
2215 domain->name, conn->cli->domain,
2216 conn->cli->user_name, nt_errstr(result)));
2217 goto schannel;
2220 DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
2221 "NTLMSSP authenticated pipe: user %s\\%s\n",
2222 domain->name, conn->cli->domain, conn->cli->user_name ));
2224 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2225 SEC_RIGHTS_MAXIMUM_ALLOWED,
2226 &conn->lsa_policy);
2227 if (NT_STATUS_IS_OK(result)) {
2228 goto done;
2231 DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
2232 "schannel\n"));
2234 cli_rpc_pipe_close(conn->lsa_pipe);
2236 schannel:
2238 /* Fall back to schannel if it's a W2K pre-SP1 box. */
2240 if (!cm_get_schannel_dcinfo(domain, &p_dcinfo)) {
2241 /* If this call fails - conn->cli can now be NULL ! */
2242 DEBUG(10, ("cm_connect_lsa: Could not get schannel auth info "
2243 "for domain %s, trying anon\n", domain->name));
2244 goto anonymous;
2246 conn->lsa_pipe = cli_rpc_pipe_open_schannel_with_key
2247 (conn->cli, PI_LSARPC, PIPE_AUTH_LEVEL_PRIVACY,
2248 domain->name, p_dcinfo, &result);
2250 if (conn->lsa_pipe == NULL) {
2251 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
2252 "domain %s using schannel. Error was %s\n",
2253 domain->name, nt_errstr(result) ));
2254 goto anonymous;
2256 DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
2257 "schannel.\n", domain->name ));
2259 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2260 SEC_RIGHTS_MAXIMUM_ALLOWED,
2261 &conn->lsa_policy);
2262 if (NT_STATUS_IS_OK(result)) {
2263 goto done;
2266 DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
2267 "anonymous\n"));
2269 cli_rpc_pipe_close(conn->lsa_pipe);
2271 anonymous:
2273 conn->lsa_pipe = cli_rpc_pipe_open_noauth(conn->cli, PI_LSARPC,
2274 &result);
2275 if (conn->lsa_pipe == NULL) {
2276 result = NT_STATUS_PIPE_NOT_AVAILABLE;
2277 goto done;
2280 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2281 SEC_RIGHTS_MAXIMUM_ALLOWED,
2282 &conn->lsa_policy);
2283 done:
2284 if (!NT_STATUS_IS_OK(result)) {
2285 invalidate_cm_connection(conn);
2286 return result;
2289 *cli = conn->lsa_pipe;
2290 *lsa_policy = conn->lsa_policy;
2291 return result;
2294 /****************************************************************************
2295 Open the netlogon pipe to this DC. Use schannel if specified in client conf.
2296 session key stored in conn->netlogon_pipe->dc->sess_key.
2297 ****************************************************************************/
2299 NTSTATUS cm_connect_netlogon(struct winbindd_domain *domain,
2300 struct rpc_pipe_client **cli)
2302 struct winbindd_cm_conn *conn;
2303 NTSTATUS result;
2305 uint32 neg_flags = NETLOGON_NEG_SELECT_AUTH2_FLAGS;
2306 uint8 mach_pwd[16];
2307 uint32 sec_chan_type;
2308 const char *account_name;
2309 struct rpc_pipe_client *netlogon_pipe = NULL;
2311 *cli = NULL;
2313 result = init_dc_connection(domain);
2314 if (!NT_STATUS_IS_OK(result)) {
2315 return result;
2318 conn = &domain->conn;
2320 if (conn->netlogon_pipe != NULL) {
2321 *cli = conn->netlogon_pipe;
2322 return NT_STATUS_OK;
2325 netlogon_pipe = cli_rpc_pipe_open_noauth(conn->cli, PI_NETLOGON,
2326 &result);
2327 if (netlogon_pipe == NULL) {
2328 return result;
2331 if ((!IS_DC) && (!domain->primary)) {
2332 /* Clear the schannel request bit and drop down */
2333 neg_flags &= ~NETLOGON_NEG_SCHANNEL;
2334 goto no_schannel;
2337 if (lp_client_schannel() != False) {
2338 neg_flags |= NETLOGON_NEG_SCHANNEL;
2341 if (!get_trust_pw_hash(domain->name, mach_pwd, &account_name,
2342 &sec_chan_type))
2344 cli_rpc_pipe_close(netlogon_pipe);
2345 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2348 result = rpccli_netlogon_setup_creds(
2349 netlogon_pipe,
2350 domain->dcname, /* server name. */
2351 domain->name, /* domain name */
2352 global_myname(), /* client name */
2353 account_name, /* machine account */
2354 mach_pwd, /* machine password */
2355 sec_chan_type, /* from get_trust_pw */
2356 &neg_flags);
2358 if (!NT_STATUS_IS_OK(result)) {
2359 cli_rpc_pipe_close(netlogon_pipe);
2360 return result;
2363 if ((lp_client_schannel() == True) &&
2364 ((neg_flags & NETLOGON_NEG_SCHANNEL) == 0)) {
2365 DEBUG(3, ("Server did not offer schannel\n"));
2366 cli_rpc_pipe_close(netlogon_pipe);
2367 return NT_STATUS_ACCESS_DENIED;
2370 no_schannel:
2371 if ((lp_client_schannel() == False) ||
2372 ((neg_flags & NETLOGON_NEG_SCHANNEL) == 0)) {
2373 /* We're done - just keep the existing connection to NETLOGON
2374 * open */
2375 conn->netlogon_pipe = netlogon_pipe;
2376 *cli = conn->netlogon_pipe;
2377 return NT_STATUS_OK;
2380 /* Using the credentials from the first pipe, open a signed and sealed
2381 second netlogon pipe. The session key is stored in the schannel
2382 part of the new pipe auth struct.
2385 conn->netlogon_pipe =
2386 cli_rpc_pipe_open_schannel_with_key(conn->cli,
2387 PI_NETLOGON,
2388 PIPE_AUTH_LEVEL_PRIVACY,
2389 domain->name,
2390 netlogon_pipe->dc,
2391 &result);
2393 /* We can now close the initial netlogon pipe. */
2394 cli_rpc_pipe_close(netlogon_pipe);
2396 if (conn->netlogon_pipe == NULL) {
2397 DEBUG(3, ("Could not open schannel'ed NETLOGON pipe. Error "
2398 "was %s\n", nt_errstr(result)));
2400 /* make sure we return something besides OK */
2401 return !NT_STATUS_IS_OK(result) ? result : NT_STATUS_PIPE_NOT_AVAILABLE;
2404 *cli = conn->netlogon_pipe;
2405 return NT_STATUS_OK;