s3:winbindd: fix problems with SIGCHLD handling (bug #7317)
[Samba.git] / source3 / winbindd / winbindd_cm.c
blob34c1a397657f1616416e2088c323ef3f4425e312
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"
63 #include "../libcli/auth/libcli_auth.h"
64 #include "../librpc/gen_ndr/cli_netlogon.h"
65 #include "../librpc/gen_ndr/cli_samr.h"
66 #include "../librpc/gen_ndr/cli_lsa.h"
67 #include "../librpc/gen_ndr/cli_dssetup.h"
69 #undef DBGC_CLASS
70 #define DBGC_CLASS DBGC_WINBIND
72 struct dc_name_ip {
73 fstring name;
74 struct sockaddr_storage ss;
77 extern struct winbindd_methods reconnect_methods;
78 extern bool override_logfile;
80 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain);
81 static void set_dc_type_and_flags( struct winbindd_domain *domain );
82 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
83 struct dc_name_ip **dcs, int *num_dcs);
85 /****************************************************************
86 Child failed to find DC's. Reschedule check.
87 ****************************************************************/
89 static void msg_failed_to_go_online(struct messaging_context *msg,
90 void *private_data,
91 uint32_t msg_type,
92 struct server_id server_id,
93 DATA_BLOB *data)
95 struct winbindd_domain *domain;
96 const char *domainname = (const char *)data->data;
98 if (data->data == NULL || data->length == 0) {
99 return;
102 DEBUG(5,("msg_fail_to_go_online: received for domain %s.\n", domainname));
104 for (domain = domain_list(); domain; domain = domain->next) {
105 if (domain->internal) {
106 continue;
109 if (strequal(domain->name, domainname)) {
110 if (domain->online) {
111 /* We're already online, ignore. */
112 DEBUG(5,("msg_fail_to_go_online: domain %s "
113 "already online.\n", domainname));
114 continue;
117 /* Reschedule the online check. */
118 set_domain_offline(domain);
119 break;
124 /****************************************************************
125 Actually cause a reconnect from a message.
126 ****************************************************************/
128 static void msg_try_to_go_online(struct messaging_context *msg,
129 void *private_data,
130 uint32_t msg_type,
131 struct server_id server_id,
132 DATA_BLOB *data)
134 struct winbindd_domain *domain;
135 const char *domainname = (const char *)data->data;
137 if (data->data == NULL || data->length == 0) {
138 return;
141 DEBUG(5,("msg_try_to_go_online: received for domain %s.\n", domainname));
143 for (domain = domain_list(); domain; domain = domain->next) {
144 if (domain->internal) {
145 continue;
148 if (strequal(domain->name, domainname)) {
150 if (domain->online) {
151 /* We're already online, ignore. */
152 DEBUG(5,("msg_try_to_go_online: domain %s "
153 "already online.\n", domainname));
154 continue;
157 /* This call takes care of setting the online
158 flag to true if we connected, or re-adding
159 the offline handler if false. Bypasses online
160 check so always does network calls. */
162 init_dc_connection_network(domain);
163 break;
168 /****************************************************************
169 Fork a child to try and contact a DC. Do this as contacting a
170 DC requires blocking lookups and we don't want to block our
171 parent.
172 ****************************************************************/
174 static bool fork_child_dc_connect(struct winbindd_domain *domain)
176 struct dc_name_ip *dcs = NULL;
177 int num_dcs = 0;
178 TALLOC_CTX *mem_ctx = NULL;
179 pid_t parent_pid = sys_getpid();
180 char *lfile = NULL;
182 if (domain->dc_probe_pid != (pid_t)-1) {
184 * We might already have a DC probe
185 * child working, check.
187 if (process_exists_by_pid(domain->dc_probe_pid)) {
188 DEBUG(10,("fork_child_dc_connect: pid %u already "
189 "checking for DC's.\n",
190 (unsigned int)domain->dc_probe_pid));
191 return true;
193 domain->dc_probe_pid = (pid_t)-1;
196 domain->dc_probe_pid = sys_fork();
198 if (domain->dc_probe_pid == (pid_t)-1) {
199 DEBUG(0, ("fork_child_dc_connect: Could not fork: %s\n", strerror(errno)));
200 return False;
203 if (domain->dc_probe_pid != (pid_t)0) {
204 /* Parent */
205 messaging_register(winbind_messaging_context(), NULL,
206 MSG_WINBIND_TRY_TO_GO_ONLINE,
207 msg_try_to_go_online);
208 messaging_register(winbind_messaging_context(), NULL,
209 MSG_WINBIND_FAILED_TO_GO_ONLINE,
210 msg_failed_to_go_online);
211 return True;
214 /* Child. */
216 /* Leave messages blocked - we will never process one. */
218 if (!override_logfile) {
219 if (asprintf(&lfile, "%s/log.winbindd-dc-connect", get_dyn_LOGFILEBASE()) == -1) {
220 DEBUG(0, ("fork_child_dc_connect: out of memory.\n"));
221 _exit(1);
225 if (!winbindd_reinit_after_fork(lfile)) {
226 messaging_send_buf(winbind_messaging_context(),
227 pid_to_procid(parent_pid),
228 MSG_WINBIND_FAILED_TO_GO_ONLINE,
229 (uint8 *)domain->name,
230 strlen(domain->name)+1);
231 _exit(1);
233 SAFE_FREE(lfile);
235 mem_ctx = talloc_init("fork_child_dc_connect");
236 if (!mem_ctx) {
237 DEBUG(0,("talloc_init failed.\n"));
238 messaging_send_buf(winbind_messaging_context(),
239 pid_to_procid(parent_pid),
240 MSG_WINBIND_FAILED_TO_GO_ONLINE,
241 (uint8 *)domain->name,
242 strlen(domain->name)+1);
243 _exit(1);
246 if ((!get_dcs(mem_ctx, domain, &dcs, &num_dcs)) || (num_dcs == 0)) {
247 /* Still offline ? Can't find DC's. */
248 messaging_send_buf(winbind_messaging_context(),
249 pid_to_procid(parent_pid),
250 MSG_WINBIND_FAILED_TO_GO_ONLINE,
251 (uint8 *)domain->name,
252 strlen(domain->name)+1);
253 _exit(0);
256 /* We got a DC. Send a message to our parent to get it to
257 try and do the same. */
259 messaging_send_buf(winbind_messaging_context(),
260 pid_to_procid(parent_pid),
261 MSG_WINBIND_TRY_TO_GO_ONLINE,
262 (uint8 *)domain->name,
263 strlen(domain->name)+1);
264 _exit(0);
267 /****************************************************************
268 Handler triggered if we're offline to try and detect a DC.
269 ****************************************************************/
271 static void check_domain_online_handler(struct event_context *ctx,
272 struct timed_event *te,
273 struct timeval now,
274 void *private_data)
276 struct winbindd_domain *domain =
277 (struct winbindd_domain *)private_data;
279 DEBUG(10,("check_domain_online_handler: called for domain "
280 "%s (online = %s)\n", domain->name,
281 domain->online ? "True" : "False" ));
283 TALLOC_FREE(domain->check_online_event);
285 /* Are we still in "startup" mode ? */
287 if (domain->startup && (now.tv_sec > domain->startup_time + 30)) {
288 /* No longer in "startup" mode. */
289 DEBUG(10,("check_domain_online_handler: domain %s no longer in 'startup' mode.\n",
290 domain->name ));
291 domain->startup = False;
294 /* We've been told to stay offline, so stay
295 that way. */
297 if (get_global_winbindd_state_offline()) {
298 DEBUG(10,("check_domain_online_handler: domain %s remaining globally offline\n",
299 domain->name ));
300 return;
303 /* Fork a child to test if it can contact a DC.
304 If it can then send ourselves a message to
305 cause a reconnect. */
307 fork_child_dc_connect(domain);
310 /****************************************************************
311 If we're still offline setup the timeout check.
312 ****************************************************************/
314 static void calc_new_online_timeout_check(struct winbindd_domain *domain)
316 int wbr = lp_winbind_reconnect_delay();
318 if (domain->startup) {
319 domain->check_online_timeout = 10;
320 } else if (domain->check_online_timeout < wbr) {
321 domain->check_online_timeout = wbr;
325 /****************************************************************
326 Set domain offline and also add handler to put us back online
327 if we detect a DC.
328 ****************************************************************/
330 void set_domain_offline(struct winbindd_domain *domain)
332 DEBUG(10,("set_domain_offline: called for domain %s\n",
333 domain->name ));
335 TALLOC_FREE(domain->check_online_event);
337 if (domain->internal) {
338 DEBUG(3,("set_domain_offline: domain %s is internal - logic error.\n",
339 domain->name ));
340 return;
343 domain->online = False;
345 /* Offline domains are always initialized. They're
346 re-initialized when they go back online. */
348 domain->initialized = True;
350 /* We only add the timeout handler that checks and
351 allows us to go back online when we've not
352 been told to remain offline. */
354 if (get_global_winbindd_state_offline()) {
355 DEBUG(10,("set_domain_offline: domain %s remaining globally offline\n",
356 domain->name ));
357 return;
360 /* If we're in startup mode, check again in 10 seconds, not in
361 lp_winbind_reconnect_delay() seconds (which is 30 seconds by default). */
363 calc_new_online_timeout_check(domain);
365 domain->check_online_event = event_add_timed(winbind_event_context(),
366 NULL,
367 timeval_current_ofs(domain->check_online_timeout,0),
368 check_domain_online_handler,
369 domain);
371 /* The above *has* to succeed for winbindd to work. */
372 if (!domain->check_online_event) {
373 smb_panic("set_domain_offline: failed to add online handler");
376 DEBUG(10,("set_domain_offline: added event handler for domain %s\n",
377 domain->name ));
379 /* Send an offline message to the idmap child when our
380 primary domain goes offline */
382 if ( domain->primary ) {
383 struct winbindd_child *idmap = idmap_child();
385 if ( idmap->pid != 0 ) {
386 messaging_send_buf(winbind_messaging_context(),
387 pid_to_procid(idmap->pid),
388 MSG_WINBIND_OFFLINE,
389 (uint8 *)domain->name,
390 strlen(domain->name)+1);
394 return;
397 /****************************************************************
398 Set domain online - if allowed.
399 ****************************************************************/
401 static void set_domain_online(struct winbindd_domain *domain)
403 DEBUG(10,("set_domain_online: called for domain %s\n",
404 domain->name ));
406 if (domain->internal) {
407 DEBUG(3,("set_domain_online: domain %s is internal - logic error.\n",
408 domain->name ));
409 return;
412 if (get_global_winbindd_state_offline()) {
413 DEBUG(10,("set_domain_online: domain %s remaining globally offline\n",
414 domain->name ));
415 return;
418 winbindd_set_locator_kdc_envs(domain);
420 /* If we are waiting to get a krb5 ticket, trigger immediately. */
421 ccache_regain_all_now();
423 /* Ok, we're out of any startup mode now... */
424 domain->startup = False;
426 if (domain->online == False) {
427 /* We were offline - now we're online. We default to
428 using the MS-RPC backend if we started offline,
429 and if we're going online for the first time we
430 should really re-initialize the backends and the
431 checks to see if we're talking to an AD or NT domain.
434 domain->initialized = False;
436 /* 'reconnect_methods' is the MS-RPC backend. */
437 if (domain->backend == &reconnect_methods) {
438 domain->backend = NULL;
442 /* Ensure we have no online timeout checks. */
443 domain->check_online_timeout = 0;
444 TALLOC_FREE(domain->check_online_event);
446 /* Ensure we ignore any pending child messages. */
447 messaging_deregister(winbind_messaging_context(),
448 MSG_WINBIND_TRY_TO_GO_ONLINE, NULL);
449 messaging_deregister(winbind_messaging_context(),
450 MSG_WINBIND_FAILED_TO_GO_ONLINE, NULL);
452 domain->online = True;
454 /* Send an online message to the idmap child when our
455 primary domain comes online */
457 if ( domain->primary ) {
458 struct winbindd_child *idmap = idmap_child();
460 if ( idmap->pid != 0 ) {
461 messaging_send_buf(winbind_messaging_context(),
462 pid_to_procid(idmap->pid),
463 MSG_WINBIND_ONLINE,
464 (uint8 *)domain->name,
465 strlen(domain->name)+1);
469 return;
472 /****************************************************************
473 Requested to set a domain online.
474 ****************************************************************/
476 void set_domain_online_request(struct winbindd_domain *domain)
478 struct timeval tev;
480 DEBUG(10,("set_domain_online_request: called for domain %s\n",
481 domain->name ));
483 if (get_global_winbindd_state_offline()) {
484 DEBUG(10,("set_domain_online_request: domain %s remaining globally offline\n",
485 domain->name ));
486 return;
489 if (domain->internal) {
490 DEBUG(10, ("set_domain_online_request: Internal domains are "
491 "always online\n"));
492 return;
495 /* We've been told it's safe to go online and
496 try and connect to a DC. But I don't believe it
497 because network manager seems to lie.
498 Wait at least 5 seconds. Heuristics suck... */
501 GetTimeOfDay(&tev);
503 /* Go into "startup" mode again. */
504 domain->startup_time = tev.tv_sec;
505 domain->startup = True;
507 tev.tv_sec += 5;
509 if (!domain->check_online_event) {
510 /* If we've come from being globally offline we
511 don't have a check online event handler set.
512 We need to add one now we're trying to go
513 back online. */
515 DEBUG(10,("set_domain_online_request: domain %s was globally offline.\n",
516 domain->name ));
519 TALLOC_FREE(domain->check_online_event);
521 domain->check_online_event = event_add_timed(winbind_event_context(),
522 NULL,
523 tev,
524 check_domain_online_handler,
525 domain);
527 /* The above *has* to succeed for winbindd to work. */
528 if (!domain->check_online_event) {
529 smb_panic("set_domain_online_request: failed to add online handler");
533 /****************************************************************
534 Add -ve connection cache entries for domain and realm.
535 ****************************************************************/
537 void winbind_add_failed_connection_entry(const struct winbindd_domain *domain,
538 const char *server,
539 NTSTATUS result)
541 add_failed_connection_entry(domain->name, server, result);
542 /* If this was the saf name for the last thing we talked to,
543 remove it. */
544 saf_delete(domain->name);
545 if (*domain->alt_name) {
546 add_failed_connection_entry(domain->alt_name, server, result);
547 saf_delete(domain->alt_name);
549 winbindd_unset_locator_kdc_env(domain);
552 /* Choose between anonymous or authenticated connections. We need to use
553 an authenticated connection if DCs have the RestrictAnonymous registry
554 entry set > 0, or the "Additional restrictions for anonymous
555 connections" set in the win2k Local Security Policy.
557 Caller to free() result in domain, username, password
560 static void cm_get_ipc_userpass(char **username, char **domain, char **password)
562 *username = (char *)secrets_fetch(SECRETS_AUTH_USER, NULL);
563 *domain = (char *)secrets_fetch(SECRETS_AUTH_DOMAIN, NULL);
564 *password = (char *)secrets_fetch(SECRETS_AUTH_PASSWORD, NULL);
566 if (*username && **username) {
568 if (!*domain || !**domain)
569 *domain = smb_xstrdup(lp_workgroup());
571 if (!*password || !**password)
572 *password = smb_xstrdup("");
574 DEBUG(3, ("cm_get_ipc_userpass: Retrieved auth-user from secrets.tdb [%s\\%s]\n",
575 *domain, *username));
577 } else {
578 DEBUG(3, ("cm_get_ipc_userpass: No auth-user defined\n"));
579 *username = smb_xstrdup("");
580 *domain = smb_xstrdup("");
581 *password = smb_xstrdup("");
585 static bool get_dc_name_via_netlogon(struct winbindd_domain *domain,
586 fstring dcname,
587 struct sockaddr_storage *dc_ss)
589 struct winbindd_domain *our_domain = NULL;
590 struct rpc_pipe_client *netlogon_pipe = NULL;
591 NTSTATUS result;
592 WERROR werr;
593 TALLOC_CTX *mem_ctx;
594 unsigned int orig_timeout;
595 const char *tmp = NULL;
596 const char *p;
598 /* Hmmmm. We can only open one connection to the NETLOGON pipe at the
599 * moment.... */
601 if (IS_DC) {
602 return False;
605 if (domain->primary) {
606 return False;
609 our_domain = find_our_domain();
611 if ((mem_ctx = talloc_init("get_dc_name_via_netlogon")) == NULL) {
612 return False;
615 result = cm_connect_netlogon(our_domain, &netlogon_pipe);
616 if (!NT_STATUS_IS_OK(result)) {
617 talloc_destroy(mem_ctx);
618 return False;
621 /* This call can take a long time - allow the server to time out.
622 35 seconds should do it. */
624 orig_timeout = rpccli_set_timeout(netlogon_pipe, 35000);
626 if (our_domain->active_directory) {
627 struct netr_DsRGetDCNameInfo *domain_info = NULL;
629 result = rpccli_netr_DsRGetDCName(netlogon_pipe,
630 mem_ctx,
631 our_domain->dcname,
632 domain->name,
633 NULL,
634 NULL,
635 DS_RETURN_DNS_NAME,
636 &domain_info,
637 &werr);
638 if (NT_STATUS_IS_OK(result) && W_ERROR_IS_OK(werr)) {
639 tmp = talloc_strdup(
640 mem_ctx, domain_info->dc_unc);
641 if (tmp == NULL) {
642 DEBUG(0, ("talloc_strdup failed\n"));
643 talloc_destroy(mem_ctx);
644 return false;
646 if (strlen(domain->alt_name) == 0) {
647 fstrcpy(domain->alt_name,
648 domain_info->domain_name);
650 if (strlen(domain->forest_name) == 0) {
651 fstrcpy(domain->forest_name,
652 domain_info->forest_name);
655 } else {
656 result = rpccli_netr_GetAnyDCName(netlogon_pipe, mem_ctx,
657 our_domain->dcname,
658 domain->name,
659 &tmp,
660 &werr);
663 /* And restore our original timeout. */
664 rpccli_set_timeout(netlogon_pipe, orig_timeout);
666 if (!NT_STATUS_IS_OK(result)) {
667 DEBUG(10,("rpccli_netr_GetAnyDCName failed: %s\n",
668 nt_errstr(result)));
669 talloc_destroy(mem_ctx);
670 return false;
673 if (!W_ERROR_IS_OK(werr)) {
674 DEBUG(10,("rpccli_netr_GetAnyDCName failed: %s\n",
675 win_errstr(werr)));
676 talloc_destroy(mem_ctx);
677 return false;
680 /* rpccli_netr_GetAnyDCName gives us a name with \\ */
681 p = strip_hostname(tmp);
683 fstrcpy(dcname, p);
685 talloc_destroy(mem_ctx);
687 DEBUG(10,("rpccli_netr_GetAnyDCName returned %s\n", dcname));
689 if (!resolve_name(dcname, dc_ss, 0x20, true)) {
690 return False;
693 return True;
697 * Helper function to assemble trust password and account name
699 static NTSTATUS get_trust_creds(const struct winbindd_domain *domain,
700 char **machine_password,
701 char **machine_account,
702 char **machine_krb5_principal)
704 const char *account_name;
705 const char *name = NULL;
707 /* If we are a DC and this is not our own domain */
709 if (IS_DC) {
710 name = domain->name;
711 } else {
712 struct winbindd_domain *our_domain = find_our_domain();
714 if (!our_domain)
715 return NT_STATUS_INVALID_SERVER_STATE;
717 name = our_domain->name;
720 if (!get_trust_pw_clear(name, machine_password,
721 &account_name, NULL))
723 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
726 if ((machine_account != NULL) &&
727 (asprintf(machine_account, "%s$", account_name) == -1))
729 return NT_STATUS_NO_MEMORY;
732 /* For now assume our machine account only exists in our domain */
734 if (machine_krb5_principal != NULL)
736 struct winbindd_domain *our_domain = find_our_domain();
738 if (!our_domain) {
739 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
742 if (asprintf(machine_krb5_principal, "%s$@%s",
743 account_name, our_domain->alt_name) == -1)
745 return NT_STATUS_NO_MEMORY;
748 strupper_m(*machine_krb5_principal);
751 return NT_STATUS_OK;
754 /************************************************************************
755 Given a fd with a just-connected TCP connection to a DC, open a connection
756 to the pipe.
757 ************************************************************************/
759 static NTSTATUS cm_prepare_connection(const struct winbindd_domain *domain,
760 const int sockfd,
761 const char *controller,
762 struct cli_state **cli,
763 bool *retry)
765 char *machine_password = NULL;
766 char *machine_krb5_principal = NULL;
767 char *machine_account = NULL;
768 char *ipc_username = NULL;
769 char *ipc_domain = NULL;
770 char *ipc_password = NULL;
772 struct named_mutex *mutex;
774 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
776 struct sockaddr peeraddr;
777 socklen_t peeraddr_len;
779 struct sockaddr_in *peeraddr_in =
780 (struct sockaddr_in *)(void *)&peeraddr;
782 DEBUG(10,("cm_prepare_connection: connecting to DC %s for domain %s\n",
783 controller, domain->name ));
785 *retry = True;
787 mutex = grab_named_mutex(talloc_tos(), controller,
788 WINBIND_SERVER_MUTEX_WAIT_TIME);
789 if (mutex == NULL) {
790 DEBUG(0,("cm_prepare_connection: mutex grab failed for %s\n",
791 controller));
792 result = NT_STATUS_POSSIBLE_DEADLOCK;
793 goto done;
796 if ((*cli = cli_initialise()) == NULL) {
797 DEBUG(1, ("Could not cli_initialize\n"));
798 result = NT_STATUS_NO_MEMORY;
799 goto done;
802 (*cli)->timeout = 10000; /* 10 seconds */
803 (*cli)->fd = sockfd;
804 fstrcpy((*cli)->desthost, controller);
805 (*cli)->use_kerberos = True;
807 peeraddr_len = sizeof(peeraddr);
809 if ((getpeername((*cli)->fd, &peeraddr, &peeraddr_len) != 0) ||
810 (peeraddr_len != sizeof(struct sockaddr_in)) ||
811 (peeraddr_in->sin_family != PF_INET))
813 DEBUG(0,("cm_prepare_connection: %s\n", strerror(errno)));
814 result = NT_STATUS_UNSUCCESSFUL;
815 goto done;
818 if (ntohs(peeraddr_in->sin_port) == 139) {
819 struct nmb_name calling;
820 struct nmb_name called;
822 make_nmb_name(&calling, global_myname(), 0x0);
823 make_nmb_name(&called, "*SMBSERVER", 0x20);
825 if (!cli_session_request(*cli, &calling, &called)) {
826 DEBUG(8, ("cli_session_request failed for %s\n",
827 controller));
828 result = NT_STATUS_UNSUCCESSFUL;
829 goto done;
833 result = cli_negprot(*cli);
835 if (!NT_STATUS_IS_OK(result)) {
836 DEBUG(1, ("cli_negprot failed: %s\n", nt_errstr(result)));
837 goto done;
840 if (!is_dc_trusted_domain_situation(domain->name) &&
841 (*cli)->protocol >= PROTOCOL_NT1 &&
842 (*cli)->capabilities & CAP_EXTENDED_SECURITY)
844 ADS_STATUS ads_status;
846 result = get_trust_creds(domain, &machine_password,
847 &machine_account,
848 &machine_krb5_principal);
849 if (!NT_STATUS_IS_OK(result)) {
850 goto anon_fallback;
853 if (lp_security() == SEC_ADS) {
855 /* Try a krb5 session */
857 (*cli)->use_kerberos = True;
858 DEBUG(5, ("connecting to %s from %s with kerberos principal "
859 "[%s] and realm [%s]\n", controller, global_myname(),
860 machine_krb5_principal, domain->alt_name));
862 winbindd_set_locator_kdc_envs(domain);
864 ads_status = cli_session_setup_spnego(*cli,
865 machine_krb5_principal,
866 machine_password,
867 lp_workgroup(),
868 domain->alt_name);
870 if (!ADS_ERR_OK(ads_status)) {
871 DEBUG(4,("failed kerberos session setup with %s\n",
872 ads_errstr(ads_status)));
875 result = ads_ntstatus(ads_status);
876 if (NT_STATUS_IS_OK(result)) {
877 /* Ensure creds are stored for NTLMSSP authenticated pipe access. */
878 result = cli_init_creds(*cli, machine_account, lp_workgroup(), machine_password);
879 if (!NT_STATUS_IS_OK(result)) {
880 goto done;
882 goto session_setup_done;
886 /* Fall back to non-kerberos session setup using NTLMSSP SPNEGO with the machine account. */
887 (*cli)->use_kerberos = False;
889 DEBUG(5, ("connecting to %s from %s with username "
890 "[%s]\\[%s]\n", controller, global_myname(),
891 lp_workgroup(), machine_account));
893 ads_status = cli_session_setup_spnego(*cli,
894 machine_account,
895 machine_password,
896 lp_workgroup(),
897 NULL);
898 if (!ADS_ERR_OK(ads_status)) {
899 DEBUG(4, ("authenticated session setup failed with %s\n",
900 ads_errstr(ads_status)));
903 result = ads_ntstatus(ads_status);
904 if (NT_STATUS_IS_OK(result)) {
905 /* Ensure creds are stored for NTLMSSP authenticated pipe access. */
906 result = cli_init_creds(*cli, machine_account, lp_workgroup(), machine_password);
907 if (!NT_STATUS_IS_OK(result)) {
908 goto done;
910 goto session_setup_done;
914 /* Fall back to non-kerberos session setup with auth_user */
916 (*cli)->use_kerberos = False;
918 cm_get_ipc_userpass(&ipc_username, &ipc_domain, &ipc_password);
920 if ((((*cli)->sec_mode & NEGOTIATE_SECURITY_CHALLENGE_RESPONSE) != 0) &&
921 (strlen(ipc_username) > 0)) {
923 /* Only try authenticated if we have a username */
925 DEBUG(5, ("connecting to %s from %s with username "
926 "[%s]\\[%s]\n", controller, global_myname(),
927 ipc_domain, ipc_username));
929 if (NT_STATUS_IS_OK(cli_session_setup(
930 *cli, ipc_username,
931 ipc_password, strlen(ipc_password)+1,
932 ipc_password, strlen(ipc_password)+1,
933 ipc_domain))) {
934 /* Successful logon with given username. */
935 result = cli_init_creds(*cli, ipc_username, ipc_domain, ipc_password);
936 if (!NT_STATUS_IS_OK(result)) {
937 goto done;
939 goto session_setup_done;
940 } else {
941 DEBUG(4, ("authenticated session setup with user %s\\%s failed.\n",
942 ipc_domain, ipc_username ));
946 anon_fallback:
948 /* Fall back to anonymous connection, this might fail later */
949 DEBUG(10,("cm_prepare_connection: falling back to anonymous "
950 "connection for DC %s\n",
951 controller ));
953 if (NT_STATUS_IS_OK(cli_session_setup(*cli, "", NULL, 0,
954 NULL, 0, ""))) {
955 DEBUG(5, ("Connected anonymously\n"));
956 result = cli_init_creds(*cli, "", "", "");
957 if (!NT_STATUS_IS_OK(result)) {
958 goto done;
960 goto session_setup_done;
963 result = cli_nt_error(*cli);
965 if (NT_STATUS_IS_OK(result))
966 result = NT_STATUS_UNSUCCESSFUL;
968 /* We can't session setup */
970 goto done;
972 session_setup_done:
974 /* cache the server name for later connections */
976 saf_store( domain->name, (*cli)->desthost );
977 if (domain->alt_name && (*cli)->use_kerberos) {
978 saf_store( domain->alt_name, (*cli)->desthost );
981 winbindd_set_locator_kdc_envs(domain);
983 result = cli_tcon_andx(*cli, "IPC$", "IPC", "", 0);
985 if (!NT_STATUS_IS_OK(result)) {
986 DEBUG(1,("failed tcon_X with %s\n", nt_errstr(result)));
987 goto done;
990 TALLOC_FREE(mutex);
991 *retry = False;
993 /* set the domain if empty; needed for schannel connections */
994 if ( !(*cli)->domain[0] ) {
995 result = cli_set_domain((*cli), domain->name);
996 if (!NT_STATUS_IS_OK(result)) {
997 return result;
1001 result = NT_STATUS_OK;
1003 done:
1004 TALLOC_FREE(mutex);
1005 SAFE_FREE(machine_account);
1006 SAFE_FREE(machine_password);
1007 SAFE_FREE(machine_krb5_principal);
1008 SAFE_FREE(ipc_username);
1009 SAFE_FREE(ipc_domain);
1010 SAFE_FREE(ipc_password);
1012 if (!NT_STATUS_IS_OK(result)) {
1013 winbind_add_failed_connection_entry(domain, controller, result);
1014 if ((*cli) != NULL) {
1015 cli_shutdown(*cli);
1016 *cli = NULL;
1020 return result;
1023 /*******************************************************************
1024 Add a dcname and sockaddr_storage pair to the end of a dc_name_ip
1025 array.
1027 Keeps the list unique by not adding duplicate entries.
1029 @param[in] mem_ctx talloc memory context to allocate from
1030 @param[in] domain_name domain of the DC
1031 @param[in] dcname name of the DC to add to the list
1032 @param[in] pss Internet address and port pair to add to the list
1033 @param[in,out] dcs array of dc_name_ip structures to add to
1034 @param[in,out] num_dcs number of dcs returned in the dcs array
1035 @return true if the list was added to, false otherwise
1036 *******************************************************************/
1038 static bool add_one_dc_unique(TALLOC_CTX *mem_ctx, const char *domain_name,
1039 const char *dcname, struct sockaddr_storage *pss,
1040 struct dc_name_ip **dcs, int *num)
1042 int i = 0;
1044 if (!NT_STATUS_IS_OK(check_negative_conn_cache(domain_name, dcname))) {
1045 DEBUG(10, ("DC %s was in the negative conn cache\n", dcname));
1046 return False;
1049 /* Make sure there's no duplicates in the list */
1050 for (i=0; i<*num; i++)
1051 if (sockaddr_equal(
1052 (struct sockaddr *)(void *)&(*dcs)[i].ss,
1053 (struct sockaddr *)(void *)pss))
1054 return False;
1056 *dcs = TALLOC_REALLOC_ARRAY(mem_ctx, *dcs, struct dc_name_ip, (*num)+1);
1058 if (*dcs == NULL)
1059 return False;
1061 fstrcpy((*dcs)[*num].name, dcname);
1062 (*dcs)[*num].ss = *pss;
1063 *num += 1;
1064 return True;
1067 static bool add_sockaddr_to_array(TALLOC_CTX *mem_ctx,
1068 struct sockaddr_storage *pss, uint16 port,
1069 struct sockaddr_storage **addrs, int *num)
1071 *addrs = TALLOC_REALLOC_ARRAY(mem_ctx, *addrs, struct sockaddr_storage, (*num)+1);
1073 if (*addrs == NULL) {
1074 *num = 0;
1075 return False;
1078 (*addrs)[*num] = *pss;
1079 set_sockaddr_port((struct sockaddr *)&(*addrs)[*num], port);
1081 *num += 1;
1082 return True;
1085 /*******************************************************************
1086 convert an ip to a name
1087 *******************************************************************/
1089 static bool dcip_to_name(TALLOC_CTX *mem_ctx,
1090 const struct winbindd_domain *domain,
1091 struct sockaddr_storage *pss,
1092 fstring name )
1094 struct ip_service ip_list;
1095 uint32_t nt_version = NETLOGON_NT_VERSION_1;
1097 ip_list.ss = *pss;
1098 ip_list.port = 0;
1100 #ifdef WITH_ADS
1101 /* For active directory servers, try to get the ldap server name.
1102 None of these failures should be considered critical for now */
1104 if (lp_security() == SEC_ADS) {
1105 ADS_STRUCT *ads;
1106 ADS_STATUS ads_status;
1107 char addr[INET6_ADDRSTRLEN];
1109 print_sockaddr(addr, sizeof(addr), pss);
1111 ads = ads_init(domain->alt_name, domain->name, addr);
1112 ads->auth.flags |= ADS_AUTH_NO_BIND;
1114 ads_status = ads_connect(ads);
1115 if (ADS_ERR_OK(ads_status)) {
1116 /* We got a cldap packet. */
1117 fstrcpy(name, ads->config.ldap_server_name);
1118 namecache_store(name, 0x20, 1, &ip_list);
1120 DEBUG(10,("dcip_to_name: flags = 0x%x\n", (unsigned int)ads->config.flags));
1122 if (domain->primary && (ads->config.flags & NBT_SERVER_KDC)) {
1123 if (ads_closest_dc(ads)) {
1124 char *sitename = sitename_fetch(ads->config.realm);
1126 /* We're going to use this KDC for this realm/domain.
1127 If we are using sites, then force the krb5 libs
1128 to use this KDC. */
1130 create_local_private_krb5_conf_for_domain(domain->alt_name,
1131 domain->name,
1132 sitename,
1133 pss);
1135 SAFE_FREE(sitename);
1136 } else {
1137 /* use an off site KDC */
1138 create_local_private_krb5_conf_for_domain(domain->alt_name,
1139 domain->name,
1140 NULL,
1141 pss);
1143 winbindd_set_locator_kdc_envs(domain);
1145 /* Ensure we contact this DC also. */
1146 saf_store( domain->name, name);
1147 saf_store( domain->alt_name, name);
1150 ads_destroy( &ads );
1151 return True;
1154 ads_destroy( &ads );
1156 #endif
1158 /* try GETDC requests next */
1160 if (send_getdc_request(mem_ctx, winbind_messaging_context(),
1161 pss, domain->name, &domain->sid,
1162 nt_version)) {
1163 const char *dc_name = NULL;
1164 int i;
1165 smb_msleep(100);
1166 for (i=0; i<5; i++) {
1167 if (receive_getdc_response(mem_ctx, pss, domain->name,
1168 &nt_version,
1169 &dc_name, NULL)) {
1170 fstrcpy(name, dc_name);
1171 namecache_store(name, 0x20, 1, &ip_list);
1172 return True;
1174 smb_msleep(500);
1178 /* try node status request */
1180 if ( name_status_find(domain->name, 0x1c, 0x20, pss, name) ) {
1181 namecache_store(name, 0x20, 1, &ip_list);
1182 return True;
1184 return False;
1187 /*******************************************************************
1188 Retrieve a list of IP addresses for domain controllers.
1190 The array is sorted in the preferred connection order.
1192 @param[in] mem_ctx talloc memory context to allocate from
1193 @param[in] domain domain to retrieve DCs for
1194 @param[out] dcs array of dcs that will be returned
1195 @param[out] num_dcs number of dcs returned in the dcs array
1196 @return always true
1197 *******************************************************************/
1199 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
1200 struct dc_name_ip **dcs, int *num_dcs)
1202 fstring dcname;
1203 struct sockaddr_storage ss;
1204 struct ip_service *ip_list = NULL;
1205 int iplist_size = 0;
1206 int i;
1207 bool is_our_domain;
1208 enum security_types sec = (enum security_types)lp_security();
1210 is_our_domain = strequal(domain->name, lp_workgroup());
1212 /* If not our domain, get the preferred DC, by asking our primary DC */
1213 if ( !is_our_domain
1214 && get_dc_name_via_netlogon(domain, dcname, &ss)
1215 && add_one_dc_unique(mem_ctx, domain->name, dcname, &ss, dcs,
1216 num_dcs) )
1218 char addr[INET6_ADDRSTRLEN];
1219 print_sockaddr(addr, sizeof(addr), &ss);
1220 DEBUG(10, ("Retrieved DC %s at %s via netlogon\n",
1221 dcname, addr));
1222 return True;
1225 if (sec == SEC_ADS) {
1226 char *sitename = NULL;
1228 /* We need to make sure we know the local site before
1229 doing any DNS queries, as this will restrict the
1230 get_sorted_dc_list() call below to only fetching
1231 DNS records for the correct site. */
1233 /* Find any DC to get the site record.
1234 We deliberately don't care about the
1235 return here. */
1237 get_dc_name(domain->name, domain->alt_name, dcname, &ss);
1239 sitename = sitename_fetch(domain->alt_name);
1240 if (sitename) {
1242 /* Do the site-specific AD dns lookup first. */
1243 get_sorted_dc_list(domain->alt_name, sitename, &ip_list,
1244 &iplist_size, True);
1246 /* Add ips to the DC array. We don't look up the name
1247 of the DC in this function, but we fill in the char*
1248 of the ip now to make the failed connection cache
1249 work */
1250 for ( i=0; i<iplist_size; i++ ) {
1251 char addr[INET6_ADDRSTRLEN];
1252 print_sockaddr(addr, sizeof(addr),
1253 &ip_list[i].ss);
1254 add_one_dc_unique(mem_ctx,
1255 domain->name,
1256 addr,
1257 &ip_list[i].ss,
1258 dcs,
1259 num_dcs);
1262 SAFE_FREE(ip_list);
1263 SAFE_FREE(sitename);
1264 iplist_size = 0;
1267 /* Now we add DCs from the main AD DNS lookup. */
1268 get_sorted_dc_list(domain->alt_name, NULL, &ip_list,
1269 &iplist_size, True);
1271 for ( i=0; i<iplist_size; i++ ) {
1272 char addr[INET6_ADDRSTRLEN];
1273 print_sockaddr(addr, sizeof(addr),
1274 &ip_list[i].ss);
1275 add_one_dc_unique(mem_ctx,
1276 domain->name,
1277 addr,
1278 &ip_list[i].ss,
1279 dcs,
1280 num_dcs);
1283 SAFE_FREE(ip_list);
1284 iplist_size = 0;
1287 /* Try standard netbios queries if no ADS */
1288 if (*num_dcs == 0) {
1289 get_sorted_dc_list(domain->name, NULL, &ip_list, &iplist_size,
1290 False);
1292 for ( i=0; i<iplist_size; i++ ) {
1293 char addr[INET6_ADDRSTRLEN];
1294 print_sockaddr(addr, sizeof(addr),
1295 &ip_list[i].ss);
1296 add_one_dc_unique(mem_ctx,
1297 domain->name,
1298 addr,
1299 &ip_list[i].ss,
1300 dcs,
1301 num_dcs);
1304 SAFE_FREE(ip_list);
1305 iplist_size = 0;
1308 return True;
1311 /*******************************************************************
1312 Find and make a connection to a DC in the given domain.
1314 @param[in] mem_ctx talloc memory context to allocate from
1315 @param[in] domain domain to find a dc in
1316 @param[out] dcname NetBIOS or FQDN of DC that's connected to
1317 @param[out] pss DC Internet address and port
1318 @param[out] fd fd of the open socket connected to the newly found dc
1319 @return true when a DC connection is made, false otherwise
1320 *******************************************************************/
1322 static bool find_new_dc(TALLOC_CTX *mem_ctx,
1323 struct winbindd_domain *domain,
1324 fstring dcname, struct sockaddr_storage *pss, int *fd)
1326 struct dc_name_ip *dcs = NULL;
1327 int num_dcs = 0;
1329 const char **dcnames = NULL;
1330 int num_dcnames = 0;
1332 struct sockaddr_storage *addrs = NULL;
1333 int num_addrs = 0;
1335 int i, fd_index;
1337 *fd = -1;
1339 again:
1340 if (!get_dcs(mem_ctx, domain, &dcs, &num_dcs) || (num_dcs == 0))
1341 return False;
1343 for (i=0; i<num_dcs; i++) {
1345 if (!add_string_to_array(mem_ctx, dcs[i].name,
1346 &dcnames, &num_dcnames)) {
1347 return False;
1349 if (!add_sockaddr_to_array(mem_ctx, &dcs[i].ss, 445,
1350 &addrs, &num_addrs)) {
1351 return False;
1354 if (!add_string_to_array(mem_ctx, dcs[i].name,
1355 &dcnames, &num_dcnames)) {
1356 return False;
1358 if (!add_sockaddr_to_array(mem_ctx, &dcs[i].ss, 139,
1359 &addrs, &num_addrs)) {
1360 return False;
1364 if ((num_dcnames == 0) || (num_dcnames != num_addrs))
1365 return False;
1367 if ((addrs == NULL) || (dcnames == NULL))
1368 return False;
1370 /* 5 second timeout. */
1371 if (!open_any_socket_out(addrs, num_addrs, 5000, &fd_index, fd) ) {
1372 for (i=0; i<num_dcs; i++) {
1373 char ab[INET6_ADDRSTRLEN];
1374 print_sockaddr(ab, sizeof(ab), &dcs[i].ss);
1375 DEBUG(10, ("find_new_dc: open_any_socket_out failed for "
1376 "domain %s address %s. Error was %s\n",
1377 domain->name, ab, strerror(errno) ));
1378 winbind_add_failed_connection_entry(domain,
1379 dcs[i].name, NT_STATUS_UNSUCCESSFUL);
1381 return False;
1384 *pss = addrs[fd_index];
1386 if (*dcnames[fd_index] != '\0' && !is_ipaddress(dcnames[fd_index])) {
1387 /* Ok, we've got a name for the DC */
1388 fstrcpy(dcname, dcnames[fd_index]);
1389 return True;
1392 /* Try to figure out the name */
1393 if (dcip_to_name(mem_ctx, domain, pss, dcname)) {
1394 return True;
1397 /* We can not continue without the DC's name */
1398 winbind_add_failed_connection_entry(domain, dcs[fd_index].name,
1399 NT_STATUS_UNSUCCESSFUL);
1401 /* Throw away all arrays as we're doing this again. */
1402 TALLOC_FREE(dcs);
1403 num_dcs = 0;
1405 TALLOC_FREE(dcnames);
1406 num_dcnames = 0;
1408 TALLOC_FREE(addrs);
1409 num_addrs = 0;
1411 close(*fd);
1412 *fd = -1;
1414 goto again;
1417 static NTSTATUS cm_open_connection(struct winbindd_domain *domain,
1418 struct winbindd_cm_conn *new_conn)
1420 TALLOC_CTX *mem_ctx;
1421 NTSTATUS result;
1422 char *saf_servername = saf_fetch( domain->name );
1423 int retries;
1425 if ((mem_ctx = talloc_init("cm_open_connection")) == NULL) {
1426 SAFE_FREE(saf_servername);
1427 set_domain_offline(domain);
1428 return NT_STATUS_NO_MEMORY;
1431 /* we have to check the server affinity cache here since
1432 later we selecte a DC based on response time and not preference */
1434 /* Check the negative connection cache
1435 before talking to it. It going down may have
1436 triggered the reconnection. */
1438 if ( saf_servername && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, saf_servername))) {
1440 DEBUG(10,("cm_open_connection: saf_servername is '%s' for domain %s\n",
1441 saf_servername, domain->name ));
1443 /* convert an ip address to a name */
1444 if (is_ipaddress( saf_servername ) ) {
1445 fstring saf_name;
1446 struct sockaddr_storage ss;
1448 if (!interpret_string_addr(&ss, saf_servername,
1449 AI_NUMERICHOST)) {
1450 return NT_STATUS_UNSUCCESSFUL;
1452 if (dcip_to_name(mem_ctx, domain, &ss, saf_name )) {
1453 fstrcpy( domain->dcname, saf_name );
1454 } else {
1455 winbind_add_failed_connection_entry(
1456 domain, saf_servername,
1457 NT_STATUS_UNSUCCESSFUL);
1459 } else {
1460 fstrcpy( domain->dcname, saf_servername );
1463 SAFE_FREE( saf_servername );
1466 for (retries = 0; retries < 3; retries++) {
1467 int fd = -1;
1468 bool retry = False;
1470 result = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1472 DEBUG(10,("cm_open_connection: dcname is '%s' for domain %s\n",
1473 domain->dcname, domain->name ));
1475 if (*domain->dcname
1476 && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, domain->dcname))
1477 && (resolve_name(domain->dcname, &domain->dcaddr, 0x20, true)))
1479 struct sockaddr_storage *addrs = NULL;
1480 int num_addrs = 0;
1481 int dummy = 0;
1483 if (!add_sockaddr_to_array(mem_ctx, &domain->dcaddr, 445, &addrs, &num_addrs)) {
1484 set_domain_offline(domain);
1485 talloc_destroy(mem_ctx);
1486 return NT_STATUS_NO_MEMORY;
1488 if (!add_sockaddr_to_array(mem_ctx, &domain->dcaddr, 139, &addrs, &num_addrs)) {
1489 set_domain_offline(domain);
1490 talloc_destroy(mem_ctx);
1491 return NT_STATUS_NO_MEMORY;
1494 /* 5 second timeout. */
1495 if (!open_any_socket_out(addrs, num_addrs, 5000, &dummy, &fd)) {
1496 fd = -1;
1500 if ((fd == -1)
1501 && !find_new_dc(mem_ctx, domain, domain->dcname, &domain->dcaddr, &fd))
1503 /* This is the one place where we will
1504 set the global winbindd offline state
1505 to true, if a "WINBINDD_OFFLINE" entry
1506 is found in the winbindd cache. */
1507 set_global_winbindd_state_offline();
1508 break;
1511 new_conn->cli = NULL;
1513 result = cm_prepare_connection(domain, fd, domain->dcname,
1514 &new_conn->cli, &retry);
1516 if (!retry)
1517 break;
1520 if (NT_STATUS_IS_OK(result)) {
1522 winbindd_set_locator_kdc_envs(domain);
1524 if (domain->online == False) {
1525 /* We're changing state from offline to online. */
1526 set_global_winbindd_state_online();
1528 set_domain_online(domain);
1529 } else {
1530 /* Ensure we setup the retry handler. */
1531 set_domain_offline(domain);
1534 talloc_destroy(mem_ctx);
1535 return result;
1538 /* Close down all open pipes on a connection. */
1540 void invalidate_cm_connection(struct winbindd_cm_conn *conn)
1542 /* We're closing down a possibly dead
1543 connection. Don't have impossibly long (10s) timeouts. */
1545 if (conn->cli) {
1546 cli_set_timeout(conn->cli, 1000); /* 1 second. */
1549 if (conn->samr_pipe != NULL) {
1550 TALLOC_FREE(conn->samr_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->lsa_pipe != NULL) {
1558 TALLOC_FREE(conn->lsa_pipe);
1559 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1560 if (conn->cli) {
1561 cli_set_timeout(conn->cli, 500);
1565 if (conn->lsa_pipe_tcp != NULL) {
1566 TALLOC_FREE(conn->lsa_pipe_tcp);
1567 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1568 if (conn->cli) {
1569 cli_set_timeout(conn->cli, 500);
1573 if (conn->netlogon_pipe != NULL) {
1574 TALLOC_FREE(conn->netlogon_pipe);
1575 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1576 if (conn->cli) {
1577 cli_set_timeout(conn->cli, 500);
1581 if (conn->cli) {
1582 cli_shutdown(conn->cli);
1585 conn->cli = NULL;
1588 void close_conns_after_fork(void)
1590 struct winbindd_domain *domain;
1592 for (domain = domain_list(); domain; domain = domain->next) {
1593 if (domain->conn.cli == NULL)
1594 continue;
1596 if (domain->conn.cli->fd == -1)
1597 continue;
1599 close(domain->conn.cli->fd);
1600 domain->conn.cli->fd = -1;
1604 static bool connection_ok(struct winbindd_domain *domain)
1606 bool ok;
1608 ok = cli_state_is_connected(domain->conn.cli);
1609 if (!ok) {
1610 DEBUG(3, ("connection_ok: Connection to %s for domain %s is not connected\n",
1611 domain->dcname, domain->name));
1612 return False;
1615 if (domain->online == False) {
1616 DEBUG(3, ("connection_ok: Domain %s is offline\n", domain->name));
1617 return False;
1620 return True;
1623 /* Initialize a new connection up to the RPC BIND.
1624 Bypass online status check so always does network calls. */
1626 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain)
1628 NTSTATUS result;
1630 /* Internal connections never use the network. */
1631 if (domain->internal) {
1632 domain->initialized = True;
1633 return NT_STATUS_OK;
1636 if (!winbindd_can_contact_domain(domain)) {
1637 invalidate_cm_connection(&domain->conn);
1638 domain->initialized = True;
1639 return NT_STATUS_OK;
1642 if (connection_ok(domain)) {
1643 if (!domain->initialized) {
1644 set_dc_type_and_flags(domain);
1646 return NT_STATUS_OK;
1649 invalidate_cm_connection(&domain->conn);
1651 result = cm_open_connection(domain, &domain->conn);
1653 if (NT_STATUS_IS_OK(result) && !domain->initialized) {
1654 set_dc_type_and_flags(domain);
1657 return result;
1660 NTSTATUS init_dc_connection(struct winbindd_domain *domain)
1662 if (domain->initialized && !domain->online) {
1663 /* We check for online status elsewhere. */
1664 return NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1667 return init_dc_connection_network(domain);
1670 static NTSTATUS init_dc_connection_rpc(struct winbindd_domain *domain)
1672 NTSTATUS status;
1674 status = init_dc_connection(domain);
1675 if (!NT_STATUS_IS_OK(status)) {
1676 return status;
1679 if (!domain->internal && domain->conn.cli == NULL) {
1680 /* happens for trusted domains without inbound trust */
1681 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
1684 return NT_STATUS_OK;
1687 /******************************************************************************
1688 Set the trust flags (direction and forest location) for a domain
1689 ******************************************************************************/
1691 static bool set_dc_type_and_flags_trustinfo( struct winbindd_domain *domain )
1693 struct winbindd_domain *our_domain;
1694 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
1695 struct netr_DomainTrustList trusts;
1696 int i;
1697 uint32 flags = (NETR_TRUST_FLAG_IN_FOREST |
1698 NETR_TRUST_FLAG_OUTBOUND |
1699 NETR_TRUST_FLAG_INBOUND);
1700 struct rpc_pipe_client *cli;
1701 TALLOC_CTX *mem_ctx = NULL;
1703 DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s\n", domain->name ));
1705 /* Our primary domain doesn't need to worry about trust flags.
1706 Force it to go through the network setup */
1707 if ( domain->primary ) {
1708 return False;
1711 our_domain = find_our_domain();
1713 if ( !connection_ok(our_domain) ) {
1714 DEBUG(3,("set_dc_type_and_flags_trustinfo: No connection to our domain!\n"));
1715 return False;
1718 /* This won't work unless our domain is AD */
1720 if ( !our_domain->active_directory ) {
1721 return False;
1724 /* Use DsEnumerateDomainTrusts to get us the trust direction
1725 and type */
1727 result = cm_connect_netlogon(our_domain, &cli);
1729 if (!NT_STATUS_IS_OK(result)) {
1730 DEBUG(5, ("set_dc_type_and_flags_trustinfo: Could not open "
1731 "a connection to %s for PIPE_NETLOGON (%s)\n",
1732 domain->name, nt_errstr(result)));
1733 return False;
1736 if ( (mem_ctx = talloc_init("set_dc_type_and_flags_trustinfo")) == NULL ) {
1737 DEBUG(0,("set_dc_type_and_flags_trustinfo: talloc_init() failed!\n"));
1738 return False;
1741 result = rpccli_netr_DsrEnumerateDomainTrusts(cli, mem_ctx,
1742 cli->desthost,
1743 flags,
1744 &trusts,
1745 NULL);
1746 if (!NT_STATUS_IS_OK(result)) {
1747 DEBUG(0,("set_dc_type_and_flags_trustinfo: "
1748 "failed to query trusted domain list: %s\n",
1749 nt_errstr(result)));
1750 talloc_destroy(mem_ctx);
1751 return false;
1754 /* Now find the domain name and get the flags */
1756 for ( i=0; i<trusts.count; i++ ) {
1757 if ( strequal( domain->name, trusts.array[i].netbios_name) ) {
1758 domain->domain_flags = trusts.array[i].trust_flags;
1759 domain->domain_type = trusts.array[i].trust_type;
1760 domain->domain_trust_attribs = trusts.array[i].trust_attributes;
1762 if ( domain->domain_type == NETR_TRUST_TYPE_UPLEVEL )
1763 domain->active_directory = True;
1765 /* This flag is only set if the domain is *our*
1766 primary domain and the primary domain is in
1767 native mode */
1769 domain->native_mode = (domain->domain_flags & NETR_TRUST_FLAG_NATIVE);
1771 DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s is %sin "
1772 "native mode.\n", domain->name,
1773 domain->native_mode ? "" : "NOT "));
1775 DEBUG(5,("set_dc_type_and_flags_trustinfo: domain %s is %s"
1776 "running active directory.\n", domain->name,
1777 domain->active_directory ? "" : "NOT "));
1780 domain->initialized = True;
1782 break;
1786 talloc_destroy( mem_ctx );
1788 return domain->initialized;
1791 /******************************************************************************
1792 We can 'sense' certain things about the DC by it's replies to certain
1793 questions.
1795 This tells us if this particular remote server is Active Directory, and if it
1796 is native mode.
1797 ******************************************************************************/
1799 static void set_dc_type_and_flags_connect( struct winbindd_domain *domain )
1801 NTSTATUS result;
1802 WERROR werr;
1803 TALLOC_CTX *mem_ctx = NULL;
1804 struct rpc_pipe_client *cli = NULL;
1805 struct policy_handle pol;
1806 union dssetup_DsRoleInfo info;
1807 union lsa_PolicyInformation *lsa_info = NULL;
1809 if (!connection_ok(domain)) {
1810 return;
1813 mem_ctx = talloc_init("set_dc_type_and_flags on domain %s\n",
1814 domain->name);
1815 if (!mem_ctx) {
1816 DEBUG(1, ("set_dc_type_and_flags_connect: talloc_init() failed\n"));
1817 return;
1820 DEBUG(5, ("set_dc_type_and_flags_connect: domain %s\n", domain->name ));
1822 result = cli_rpc_pipe_open_noauth(domain->conn.cli,
1823 &ndr_table_dssetup.syntax_id,
1824 &cli);
1826 if (!NT_STATUS_IS_OK(result)) {
1827 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
1828 "PI_DSSETUP on domain %s: (%s)\n",
1829 domain->name, nt_errstr(result)));
1831 /* if this is just a non-AD domain we need to continue
1832 * identifying so that we can in the end return with
1833 * domain->initialized = True - gd */
1835 goto no_dssetup;
1838 result = rpccli_dssetup_DsRoleGetPrimaryDomainInformation(cli, mem_ctx,
1839 DS_ROLE_BASIC_INFORMATION,
1840 &info,
1841 &werr);
1842 TALLOC_FREE(cli);
1844 if (!NT_STATUS_IS_OK(result)) {
1845 DEBUG(5, ("set_dc_type_and_flags_connect: rpccli_ds_getprimarydominfo "
1846 "on domain %s failed: (%s)\n",
1847 domain->name, nt_errstr(result)));
1849 /* older samba3 DCs will return DCERPC_FAULT_OP_RNG_ERROR for
1850 * every opcode on the DSSETUP pipe, continue with
1851 * no_dssetup mode here as well to get domain->initialized
1852 * set - gd */
1854 if (NT_STATUS_V(result) == DCERPC_FAULT_OP_RNG_ERROR) {
1855 goto no_dssetup;
1858 TALLOC_FREE(mem_ctx);
1859 return;
1862 if ((info.basic.flags & DS_ROLE_PRIMARY_DS_RUNNING) &&
1863 !(info.basic.flags & DS_ROLE_PRIMARY_DS_MIXED_MODE)) {
1864 domain->native_mode = True;
1865 } else {
1866 domain->native_mode = False;
1869 no_dssetup:
1870 result = cli_rpc_pipe_open_noauth(domain->conn.cli,
1871 &ndr_table_lsarpc.syntax_id, &cli);
1873 if (!NT_STATUS_IS_OK(result)) {
1874 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
1875 "PI_LSARPC on domain %s: (%s)\n",
1876 domain->name, nt_errstr(result)));
1877 TALLOC_FREE(cli);
1878 TALLOC_FREE(mem_ctx);
1879 return;
1882 result = rpccli_lsa_open_policy2(cli, mem_ctx, True,
1883 SEC_FLAG_MAXIMUM_ALLOWED, &pol);
1885 if (NT_STATUS_IS_OK(result)) {
1886 /* This particular query is exactly what Win2k clients use
1887 to determine that the DC is active directory */
1888 result = rpccli_lsa_QueryInfoPolicy2(cli, mem_ctx,
1889 &pol,
1890 LSA_POLICY_INFO_DNS,
1891 &lsa_info);
1894 if (NT_STATUS_IS_OK(result)) {
1895 domain->active_directory = True;
1897 if (lsa_info->dns.name.string) {
1898 fstrcpy(domain->name, lsa_info->dns.name.string);
1901 if (lsa_info->dns.dns_domain.string) {
1902 fstrcpy(domain->alt_name,
1903 lsa_info->dns.dns_domain.string);
1906 /* See if we can set some domain trust flags about
1907 ourself */
1909 if (lsa_info->dns.dns_forest.string) {
1910 fstrcpy(domain->forest_name,
1911 lsa_info->dns.dns_forest.string);
1913 if (strequal(domain->forest_name, domain->alt_name)) {
1914 domain->domain_flags |= NETR_TRUST_FLAG_TREEROOT;
1918 if (lsa_info->dns.sid) {
1919 sid_copy(&domain->sid, lsa_info->dns.sid);
1921 } else {
1922 domain->active_directory = False;
1924 result = rpccli_lsa_open_policy(cli, mem_ctx, True,
1925 SEC_FLAG_MAXIMUM_ALLOWED,
1926 &pol);
1928 if (!NT_STATUS_IS_OK(result)) {
1929 goto done;
1932 result = rpccli_lsa_QueryInfoPolicy(cli, mem_ctx,
1933 &pol,
1934 LSA_POLICY_INFO_ACCOUNT_DOMAIN,
1935 &lsa_info);
1937 if (NT_STATUS_IS_OK(result)) {
1939 if (lsa_info->account_domain.name.string) {
1940 fstrcpy(domain->name,
1941 lsa_info->account_domain.name.string);
1944 if (lsa_info->account_domain.sid) {
1945 sid_copy(&domain->sid, lsa_info->account_domain.sid);
1949 done:
1951 DEBUG(5, ("set_dc_type_and_flags_connect: domain %s is %sin native mode.\n",
1952 domain->name, domain->native_mode ? "" : "NOT "));
1954 DEBUG(5,("set_dc_type_and_flags_connect: domain %s is %srunning active directory.\n",
1955 domain->name, domain->active_directory ? "" : "NOT "));
1957 domain->can_do_ncacn_ip_tcp = domain->active_directory;
1959 TALLOC_FREE(cli);
1961 TALLOC_FREE(mem_ctx);
1963 domain->initialized = True;
1966 /**********************************************************************
1967 Set the domain_flags (trust attributes, domain operating modes, etc...
1968 ***********************************************************************/
1970 static void set_dc_type_and_flags( struct winbindd_domain *domain )
1972 /* we always have to contact our primary domain */
1974 if ( domain->primary ) {
1975 DEBUG(10,("set_dc_type_and_flags: setting up flags for "
1976 "primary domain\n"));
1977 set_dc_type_and_flags_connect( domain );
1978 return;
1981 /* Use our DC to get the information if possible */
1983 if ( !set_dc_type_and_flags_trustinfo( domain ) ) {
1984 /* Otherwise, fallback to contacting the
1985 domain directly */
1986 set_dc_type_and_flags_connect( domain );
1989 return;
1994 /**********************************************************************
1995 ***********************************************************************/
1997 static bool cm_get_schannel_creds(struct winbindd_domain *domain,
1998 struct netlogon_creds_CredentialState **ppdc)
2000 NTSTATUS result;
2001 struct rpc_pipe_client *netlogon_pipe;
2003 if (lp_client_schannel() == False) {
2004 return False;
2007 result = cm_connect_netlogon(domain, &netlogon_pipe);
2008 if (!NT_STATUS_IS_OK(result)) {
2009 return False;
2012 /* Return a pointer to the struct netlogon_creds_CredentialState from the
2013 netlogon pipe. */
2015 if (!domain->conn.netlogon_pipe->dc) {
2016 return false;
2019 *ppdc = domain->conn.netlogon_pipe->dc;
2020 return True;
2023 NTSTATUS cm_connect_sam(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2024 struct rpc_pipe_client **cli, struct policy_handle *sam_handle)
2026 struct winbindd_cm_conn *conn;
2027 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2028 struct netlogon_creds_CredentialState *p_creds;
2029 char *machine_password = NULL;
2030 char *machine_account = NULL;
2031 char *domain_name = NULL;
2033 result = init_dc_connection_rpc(domain);
2034 if (!NT_STATUS_IS_OK(result)) {
2035 return result;
2038 conn = &domain->conn;
2040 if (rpccli_is_connected(conn->samr_pipe)) {
2041 goto done;
2044 TALLOC_FREE(conn->samr_pipe);
2047 * No SAMR pipe yet. Attempt to get an NTLMSSP SPNEGO authenticated
2048 * sign and sealed pipe using the machine account password by
2049 * preference. If we can't - try schannel, if that fails, try
2050 * anonymous.
2053 if ((conn->cli->user_name[0] == '\0') ||
2054 (conn->cli->domain[0] == '\0') ||
2055 (conn->cli->password == NULL || conn->cli->password[0] == '\0'))
2057 result = get_trust_creds(domain, &machine_password,
2058 &machine_account, NULL);
2059 if (!NT_STATUS_IS_OK(result)) {
2060 DEBUG(10, ("cm_connect_sam: No no user available for "
2061 "domain %s, trying schannel\n", conn->cli->domain));
2062 goto schannel;
2064 domain_name = domain->name;
2065 } else {
2066 machine_password = SMB_STRDUP(conn->cli->password);
2067 machine_account = SMB_STRDUP(conn->cli->user_name);
2068 domain_name = conn->cli->domain;
2071 if (!machine_password || !machine_account) {
2072 result = NT_STATUS_NO_MEMORY;
2073 goto done;
2076 /* We have an authenticated connection. Use a NTLMSSP SPNEGO
2077 authenticated SAMR pipe with sign & seal. */
2078 result = cli_rpc_pipe_open_spnego_ntlmssp(conn->cli,
2079 &ndr_table_samr.syntax_id,
2080 NCACN_NP,
2081 DCERPC_AUTH_LEVEL_PRIVACY,
2082 domain_name,
2083 machine_account,
2084 machine_password,
2085 &conn->samr_pipe);
2087 if (!NT_STATUS_IS_OK(result)) {
2088 DEBUG(10,("cm_connect_sam: failed to connect to SAMR "
2089 "pipe for domain %s using NTLMSSP "
2090 "authenticated pipe: user %s\\%s. Error was "
2091 "%s\n", domain->name, domain_name,
2092 machine_account, nt_errstr(result)));
2093 goto schannel;
2096 DEBUG(10,("cm_connect_sam: connected to SAMR pipe for "
2097 "domain %s using NTLMSSP authenticated "
2098 "pipe: user %s\\%s\n", domain->name,
2099 domain_name, machine_account));
2101 result = rpccli_samr_Connect2(conn->samr_pipe, mem_ctx,
2102 conn->samr_pipe->desthost,
2103 SEC_FLAG_MAXIMUM_ALLOWED,
2104 &conn->sam_connect_handle);
2105 if (NT_STATUS_IS_OK(result)) {
2106 goto open_domain;
2108 DEBUG(10,("cm_connect_sam: ntlmssp-sealed rpccli_samr_Connect2 "
2109 "failed for domain %s, error was %s. Trying schannel\n",
2110 domain->name, nt_errstr(result) ));
2111 TALLOC_FREE(conn->samr_pipe);
2113 schannel:
2115 /* Fall back to schannel if it's a W2K pre-SP1 box. */
2117 if (!cm_get_schannel_creds(domain, &p_creds)) {
2118 /* If this call fails - conn->cli can now be NULL ! */
2119 DEBUG(10, ("cm_connect_sam: Could not get schannel auth info "
2120 "for domain %s, trying anon\n", domain->name));
2121 goto anonymous;
2123 result = cli_rpc_pipe_open_schannel_with_key
2124 (conn->cli, &ndr_table_samr.syntax_id, NCACN_NP,
2125 DCERPC_AUTH_LEVEL_PRIVACY,
2126 domain->name, &p_creds, &conn->samr_pipe);
2128 if (!NT_STATUS_IS_OK(result)) {
2129 DEBUG(10,("cm_connect_sam: failed to connect to SAMR pipe for "
2130 "domain %s using schannel. Error was %s\n",
2131 domain->name, nt_errstr(result) ));
2132 goto anonymous;
2134 DEBUG(10,("cm_connect_sam: connected to SAMR pipe for domain %s using "
2135 "schannel.\n", domain->name ));
2137 result = rpccli_samr_Connect2(conn->samr_pipe, mem_ctx,
2138 conn->samr_pipe->desthost,
2139 SEC_FLAG_MAXIMUM_ALLOWED,
2140 &conn->sam_connect_handle);
2141 if (NT_STATUS_IS_OK(result)) {
2142 goto open_domain;
2144 DEBUG(10,("cm_connect_sam: schannel-sealed rpccli_samr_Connect2 failed "
2145 "for domain %s, error was %s. Trying anonymous\n",
2146 domain->name, nt_errstr(result) ));
2147 TALLOC_FREE(conn->samr_pipe);
2149 anonymous:
2151 /* Finally fall back to anonymous. */
2152 result = cli_rpc_pipe_open_noauth(conn->cli, &ndr_table_samr.syntax_id,
2153 &conn->samr_pipe);
2155 if (!NT_STATUS_IS_OK(result)) {
2156 goto done;
2159 result = rpccli_samr_Connect2(conn->samr_pipe, mem_ctx,
2160 conn->samr_pipe->desthost,
2161 SEC_FLAG_MAXIMUM_ALLOWED,
2162 &conn->sam_connect_handle);
2163 if (!NT_STATUS_IS_OK(result)) {
2164 DEBUG(10,("cm_connect_sam: rpccli_samr_Connect2 failed "
2165 "for domain %s Error was %s\n",
2166 domain->name, nt_errstr(result) ));
2167 goto done;
2170 open_domain:
2171 result = rpccli_samr_OpenDomain(conn->samr_pipe,
2172 mem_ctx,
2173 &conn->sam_connect_handle,
2174 SEC_FLAG_MAXIMUM_ALLOWED,
2175 &domain->sid,
2176 &conn->sam_domain_handle);
2178 done:
2180 if (NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
2182 * if we got access denied, we might just have no access rights
2183 * to talk to the remote samr server server (e.g. when we are a
2184 * PDC and we are connecting a w2k8 pdc via an interdomain
2185 * trust). In that case do not invalidate the whole connection
2186 * stack
2188 TALLOC_FREE(conn->samr_pipe);
2189 ZERO_STRUCT(conn->sam_domain_handle);
2190 return result;
2191 } else if (!NT_STATUS_IS_OK(result)) {
2192 invalidate_cm_connection(conn);
2193 return result;
2196 *cli = conn->samr_pipe;
2197 *sam_handle = conn->sam_domain_handle;
2198 SAFE_FREE(machine_password);
2199 SAFE_FREE(machine_account);
2200 return result;
2203 /**********************************************************************
2204 open an schanneld ncacn_ip_tcp connection to LSA
2205 ***********************************************************************/
2207 NTSTATUS cm_connect_lsa_tcp(struct winbindd_domain *domain,
2208 TALLOC_CTX *mem_ctx,
2209 struct rpc_pipe_client **cli)
2211 struct winbindd_cm_conn *conn;
2212 NTSTATUS status;
2214 DEBUG(10,("cm_connect_lsa_tcp\n"));
2216 status = init_dc_connection_rpc(domain);
2217 if (!NT_STATUS_IS_OK(status)) {
2218 return status;
2221 conn = &domain->conn;
2223 if (conn->lsa_pipe_tcp &&
2224 conn->lsa_pipe_tcp->transport->transport == NCACN_IP_TCP &&
2225 conn->lsa_pipe_tcp->auth->auth_level == DCERPC_AUTH_LEVEL_PRIVACY &&
2226 rpccli_is_connected(conn->lsa_pipe_tcp)) {
2227 goto done;
2230 TALLOC_FREE(conn->lsa_pipe_tcp);
2232 status = cli_rpc_pipe_open_schannel(conn->cli,
2233 &ndr_table_lsarpc.syntax_id,
2234 NCACN_IP_TCP,
2235 DCERPC_AUTH_LEVEL_PRIVACY,
2236 domain->name,
2237 &conn->lsa_pipe_tcp);
2238 if (!NT_STATUS_IS_OK(status)) {
2239 DEBUG(10,("cli_rpc_pipe_open_schannel failed: %s\n",
2240 nt_errstr(status)));
2241 goto done;
2244 done:
2245 if (!NT_STATUS_IS_OK(status)) {
2246 TALLOC_FREE(conn->lsa_pipe_tcp);
2247 return status;
2250 *cli = conn->lsa_pipe_tcp;
2252 return status;
2255 NTSTATUS cm_connect_lsa(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2256 struct rpc_pipe_client **cli, struct policy_handle *lsa_policy)
2258 struct winbindd_cm_conn *conn;
2259 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2260 struct netlogon_creds_CredentialState *p_creds;
2262 result = init_dc_connection_rpc(domain);
2263 if (!NT_STATUS_IS_OK(result))
2264 return result;
2266 conn = &domain->conn;
2268 if (rpccli_is_connected(conn->lsa_pipe)) {
2269 goto done;
2272 TALLOC_FREE(conn->lsa_pipe);
2274 if ((conn->cli->user_name[0] == '\0') ||
2275 (conn->cli->domain[0] == '\0') ||
2276 (conn->cli->password == NULL || conn->cli->password[0] == '\0')) {
2277 DEBUG(10, ("cm_connect_lsa: No no user available for "
2278 "domain %s, trying schannel\n", conn->cli->domain));
2279 goto schannel;
2282 /* We have an authenticated connection. Use a NTLMSSP SPNEGO
2283 * authenticated LSA pipe with sign & seal. */
2284 result = cli_rpc_pipe_open_spnego_ntlmssp
2285 (conn->cli, &ndr_table_lsarpc.syntax_id, NCACN_NP,
2286 DCERPC_AUTH_LEVEL_PRIVACY,
2287 conn->cli->domain, conn->cli->user_name, conn->cli->password,
2288 &conn->lsa_pipe);
2290 if (!NT_STATUS_IS_OK(result)) {
2291 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
2292 "domain %s using NTLMSSP authenticated pipe: user "
2293 "%s\\%s. Error was %s. Trying schannel.\n",
2294 domain->name, conn->cli->domain,
2295 conn->cli->user_name, nt_errstr(result)));
2296 goto schannel;
2299 DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
2300 "NTLMSSP authenticated pipe: user %s\\%s\n",
2301 domain->name, conn->cli->domain, conn->cli->user_name ));
2303 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2304 SEC_FLAG_MAXIMUM_ALLOWED,
2305 &conn->lsa_policy);
2306 if (NT_STATUS_IS_OK(result)) {
2307 goto done;
2310 DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
2311 "schannel\n"));
2313 TALLOC_FREE(conn->lsa_pipe);
2315 schannel:
2317 /* Fall back to schannel if it's a W2K pre-SP1 box. */
2319 if (!cm_get_schannel_creds(domain, &p_creds)) {
2320 /* If this call fails - conn->cli can now be NULL ! */
2321 DEBUG(10, ("cm_connect_lsa: Could not get schannel auth info "
2322 "for domain %s, trying anon\n", domain->name));
2323 goto anonymous;
2325 result = cli_rpc_pipe_open_schannel_with_key
2326 (conn->cli, &ndr_table_lsarpc.syntax_id, NCACN_NP,
2327 DCERPC_AUTH_LEVEL_PRIVACY,
2328 domain->name, &p_creds, &conn->lsa_pipe);
2330 if (!NT_STATUS_IS_OK(result)) {
2331 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
2332 "domain %s using schannel. Error was %s\n",
2333 domain->name, nt_errstr(result) ));
2334 goto anonymous;
2336 DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
2337 "schannel.\n", domain->name ));
2339 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2340 SEC_FLAG_MAXIMUM_ALLOWED,
2341 &conn->lsa_policy);
2342 if (NT_STATUS_IS_OK(result)) {
2343 goto done;
2346 DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
2347 "anonymous\n"));
2349 TALLOC_FREE(conn->lsa_pipe);
2351 anonymous:
2353 result = cli_rpc_pipe_open_noauth(conn->cli,
2354 &ndr_table_lsarpc.syntax_id,
2355 &conn->lsa_pipe);
2356 if (!NT_STATUS_IS_OK(result)) {
2357 result = NT_STATUS_PIPE_NOT_AVAILABLE;
2358 goto done;
2361 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2362 SEC_FLAG_MAXIMUM_ALLOWED,
2363 &conn->lsa_policy);
2364 done:
2365 if (!NT_STATUS_IS_OK(result)) {
2366 invalidate_cm_connection(conn);
2367 return result;
2370 *cli = conn->lsa_pipe;
2371 *lsa_policy = conn->lsa_policy;
2372 return result;
2375 /****************************************************************************
2376 Open the netlogon pipe to this DC. Use schannel if specified in client conf.
2377 session key stored in conn->netlogon_pipe->dc->sess_key.
2378 ****************************************************************************/
2380 NTSTATUS cm_connect_netlogon(struct winbindd_domain *domain,
2381 struct rpc_pipe_client **cli)
2383 struct winbindd_cm_conn *conn;
2384 NTSTATUS result;
2386 uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS;
2387 uint8 mach_pwd[16];
2388 enum netr_SchannelType sec_chan_type;
2389 const char *account_name;
2390 struct rpc_pipe_client *netlogon_pipe = NULL;
2392 *cli = NULL;
2394 result = init_dc_connection_rpc(domain);
2395 if (!NT_STATUS_IS_OK(result)) {
2396 return result;
2399 conn = &domain->conn;
2401 if (rpccli_is_connected(conn->netlogon_pipe)) {
2402 *cli = conn->netlogon_pipe;
2403 return NT_STATUS_OK;
2406 TALLOC_FREE(conn->netlogon_pipe);
2408 result = cli_rpc_pipe_open_noauth(conn->cli,
2409 &ndr_table_netlogon.syntax_id,
2410 &netlogon_pipe);
2411 if (!NT_STATUS_IS_OK(result)) {
2412 return result;
2415 if ((!IS_DC) && (!domain->primary)) {
2416 /* Clear the schannel request bit and drop down */
2417 neg_flags &= ~NETLOGON_NEG_SCHANNEL;
2418 goto no_schannel;
2421 if (lp_client_schannel() != False) {
2422 neg_flags |= NETLOGON_NEG_SCHANNEL;
2425 if (!get_trust_pw_hash(domain->name, mach_pwd, &account_name,
2426 &sec_chan_type))
2428 TALLOC_FREE(netlogon_pipe);
2429 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2432 result = rpccli_netlogon_setup_creds(
2433 netlogon_pipe,
2434 domain->dcname, /* server name. */
2435 domain->name, /* domain name */
2436 global_myname(), /* client name */
2437 account_name, /* machine account */
2438 mach_pwd, /* machine password */
2439 sec_chan_type, /* from get_trust_pw */
2440 &neg_flags);
2442 if (!NT_STATUS_IS_OK(result)) {
2443 TALLOC_FREE(netlogon_pipe);
2444 return result;
2447 if ((lp_client_schannel() == True) &&
2448 ((neg_flags & NETLOGON_NEG_SCHANNEL) == 0)) {
2449 DEBUG(3, ("Server did not offer schannel\n"));
2450 TALLOC_FREE(netlogon_pipe);
2451 return NT_STATUS_ACCESS_DENIED;
2454 no_schannel:
2455 if ((lp_client_schannel() == False) ||
2456 ((neg_flags & NETLOGON_NEG_SCHANNEL) == 0)) {
2458 * NetSamLogonEx only works for schannel
2460 domain->can_do_samlogon_ex = False;
2462 /* We're done - just keep the existing connection to NETLOGON
2463 * open */
2464 conn->netlogon_pipe = netlogon_pipe;
2465 *cli = conn->netlogon_pipe;
2466 return NT_STATUS_OK;
2469 /* Using the credentials from the first pipe, open a signed and sealed
2470 second netlogon pipe. The session key is stored in the schannel
2471 part of the new pipe auth struct.
2474 result = cli_rpc_pipe_open_schannel_with_key(
2475 conn->cli, &ndr_table_netlogon.syntax_id, NCACN_NP,
2476 DCERPC_AUTH_LEVEL_PRIVACY, domain->name, &netlogon_pipe->dc,
2477 &conn->netlogon_pipe);
2479 /* We can now close the initial netlogon pipe. */
2480 TALLOC_FREE(netlogon_pipe);
2482 if (!NT_STATUS_IS_OK(result)) {
2483 DEBUG(3, ("Could not open schannel'ed NETLOGON pipe. Error "
2484 "was %s\n", nt_errstr(result)));
2486 invalidate_cm_connection(conn);
2487 return result;
2491 * Always try netr_LogonSamLogonEx. We will fall back for NT4
2492 * which gives DCERPC_FAULT_OP_RNG_ERROR (function not
2493 * supported). We used to only try SamLogonEx for AD, but
2494 * Samba DCs can also do it. And because we don't distinguish
2495 * between Samba and NT4, always try it once.
2497 domain->can_do_samlogon_ex = true;
2499 *cli = conn->netlogon_pipe;
2500 return NT_STATUS_OK;