s3: Use smbsock_any_connect in winbind
[Samba.git] / source3 / winbindd / winbindd_cm.c
blob6d99f642e6712cdbbe530c6acadde72416cfc364
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 parent_pid = sys_getpid();
175 char *lfile = NULL;
177 if (domain->dc_probe_pid != (pid_t)-1) {
179 * We might already have a DC probe
180 * child working, check.
182 if (process_exists_by_pid(domain->dc_probe_pid)) {
183 DEBUG(10,("fork_child_dc_connect: pid %u already "
184 "checking for DC's.\n",
185 (unsigned int)domain->dc_probe_pid));
186 return true;
188 domain->dc_probe_pid = (pid_t)-1;
191 domain->dc_probe_pid = sys_fork();
193 if (domain->dc_probe_pid == (pid_t)-1) {
194 DEBUG(0, ("fork_child_dc_connect: Could not fork: %s\n", strerror(errno)));
195 return False;
198 if (domain->dc_probe_pid != (pid_t)0) {
199 /* Parent */
200 messaging_register(winbind_messaging_context(), NULL,
201 MSG_WINBIND_TRY_TO_GO_ONLINE,
202 msg_try_to_go_online);
203 messaging_register(winbind_messaging_context(), NULL,
204 MSG_WINBIND_FAILED_TO_GO_ONLINE,
205 msg_failed_to_go_online);
206 return True;
209 /* Child. */
211 /* Leave messages blocked - we will never process one. */
213 if (!override_logfile) {
214 if (asprintf(&lfile, "%s/log.winbindd-dc-connect", get_dyn_LOGFILEBASE()) == -1) {
215 DEBUG(0, ("fork_child_dc_connect: out of memory.\n"));
216 _exit(1);
220 if (!winbindd_reinit_after_fork(lfile)) {
221 messaging_send_buf(winbind_messaging_context(),
222 pid_to_procid(parent_pid),
223 MSG_WINBIND_FAILED_TO_GO_ONLINE,
224 (uint8 *)domain->name,
225 strlen(domain->name)+1);
226 _exit(1);
228 SAFE_FREE(lfile);
230 mem_ctx = talloc_init("fork_child_dc_connect");
231 if (!mem_ctx) {
232 DEBUG(0,("talloc_init failed.\n"));
233 messaging_send_buf(winbind_messaging_context(),
234 pid_to_procid(parent_pid),
235 MSG_WINBIND_FAILED_TO_GO_ONLINE,
236 (uint8 *)domain->name,
237 strlen(domain->name)+1);
238 _exit(1);
241 if ((!get_dcs(mem_ctx, domain, &dcs, &num_dcs)) || (num_dcs == 0)) {
242 /* Still offline ? Can't find DC's. */
243 messaging_send_buf(winbind_messaging_context(),
244 pid_to_procid(parent_pid),
245 MSG_WINBIND_FAILED_TO_GO_ONLINE,
246 (uint8 *)domain->name,
247 strlen(domain->name)+1);
248 _exit(0);
251 /* We got a DC. Send a message to our parent to get it to
252 try and do the same. */
254 messaging_send_buf(winbind_messaging_context(),
255 pid_to_procid(parent_pid),
256 MSG_WINBIND_TRY_TO_GO_ONLINE,
257 (uint8 *)domain->name,
258 strlen(domain->name)+1);
259 _exit(0);
262 /****************************************************************
263 Handler triggered if we're offline to try and detect a DC.
264 ****************************************************************/
266 static void check_domain_online_handler(struct event_context *ctx,
267 struct timed_event *te,
268 struct timeval now,
269 void *private_data)
271 struct winbindd_domain *domain =
272 (struct winbindd_domain *)private_data;
274 DEBUG(10,("check_domain_online_handler: called for domain "
275 "%s (online = %s)\n", domain->name,
276 domain->online ? "True" : "False" ));
278 TALLOC_FREE(domain->check_online_event);
280 /* Are we still in "startup" mode ? */
282 if (domain->startup && (now.tv_sec > domain->startup_time + 30)) {
283 /* No longer in "startup" mode. */
284 DEBUG(10,("check_domain_online_handler: domain %s no longer in 'startup' mode.\n",
285 domain->name ));
286 domain->startup = False;
289 /* We've been told to stay offline, so stay
290 that way. */
292 if (get_global_winbindd_state_offline()) {
293 DEBUG(10,("check_domain_online_handler: domain %s remaining globally offline\n",
294 domain->name ));
295 return;
298 /* Fork a child to test if it can contact a DC.
299 If it can then send ourselves a message to
300 cause a reconnect. */
302 fork_child_dc_connect(domain);
305 /****************************************************************
306 If we're still offline setup the timeout check.
307 ****************************************************************/
309 static void calc_new_online_timeout_check(struct winbindd_domain *domain)
311 int wbr = lp_winbind_reconnect_delay();
313 if (domain->startup) {
314 domain->check_online_timeout = 10;
315 } else if (domain->check_online_timeout < wbr) {
316 domain->check_online_timeout = wbr;
320 /****************************************************************
321 Set domain offline and also add handler to put us back online
322 if we detect a DC.
323 ****************************************************************/
325 void set_domain_offline(struct winbindd_domain *domain)
327 DEBUG(10,("set_domain_offline: called for domain %s\n",
328 domain->name ));
330 TALLOC_FREE(domain->check_online_event);
332 if (domain->internal) {
333 DEBUG(3,("set_domain_offline: domain %s is internal - logic error.\n",
334 domain->name ));
335 return;
338 domain->online = False;
340 /* Offline domains are always initialized. They're
341 re-initialized when they go back online. */
343 domain->initialized = True;
345 /* We only add the timeout handler that checks and
346 allows us to go back online when we've not
347 been told to remain offline. */
349 if (get_global_winbindd_state_offline()) {
350 DEBUG(10,("set_domain_offline: domain %s remaining globally offline\n",
351 domain->name ));
352 return;
355 /* If we're in statup mode, check again in 10 seconds, not in
356 lp_winbind_reconnect_delay() seconds (which is 30 seconds by default). */
358 calc_new_online_timeout_check(domain);
360 domain->check_online_event = event_add_timed(winbind_event_context(),
361 NULL,
362 timeval_current_ofs(domain->check_online_timeout,0),
363 check_domain_online_handler,
364 domain);
366 /* The above *has* to succeed for winbindd to work. */
367 if (!domain->check_online_event) {
368 smb_panic("set_domain_offline: failed to add online handler");
371 DEBUG(10,("set_domain_offline: added event handler for domain %s\n",
372 domain->name ));
374 /* Send an offline message to the idmap child when our
375 primary domain goes offline */
377 if ( domain->primary ) {
378 struct winbindd_child *idmap = idmap_child();
380 if ( idmap->pid != 0 ) {
381 messaging_send_buf(winbind_messaging_context(),
382 pid_to_procid(idmap->pid),
383 MSG_WINBIND_OFFLINE,
384 (uint8 *)domain->name,
385 strlen(domain->name)+1);
389 return;
392 /****************************************************************
393 Set domain online - if allowed.
394 ****************************************************************/
396 static void set_domain_online(struct winbindd_domain *domain)
398 DEBUG(10,("set_domain_online: called for domain %s\n",
399 domain->name ));
401 if (domain->internal) {
402 DEBUG(3,("set_domain_online: domain %s is internal - logic error.\n",
403 domain->name ));
404 return;
407 if (get_global_winbindd_state_offline()) {
408 DEBUG(10,("set_domain_online: domain %s remaining globally offline\n",
409 domain->name ));
410 return;
413 winbindd_set_locator_kdc_envs(domain);
415 /* If we are waiting to get a krb5 ticket, trigger immediately. */
416 ccache_regain_all_now();
418 /* Ok, we're out of any startup mode now... */
419 domain->startup = False;
421 if (domain->online == False) {
422 /* We were offline - now we're online. We default to
423 using the MS-RPC backend if we started offline,
424 and if we're going online for the first time we
425 should really re-initialize the backends and the
426 checks to see if we're talking to an AD or NT domain.
429 domain->initialized = False;
431 /* 'reconnect_methods' is the MS-RPC backend. */
432 if (domain->backend == &reconnect_methods) {
433 domain->backend = NULL;
437 /* Ensure we have no online timeout checks. */
438 domain->check_online_timeout = 0;
439 TALLOC_FREE(domain->check_online_event);
441 /* Ensure we ignore any pending child messages. */
442 messaging_deregister(winbind_messaging_context(),
443 MSG_WINBIND_TRY_TO_GO_ONLINE, NULL);
444 messaging_deregister(winbind_messaging_context(),
445 MSG_WINBIND_FAILED_TO_GO_ONLINE, NULL);
447 domain->online = True;
449 /* Send an online message to the idmap child when our
450 primary domain comes online */
452 if ( domain->primary ) {
453 struct winbindd_child *idmap = idmap_child();
455 if ( idmap->pid != 0 ) {
456 messaging_send_buf(winbind_messaging_context(),
457 pid_to_procid(idmap->pid),
458 MSG_WINBIND_ONLINE,
459 (uint8 *)domain->name,
460 strlen(domain->name)+1);
464 return;
467 /****************************************************************
468 Requested to set a domain online.
469 ****************************************************************/
471 void set_domain_online_request(struct winbindd_domain *domain)
473 struct timeval tev;
475 DEBUG(10,("set_domain_online_request: called for domain %s\n",
476 domain->name ));
478 if (get_global_winbindd_state_offline()) {
479 DEBUG(10,("set_domain_online_request: domain %s remaining globally offline\n",
480 domain->name ));
481 return;
484 /* We've been told it's safe to go online and
485 try and connect to a DC. But I don't believe it
486 because network manager seems to lie.
487 Wait at least 5 seconds. Heuristics suck... */
490 GetTimeOfDay(&tev);
492 /* Go into "startup" mode again. */
493 domain->startup_time = tev.tv_sec;
494 domain->startup = True;
496 tev.tv_sec += 5;
498 if (!domain->check_online_event) {
499 /* If we've come from being globally offline we
500 don't have a check online event handler set.
501 We need to add one now we're trying to go
502 back online. */
504 DEBUG(10,("set_domain_online_request: domain %s was globally offline.\n",
505 domain->name ));
508 TALLOC_FREE(domain->check_online_event);
510 domain->check_online_event = event_add_timed(winbind_event_context(),
511 NULL,
512 tev,
513 check_domain_online_handler,
514 domain);
516 /* The above *has* to succeed for winbindd to work. */
517 if (!domain->check_online_event) {
518 smb_panic("set_domain_online_request: failed to add online handler");
522 /****************************************************************
523 Add -ve connection cache entries for domain and realm.
524 ****************************************************************/
526 void winbind_add_failed_connection_entry(const struct winbindd_domain *domain,
527 const char *server,
528 NTSTATUS result)
530 add_failed_connection_entry(domain->name, server, result);
531 /* If this was the saf name for the last thing we talked to,
532 remove it. */
533 saf_delete(domain->name);
534 if (*domain->alt_name) {
535 add_failed_connection_entry(domain->alt_name, server, result);
536 saf_delete(domain->alt_name);
538 winbindd_unset_locator_kdc_env(domain);
541 /* Choose between anonymous or authenticated connections. We need to use
542 an authenticated connection if DCs have the RestrictAnonymous registry
543 entry set > 0, or the "Additional restrictions for anonymous
544 connections" set in the win2k Local Security Policy.
546 Caller to free() result in domain, username, password
549 static void cm_get_ipc_userpass(char **username, char **domain, char **password)
551 *username = (char *)secrets_fetch(SECRETS_AUTH_USER, NULL);
552 *domain = (char *)secrets_fetch(SECRETS_AUTH_DOMAIN, NULL);
553 *password = (char *)secrets_fetch(SECRETS_AUTH_PASSWORD, NULL);
555 if (*username && **username) {
557 if (!*domain || !**domain)
558 *domain = smb_xstrdup(lp_workgroup());
560 if (!*password || !**password)
561 *password = smb_xstrdup("");
563 DEBUG(3, ("cm_get_ipc_userpass: Retrieved auth-user from secrets.tdb [%s\\%s]\n",
564 *domain, *username));
566 } else {
567 DEBUG(3, ("cm_get_ipc_userpass: No auth-user defined\n"));
568 *username = smb_xstrdup("");
569 *domain = smb_xstrdup("");
570 *password = smb_xstrdup("");
574 static bool get_dc_name_via_netlogon(struct winbindd_domain *domain,
575 fstring dcname,
576 struct sockaddr_storage *dc_ss)
578 struct winbindd_domain *our_domain = NULL;
579 struct rpc_pipe_client *netlogon_pipe = NULL;
580 NTSTATUS result;
581 WERROR werr;
582 TALLOC_CTX *mem_ctx;
583 unsigned int orig_timeout;
584 const char *tmp = NULL;
585 const char *p;
587 /* Hmmmm. We can only open one connection to the NETLOGON pipe at the
588 * moment.... */
590 if (IS_DC) {
591 return False;
594 if (domain->primary) {
595 return False;
598 our_domain = find_our_domain();
600 if ((mem_ctx = talloc_init("get_dc_name_via_netlogon")) == NULL) {
601 return False;
604 result = cm_connect_netlogon(our_domain, &netlogon_pipe);
605 if (!NT_STATUS_IS_OK(result)) {
606 talloc_destroy(mem_ctx);
607 return False;
610 /* This call can take a long time - allow the server to time out.
611 35 seconds should do it. */
613 orig_timeout = rpccli_set_timeout(netlogon_pipe, 35000);
615 if (our_domain->active_directory) {
616 struct netr_DsRGetDCNameInfo *domain_info = NULL;
618 result = rpccli_netr_DsRGetDCName(netlogon_pipe,
619 mem_ctx,
620 our_domain->dcname,
621 domain->name,
622 NULL,
623 NULL,
624 DS_RETURN_DNS_NAME,
625 &domain_info,
626 &werr);
627 if (NT_STATUS_IS_OK(result) && W_ERROR_IS_OK(werr)) {
628 tmp = talloc_strdup(
629 mem_ctx, domain_info->dc_unc);
630 if (tmp == NULL) {
631 DEBUG(0, ("talloc_strdup failed\n"));
632 talloc_destroy(mem_ctx);
633 return false;
635 if (strlen(domain->alt_name) == 0) {
636 fstrcpy(domain->alt_name,
637 domain_info->domain_name);
639 if (strlen(domain->forest_name) == 0) {
640 fstrcpy(domain->forest_name,
641 domain_info->forest_name);
644 } else {
645 result = rpccli_netr_GetAnyDCName(netlogon_pipe, mem_ctx,
646 our_domain->dcname,
647 domain->name,
648 &tmp,
649 &werr);
652 /* And restore our original timeout. */
653 rpccli_set_timeout(netlogon_pipe, orig_timeout);
655 if (!NT_STATUS_IS_OK(result)) {
656 DEBUG(10,("rpccli_netr_GetAnyDCName failed: %s\n",
657 nt_errstr(result)));
658 talloc_destroy(mem_ctx);
659 return false;
662 if (!W_ERROR_IS_OK(werr)) {
663 DEBUG(10,("rpccli_netr_GetAnyDCName failed: %s\n",
664 win_errstr(werr)));
665 talloc_destroy(mem_ctx);
666 return false;
669 /* rpccli_netr_GetAnyDCName gives us a name with \\ */
670 p = strip_hostname(tmp);
672 fstrcpy(dcname, p);
674 talloc_destroy(mem_ctx);
676 DEBUG(10,("rpccli_netr_GetAnyDCName returned %s\n", dcname));
678 if (!resolve_name(dcname, dc_ss, 0x20)) {
679 return False;
682 return True;
686 * Helper function to assemble trust password and account name
688 static NTSTATUS get_trust_creds(const struct winbindd_domain *domain,
689 char **machine_password,
690 char **machine_account,
691 char **machine_krb5_principal)
693 const char *account_name;
694 const char *name = NULL;
696 /* If we are a DC and this is not our own domain */
698 if (IS_DC) {
699 name = domain->name;
700 } else {
701 struct winbindd_domain *our_domain = find_our_domain();
703 if (!our_domain)
704 return NT_STATUS_INVALID_SERVER_STATE;
706 name = our_domain->name;
709 if (!get_trust_pw_clear(name, machine_password,
710 &account_name, NULL))
712 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
715 if ((machine_account != NULL) &&
716 (asprintf(machine_account, "%s$", account_name) == -1))
718 return NT_STATUS_NO_MEMORY;
721 /* For now assume our machine account only exists in our domain */
723 if (machine_krb5_principal != NULL)
725 struct winbindd_domain *our_domain = find_our_domain();
727 if (!our_domain) {
728 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
731 if (asprintf(machine_krb5_principal, "%s$@%s",
732 account_name, our_domain->alt_name) == -1)
734 return NT_STATUS_NO_MEMORY;
737 strupper_m(*machine_krb5_principal);
740 return NT_STATUS_OK;
743 /************************************************************************
744 Given a fd with a just-connected TCP connection to a DC, open a connection
745 to the pipe.
746 ************************************************************************/
748 static NTSTATUS cm_prepare_connection(const struct winbindd_domain *domain,
749 const int sockfd,
750 const char *controller,
751 struct cli_state **cli,
752 bool *retry)
754 char *machine_password = NULL;
755 char *machine_krb5_principal = NULL;
756 char *machine_account = NULL;
757 char *ipc_username = NULL;
758 char *ipc_domain = NULL;
759 char *ipc_password = NULL;
761 struct named_mutex *mutex;
763 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
765 struct sockaddr peeraddr;
766 socklen_t peeraddr_len;
768 struct sockaddr_in *peeraddr_in = (struct sockaddr_in *)&peeraddr;
770 DEBUG(10,("cm_prepare_connection: connecting to DC %s for domain %s\n",
771 controller, domain->name ));
773 *retry = True;
775 mutex = grab_named_mutex(talloc_tos(), controller,
776 WINBIND_SERVER_MUTEX_WAIT_TIME);
777 if (mutex == NULL) {
778 DEBUG(0,("cm_prepare_connection: mutex grab failed for %s\n",
779 controller));
780 result = NT_STATUS_POSSIBLE_DEADLOCK;
781 goto done;
784 if ((*cli = cli_initialise()) == NULL) {
785 DEBUG(1, ("Could not cli_initialize\n"));
786 result = NT_STATUS_NO_MEMORY;
787 goto done;
790 (*cli)->timeout = 10000; /* 10 seconds */
791 (*cli)->fd = sockfd;
792 fstrcpy((*cli)->desthost, controller);
793 (*cli)->use_kerberos = True;
795 peeraddr_len = sizeof(peeraddr);
797 if ((getpeername((*cli)->fd, &peeraddr, &peeraddr_len) != 0)) {
798 DEBUG(0,("cm_prepare_connection: getpeername failed with: %s\n",
799 strerror(errno)));
800 result = NT_STATUS_UNSUCCESSFUL;
801 goto done;
804 if ((peeraddr_len != sizeof(struct sockaddr_in))
805 #ifdef HAVE_IPV6
806 && (peeraddr_len != sizeof(struct sockaddr_in6))
807 #endif
809 DEBUG(0,("cm_prepare_connection: got unexpected peeraddr len %d\n",
810 peeraddr_len));
811 result = NT_STATUS_UNSUCCESSFUL;
812 goto done;
815 if ((peeraddr_in->sin_family != PF_INET)
816 #ifdef HAVE_IPV6
817 && (peeraddr_in->sin_family != PF_INET6)
818 #endif
820 DEBUG(0,("cm_prepare_connection: got unexpected family %d\n",
821 peeraddr_in->sin_family));
822 result = NT_STATUS_UNSUCCESSFUL;
823 goto done;
826 result = cli_negprot(*cli);
828 if (!NT_STATUS_IS_OK(result)) {
829 DEBUG(1, ("cli_negprot failed: %s\n", nt_errstr(result)));
830 goto done;
833 if (!is_dc_trusted_domain_situation(domain->name) &&
834 (*cli)->protocol >= PROTOCOL_NT1 &&
835 (*cli)->capabilities & CAP_EXTENDED_SECURITY)
837 ADS_STATUS ads_status;
839 result = get_trust_creds(domain, &machine_password,
840 &machine_account,
841 &machine_krb5_principal);
842 if (!NT_STATUS_IS_OK(result)) {
843 goto anon_fallback;
846 if (lp_security() == SEC_ADS) {
848 /* Try a krb5 session */
850 (*cli)->use_kerberos = True;
851 DEBUG(5, ("connecting to %s from %s with kerberos principal "
852 "[%s] and realm [%s]\n", controller, global_myname(),
853 machine_krb5_principal, domain->alt_name));
855 winbindd_set_locator_kdc_envs(domain);
857 ads_status = cli_session_setup_spnego(*cli,
858 machine_krb5_principal,
859 machine_password,
860 lp_workgroup(),
861 domain->alt_name);
863 if (!ADS_ERR_OK(ads_status)) {
864 DEBUG(4,("failed kerberos session setup with %s\n",
865 ads_errstr(ads_status)));
868 result = ads_ntstatus(ads_status);
869 if (NT_STATUS_IS_OK(result)) {
870 /* Ensure creds are stored for NTLMSSP authenticated pipe access. */
871 result = cli_init_creds(*cli, machine_account, lp_workgroup(), machine_password);
872 if (!NT_STATUS_IS_OK(result)) {
873 goto done;
875 goto session_setup_done;
879 /* Fall back to non-kerberos session setup using NTLMSSP SPNEGO with the machine account. */
880 (*cli)->use_kerberos = False;
882 DEBUG(5, ("connecting to %s from %s with username "
883 "[%s]\\[%s]\n", controller, global_myname(),
884 lp_workgroup(), machine_account));
886 ads_status = cli_session_setup_spnego(*cli,
887 machine_account,
888 machine_password,
889 lp_workgroup(),
890 NULL);
891 if (!ADS_ERR_OK(ads_status)) {
892 DEBUG(4, ("authenticated session setup failed with %s\n",
893 ads_errstr(ads_status)));
896 result = ads_ntstatus(ads_status);
897 if (NT_STATUS_IS_OK(result)) {
898 /* Ensure creds are stored for NTLMSSP authenticated pipe access. */
899 result = cli_init_creds(*cli, machine_account, lp_workgroup(), machine_password);
900 if (!NT_STATUS_IS_OK(result)) {
901 goto done;
903 goto session_setup_done;
907 /* Fall back to non-kerberos session setup with auth_user */
909 (*cli)->use_kerberos = False;
911 cm_get_ipc_userpass(&ipc_username, &ipc_domain, &ipc_password);
913 if ((((*cli)->sec_mode & NEGOTIATE_SECURITY_CHALLENGE_RESPONSE) != 0) &&
914 (strlen(ipc_username) > 0)) {
916 /* Only try authenticated if we have a username */
918 DEBUG(5, ("connecting to %s from %s with username "
919 "[%s]\\[%s]\n", controller, global_myname(),
920 ipc_domain, ipc_username));
922 if (NT_STATUS_IS_OK(cli_session_setup(
923 *cli, ipc_username,
924 ipc_password, strlen(ipc_password)+1,
925 ipc_password, strlen(ipc_password)+1,
926 ipc_domain))) {
927 /* Successful logon with given username. */
928 result = cli_init_creds(*cli, ipc_username, ipc_domain, ipc_password);
929 if (!NT_STATUS_IS_OK(result)) {
930 goto done;
932 goto session_setup_done;
933 } else {
934 DEBUG(4, ("authenticated session setup with user %s\\%s failed.\n",
935 ipc_domain, ipc_username ));
939 anon_fallback:
941 /* Fall back to anonymous connection, this might fail later */
942 DEBUG(10,("cm_prepare_connection: falling back to anonymous "
943 "connection for DC %s\n",
944 controller ));
946 if (NT_STATUS_IS_OK(cli_session_setup(*cli, "", NULL, 0,
947 NULL, 0, ""))) {
948 DEBUG(5, ("Connected anonymously\n"));
949 result = cli_init_creds(*cli, "", "", "");
950 if (!NT_STATUS_IS_OK(result)) {
951 goto done;
953 goto session_setup_done;
956 result = cli_nt_error(*cli);
958 if (NT_STATUS_IS_OK(result))
959 result = NT_STATUS_UNSUCCESSFUL;
961 /* We can't session setup */
963 goto done;
965 session_setup_done:
967 /* cache the server name for later connections */
969 saf_store( domain->name, (*cli)->desthost );
970 if (domain->alt_name && (*cli)->use_kerberos) {
971 saf_store( domain->alt_name, (*cli)->desthost );
974 winbindd_set_locator_kdc_envs(domain);
976 result = cli_tcon_andx(*cli, "IPC$", "IPC", "", 0);
978 if (!NT_STATUS_IS_OK(result)) {
979 DEBUG(1,("failed tcon_X with %s\n", nt_errstr(result)));
980 goto done;
983 TALLOC_FREE(mutex);
984 *retry = False;
986 /* set the domain if empty; needed for schannel connections */
987 if ( !(*cli)->domain[0] ) {
988 result = cli_set_domain((*cli), domain->name);
989 if (!NT_STATUS_IS_OK(result)) {
990 return result;
994 result = NT_STATUS_OK;
996 done:
997 TALLOC_FREE(mutex);
998 SAFE_FREE(machine_account);
999 SAFE_FREE(machine_password);
1000 SAFE_FREE(machine_krb5_principal);
1001 SAFE_FREE(ipc_username);
1002 SAFE_FREE(ipc_domain);
1003 SAFE_FREE(ipc_password);
1005 if (!NT_STATUS_IS_OK(result)) {
1006 winbind_add_failed_connection_entry(domain, controller, result);
1007 if ((*cli) != NULL) {
1008 cli_shutdown(*cli);
1009 *cli = NULL;
1013 return result;
1016 /*******************************************************************
1017 Add a dcname and sockaddr_storage pair to the end of a dc_name_ip
1018 array.
1020 Keeps the list unique by not adding duplicate entries.
1022 @param[in] mem_ctx talloc memory context to allocate from
1023 @param[in] domain_name domain of the DC
1024 @param[in] dcname name of the DC to add to the list
1025 @param[in] pss Internet address and port pair to add to the list
1026 @param[in,out] dcs array of dc_name_ip structures to add to
1027 @param[in,out] num_dcs number of dcs returned in the dcs array
1028 @return true if the list was added to, false otherwise
1029 *******************************************************************/
1031 static bool add_one_dc_unique(TALLOC_CTX *mem_ctx, const char *domain_name,
1032 const char *dcname, struct sockaddr_storage *pss,
1033 struct dc_name_ip **dcs, int *num)
1035 int i = 0;
1037 if (!NT_STATUS_IS_OK(check_negative_conn_cache(domain_name, dcname))) {
1038 DEBUG(10, ("DC %s was in the negative conn cache\n", dcname));
1039 return False;
1042 /* Make sure there's no duplicates in the list */
1043 for (i=0; i<*num; i++)
1044 if (sockaddr_equal((struct sockaddr *)&(*dcs)[i].ss, (struct sockaddr *)pss))
1045 return False;
1047 *dcs = TALLOC_REALLOC_ARRAY(mem_ctx, *dcs, struct dc_name_ip, (*num)+1);
1049 if (*dcs == NULL)
1050 return False;
1052 fstrcpy((*dcs)[*num].name, dcname);
1053 (*dcs)[*num].ss = *pss;
1054 *num += 1;
1055 return True;
1058 static bool add_sockaddr_to_array(TALLOC_CTX *mem_ctx,
1059 struct sockaddr_storage *pss, uint16 port,
1060 struct sockaddr_storage **addrs, int *num)
1062 *addrs = TALLOC_REALLOC_ARRAY(mem_ctx, *addrs, struct sockaddr_storage, (*num)+1);
1064 if (*addrs == NULL) {
1065 *num = 0;
1066 return False;
1069 (*addrs)[*num] = *pss;
1070 set_sockaddr_port((struct sockaddr *)&(*addrs)[*num], port);
1072 *num += 1;
1073 return True;
1076 /*******************************************************************
1077 convert an ip to a name
1078 *******************************************************************/
1080 static bool dcip_to_name(TALLOC_CTX *mem_ctx,
1081 const struct winbindd_domain *domain,
1082 struct sockaddr_storage *pss,
1083 fstring name )
1085 struct ip_service ip_list;
1086 uint32_t nt_version = NETLOGON_NT_VERSION_1;
1088 ip_list.ss = *pss;
1089 ip_list.port = 0;
1091 #ifdef WITH_ADS
1092 /* For active directory servers, try to get the ldap server name.
1093 None of these failures should be considered critical for now */
1095 if (lp_security() == SEC_ADS) {
1096 ADS_STRUCT *ads;
1097 ADS_STATUS ads_status;
1098 char addr[INET6_ADDRSTRLEN];
1100 print_sockaddr(addr, sizeof(addr), pss);
1102 ads = ads_init(domain->alt_name, domain->name, addr);
1103 ads->auth.flags |= ADS_AUTH_NO_BIND;
1105 ads_status = ads_connect(ads);
1106 if (ADS_ERR_OK(ads_status)) {
1107 /* We got a cldap packet. */
1108 fstrcpy(name, ads->config.ldap_server_name);
1109 namecache_store(name, 0x20, 1, &ip_list);
1111 DEBUG(10,("dcip_to_name: flags = 0x%x\n", (unsigned int)ads->config.flags));
1113 if (domain->primary && (ads->config.flags & NBT_SERVER_KDC)) {
1114 if (ads_closest_dc(ads)) {
1115 char *sitename = sitename_fetch(ads->config.realm);
1117 /* We're going to use this KDC for this realm/domain.
1118 If we are using sites, then force the krb5 libs
1119 to use this KDC. */
1121 create_local_private_krb5_conf_for_domain(domain->alt_name,
1122 domain->name,
1123 sitename,
1124 pss,
1125 name);
1127 SAFE_FREE(sitename);
1128 } else {
1129 /* use an off site KDC */
1130 create_local_private_krb5_conf_for_domain(domain->alt_name,
1131 domain->name,
1132 NULL,
1133 pss,
1134 name);
1136 winbindd_set_locator_kdc_envs(domain);
1138 /* Ensure we contact this DC also. */
1139 saf_store( domain->name, name);
1140 saf_store( domain->alt_name, name);
1143 ads_destroy( &ads );
1144 return True;
1147 ads_destroy( &ads );
1149 #endif
1151 /* try GETDC requests next */
1153 if (send_getdc_request(mem_ctx, winbind_messaging_context(),
1154 pss, domain->name, &domain->sid,
1155 nt_version)) {
1156 const char *dc_name = NULL;
1157 int i;
1158 smb_msleep(100);
1159 for (i=0; i<5; i++) {
1160 if (receive_getdc_response(mem_ctx, pss, domain->name,
1161 &nt_version,
1162 &dc_name, NULL)) {
1163 fstrcpy(name, dc_name);
1164 namecache_store(name, 0x20, 1, &ip_list);
1165 return True;
1167 smb_msleep(500);
1171 /* try node status request */
1173 if ( name_status_find(domain->name, 0x1c, 0x20, pss, name) ) {
1174 namecache_store(name, 0x20, 1, &ip_list);
1175 return True;
1177 return False;
1180 /*******************************************************************
1181 Retrieve a list of IP addresses for domain controllers.
1183 The array is sorted in the preferred connection order.
1185 @param[in] mem_ctx talloc memory context to allocate from
1186 @param[in] domain domain to retrieve DCs for
1187 @param[out] dcs array of dcs that will be returned
1188 @param[out] num_dcs number of dcs returned in the dcs array
1189 @return always true
1190 *******************************************************************/
1192 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
1193 struct dc_name_ip **dcs, int *num_dcs)
1195 fstring dcname;
1196 struct sockaddr_storage ss;
1197 struct ip_service *ip_list = NULL;
1198 int iplist_size = 0;
1199 int i;
1200 bool is_our_domain;
1201 enum security_types sec = (enum security_types)lp_security();
1203 is_our_domain = strequal(domain->name, lp_workgroup());
1205 /* If not our domain, get the preferred DC, by asking our primary DC */
1206 if ( !is_our_domain
1207 && get_dc_name_via_netlogon(domain, dcname, &ss)
1208 && add_one_dc_unique(mem_ctx, domain->name, dcname, &ss, dcs,
1209 num_dcs) )
1211 char addr[INET6_ADDRSTRLEN];
1212 print_sockaddr(addr, sizeof(addr), &ss);
1213 DEBUG(10, ("Retrieved DC %s at %s via netlogon\n",
1214 dcname, addr));
1215 return True;
1218 if (sec == SEC_ADS) {
1219 char *sitename = NULL;
1221 /* We need to make sure we know the local site before
1222 doing any DNS queries, as this will restrict the
1223 get_sorted_dc_list() call below to only fetching
1224 DNS records for the correct site. */
1226 /* Find any DC to get the site record.
1227 We deliberately don't care about the
1228 return here. */
1230 get_dc_name(domain->name, domain->alt_name, dcname, &ss);
1232 sitename = sitename_fetch(domain->alt_name);
1233 if (sitename) {
1235 /* Do the site-specific AD dns lookup first. */
1236 get_sorted_dc_list(domain->alt_name, sitename, &ip_list,
1237 &iplist_size, True);
1239 /* Add ips to the DC array. We don't look up the name
1240 of the DC in this function, but we fill in the char*
1241 of the ip now to make the failed connection cache
1242 work */
1243 for ( i=0; i<iplist_size; i++ ) {
1244 char addr[INET6_ADDRSTRLEN];
1245 print_sockaddr(addr, sizeof(addr),
1246 &ip_list[i].ss);
1247 add_one_dc_unique(mem_ctx,
1248 domain->name,
1249 addr,
1250 &ip_list[i].ss,
1251 dcs,
1252 num_dcs);
1255 SAFE_FREE(ip_list);
1256 SAFE_FREE(sitename);
1257 iplist_size = 0;
1260 /* Now we add DCs from the main AD DNS lookup. */
1261 get_sorted_dc_list(domain->alt_name, NULL, &ip_list,
1262 &iplist_size, True);
1264 for ( i=0; i<iplist_size; i++ ) {
1265 char addr[INET6_ADDRSTRLEN];
1266 print_sockaddr(addr, sizeof(addr),
1267 &ip_list[i].ss);
1268 add_one_dc_unique(mem_ctx,
1269 domain->name,
1270 addr,
1271 &ip_list[i].ss,
1272 dcs,
1273 num_dcs);
1276 SAFE_FREE(ip_list);
1277 iplist_size = 0;
1280 /* Try standard netbios queries if no ADS */
1281 if (*num_dcs == 0) {
1282 get_sorted_dc_list(domain->name, NULL, &ip_list, &iplist_size,
1283 False);
1285 for ( i=0; i<iplist_size; i++ ) {
1286 char addr[INET6_ADDRSTRLEN];
1287 print_sockaddr(addr, sizeof(addr),
1288 &ip_list[i].ss);
1289 add_one_dc_unique(mem_ctx,
1290 domain->name,
1291 addr,
1292 &ip_list[i].ss,
1293 dcs,
1294 num_dcs);
1297 SAFE_FREE(ip_list);
1298 iplist_size = 0;
1301 return True;
1304 /*******************************************************************
1305 Find and make a connection to a DC in the given domain.
1307 @param[in] mem_ctx talloc memory context to allocate from
1308 @param[in] domain domain to find a dc in
1309 @param[out] dcname NetBIOS or FQDN of DC that's connected to
1310 @param[out] pss DC Internet address and port
1311 @param[out] fd fd of the open socket connected to the newly found dc
1312 @return true when a DC connection is made, false otherwise
1313 *******************************************************************/
1315 static bool find_new_dc(TALLOC_CTX *mem_ctx,
1316 struct winbindd_domain *domain,
1317 fstring dcname, struct sockaddr_storage *pss, int *fd)
1319 struct dc_name_ip *dcs = NULL;
1320 int num_dcs = 0;
1322 const char **dcnames = NULL;
1323 int num_dcnames = 0;
1325 struct sockaddr_storage *addrs = NULL;
1326 int num_addrs = 0;
1328 int i;
1329 size_t fd_index;
1331 NTSTATUS status;
1333 *fd = -1;
1335 again:
1336 if (!get_dcs(mem_ctx, domain, &dcs, &num_dcs) || (num_dcs == 0))
1337 return False;
1339 for (i=0; i<num_dcs; i++) {
1341 if (!add_string_to_array(mem_ctx, dcs[i].name,
1342 &dcnames, &num_dcnames)) {
1343 return False;
1345 if (!add_sockaddr_to_array(mem_ctx, &dcs[i].ss, 445,
1346 &addrs, &num_addrs)) {
1347 return False;
1351 if ((num_dcnames == 0) || (num_dcnames != num_addrs))
1352 return False;
1354 if ((addrs == NULL) || (dcnames == NULL))
1355 return False;
1357 status = smbsock_any_connect(addrs, dcnames, num_addrs,
1358 fd, &fd_index, NULL);
1359 if (!NT_STATUS_IS_OK(status)) {
1360 for (i=0; i<num_dcs; i++) {
1361 char ab[INET6_ADDRSTRLEN];
1362 print_sockaddr(ab, sizeof(ab), &dcs[i].ss);
1363 DEBUG(10, ("find_new_dc: smbsock_any_connect failed for "
1364 "domain %s address %s. Error was %s\n",
1365 domain->name, ab, nt_errstr(status) ));
1366 winbind_add_failed_connection_entry(domain,
1367 dcs[i].name, NT_STATUS_UNSUCCESSFUL);
1369 return False;
1372 *pss = addrs[fd_index];
1374 if (*dcnames[fd_index] != '\0' && !is_ipaddress(dcnames[fd_index])) {
1375 /* Ok, we've got a name for the DC */
1376 fstrcpy(dcname, dcnames[fd_index]);
1377 return True;
1380 /* Try to figure out the name */
1381 if (dcip_to_name(mem_ctx, domain, pss, dcname)) {
1382 return True;
1385 /* We can not continue without the DC's name */
1386 winbind_add_failed_connection_entry(domain, dcs[fd_index].name,
1387 NT_STATUS_UNSUCCESSFUL);
1389 /* Throw away all arrays as we're doing this again. */
1390 TALLOC_FREE(dcs);
1391 num_dcs = 0;
1393 TALLOC_FREE(dcnames);
1394 num_dcnames = 0;
1396 TALLOC_FREE(addrs);
1397 num_addrs = 0;
1399 close(*fd);
1400 *fd = -1;
1402 goto again;
1405 static NTSTATUS cm_open_connection(struct winbindd_domain *domain,
1406 struct winbindd_cm_conn *new_conn)
1408 TALLOC_CTX *mem_ctx;
1409 NTSTATUS result;
1410 char *saf_servername = saf_fetch( domain->name );
1411 int retries;
1413 if ((mem_ctx = talloc_init("cm_open_connection")) == NULL) {
1414 SAFE_FREE(saf_servername);
1415 set_domain_offline(domain);
1416 return NT_STATUS_NO_MEMORY;
1419 /* we have to check the server affinity cache here since
1420 later we selecte a DC based on response time and not preference */
1422 /* Check the negative connection cache
1423 before talking to it. It going down may have
1424 triggered the reconnection. */
1426 if ( saf_servername && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, saf_servername))) {
1428 DEBUG(10,("cm_open_connection: saf_servername is '%s' for domain %s\n",
1429 saf_servername, domain->name ));
1431 /* convert an ip address to a name */
1432 if (is_ipaddress( saf_servername ) ) {
1433 fstring saf_name;
1434 struct sockaddr_storage ss;
1436 if (!interpret_string_addr(&ss, saf_servername,
1437 AI_NUMERICHOST)) {
1438 return NT_STATUS_UNSUCCESSFUL;
1440 if (dcip_to_name(mem_ctx, domain, &ss, saf_name )) {
1441 fstrcpy( domain->dcname, saf_name );
1442 } else {
1443 winbind_add_failed_connection_entry(
1444 domain, saf_servername,
1445 NT_STATUS_UNSUCCESSFUL);
1447 } else {
1448 fstrcpy( domain->dcname, saf_servername );
1451 SAFE_FREE( saf_servername );
1454 for (retries = 0; retries < 3; retries++) {
1455 int fd = -1;
1456 bool retry = False;
1458 result = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1460 DEBUG(10,("cm_open_connection: dcname is '%s' for domain %s\n",
1461 domain->dcname, domain->name ));
1463 if (*domain->dcname
1464 && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, domain->dcname))
1465 && (resolve_name(domain->dcname, &domain->dcaddr, 0x20)))
1467 NTSTATUS status;
1469 status = smbsock_connect(&domain->dcaddr, NULL, NULL,
1470 &fd, NULL);
1471 if (!NT_STATUS_IS_OK(status)) {
1472 fd = -1;
1476 if ((fd == -1)
1477 && !find_new_dc(mem_ctx, domain, domain->dcname, &domain->dcaddr, &fd))
1479 /* This is the one place where we will
1480 set the global winbindd offline state
1481 to true, if a "WINBINDD_OFFLINE" entry
1482 is found in the winbindd cache. */
1483 set_global_winbindd_state_offline();
1484 break;
1487 new_conn->cli = NULL;
1489 result = cm_prepare_connection(domain, fd, domain->dcname,
1490 &new_conn->cli, &retry);
1492 if (!retry)
1493 break;
1496 if (NT_STATUS_IS_OK(result)) {
1498 winbindd_set_locator_kdc_envs(domain);
1500 if (domain->online == False) {
1501 /* We're changing state from offline to online. */
1502 set_global_winbindd_state_online();
1504 set_domain_online(domain);
1505 } else {
1506 /* Ensure we setup the retry handler. */
1507 set_domain_offline(domain);
1510 talloc_destroy(mem_ctx);
1511 return result;
1514 /* Close down all open pipes on a connection. */
1516 void invalidate_cm_connection(struct winbindd_cm_conn *conn)
1518 /* We're closing down a possibly dead
1519 connection. Don't have impossibly long (10s) timeouts. */
1521 if (conn->cli) {
1522 cli_set_timeout(conn->cli, 1000); /* 1 second. */
1525 if (conn->samr_pipe != NULL) {
1526 TALLOC_FREE(conn->samr_pipe);
1527 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1528 if (conn->cli) {
1529 cli_set_timeout(conn->cli, 500);
1533 if (conn->lsa_pipe != NULL) {
1534 TALLOC_FREE(conn->lsa_pipe);
1535 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1536 if (conn->cli) {
1537 cli_set_timeout(conn->cli, 500);
1541 if (conn->lsa_pipe_tcp != NULL) {
1542 TALLOC_FREE(conn->lsa_pipe_tcp);
1543 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1544 if (conn->cli) {
1545 cli_set_timeout(conn->cli, 500);
1549 if (conn->netlogon_pipe != NULL) {
1550 TALLOC_FREE(conn->netlogon_pipe);
1551 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1552 if (conn->cli) {
1553 cli_set_timeout(conn->cli, 500);
1557 if (conn->cli) {
1558 cli_shutdown(conn->cli);
1561 conn->cli = NULL;
1564 void close_conns_after_fork(void)
1566 struct winbindd_domain *domain;
1568 for (domain = domain_list(); domain; domain = domain->next) {
1569 if (domain->conn.cli == NULL)
1570 continue;
1572 if (domain->conn.cli->fd == -1)
1573 continue;
1575 close(domain->conn.cli->fd);
1576 domain->conn.cli->fd = -1;
1580 static bool connection_ok(struct winbindd_domain *domain)
1582 bool ok;
1584 ok = cli_state_is_connected(domain->conn.cli);
1585 if (!ok) {
1586 DEBUG(3, ("connection_ok: Connection to %s for domain %s is not connected\n",
1587 domain->dcname, domain->name));
1588 return False;
1591 if (domain->online == False) {
1592 DEBUG(3, ("connection_ok: Domain %s is offline\n", domain->name));
1593 return False;
1596 return True;
1599 /* Initialize a new connection up to the RPC BIND.
1600 Bypass online status check so always does network calls. */
1602 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain)
1604 NTSTATUS result;
1606 /* Internal connections never use the network. */
1607 if (domain->internal) {
1608 domain->initialized = True;
1609 return NT_STATUS_OK;
1612 if (!winbindd_can_contact_domain(domain)) {
1613 invalidate_cm_connection(&domain->conn);
1614 domain->initialized = True;
1615 return NT_STATUS_OK;
1618 if (connection_ok(domain)) {
1619 if (!domain->initialized) {
1620 set_dc_type_and_flags(domain);
1622 return NT_STATUS_OK;
1625 invalidate_cm_connection(&domain->conn);
1627 result = cm_open_connection(domain, &domain->conn);
1629 if (NT_STATUS_IS_OK(result) && !domain->initialized) {
1630 set_dc_type_and_flags(domain);
1633 return result;
1636 NTSTATUS init_dc_connection(struct winbindd_domain *domain)
1638 if (domain->initialized && !domain->online) {
1639 /* We check for online status elsewhere. */
1640 return NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1643 return init_dc_connection_network(domain);
1646 static NTSTATUS init_dc_connection_rpc(struct winbindd_domain *domain)
1648 NTSTATUS status;
1650 status = init_dc_connection(domain);
1651 if (!NT_STATUS_IS_OK(status)) {
1652 return status;
1655 if (!domain->internal && domain->conn.cli == NULL) {
1656 /* happens for trusted domains without inbound trust */
1657 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
1660 return NT_STATUS_OK;
1663 /******************************************************************************
1664 Set the trust flags (direction and forest location) for a domain
1665 ******************************************************************************/
1667 static bool set_dc_type_and_flags_trustinfo( struct winbindd_domain *domain )
1669 struct winbindd_domain *our_domain;
1670 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
1671 struct netr_DomainTrustList trusts;
1672 int i;
1673 uint32 flags = (NETR_TRUST_FLAG_IN_FOREST |
1674 NETR_TRUST_FLAG_OUTBOUND |
1675 NETR_TRUST_FLAG_INBOUND);
1676 struct rpc_pipe_client *cli;
1677 TALLOC_CTX *mem_ctx = NULL;
1679 DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s\n", domain->name ));
1681 /* Our primary domain doesn't need to worry about trust flags.
1682 Force it to go through the network setup */
1683 if ( domain->primary ) {
1684 return False;
1687 our_domain = find_our_domain();
1689 if ( !connection_ok(our_domain) ) {
1690 DEBUG(3,("set_dc_type_and_flags_trustinfo: No connection to our domain!\n"));
1691 return False;
1694 /* This won't work unless our domain is AD */
1696 if ( !our_domain->active_directory ) {
1697 return False;
1700 /* Use DsEnumerateDomainTrusts to get us the trust direction
1701 and type */
1703 result = cm_connect_netlogon(our_domain, &cli);
1705 if (!NT_STATUS_IS_OK(result)) {
1706 DEBUG(5, ("set_dc_type_and_flags_trustinfo: Could not open "
1707 "a connection to %s for PIPE_NETLOGON (%s)\n",
1708 domain->name, nt_errstr(result)));
1709 return False;
1712 if ( (mem_ctx = talloc_init("set_dc_type_and_flags_trustinfo")) == NULL ) {
1713 DEBUG(0,("set_dc_type_and_flags_trustinfo: talloc_init() failed!\n"));
1714 return False;
1717 result = rpccli_netr_DsrEnumerateDomainTrusts(cli, mem_ctx,
1718 cli->desthost,
1719 flags,
1720 &trusts,
1721 NULL);
1722 if (!NT_STATUS_IS_OK(result)) {
1723 DEBUG(0,("set_dc_type_and_flags_trustinfo: "
1724 "failed to query trusted domain list: %s\n",
1725 nt_errstr(result)));
1726 talloc_destroy(mem_ctx);
1727 return false;
1730 /* Now find the domain name and get the flags */
1732 for ( i=0; i<trusts.count; i++ ) {
1733 if ( strequal( domain->name, trusts.array[i].netbios_name) ) {
1734 domain->domain_flags = trusts.array[i].trust_flags;
1735 domain->domain_type = trusts.array[i].trust_type;
1736 domain->domain_trust_attribs = trusts.array[i].trust_attributes;
1738 if ( domain->domain_type == NETR_TRUST_TYPE_UPLEVEL )
1739 domain->active_directory = True;
1741 /* This flag is only set if the domain is *our*
1742 primary domain and the primary domain is in
1743 native mode */
1745 domain->native_mode = (domain->domain_flags & NETR_TRUST_FLAG_NATIVE);
1747 DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s is %sin "
1748 "native mode.\n", domain->name,
1749 domain->native_mode ? "" : "NOT "));
1751 DEBUG(5,("set_dc_type_and_flags_trustinfo: domain %s is %s"
1752 "running active directory.\n", domain->name,
1753 domain->active_directory ? "" : "NOT "));
1756 domain->initialized = True;
1758 break;
1762 talloc_destroy( mem_ctx );
1764 return domain->initialized;
1767 /******************************************************************************
1768 We can 'sense' certain things about the DC by it's replies to certain
1769 questions.
1771 This tells us if this particular remote server is Active Directory, and if it
1772 is native mode.
1773 ******************************************************************************/
1775 static void set_dc_type_and_flags_connect( struct winbindd_domain *domain )
1777 NTSTATUS result;
1778 WERROR werr;
1779 TALLOC_CTX *mem_ctx = NULL;
1780 struct rpc_pipe_client *cli = NULL;
1781 struct policy_handle pol;
1782 union dssetup_DsRoleInfo info;
1783 union lsa_PolicyInformation *lsa_info = NULL;
1785 if (!connection_ok(domain)) {
1786 return;
1789 mem_ctx = talloc_init("set_dc_type_and_flags on domain %s\n",
1790 domain->name);
1791 if (!mem_ctx) {
1792 DEBUG(1, ("set_dc_type_and_flags_connect: talloc_init() failed\n"));
1793 return;
1796 DEBUG(5, ("set_dc_type_and_flags_connect: domain %s\n", domain->name ));
1798 result = cli_rpc_pipe_open_noauth(domain->conn.cli,
1799 &ndr_table_dssetup.syntax_id,
1800 &cli);
1802 if (!NT_STATUS_IS_OK(result)) {
1803 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
1804 "PI_DSSETUP on domain %s: (%s)\n",
1805 domain->name, nt_errstr(result)));
1807 /* if this is just a non-AD domain we need to continue
1808 * identifying so that we can in the end return with
1809 * domain->initialized = True - gd */
1811 goto no_dssetup;
1814 result = rpccli_dssetup_DsRoleGetPrimaryDomainInformation(cli, mem_ctx,
1815 DS_ROLE_BASIC_INFORMATION,
1816 &info,
1817 &werr);
1818 TALLOC_FREE(cli);
1820 if (!NT_STATUS_IS_OK(result)) {
1821 DEBUG(5, ("set_dc_type_and_flags_connect: rpccli_ds_getprimarydominfo "
1822 "on domain %s failed: (%s)\n",
1823 domain->name, nt_errstr(result)));
1825 /* older samba3 DCs will return DCERPC_FAULT_OP_RNG_ERROR for
1826 * every opcode on the DSSETUP pipe, continue with
1827 * no_dssetup mode here as well to get domain->initialized
1828 * set - gd */
1830 if (NT_STATUS_V(result) == DCERPC_FAULT_OP_RNG_ERROR) {
1831 goto no_dssetup;
1834 TALLOC_FREE(mem_ctx);
1835 return;
1838 if ((info.basic.flags & DS_ROLE_PRIMARY_DS_RUNNING) &&
1839 !(info.basic.flags & DS_ROLE_PRIMARY_DS_MIXED_MODE)) {
1840 domain->native_mode = True;
1841 } else {
1842 domain->native_mode = False;
1845 no_dssetup:
1846 result = cli_rpc_pipe_open_noauth(domain->conn.cli,
1847 &ndr_table_lsarpc.syntax_id, &cli);
1849 if (!NT_STATUS_IS_OK(result)) {
1850 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
1851 "PI_LSARPC on domain %s: (%s)\n",
1852 domain->name, nt_errstr(result)));
1853 TALLOC_FREE(cli);
1854 TALLOC_FREE(mem_ctx);
1855 return;
1858 result = rpccli_lsa_open_policy2(cli, mem_ctx, True,
1859 SEC_FLAG_MAXIMUM_ALLOWED, &pol);
1861 if (NT_STATUS_IS_OK(result)) {
1862 /* This particular query is exactly what Win2k clients use
1863 to determine that the DC is active directory */
1864 result = rpccli_lsa_QueryInfoPolicy2(cli, mem_ctx,
1865 &pol,
1866 LSA_POLICY_INFO_DNS,
1867 &lsa_info);
1870 if (NT_STATUS_IS_OK(result)) {
1871 domain->active_directory = True;
1873 if (lsa_info->dns.name.string) {
1874 fstrcpy(domain->name, lsa_info->dns.name.string);
1877 if (lsa_info->dns.dns_domain.string) {
1878 fstrcpy(domain->alt_name,
1879 lsa_info->dns.dns_domain.string);
1882 /* See if we can set some domain trust flags about
1883 ourself */
1885 if (lsa_info->dns.dns_forest.string) {
1886 fstrcpy(domain->forest_name,
1887 lsa_info->dns.dns_forest.string);
1889 if (strequal(domain->forest_name, domain->alt_name)) {
1890 domain->domain_flags |= NETR_TRUST_FLAG_TREEROOT;
1894 if (lsa_info->dns.sid) {
1895 sid_copy(&domain->sid, lsa_info->dns.sid);
1897 } else {
1898 domain->active_directory = False;
1900 result = rpccli_lsa_open_policy(cli, mem_ctx, True,
1901 SEC_FLAG_MAXIMUM_ALLOWED,
1902 &pol);
1904 if (!NT_STATUS_IS_OK(result)) {
1905 goto done;
1908 result = rpccli_lsa_QueryInfoPolicy(cli, mem_ctx,
1909 &pol,
1910 LSA_POLICY_INFO_ACCOUNT_DOMAIN,
1911 &lsa_info);
1913 if (NT_STATUS_IS_OK(result)) {
1915 if (lsa_info->account_domain.name.string) {
1916 fstrcpy(domain->name,
1917 lsa_info->account_domain.name.string);
1920 if (lsa_info->account_domain.sid) {
1921 sid_copy(&domain->sid, lsa_info->account_domain.sid);
1925 done:
1927 DEBUG(5, ("set_dc_type_and_flags_connect: domain %s is %sin native mode.\n",
1928 domain->name, domain->native_mode ? "" : "NOT "));
1930 DEBUG(5,("set_dc_type_and_flags_connect: domain %s is %srunning active directory.\n",
1931 domain->name, domain->active_directory ? "" : "NOT "));
1933 domain->can_do_ncacn_ip_tcp = domain->active_directory;
1935 TALLOC_FREE(cli);
1937 TALLOC_FREE(mem_ctx);
1939 domain->initialized = True;
1942 /**********************************************************************
1943 Set the domain_flags (trust attributes, domain operating modes, etc...
1944 ***********************************************************************/
1946 static void set_dc_type_and_flags( struct winbindd_domain *domain )
1948 /* we always have to contact our primary domain */
1950 if ( domain->primary ) {
1951 DEBUG(10,("set_dc_type_and_flags: setting up flags for "
1952 "primary domain\n"));
1953 set_dc_type_and_flags_connect( domain );
1954 return;
1957 /* Use our DC to get the information if possible */
1959 if ( !set_dc_type_and_flags_trustinfo( domain ) ) {
1960 /* Otherwise, fallback to contacting the
1961 domain directly */
1962 set_dc_type_and_flags_connect( domain );
1965 return;
1970 /**********************************************************************
1971 ***********************************************************************/
1973 static bool cm_get_schannel_dcinfo(struct winbindd_domain *domain,
1974 struct dcinfo **ppdc)
1976 NTSTATUS result;
1977 struct rpc_pipe_client *netlogon_pipe;
1979 if (lp_client_schannel() == False) {
1980 return False;
1983 result = cm_connect_netlogon(domain, &netlogon_pipe);
1984 if (!NT_STATUS_IS_OK(result)) {
1985 return False;
1988 /* Return a pointer to the struct dcinfo from the
1989 netlogon pipe. */
1991 if (!domain->conn.netlogon_pipe->dc) {
1992 return false;
1995 *ppdc = domain->conn.netlogon_pipe->dc;
1996 return True;
1999 NTSTATUS cm_connect_sam(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2000 struct rpc_pipe_client **cli, struct policy_handle *sam_handle)
2002 struct winbindd_cm_conn *conn;
2003 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2004 struct dcinfo *p_dcinfo;
2005 char *machine_password = NULL;
2006 char *machine_account = NULL;
2007 char *domain_name = NULL;
2009 result = init_dc_connection_rpc(domain);
2010 if (!NT_STATUS_IS_OK(result)) {
2011 return result;
2014 conn = &domain->conn;
2016 if (rpccli_is_connected(conn->samr_pipe)) {
2017 goto done;
2020 TALLOC_FREE(conn->samr_pipe);
2023 * No SAMR pipe yet. Attempt to get an NTLMSSP SPNEGO authenticated
2024 * sign and sealed pipe using the machine account password by
2025 * preference. If we can't - try schannel, if that fails, try
2026 * anonymous.
2029 if ((conn->cli->user_name[0] == '\0') ||
2030 (conn->cli->domain[0] == '\0') ||
2031 (conn->cli->password == NULL || conn->cli->password[0] == '\0'))
2033 result = get_trust_creds(domain, &machine_password,
2034 &machine_account, NULL);
2035 if (!NT_STATUS_IS_OK(result)) {
2036 DEBUG(10, ("cm_connect_sam: No no user available for "
2037 "domain %s, trying schannel\n", conn->cli->domain));
2038 goto schannel;
2040 domain_name = domain->name;
2041 } else {
2042 machine_password = SMB_STRDUP(conn->cli->password);
2043 machine_account = SMB_STRDUP(conn->cli->user_name);
2044 domain_name = conn->cli->domain;
2047 if (!machine_password || !machine_account) {
2048 result = NT_STATUS_NO_MEMORY;
2049 goto done;
2052 /* We have an authenticated connection. Use a NTLMSSP SPNEGO
2053 authenticated SAMR pipe with sign & seal. */
2054 result = cli_rpc_pipe_open_spnego_ntlmssp(conn->cli,
2055 &ndr_table_samr.syntax_id,
2056 NCACN_NP,
2057 PIPE_AUTH_LEVEL_PRIVACY,
2058 domain_name,
2059 machine_account,
2060 machine_password,
2061 &conn->samr_pipe);
2063 if (!NT_STATUS_IS_OK(result)) {
2064 DEBUG(10,("cm_connect_sam: failed to connect to SAMR "
2065 "pipe for domain %s using NTLMSSP "
2066 "authenticated pipe: user %s\\%s. Error was "
2067 "%s\n", domain->name, domain_name,
2068 machine_account, nt_errstr(result)));
2069 goto schannel;
2072 DEBUG(10,("cm_connect_sam: connected to SAMR pipe for "
2073 "domain %s using NTLMSSP authenticated "
2074 "pipe: user %s\\%s\n", domain->name,
2075 domain_name, machine_account));
2077 result = rpccli_samr_Connect2(conn->samr_pipe, mem_ctx,
2078 conn->samr_pipe->desthost,
2079 SEC_FLAG_MAXIMUM_ALLOWED,
2080 &conn->sam_connect_handle);
2081 if (NT_STATUS_IS_OK(result)) {
2082 goto open_domain;
2084 DEBUG(10,("cm_connect_sam: ntlmssp-sealed rpccli_samr_Connect2 "
2085 "failed for domain %s, error was %s. Trying schannel\n",
2086 domain->name, nt_errstr(result) ));
2087 TALLOC_FREE(conn->samr_pipe);
2089 schannel:
2091 /* Fall back to schannel if it's a W2K pre-SP1 box. */
2093 if (!cm_get_schannel_dcinfo(domain, &p_dcinfo)) {
2094 /* If this call fails - conn->cli can now be NULL ! */
2095 DEBUG(10, ("cm_connect_sam: Could not get schannel auth info "
2096 "for domain %s, trying anon\n", domain->name));
2097 goto anonymous;
2099 result = cli_rpc_pipe_open_schannel_with_key
2100 (conn->cli, &ndr_table_samr.syntax_id, NCACN_NP,
2101 PIPE_AUTH_LEVEL_PRIVACY,
2102 domain->name, p_dcinfo, &conn->samr_pipe);
2104 if (!NT_STATUS_IS_OK(result)) {
2105 DEBUG(10,("cm_connect_sam: failed to connect to SAMR pipe for "
2106 "domain %s using schannel. Error was %s\n",
2107 domain->name, nt_errstr(result) ));
2108 goto anonymous;
2110 DEBUG(10,("cm_connect_sam: connected to SAMR pipe for domain %s using "
2111 "schannel.\n", domain->name ));
2113 result = rpccli_samr_Connect2(conn->samr_pipe, mem_ctx,
2114 conn->samr_pipe->desthost,
2115 SEC_FLAG_MAXIMUM_ALLOWED,
2116 &conn->sam_connect_handle);
2117 if (NT_STATUS_IS_OK(result)) {
2118 goto open_domain;
2120 DEBUG(10,("cm_connect_sam: schannel-sealed rpccli_samr_Connect2 failed "
2121 "for domain %s, error was %s. Trying anonymous\n",
2122 domain->name, nt_errstr(result) ));
2123 TALLOC_FREE(conn->samr_pipe);
2125 anonymous:
2127 /* Finally fall back to anonymous. */
2128 result = cli_rpc_pipe_open_noauth(conn->cli, &ndr_table_samr.syntax_id,
2129 &conn->samr_pipe);
2131 if (!NT_STATUS_IS_OK(result)) {
2132 goto done;
2135 result = rpccli_samr_Connect2(conn->samr_pipe, mem_ctx,
2136 conn->samr_pipe->desthost,
2137 SEC_FLAG_MAXIMUM_ALLOWED,
2138 &conn->sam_connect_handle);
2139 if (!NT_STATUS_IS_OK(result)) {
2140 DEBUG(10,("cm_connect_sam: rpccli_samr_Connect2 failed "
2141 "for domain %s Error was %s\n",
2142 domain->name, nt_errstr(result) ));
2143 goto done;
2146 open_domain:
2147 result = rpccli_samr_OpenDomain(conn->samr_pipe,
2148 mem_ctx,
2149 &conn->sam_connect_handle,
2150 SEC_FLAG_MAXIMUM_ALLOWED,
2151 &domain->sid,
2152 &conn->sam_domain_handle);
2154 done:
2156 if (NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
2158 * if we got access denied, we might just have no access rights
2159 * to talk to the remote samr server server (e.g. when we are a
2160 * PDC and we are connecting a w2k8 pdc via an interdomain
2161 * trust). In that case do not invalidate the whole connection
2162 * stack
2164 TALLOC_FREE(conn->samr_pipe);
2165 ZERO_STRUCT(conn->sam_domain_handle);
2166 return result;
2167 } else if (!NT_STATUS_IS_OK(result)) {
2168 invalidate_cm_connection(conn);
2169 return result;
2172 *cli = conn->samr_pipe;
2173 *sam_handle = conn->sam_domain_handle;
2174 SAFE_FREE(machine_password);
2175 SAFE_FREE(machine_account);
2176 return result;
2179 /**********************************************************************
2180 open an schanneld ncacn_ip_tcp connection to LSA
2181 ***********************************************************************/
2183 NTSTATUS cm_connect_lsa_tcp(struct winbindd_domain *domain,
2184 TALLOC_CTX *mem_ctx,
2185 struct rpc_pipe_client **cli)
2187 struct winbindd_cm_conn *conn;
2188 struct dcinfo *dcinfo;
2189 NTSTATUS status;
2191 DEBUG(10,("cm_connect_lsa_tcp\n"));
2193 status = init_dc_connection_rpc(domain);
2194 if (!NT_STATUS_IS_OK(status)) {
2195 return status;
2198 conn = &domain->conn;
2200 if (conn->lsa_pipe_tcp &&
2201 conn->lsa_pipe_tcp->transport->transport == NCACN_IP_TCP &&
2202 conn->lsa_pipe_tcp->auth->auth_level == PIPE_AUTH_LEVEL_PRIVACY &&
2203 rpccli_is_connected(conn->lsa_pipe_tcp)) {
2204 goto done;
2207 TALLOC_FREE(conn->lsa_pipe_tcp);
2209 if (!cm_get_schannel_dcinfo(domain, &dcinfo)) {
2210 status = NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2211 goto done;
2214 status = cli_rpc_pipe_open_schannel_with_key(conn->cli,
2215 &ndr_table_lsarpc.syntax_id,
2216 NCACN_IP_TCP,
2217 PIPE_AUTH_LEVEL_PRIVACY,
2218 domain->name,
2219 dcinfo,
2220 &conn->lsa_pipe_tcp);
2221 if (!NT_STATUS_IS_OK(status)) {
2222 DEBUG(10,("cli_rpc_pipe_open_schannel_with_key failed: %s\n",
2223 nt_errstr(status)));
2224 goto done;
2227 done:
2228 if (!NT_STATUS_IS_OK(status)) {
2229 TALLOC_FREE(conn->lsa_pipe_tcp);
2230 return status;
2233 *cli = conn->lsa_pipe_tcp;
2235 return status;
2238 NTSTATUS cm_connect_lsa(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2239 struct rpc_pipe_client **cli, struct policy_handle *lsa_policy)
2241 struct winbindd_cm_conn *conn;
2242 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2243 struct dcinfo *p_dcinfo;
2245 result = init_dc_connection_rpc(domain);
2246 if (!NT_STATUS_IS_OK(result))
2247 return result;
2249 conn = &domain->conn;
2251 if (rpccli_is_connected(conn->lsa_pipe)) {
2252 goto done;
2255 TALLOC_FREE(conn->lsa_pipe);
2257 if ((conn->cli->user_name[0] == '\0') ||
2258 (conn->cli->domain[0] == '\0') ||
2259 (conn->cli->password == NULL || conn->cli->password[0] == '\0')) {
2260 DEBUG(10, ("cm_connect_lsa: No no user available for "
2261 "domain %s, trying schannel\n", conn->cli->domain));
2262 goto schannel;
2265 /* We have an authenticated connection. Use a NTLMSSP SPNEGO
2266 * authenticated LSA pipe with sign & seal. */
2267 result = cli_rpc_pipe_open_spnego_ntlmssp
2268 (conn->cli, &ndr_table_lsarpc.syntax_id, NCACN_NP,
2269 PIPE_AUTH_LEVEL_PRIVACY,
2270 conn->cli->domain, conn->cli->user_name, conn->cli->password,
2271 &conn->lsa_pipe);
2273 if (!NT_STATUS_IS_OK(result)) {
2274 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
2275 "domain %s using NTLMSSP authenticated pipe: user "
2276 "%s\\%s. Error was %s. Trying schannel.\n",
2277 domain->name, conn->cli->domain,
2278 conn->cli->user_name, nt_errstr(result)));
2279 goto schannel;
2282 DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
2283 "NTLMSSP authenticated pipe: user %s\\%s\n",
2284 domain->name, conn->cli->domain, conn->cli->user_name ));
2286 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2287 SEC_FLAG_MAXIMUM_ALLOWED,
2288 &conn->lsa_policy);
2289 if (NT_STATUS_IS_OK(result)) {
2290 goto done;
2293 DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
2294 "schannel\n"));
2296 TALLOC_FREE(conn->lsa_pipe);
2298 schannel:
2300 /* Fall back to schannel if it's a W2K pre-SP1 box. */
2302 if (!cm_get_schannel_dcinfo(domain, &p_dcinfo)) {
2303 /* If this call fails - conn->cli can now be NULL ! */
2304 DEBUG(10, ("cm_connect_lsa: Could not get schannel auth info "
2305 "for domain %s, trying anon\n", domain->name));
2306 goto anonymous;
2308 result = cli_rpc_pipe_open_schannel_with_key
2309 (conn->cli, &ndr_table_lsarpc.syntax_id, NCACN_NP,
2310 PIPE_AUTH_LEVEL_PRIVACY,
2311 domain->name, p_dcinfo, &conn->lsa_pipe);
2313 if (!NT_STATUS_IS_OK(result)) {
2314 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
2315 "domain %s using schannel. Error was %s\n",
2316 domain->name, nt_errstr(result) ));
2317 goto anonymous;
2319 DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
2320 "schannel.\n", domain->name ));
2322 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2323 SEC_FLAG_MAXIMUM_ALLOWED,
2324 &conn->lsa_policy);
2325 if (NT_STATUS_IS_OK(result)) {
2326 goto done;
2329 DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
2330 "anonymous\n"));
2332 TALLOC_FREE(conn->lsa_pipe);
2334 anonymous:
2336 result = cli_rpc_pipe_open_noauth(conn->cli,
2337 &ndr_table_lsarpc.syntax_id,
2338 &conn->lsa_pipe);
2339 if (!NT_STATUS_IS_OK(result)) {
2340 result = NT_STATUS_PIPE_NOT_AVAILABLE;
2341 goto done;
2344 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2345 SEC_FLAG_MAXIMUM_ALLOWED,
2346 &conn->lsa_policy);
2347 done:
2348 if (!NT_STATUS_IS_OK(result)) {
2349 invalidate_cm_connection(conn);
2350 return result;
2353 *cli = conn->lsa_pipe;
2354 *lsa_policy = conn->lsa_policy;
2355 return result;
2358 /****************************************************************************
2359 Open the netlogon pipe to this DC. Use schannel if specified in client conf.
2360 session key stored in conn->netlogon_pipe->dc->sess_key.
2361 ****************************************************************************/
2363 NTSTATUS cm_connect_netlogon(struct winbindd_domain *domain,
2364 struct rpc_pipe_client **cli)
2366 struct winbindd_cm_conn *conn;
2367 NTSTATUS result;
2369 uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS;
2370 uint8 mach_pwd[16];
2371 uint32 sec_chan_type;
2372 const char *account_name;
2373 struct rpc_pipe_client *netlogon_pipe = NULL;
2375 *cli = NULL;
2377 result = init_dc_connection_rpc(domain);
2378 if (!NT_STATUS_IS_OK(result)) {
2379 return result;
2382 conn = &domain->conn;
2384 if (rpccli_is_connected(conn->netlogon_pipe)) {
2385 *cli = conn->netlogon_pipe;
2386 return NT_STATUS_OK;
2389 TALLOC_FREE(conn->netlogon_pipe);
2391 result = cli_rpc_pipe_open_noauth(conn->cli,
2392 &ndr_table_netlogon.syntax_id,
2393 &netlogon_pipe);
2394 if (!NT_STATUS_IS_OK(result)) {
2395 return result;
2398 if ((!IS_DC) && (!domain->primary)) {
2399 /* Clear the schannel request bit and drop down */
2400 neg_flags &= ~NETLOGON_NEG_SCHANNEL;
2401 goto no_schannel;
2404 if (lp_client_schannel() != False) {
2405 neg_flags |= NETLOGON_NEG_SCHANNEL;
2408 if (!get_trust_pw_hash(domain->name, mach_pwd, &account_name,
2409 &sec_chan_type))
2411 TALLOC_FREE(netlogon_pipe);
2412 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2415 result = rpccli_netlogon_setup_creds(
2416 netlogon_pipe,
2417 domain->dcname, /* server name. */
2418 domain->name, /* domain name */
2419 global_myname(), /* client name */
2420 account_name, /* machine account */
2421 mach_pwd, /* machine password */
2422 sec_chan_type, /* from get_trust_pw */
2423 &neg_flags);
2425 if (!NT_STATUS_IS_OK(result)) {
2426 TALLOC_FREE(netlogon_pipe);
2427 return result;
2430 if ((lp_client_schannel() == True) &&
2431 ((neg_flags & NETLOGON_NEG_SCHANNEL) == 0)) {
2432 DEBUG(3, ("Server did not offer schannel\n"));
2433 TALLOC_FREE(netlogon_pipe);
2434 return NT_STATUS_ACCESS_DENIED;
2437 no_schannel:
2438 if ((lp_client_schannel() == False) ||
2439 ((neg_flags & NETLOGON_NEG_SCHANNEL) == 0)) {
2441 * NetSamLogonEx only works for schannel
2443 domain->can_do_samlogon_ex = False;
2445 /* We're done - just keep the existing connection to NETLOGON
2446 * open */
2447 conn->netlogon_pipe = netlogon_pipe;
2448 *cli = conn->netlogon_pipe;
2449 return NT_STATUS_OK;
2452 /* Using the credentials from the first pipe, open a signed and sealed
2453 second netlogon pipe. The session key is stored in the schannel
2454 part of the new pipe auth struct.
2457 result = cli_rpc_pipe_open_schannel_with_key(
2458 conn->cli, &ndr_table_netlogon.syntax_id, NCACN_NP,
2459 PIPE_AUTH_LEVEL_PRIVACY, domain->name, netlogon_pipe->dc,
2460 &conn->netlogon_pipe);
2462 /* We can now close the initial netlogon pipe. */
2463 TALLOC_FREE(netlogon_pipe);
2465 if (!NT_STATUS_IS_OK(result)) {
2466 DEBUG(3, ("Could not open schannel'ed NETLOGON pipe. Error "
2467 "was %s\n", nt_errstr(result)));
2469 invalidate_cm_connection(conn);
2470 return result;
2474 * Try NetSamLogonEx for AD domains
2476 domain->can_do_samlogon_ex = domain->active_directory;
2478 *cli = conn->netlogon_pipe;
2479 return NT_STATUS_OK;