Merge branch 'master' of /home/tridge/samba/git/combined
[Samba/aatanasov.git] / source3 / winbindd / winbindd_cm.c
blob450bb1bc06cd9249813aed642578ba745b1f8ab4
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"
65 #undef DBGC_CLASS
66 #define DBGC_CLASS DBGC_WINBIND
68 struct dc_name_ip {
69 fstring name;
70 struct sockaddr_storage ss;
73 extern struct winbindd_methods reconnect_methods;
74 extern bool override_logfile;
76 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain);
77 static void set_dc_type_and_flags( struct winbindd_domain *domain );
78 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
79 struct dc_name_ip **dcs, int *num_dcs);
81 /****************************************************************
82 Child failed to find DC's. Reschedule check.
83 ****************************************************************/
85 static void msg_failed_to_go_online(struct messaging_context *msg,
86 void *private_data,
87 uint32_t msg_type,
88 struct server_id server_id,
89 DATA_BLOB *data)
91 struct winbindd_domain *domain;
92 const char *domainname = (const char *)data->data;
94 if (data->data == NULL || data->length == 0) {
95 return;
98 DEBUG(5,("msg_fail_to_go_online: received for domain %s.\n", domainname));
100 for (domain = domain_list(); domain; domain = domain->next) {
101 if (domain->internal) {
102 continue;
105 if (strequal(domain->name, domainname)) {
106 if (domain->online) {
107 /* We're already online, ignore. */
108 DEBUG(5,("msg_fail_to_go_online: domain %s "
109 "already online.\n", domainname));
110 continue;
113 /* Reschedule the online check. */
114 set_domain_offline(domain);
115 break;
120 /****************************************************************
121 Actually cause a reconnect from a message.
122 ****************************************************************/
124 static void msg_try_to_go_online(struct messaging_context *msg,
125 void *private_data,
126 uint32_t msg_type,
127 struct server_id server_id,
128 DATA_BLOB *data)
130 struct winbindd_domain *domain;
131 const char *domainname = (const char *)data->data;
133 if (data->data == NULL || data->length == 0) {
134 return;
137 DEBUG(5,("msg_try_to_go_online: received for domain %s.\n", domainname));
139 for (domain = domain_list(); domain; domain = domain->next) {
140 if (domain->internal) {
141 continue;
144 if (strequal(domain->name, domainname)) {
146 if (domain->online) {
147 /* We're already online, ignore. */
148 DEBUG(5,("msg_try_to_go_online: domain %s "
149 "already online.\n", domainname));
150 continue;
153 /* This call takes care of setting the online
154 flag to true if we connected, or re-adding
155 the offline handler if false. Bypasses online
156 check so always does network calls. */
158 init_dc_connection_network(domain);
159 break;
164 /****************************************************************
165 Fork a child to try and contact a DC. Do this as contacting a
166 DC requires blocking lookups and we don't want to block our
167 parent.
168 ****************************************************************/
170 static bool fork_child_dc_connect(struct winbindd_domain *domain)
172 struct dc_name_ip *dcs = NULL;
173 int num_dcs = 0;
174 TALLOC_CTX *mem_ctx = NULL;
175 pid_t parent_pid = sys_getpid();
176 char *lfile = NULL;
178 /* Stop zombies */
179 CatchChild();
181 if (domain->dc_probe_pid != (pid_t)-1) {
183 * We might already have a DC probe
184 * child working, check.
186 if (process_exists_by_pid(domain->dc_probe_pid)) {
187 DEBUG(10,("fork_child_dc_connect: pid %u already "
188 "checking for DC's.\n",
189 (unsigned int)domain->dc_probe_pid));
190 return true;
192 domain->dc_probe_pid = (pid_t)-1;
195 domain->dc_probe_pid = sys_fork();
197 if (domain->dc_probe_pid == (pid_t)-1) {
198 DEBUG(0, ("fork_child_dc_connect: Could not fork: %s\n", strerror(errno)));
199 return False;
202 if (domain->dc_probe_pid != (pid_t)0) {
203 /* Parent */
204 messaging_register(winbind_messaging_context(), NULL,
205 MSG_WINBIND_TRY_TO_GO_ONLINE,
206 msg_try_to_go_online);
207 messaging_register(winbind_messaging_context(), NULL,
208 MSG_WINBIND_FAILED_TO_GO_ONLINE,
209 msg_failed_to_go_online);
210 return True;
213 /* Child. */
215 /* Leave messages blocked - we will never process one. */
217 if (!override_logfile) {
218 if (asprintf(&lfile, "%s/log.winbindd-dc-connect", get_dyn_LOGFILEBASE()) == -1) {
219 DEBUG(0, ("fork_child_dc_connect: out of memory.\n"));
220 _exit(1);
224 if (!winbindd_reinit_after_fork(lfile)) {
225 messaging_send_buf(winbind_messaging_context(),
226 pid_to_procid(parent_pid),
227 MSG_WINBIND_FAILED_TO_GO_ONLINE,
228 (uint8 *)domain->name,
229 strlen(domain->name)+1);
230 _exit(1);
232 SAFE_FREE(lfile);
234 mem_ctx = talloc_init("fork_child_dc_connect");
235 if (!mem_ctx) {
236 DEBUG(0,("talloc_init failed.\n"));
237 messaging_send_buf(winbind_messaging_context(),
238 pid_to_procid(parent_pid),
239 MSG_WINBIND_FAILED_TO_GO_ONLINE,
240 (uint8 *)domain->name,
241 strlen(domain->name)+1);
242 _exit(1);
245 if ((!get_dcs(mem_ctx, domain, &dcs, &num_dcs)) || (num_dcs == 0)) {
246 /* Still offline ? Can't find DC's. */
247 messaging_send_buf(winbind_messaging_context(),
248 pid_to_procid(parent_pid),
249 MSG_WINBIND_FAILED_TO_GO_ONLINE,
250 (uint8 *)domain->name,
251 strlen(domain->name)+1);
252 _exit(0);
255 /* We got a DC. Send a message to our parent to get it to
256 try and do the same. */
258 messaging_send_buf(winbind_messaging_context(),
259 pid_to_procid(parent_pid),
260 MSG_WINBIND_TRY_TO_GO_ONLINE,
261 (uint8 *)domain->name,
262 strlen(domain->name)+1);
263 _exit(0);
266 /****************************************************************
267 Handler triggered if we're offline to try and detect a DC.
268 ****************************************************************/
270 static void check_domain_online_handler(struct event_context *ctx,
271 struct timed_event *te,
272 struct timeval now,
273 void *private_data)
275 struct winbindd_domain *domain =
276 (struct winbindd_domain *)private_data;
278 DEBUG(10,("check_domain_online_handler: called for domain "
279 "%s (online = %s)\n", domain->name,
280 domain->online ? "True" : "False" ));
282 TALLOC_FREE(domain->check_online_event);
284 /* Are we still in "startup" mode ? */
286 if (domain->startup && (now.tv_sec > domain->startup_time + 30)) {
287 /* No longer in "startup" mode. */
288 DEBUG(10,("check_domain_online_handler: domain %s no longer in 'startup' mode.\n",
289 domain->name ));
290 domain->startup = False;
293 /* We've been told to stay offline, so stay
294 that way. */
296 if (get_global_winbindd_state_offline()) {
297 DEBUG(10,("check_domain_online_handler: domain %s remaining globally offline\n",
298 domain->name ));
299 return;
302 /* Fork a child to test if it can contact a DC.
303 If it can then send ourselves a message to
304 cause a reconnect. */
306 fork_child_dc_connect(domain);
309 /****************************************************************
310 If we're still offline setup the timeout check.
311 ****************************************************************/
313 static void calc_new_online_timeout_check(struct winbindd_domain *domain)
315 int wbr = lp_winbind_reconnect_delay();
317 if (domain->startup) {
318 domain->check_online_timeout = 10;
319 } else if (domain->check_online_timeout < wbr) {
320 domain->check_online_timeout = wbr;
324 /****************************************************************
325 Set domain offline and also add handler to put us back online
326 if we detect a DC.
327 ****************************************************************/
329 void set_domain_offline(struct winbindd_domain *domain)
331 DEBUG(10,("set_domain_offline: called for domain %s\n",
332 domain->name ));
334 TALLOC_FREE(domain->check_online_event);
336 if (domain->internal) {
337 DEBUG(3,("set_domain_offline: domain %s is internal - logic error.\n",
338 domain->name ));
339 return;
342 domain->online = False;
344 /* Offline domains are always initialized. They're
345 re-initialized when they go back online. */
347 domain->initialized = True;
349 /* We only add the timeout handler that checks and
350 allows us to go back online when we've not
351 been told to remain offline. */
353 if (get_global_winbindd_state_offline()) {
354 DEBUG(10,("set_domain_offline: domain %s remaining globally offline\n",
355 domain->name ));
356 return;
359 /* If we're in startup mode, check again in 10 seconds, not in
360 lp_winbind_reconnect_delay() seconds (which is 30 seconds by default). */
362 calc_new_online_timeout_check(domain);
364 domain->check_online_event = event_add_timed(winbind_event_context(),
365 NULL,
366 timeval_current_ofs(domain->check_online_timeout,0),
367 check_domain_online_handler,
368 domain);
370 /* The above *has* to succeed for winbindd to work. */
371 if (!domain->check_online_event) {
372 smb_panic("set_domain_offline: failed to add online handler");
375 DEBUG(10,("set_domain_offline: added event handler for domain %s\n",
376 domain->name ));
378 /* Send an offline message to the idmap child when our
379 primary domain goes offline */
381 if ( domain->primary ) {
382 struct winbindd_child *idmap = idmap_child();
384 if ( idmap->pid != 0 ) {
385 messaging_send_buf(winbind_messaging_context(),
386 pid_to_procid(idmap->pid),
387 MSG_WINBIND_OFFLINE,
388 (uint8 *)domain->name,
389 strlen(domain->name)+1);
393 return;
396 /****************************************************************
397 Set domain online - if allowed.
398 ****************************************************************/
400 static void set_domain_online(struct winbindd_domain *domain)
402 DEBUG(10,("set_domain_online: called for domain %s\n",
403 domain->name ));
405 if (domain->internal) {
406 DEBUG(3,("set_domain_online: domain %s is internal - logic error.\n",
407 domain->name ));
408 return;
411 if (get_global_winbindd_state_offline()) {
412 DEBUG(10,("set_domain_online: domain %s remaining globally offline\n",
413 domain->name ));
414 return;
417 winbindd_set_locator_kdc_envs(domain);
419 /* If we are waiting to get a krb5 ticket, trigger immediately. */
420 ccache_regain_all_now();
422 /* Ok, we're out of any startup mode now... */
423 domain->startup = False;
425 if (domain->online == False) {
426 /* We were offline - now we're online. We default to
427 using the MS-RPC backend if we started offline,
428 and if we're going online for the first time we
429 should really re-initialize the backends and the
430 checks to see if we're talking to an AD or NT domain.
433 domain->initialized = False;
435 /* 'reconnect_methods' is the MS-RPC backend. */
436 if (domain->backend == &reconnect_methods) {
437 domain->backend = NULL;
441 /* Ensure we have no online timeout checks. */
442 domain->check_online_timeout = 0;
443 TALLOC_FREE(domain->check_online_event);
445 /* Ensure we ignore any pending child messages. */
446 messaging_deregister(winbind_messaging_context(),
447 MSG_WINBIND_TRY_TO_GO_ONLINE, NULL);
448 messaging_deregister(winbind_messaging_context(),
449 MSG_WINBIND_FAILED_TO_GO_ONLINE, NULL);
451 domain->online = True;
453 /* Send an online message to the idmap child when our
454 primary domain comes online */
456 if ( domain->primary ) {
457 struct winbindd_child *idmap = idmap_child();
459 if ( idmap->pid != 0 ) {
460 messaging_send_buf(winbind_messaging_context(),
461 pid_to_procid(idmap->pid),
462 MSG_WINBIND_ONLINE,
463 (uint8 *)domain->name,
464 strlen(domain->name)+1);
468 return;
471 /****************************************************************
472 Requested to set a domain online.
473 ****************************************************************/
475 void set_domain_online_request(struct winbindd_domain *domain)
477 struct timeval tev;
479 DEBUG(10,("set_domain_online_request: called for domain %s\n",
480 domain->name ));
482 if (get_global_winbindd_state_offline()) {
483 DEBUG(10,("set_domain_online_request: domain %s remaining globally offline\n",
484 domain->name ));
485 return;
488 if (domain->internal) {
489 DEBUG(10, ("set_domain_online_request: Internal domains are "
490 "always online\n"));
491 return;
494 /* We've been told it's safe to go online and
495 try and connect to a DC. But I don't believe it
496 because network manager seems to lie.
497 Wait at least 5 seconds. Heuristics suck... */
500 GetTimeOfDay(&tev);
502 /* Go into "startup" mode again. */
503 domain->startup_time = tev.tv_sec;
504 domain->startup = True;
506 tev.tv_sec += 5;
508 if (!domain->check_online_event) {
509 /* If we've come from being globally offline we
510 don't have a check online event handler set.
511 We need to add one now we're trying to go
512 back online. */
514 DEBUG(10,("set_domain_online_request: domain %s was globally offline.\n",
515 domain->name ));
518 TALLOC_FREE(domain->check_online_event);
520 domain->check_online_event = event_add_timed(winbind_event_context(),
521 NULL,
522 tev,
523 check_domain_online_handler,
524 domain);
526 /* The above *has* to succeed for winbindd to work. */
527 if (!domain->check_online_event) {
528 smb_panic("set_domain_online_request: failed to add online handler");
532 /****************************************************************
533 Add -ve connection cache entries for domain and realm.
534 ****************************************************************/
536 void winbind_add_failed_connection_entry(const struct winbindd_domain *domain,
537 const char *server,
538 NTSTATUS result)
540 add_failed_connection_entry(domain->name, server, result);
541 /* If this was the saf name for the last thing we talked to,
542 remove it. */
543 saf_delete(domain->name);
544 if (*domain->alt_name) {
545 add_failed_connection_entry(domain->alt_name, server, result);
546 saf_delete(domain->alt_name);
548 winbindd_unset_locator_kdc_env(domain);
551 /* Choose between anonymous or authenticated connections. We need to use
552 an authenticated connection if DCs have the RestrictAnonymous registry
553 entry set > 0, or the "Additional restrictions for anonymous
554 connections" set in the win2k Local Security Policy.
556 Caller to free() result in domain, username, password
559 static void cm_get_ipc_userpass(char **username, char **domain, char **password)
561 *username = (char *)secrets_fetch(SECRETS_AUTH_USER, NULL);
562 *domain = (char *)secrets_fetch(SECRETS_AUTH_DOMAIN, NULL);
563 *password = (char *)secrets_fetch(SECRETS_AUTH_PASSWORD, NULL);
565 if (*username && **username) {
567 if (!*domain || !**domain)
568 *domain = smb_xstrdup(lp_workgroup());
570 if (!*password || !**password)
571 *password = smb_xstrdup("");
573 DEBUG(3, ("cm_get_ipc_userpass: Retrieved auth-user from secrets.tdb [%s\\%s]\n",
574 *domain, *username));
576 } else {
577 DEBUG(3, ("cm_get_ipc_userpass: No auth-user defined\n"));
578 *username = smb_xstrdup("");
579 *domain = smb_xstrdup("");
580 *password = smb_xstrdup("");
584 static bool get_dc_name_via_netlogon(struct winbindd_domain *domain,
585 fstring dcname,
586 struct sockaddr_storage *dc_ss)
588 struct winbindd_domain *our_domain = NULL;
589 struct rpc_pipe_client *netlogon_pipe = NULL;
590 NTSTATUS result;
591 WERROR werr;
592 TALLOC_CTX *mem_ctx;
593 unsigned int orig_timeout;
594 const char *tmp = NULL;
595 const char *p;
597 /* Hmmmm. We can only open one connection to the NETLOGON pipe at the
598 * moment.... */
600 if (IS_DC) {
601 return False;
604 if (domain->primary) {
605 return False;
608 our_domain = find_our_domain();
610 if ((mem_ctx = talloc_init("get_dc_name_via_netlogon")) == NULL) {
611 return False;
614 result = cm_connect_netlogon(our_domain, &netlogon_pipe);
615 if (!NT_STATUS_IS_OK(result)) {
616 talloc_destroy(mem_ctx);
617 return False;
620 /* This call can take a long time - allow the server to time out.
621 35 seconds should do it. */
623 orig_timeout = rpccli_set_timeout(netlogon_pipe, 35000);
625 if (our_domain->active_directory) {
626 struct netr_DsRGetDCNameInfo *domain_info = NULL;
628 result = rpccli_netr_DsRGetDCName(netlogon_pipe,
629 mem_ctx,
630 our_domain->dcname,
631 domain->name,
632 NULL,
633 NULL,
634 DS_RETURN_DNS_NAME,
635 &domain_info,
636 &werr);
637 if (NT_STATUS_IS_OK(result) && W_ERROR_IS_OK(werr)) {
638 tmp = talloc_strdup(
639 mem_ctx, domain_info->dc_unc);
640 if (tmp == NULL) {
641 DEBUG(0, ("talloc_strdup failed\n"));
642 talloc_destroy(mem_ctx);
643 return false;
645 if (strlen(domain->alt_name) == 0) {
646 fstrcpy(domain->alt_name,
647 domain_info->domain_name);
649 if (strlen(domain->forest_name) == 0) {
650 fstrcpy(domain->forest_name,
651 domain_info->forest_name);
654 } else {
655 result = rpccli_netr_GetAnyDCName(netlogon_pipe, mem_ctx,
656 our_domain->dcname,
657 domain->name,
658 &tmp,
659 &werr);
662 /* And restore our original timeout. */
663 rpccli_set_timeout(netlogon_pipe, orig_timeout);
665 if (!NT_STATUS_IS_OK(result)) {
666 DEBUG(10,("rpccli_netr_GetAnyDCName failed: %s\n",
667 nt_errstr(result)));
668 talloc_destroy(mem_ctx);
669 return false;
672 if (!W_ERROR_IS_OK(werr)) {
673 DEBUG(10,("rpccli_netr_GetAnyDCName failed: %s\n",
674 win_errstr(werr)));
675 talloc_destroy(mem_ctx);
676 return false;
679 /* rpccli_netr_GetAnyDCName gives us a name with \\ */
680 p = strip_hostname(tmp);
682 fstrcpy(dcname, p);
684 talloc_destroy(mem_ctx);
686 DEBUG(10,("rpccli_netr_GetAnyDCName returned %s\n", dcname));
688 if (!resolve_name(dcname, dc_ss, 0x20, true)) {
689 return False;
692 return True;
696 * Helper function to assemble trust password and account name
698 static NTSTATUS get_trust_creds(const struct winbindd_domain *domain,
699 char **machine_password,
700 char **machine_account,
701 char **machine_krb5_principal)
703 const char *account_name;
704 const char *name = NULL;
706 /* If we are a DC and this is not our own domain */
708 if (IS_DC) {
709 name = domain->name;
710 } else {
711 struct winbindd_domain *our_domain = find_our_domain();
713 if (!our_domain)
714 return NT_STATUS_INVALID_SERVER_STATE;
716 name = our_domain->name;
719 if (!get_trust_pw_clear(name, machine_password,
720 &account_name, NULL))
722 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
725 if ((machine_account != NULL) &&
726 (asprintf(machine_account, "%s$", account_name) == -1))
728 return NT_STATUS_NO_MEMORY;
731 /* For now assume our machine account only exists in our domain */
733 if (machine_krb5_principal != NULL)
735 struct winbindd_domain *our_domain = find_our_domain();
737 if (!our_domain) {
738 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
741 if (asprintf(machine_krb5_principal, "%s$@%s",
742 account_name, our_domain->alt_name) == -1)
744 return NT_STATUS_NO_MEMORY;
747 strupper_m(*machine_krb5_principal);
750 return NT_STATUS_OK;
753 /************************************************************************
754 Given a fd with a just-connected TCP connection to a DC, open a connection
755 to the pipe.
756 ************************************************************************/
758 static NTSTATUS cm_prepare_connection(const struct winbindd_domain *domain,
759 const int sockfd,
760 const char *controller,
761 struct cli_state **cli,
762 bool *retry)
764 char *machine_password = NULL;
765 char *machine_krb5_principal = NULL;
766 char *machine_account = NULL;
767 char *ipc_username = NULL;
768 char *ipc_domain = NULL;
769 char *ipc_password = NULL;
771 struct named_mutex *mutex;
773 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
775 struct sockaddr peeraddr;
776 socklen_t peeraddr_len;
778 struct sockaddr_in *peeraddr_in =
779 (struct sockaddr_in *)(void *)&peeraddr;
781 DEBUG(10,("cm_prepare_connection: connecting to DC %s for domain %s\n",
782 controller, domain->name ));
784 *retry = True;
786 mutex = grab_named_mutex(talloc_tos(), controller,
787 WINBIND_SERVER_MUTEX_WAIT_TIME);
788 if (mutex == NULL) {
789 DEBUG(0,("cm_prepare_connection: mutex grab failed for %s\n",
790 controller));
791 result = NT_STATUS_POSSIBLE_DEADLOCK;
792 goto done;
795 if ((*cli = cli_initialise()) == NULL) {
796 DEBUG(1, ("Could not cli_initialize\n"));
797 result = NT_STATUS_NO_MEMORY;
798 goto done;
801 (*cli)->timeout = 10000; /* 10 seconds */
802 (*cli)->fd = sockfd;
803 fstrcpy((*cli)->desthost, controller);
804 (*cli)->use_kerberos = True;
806 peeraddr_len = sizeof(peeraddr);
808 if ((getpeername((*cli)->fd, &peeraddr, &peeraddr_len) != 0) ||
809 (peeraddr_len != sizeof(struct sockaddr_in)) ||
810 (peeraddr_in->sin_family != PF_INET))
812 DEBUG(0,("cm_prepare_connection: %s\n", strerror(errno)));
813 result = NT_STATUS_UNSUCCESSFUL;
814 goto done;
817 if (ntohs(peeraddr_in->sin_port) == 139) {
818 struct nmb_name calling;
819 struct nmb_name called;
821 make_nmb_name(&calling, global_myname(), 0x0);
822 make_nmb_name(&called, "*SMBSERVER", 0x20);
824 if (!cli_session_request(*cli, &calling, &called)) {
825 DEBUG(8, ("cli_session_request failed for %s\n",
826 controller));
827 result = NT_STATUS_UNSUCCESSFUL;
828 goto done;
832 result = cli_negprot(*cli);
834 if (!NT_STATUS_IS_OK(result)) {
835 DEBUG(1, ("cli_negprot failed: %s\n", nt_errstr(result)));
836 goto done;
839 if (!is_dc_trusted_domain_situation(domain->name) &&
840 (*cli)->protocol >= PROTOCOL_NT1 &&
841 (*cli)->capabilities & CAP_EXTENDED_SECURITY)
843 ADS_STATUS ads_status;
845 result = get_trust_creds(domain, &machine_password,
846 &machine_account,
847 &machine_krb5_principal);
848 if (!NT_STATUS_IS_OK(result)) {
849 goto anon_fallback;
852 if (lp_security() == SEC_ADS) {
854 /* Try a krb5 session */
856 (*cli)->use_kerberos = True;
857 DEBUG(5, ("connecting to %s from %s with kerberos principal "
858 "[%s] and realm [%s]\n", controller, global_myname(),
859 machine_krb5_principal, domain->alt_name));
861 winbindd_set_locator_kdc_envs(domain);
863 ads_status = cli_session_setup_spnego(*cli,
864 machine_krb5_principal,
865 machine_password,
866 lp_workgroup(),
867 domain->alt_name);
869 if (!ADS_ERR_OK(ads_status)) {
870 DEBUG(4,("failed kerberos session setup with %s\n",
871 ads_errstr(ads_status)));
874 result = ads_ntstatus(ads_status);
875 if (NT_STATUS_IS_OK(result)) {
876 /* Ensure creds are stored for NTLMSSP authenticated pipe access. */
877 result = cli_init_creds(*cli, machine_account, lp_workgroup(), machine_password);
878 if (!NT_STATUS_IS_OK(result)) {
879 goto done;
881 goto session_setup_done;
885 /* Fall back to non-kerberos session setup using NTLMSSP SPNEGO with the machine account. */
886 (*cli)->use_kerberos = False;
888 DEBUG(5, ("connecting to %s from %s with username "
889 "[%s]\\[%s]\n", controller, global_myname(),
890 lp_workgroup(), machine_account));
892 ads_status = cli_session_setup_spnego(*cli,
893 machine_account,
894 machine_password,
895 lp_workgroup(),
896 NULL);
897 if (!ADS_ERR_OK(ads_status)) {
898 DEBUG(4, ("authenticated session setup failed with %s\n",
899 ads_errstr(ads_status)));
902 result = ads_ntstatus(ads_status);
903 if (NT_STATUS_IS_OK(result)) {
904 /* Ensure creds are stored for NTLMSSP authenticated pipe access. */
905 result = cli_init_creds(*cli, machine_account, lp_workgroup(), machine_password);
906 if (!NT_STATUS_IS_OK(result)) {
907 goto done;
909 goto session_setup_done;
913 /* Fall back to non-kerberos session setup with auth_user */
915 (*cli)->use_kerberos = False;
917 cm_get_ipc_userpass(&ipc_username, &ipc_domain, &ipc_password);
919 if ((((*cli)->sec_mode & NEGOTIATE_SECURITY_CHALLENGE_RESPONSE) != 0) &&
920 (strlen(ipc_username) > 0)) {
922 /* Only try authenticated if we have a username */
924 DEBUG(5, ("connecting to %s from %s with username "
925 "[%s]\\[%s]\n", controller, global_myname(),
926 ipc_domain, ipc_username));
928 if (NT_STATUS_IS_OK(cli_session_setup(
929 *cli, ipc_username,
930 ipc_password, strlen(ipc_password)+1,
931 ipc_password, strlen(ipc_password)+1,
932 ipc_domain))) {
933 /* Successful logon with given username. */
934 result = cli_init_creds(*cli, ipc_username, ipc_domain, ipc_password);
935 if (!NT_STATUS_IS_OK(result)) {
936 goto done;
938 goto session_setup_done;
939 } else {
940 DEBUG(4, ("authenticated session setup with user %s\\%s failed.\n",
941 ipc_domain, ipc_username ));
945 anon_fallback:
947 /* Fall back to anonymous connection, this might fail later */
948 DEBUG(10,("cm_prepare_connection: falling back to anonymous "
949 "connection for DC %s\n",
950 controller ));
952 if (NT_STATUS_IS_OK(cli_session_setup(*cli, "", NULL, 0,
953 NULL, 0, ""))) {
954 DEBUG(5, ("Connected anonymously\n"));
955 result = cli_init_creds(*cli, "", "", "");
956 if (!NT_STATUS_IS_OK(result)) {
957 goto done;
959 goto session_setup_done;
962 result = cli_nt_error(*cli);
964 if (NT_STATUS_IS_OK(result))
965 result = NT_STATUS_UNSUCCESSFUL;
967 /* We can't session setup */
969 goto done;
971 session_setup_done:
973 /* cache the server name for later connections */
975 saf_store( domain->name, (*cli)->desthost );
976 if (domain->alt_name && (*cli)->use_kerberos) {
977 saf_store( domain->alt_name, (*cli)->desthost );
980 winbindd_set_locator_kdc_envs(domain);
982 result = cli_tcon_andx(*cli, "IPC$", "IPC", "", 0);
984 if (!NT_STATUS_IS_OK(result)) {
985 DEBUG(1,("failed tcon_X with %s\n", nt_errstr(result)));
986 goto done;
989 TALLOC_FREE(mutex);
990 *retry = False;
992 /* set the domain if empty; needed for schannel connections */
993 if ( !(*cli)->domain[0] ) {
994 result = cli_set_domain((*cli), domain->name);
995 if (!NT_STATUS_IS_OK(result)) {
996 return result;
1000 result = NT_STATUS_OK;
1002 done:
1003 TALLOC_FREE(mutex);
1004 SAFE_FREE(machine_account);
1005 SAFE_FREE(machine_password);
1006 SAFE_FREE(machine_krb5_principal);
1007 SAFE_FREE(ipc_username);
1008 SAFE_FREE(ipc_domain);
1009 SAFE_FREE(ipc_password);
1011 if (!NT_STATUS_IS_OK(result)) {
1012 winbind_add_failed_connection_entry(domain, controller, result);
1013 if ((*cli) != NULL) {
1014 cli_shutdown(*cli);
1015 *cli = NULL;
1019 return result;
1022 /*******************************************************************
1023 Add a dcname and sockaddr_storage pair to the end of a dc_name_ip
1024 array.
1026 Keeps the list unique by not adding duplicate entries.
1028 @param[in] mem_ctx talloc memory context to allocate from
1029 @param[in] domain_name domain of the DC
1030 @param[in] dcname name of the DC to add to the list
1031 @param[in] pss Internet address and port pair to add to the list
1032 @param[in,out] dcs array of dc_name_ip structures to add to
1033 @param[in,out] num_dcs number of dcs returned in the dcs array
1034 @return true if the list was added to, false otherwise
1035 *******************************************************************/
1037 static bool add_one_dc_unique(TALLOC_CTX *mem_ctx, const char *domain_name,
1038 const char *dcname, struct sockaddr_storage *pss,
1039 struct dc_name_ip **dcs, int *num)
1041 int i = 0;
1043 if (!NT_STATUS_IS_OK(check_negative_conn_cache(domain_name, dcname))) {
1044 DEBUG(10, ("DC %s was in the negative conn cache\n", dcname));
1045 return False;
1048 /* Make sure there's no duplicates in the list */
1049 for (i=0; i<*num; i++)
1050 if (sockaddr_equal(
1051 (struct sockaddr *)(void *)&(*dcs)[i].ss,
1052 (struct sockaddr *)(void *)pss))
1053 return False;
1055 *dcs = TALLOC_REALLOC_ARRAY(mem_ctx, *dcs, struct dc_name_ip, (*num)+1);
1057 if (*dcs == NULL)
1058 return False;
1060 fstrcpy((*dcs)[*num].name, dcname);
1061 (*dcs)[*num].ss = *pss;
1062 *num += 1;
1063 return True;
1066 static bool add_sockaddr_to_array(TALLOC_CTX *mem_ctx,
1067 struct sockaddr_storage *pss, uint16 port,
1068 struct sockaddr_storage **addrs, int *num)
1070 *addrs = TALLOC_REALLOC_ARRAY(mem_ctx, *addrs, struct sockaddr_storage, (*num)+1);
1072 if (*addrs == NULL) {
1073 *num = 0;
1074 return False;
1077 (*addrs)[*num] = *pss;
1078 set_sockaddr_port((struct sockaddr *)&(*addrs)[*num], port);
1080 *num += 1;
1081 return True;
1084 /*******************************************************************
1085 convert an ip to a name
1086 *******************************************************************/
1088 static bool dcip_to_name(TALLOC_CTX *mem_ctx,
1089 const struct winbindd_domain *domain,
1090 struct sockaddr_storage *pss,
1091 fstring name )
1093 struct ip_service ip_list;
1094 uint32_t nt_version = NETLOGON_NT_VERSION_1;
1096 ip_list.ss = *pss;
1097 ip_list.port = 0;
1099 #ifdef WITH_ADS
1100 /* For active directory servers, try to get the ldap server name.
1101 None of these failures should be considered critical for now */
1103 if (lp_security() == SEC_ADS) {
1104 ADS_STRUCT *ads;
1105 ADS_STATUS ads_status;
1106 char addr[INET6_ADDRSTRLEN];
1108 print_sockaddr(addr, sizeof(addr), pss);
1110 ads = ads_init(domain->alt_name, domain->name, addr);
1111 ads->auth.flags |= ADS_AUTH_NO_BIND;
1113 ads_status = ads_connect(ads);
1114 if (ADS_ERR_OK(ads_status)) {
1115 /* We got a cldap packet. */
1116 fstrcpy(name, ads->config.ldap_server_name);
1117 namecache_store(name, 0x20, 1, &ip_list);
1119 DEBUG(10,("dcip_to_name: flags = 0x%x\n", (unsigned int)ads->config.flags));
1121 if (domain->primary && (ads->config.flags & NBT_SERVER_KDC)) {
1122 if (ads_closest_dc(ads)) {
1123 char *sitename = sitename_fetch(ads->config.realm);
1125 /* We're going to use this KDC for this realm/domain.
1126 If we are using sites, then force the krb5 libs
1127 to use this KDC. */
1129 create_local_private_krb5_conf_for_domain(domain->alt_name,
1130 domain->name,
1131 sitename,
1132 pss);
1134 SAFE_FREE(sitename);
1135 } else {
1136 /* use an off site KDC */
1137 create_local_private_krb5_conf_for_domain(domain->alt_name,
1138 domain->name,
1139 NULL,
1140 pss);
1142 winbindd_set_locator_kdc_envs(domain);
1144 /* Ensure we contact this DC also. */
1145 saf_store( domain->name, name);
1146 saf_store( domain->alt_name, name);
1149 ads_destroy( &ads );
1150 return True;
1153 ads_destroy( &ads );
1155 #endif
1157 /* try GETDC requests next */
1159 if (send_getdc_request(mem_ctx, winbind_messaging_context(),
1160 pss, domain->name, &domain->sid,
1161 nt_version)) {
1162 const char *dc_name = NULL;
1163 int i;
1164 smb_msleep(100);
1165 for (i=0; i<5; i++) {
1166 if (receive_getdc_response(mem_ctx, pss, domain->name,
1167 &nt_version,
1168 &dc_name, NULL)) {
1169 fstrcpy(name, dc_name);
1170 namecache_store(name, 0x20, 1, &ip_list);
1171 return True;
1173 smb_msleep(500);
1177 /* try node status request */
1179 if ( name_status_find(domain->name, 0x1c, 0x20, pss, name) ) {
1180 namecache_store(name, 0x20, 1, &ip_list);
1181 return True;
1183 return False;
1186 /*******************************************************************
1187 Retrieve a list of IP addresses for domain controllers.
1189 The array is sorted in the preferred connection order.
1191 @param[in] mem_ctx talloc memory context to allocate from
1192 @param[in] domain domain to retrieve DCs for
1193 @param[out] dcs array of dcs that will be returned
1194 @param[out] num_dcs number of dcs returned in the dcs array
1195 @return always true
1196 *******************************************************************/
1198 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
1199 struct dc_name_ip **dcs, int *num_dcs)
1201 fstring dcname;
1202 struct sockaddr_storage ss;
1203 struct ip_service *ip_list = NULL;
1204 int iplist_size = 0;
1205 int i;
1206 bool is_our_domain;
1207 enum security_types sec = (enum security_types)lp_security();
1209 is_our_domain = strequal(domain->name, lp_workgroup());
1211 /* If not our domain, get the preferred DC, by asking our primary DC */
1212 if ( !is_our_domain
1213 && get_dc_name_via_netlogon(domain, dcname, &ss)
1214 && add_one_dc_unique(mem_ctx, domain->name, dcname, &ss, dcs,
1215 num_dcs) )
1217 char addr[INET6_ADDRSTRLEN];
1218 print_sockaddr(addr, sizeof(addr), &ss);
1219 DEBUG(10, ("Retrieved DC %s at %s via netlogon\n",
1220 dcname, addr));
1221 return True;
1224 if (sec == SEC_ADS) {
1225 char *sitename = NULL;
1227 /* We need to make sure we know the local site before
1228 doing any DNS queries, as this will restrict the
1229 get_sorted_dc_list() call below to only fetching
1230 DNS records for the correct site. */
1232 /* Find any DC to get the site record.
1233 We deliberately don't care about the
1234 return here. */
1236 get_dc_name(domain->name, domain->alt_name, dcname, &ss);
1238 sitename = sitename_fetch(domain->alt_name);
1239 if (sitename) {
1241 /* Do the site-specific AD dns lookup first. */
1242 get_sorted_dc_list(domain->alt_name, sitename, &ip_list,
1243 &iplist_size, True);
1245 /* Add ips to the DC array. We don't look up the name
1246 of the DC in this function, but we fill in the char*
1247 of the ip now to make the failed connection cache
1248 work */
1249 for ( i=0; i<iplist_size; i++ ) {
1250 char addr[INET6_ADDRSTRLEN];
1251 print_sockaddr(addr, sizeof(addr),
1252 &ip_list[i].ss);
1253 add_one_dc_unique(mem_ctx,
1254 domain->name,
1255 addr,
1256 &ip_list[i].ss,
1257 dcs,
1258 num_dcs);
1261 SAFE_FREE(ip_list);
1262 SAFE_FREE(sitename);
1263 iplist_size = 0;
1266 /* Now we add DCs from the main AD DNS lookup. */
1267 get_sorted_dc_list(domain->alt_name, NULL, &ip_list,
1268 &iplist_size, True);
1270 for ( i=0; i<iplist_size; i++ ) {
1271 char addr[INET6_ADDRSTRLEN];
1272 print_sockaddr(addr, sizeof(addr),
1273 &ip_list[i].ss);
1274 add_one_dc_unique(mem_ctx,
1275 domain->name,
1276 addr,
1277 &ip_list[i].ss,
1278 dcs,
1279 num_dcs);
1282 SAFE_FREE(ip_list);
1283 iplist_size = 0;
1286 /* Try standard netbios queries if no ADS */
1287 if (*num_dcs == 0) {
1288 get_sorted_dc_list(domain->name, NULL, &ip_list, &iplist_size,
1289 False);
1291 for ( i=0; i<iplist_size; i++ ) {
1292 char addr[INET6_ADDRSTRLEN];
1293 print_sockaddr(addr, sizeof(addr),
1294 &ip_list[i].ss);
1295 add_one_dc_unique(mem_ctx,
1296 domain->name,
1297 addr,
1298 &ip_list[i].ss,
1299 dcs,
1300 num_dcs);
1303 SAFE_FREE(ip_list);
1304 iplist_size = 0;
1307 return True;
1310 /*******************************************************************
1311 Find and make a connection to a DC in the given domain.
1313 @param[in] mem_ctx talloc memory context to allocate from
1314 @param[in] domain domain to find a dc in
1315 @param[out] dcname NetBIOS or FQDN of DC that's connected to
1316 @param[out] pss DC Internet address and port
1317 @param[out] fd fd of the open socket connected to the newly found dc
1318 @return true when a DC connection is made, false otherwise
1319 *******************************************************************/
1321 static bool find_new_dc(TALLOC_CTX *mem_ctx,
1322 struct winbindd_domain *domain,
1323 fstring dcname, struct sockaddr_storage *pss, int *fd)
1325 struct dc_name_ip *dcs = NULL;
1326 int num_dcs = 0;
1328 const char **dcnames = NULL;
1329 int num_dcnames = 0;
1331 struct sockaddr_storage *addrs = NULL;
1332 int num_addrs = 0;
1334 int i, fd_index;
1336 *fd = -1;
1338 again:
1339 if (!get_dcs(mem_ctx, domain, &dcs, &num_dcs) || (num_dcs == 0))
1340 return False;
1342 for (i=0; i<num_dcs; i++) {
1344 if (!add_string_to_array(mem_ctx, dcs[i].name,
1345 &dcnames, &num_dcnames)) {
1346 return False;
1348 if (!add_sockaddr_to_array(mem_ctx, &dcs[i].ss, 445,
1349 &addrs, &num_addrs)) {
1350 return False;
1353 if (!add_string_to_array(mem_ctx, dcs[i].name,
1354 &dcnames, &num_dcnames)) {
1355 return False;
1357 if (!add_sockaddr_to_array(mem_ctx, &dcs[i].ss, 139,
1358 &addrs, &num_addrs)) {
1359 return False;
1363 if ((num_dcnames == 0) || (num_dcnames != num_addrs))
1364 return False;
1366 if ((addrs == NULL) || (dcnames == NULL))
1367 return False;
1369 /* 5 second timeout. */
1370 if (!open_any_socket_out(addrs, num_addrs, 5000, &fd_index, fd) ) {
1371 for (i=0; i<num_dcs; i++) {
1372 char ab[INET6_ADDRSTRLEN];
1373 print_sockaddr(ab, sizeof(ab), &dcs[i].ss);
1374 DEBUG(10, ("find_new_dc: open_any_socket_out failed for "
1375 "domain %s address %s. Error was %s\n",
1376 domain->name, ab, strerror(errno) ));
1377 winbind_add_failed_connection_entry(domain,
1378 dcs[i].name, NT_STATUS_UNSUCCESSFUL);
1380 return False;
1383 *pss = addrs[fd_index];
1385 if (*dcnames[fd_index] != '\0' && !is_ipaddress(dcnames[fd_index])) {
1386 /* Ok, we've got a name for the DC */
1387 fstrcpy(dcname, dcnames[fd_index]);
1388 return True;
1391 /* Try to figure out the name */
1392 if (dcip_to_name(mem_ctx, domain, pss, dcname)) {
1393 return True;
1396 /* We can not continue without the DC's name */
1397 winbind_add_failed_connection_entry(domain, dcs[fd_index].name,
1398 NT_STATUS_UNSUCCESSFUL);
1400 /* Throw away all arrays as we're doing this again. */
1401 TALLOC_FREE(dcs);
1402 num_dcs = 0;
1404 TALLOC_FREE(dcnames);
1405 num_dcnames = 0;
1407 TALLOC_FREE(addrs);
1408 num_addrs = 0;
1410 close(*fd);
1411 *fd = -1;
1413 goto again;
1416 static NTSTATUS cm_open_connection(struct winbindd_domain *domain,
1417 struct winbindd_cm_conn *new_conn)
1419 TALLOC_CTX *mem_ctx;
1420 NTSTATUS result;
1421 char *saf_servername = saf_fetch( domain->name );
1422 int retries;
1424 if ((mem_ctx = talloc_init("cm_open_connection")) == NULL) {
1425 SAFE_FREE(saf_servername);
1426 set_domain_offline(domain);
1427 return NT_STATUS_NO_MEMORY;
1430 /* we have to check the server affinity cache here since
1431 later we selecte a DC based on response time and not preference */
1433 /* Check the negative connection cache
1434 before talking to it. It going down may have
1435 triggered the reconnection. */
1437 if ( saf_servername && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, saf_servername))) {
1439 DEBUG(10,("cm_open_connection: saf_servername is '%s' for domain %s\n",
1440 saf_servername, domain->name ));
1442 /* convert an ip address to a name */
1443 if (is_ipaddress( saf_servername ) ) {
1444 fstring saf_name;
1445 struct sockaddr_storage ss;
1447 if (!interpret_string_addr(&ss, saf_servername,
1448 AI_NUMERICHOST)) {
1449 return NT_STATUS_UNSUCCESSFUL;
1451 if (dcip_to_name(mem_ctx, domain, &ss, saf_name )) {
1452 fstrcpy( domain->dcname, saf_name );
1453 } else {
1454 winbind_add_failed_connection_entry(
1455 domain, saf_servername,
1456 NT_STATUS_UNSUCCESSFUL);
1458 } else {
1459 fstrcpy( domain->dcname, saf_servername );
1462 SAFE_FREE( saf_servername );
1465 for (retries = 0; retries < 3; retries++) {
1466 int fd = -1;
1467 bool retry = False;
1469 result = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1471 DEBUG(10,("cm_open_connection: dcname is '%s' for domain %s\n",
1472 domain->dcname, domain->name ));
1474 if (*domain->dcname
1475 && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, domain->dcname))
1476 && (resolve_name(domain->dcname, &domain->dcaddr, 0x20, true)))
1478 struct sockaddr_storage *addrs = NULL;
1479 int num_addrs = 0;
1480 int dummy = 0;
1482 if (!add_sockaddr_to_array(mem_ctx, &domain->dcaddr, 445, &addrs, &num_addrs)) {
1483 set_domain_offline(domain);
1484 talloc_destroy(mem_ctx);
1485 return NT_STATUS_NO_MEMORY;
1487 if (!add_sockaddr_to_array(mem_ctx, &domain->dcaddr, 139, &addrs, &num_addrs)) {
1488 set_domain_offline(domain);
1489 talloc_destroy(mem_ctx);
1490 return NT_STATUS_NO_MEMORY;
1493 /* 5 second timeout. */
1494 if (!open_any_socket_out(addrs, num_addrs, 5000, &dummy, &fd)) {
1495 fd = -1;
1499 if ((fd == -1)
1500 && !find_new_dc(mem_ctx, domain, domain->dcname, &domain->dcaddr, &fd))
1502 /* This is the one place where we will
1503 set the global winbindd offline state
1504 to true, if a "WINBINDD_OFFLINE" entry
1505 is found in the winbindd cache. */
1506 set_global_winbindd_state_offline();
1507 break;
1510 new_conn->cli = NULL;
1512 result = cm_prepare_connection(domain, fd, domain->dcname,
1513 &new_conn->cli, &retry);
1515 if (!retry)
1516 break;
1519 if (NT_STATUS_IS_OK(result)) {
1521 winbindd_set_locator_kdc_envs(domain);
1523 if (domain->online == False) {
1524 /* We're changing state from offline to online. */
1525 set_global_winbindd_state_online();
1527 set_domain_online(domain);
1528 } else {
1529 /* Ensure we setup the retry handler. */
1530 set_domain_offline(domain);
1533 talloc_destroy(mem_ctx);
1534 return result;
1537 /* Close down all open pipes on a connection. */
1539 void invalidate_cm_connection(struct winbindd_cm_conn *conn)
1541 /* We're closing down a possibly dead
1542 connection. Don't have impossibly long (10s) timeouts. */
1544 if (conn->cli) {
1545 cli_set_timeout(conn->cli, 1000); /* 1 second. */
1548 if (conn->samr_pipe != NULL) {
1549 TALLOC_FREE(conn->samr_pipe);
1550 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1551 if (conn->cli) {
1552 cli_set_timeout(conn->cli, 500);
1556 if (conn->lsa_pipe != NULL) {
1557 TALLOC_FREE(conn->lsa_pipe);
1558 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1559 if (conn->cli) {
1560 cli_set_timeout(conn->cli, 500);
1564 if (conn->netlogon_pipe != NULL) {
1565 TALLOC_FREE(conn->netlogon_pipe);
1566 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1567 if (conn->cli) {
1568 cli_set_timeout(conn->cli, 500);
1572 if (conn->cli) {
1573 cli_shutdown(conn->cli);
1576 conn->cli = NULL;
1579 void close_conns_after_fork(void)
1581 struct winbindd_domain *domain;
1583 for (domain = domain_list(); domain; domain = domain->next) {
1584 if (domain->conn.cli == NULL)
1585 continue;
1587 if (domain->conn.cli->fd == -1)
1588 continue;
1590 close(domain->conn.cli->fd);
1591 domain->conn.cli->fd = -1;
1595 static bool connection_ok(struct winbindd_domain *domain)
1597 if (domain->conn.cli == NULL) {
1598 DEBUG(8, ("connection_ok: Connection to %s for domain %s has NULL "
1599 "cli!\n", domain->dcname, domain->name));
1600 return False;
1603 if (!domain->conn.cli->initialised) {
1604 DEBUG(3, ("connection_ok: Connection to %s for domain %s was never "
1605 "initialised!\n", domain->dcname, domain->name));
1606 return False;
1609 if (domain->conn.cli->fd == -1) {
1610 DEBUG(3, ("connection_ok: Connection to %s for domain %s has died or was "
1611 "never started (fd == -1)\n",
1612 domain->dcname, domain->name));
1613 return False;
1616 if (domain->online == False) {
1617 DEBUG(3, ("connection_ok: Domain %s is offline\n", domain->name));
1618 return False;
1621 return True;
1624 /* Initialize a new connection up to the RPC BIND.
1625 Bypass online status check so always does network calls. */
1627 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain)
1629 NTSTATUS result;
1631 /* Internal connections never use the network. */
1632 if (domain->internal) {
1633 domain->initialized = True;
1634 return NT_STATUS_OK;
1637 if (connection_ok(domain)) {
1638 if (!domain->initialized) {
1639 set_dc_type_and_flags(domain);
1641 return NT_STATUS_OK;
1644 invalidate_cm_connection(&domain->conn);
1646 result = cm_open_connection(domain, &domain->conn);
1648 if (NT_STATUS_IS_OK(result) && !domain->initialized) {
1649 set_dc_type_and_flags(domain);
1652 return result;
1655 NTSTATUS init_dc_connection(struct winbindd_domain *domain)
1657 if (domain->initialized && !domain->online) {
1658 /* We check for online status elsewhere. */
1659 return NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1662 return init_dc_connection_network(domain);
1665 /******************************************************************************
1666 Set the trust flags (direction and forest location) for a domain
1667 ******************************************************************************/
1669 static bool set_dc_type_and_flags_trustinfo( struct winbindd_domain *domain )
1671 struct winbindd_domain *our_domain;
1672 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
1673 struct netr_DomainTrustList trusts;
1674 int i;
1675 uint32 flags = (NETR_TRUST_FLAG_IN_FOREST |
1676 NETR_TRUST_FLAG_OUTBOUND |
1677 NETR_TRUST_FLAG_INBOUND);
1678 struct rpc_pipe_client *cli;
1679 TALLOC_CTX *mem_ctx = NULL;
1681 DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s\n", domain->name ));
1683 /* Our primary domain doesn't need to worry about trust flags.
1684 Force it to go through the network setup */
1685 if ( domain->primary ) {
1686 return False;
1689 our_domain = find_our_domain();
1691 if ( !connection_ok(our_domain) ) {
1692 DEBUG(3,("set_dc_type_and_flags_trustinfo: No connection to our domain!\n"));
1693 return False;
1696 /* This won't work unless our domain is AD */
1698 if ( !our_domain->active_directory ) {
1699 return False;
1702 /* Use DsEnumerateDomainTrusts to get us the trust direction
1703 and type */
1705 result = cm_connect_netlogon(our_domain, &cli);
1707 if (!NT_STATUS_IS_OK(result)) {
1708 DEBUG(5, ("set_dc_type_and_flags_trustinfo: Could not open "
1709 "a connection to %s for PIPE_NETLOGON (%s)\n",
1710 domain->name, nt_errstr(result)));
1711 return False;
1714 if ( (mem_ctx = talloc_init("set_dc_type_and_flags_trustinfo")) == NULL ) {
1715 DEBUG(0,("set_dc_type_and_flags_trustinfo: talloc_init() failed!\n"));
1716 return False;
1719 result = rpccli_netr_DsrEnumerateDomainTrusts(cli, mem_ctx,
1720 cli->desthost,
1721 flags,
1722 &trusts,
1723 NULL);
1724 if (!NT_STATUS_IS_OK(result)) {
1725 DEBUG(0,("set_dc_type_and_flags_trustinfo: "
1726 "failed to query trusted domain list: %s\n",
1727 nt_errstr(result)));
1728 talloc_destroy(mem_ctx);
1729 return false;
1732 /* Now find the domain name and get the flags */
1734 for ( i=0; i<trusts.count; i++ ) {
1735 if ( strequal( domain->name, trusts.array[i].netbios_name) ) {
1736 domain->domain_flags = trusts.array[i].trust_flags;
1737 domain->domain_type = trusts.array[i].trust_type;
1738 domain->domain_trust_attribs = trusts.array[i].trust_attributes;
1740 if ( domain->domain_type == NETR_TRUST_TYPE_UPLEVEL )
1741 domain->active_directory = True;
1743 /* This flag is only set if the domain is *our*
1744 primary domain and the primary domain is in
1745 native mode */
1747 domain->native_mode = (domain->domain_flags & NETR_TRUST_FLAG_NATIVE);
1749 DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s is %sin "
1750 "native mode.\n", domain->name,
1751 domain->native_mode ? "" : "NOT "));
1753 DEBUG(5,("set_dc_type_and_flags_trustinfo: domain %s is %s"
1754 "running active directory.\n", domain->name,
1755 domain->active_directory ? "" : "NOT "));
1758 domain->initialized = True;
1760 if ( !winbindd_can_contact_domain( domain) )
1761 domain->internal = True;
1763 break;
1767 talloc_destroy( mem_ctx );
1769 return domain->initialized;
1772 /******************************************************************************
1773 We can 'sense' certain things about the DC by it's replies to certain
1774 questions.
1776 This tells us if this particular remote server is Active Directory, and if it
1777 is native mode.
1778 ******************************************************************************/
1780 static void set_dc_type_and_flags_connect( struct winbindd_domain *domain )
1782 NTSTATUS result;
1783 WERROR werr;
1784 TALLOC_CTX *mem_ctx = NULL;
1785 struct rpc_pipe_client *cli = NULL;
1786 struct policy_handle pol;
1787 union dssetup_DsRoleInfo info;
1788 union lsa_PolicyInformation *lsa_info = NULL;
1790 if (!connection_ok(domain)) {
1791 return;
1794 mem_ctx = talloc_init("set_dc_type_and_flags on domain %s\n",
1795 domain->name);
1796 if (!mem_ctx) {
1797 DEBUG(1, ("set_dc_type_and_flags_connect: talloc_init() failed\n"));
1798 return;
1801 DEBUG(5, ("set_dc_type_and_flags_connect: domain %s\n", domain->name ));
1803 result = cli_rpc_pipe_open_noauth(domain->conn.cli,
1804 &ndr_table_dssetup.syntax_id,
1805 &cli);
1807 if (!NT_STATUS_IS_OK(result)) {
1808 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
1809 "PI_DSSETUP on domain %s: (%s)\n",
1810 domain->name, nt_errstr(result)));
1812 /* if this is just a non-AD domain we need to continue
1813 * identifying so that we can in the end return with
1814 * domain->initialized = True - gd */
1816 goto no_dssetup;
1819 result = rpccli_dssetup_DsRoleGetPrimaryDomainInformation(cli, mem_ctx,
1820 DS_ROLE_BASIC_INFORMATION,
1821 &info,
1822 &werr);
1823 TALLOC_FREE(cli);
1825 if (!NT_STATUS_IS_OK(result)) {
1826 DEBUG(5, ("set_dc_type_and_flags_connect: rpccli_ds_getprimarydominfo "
1827 "on domain %s failed: (%s)\n",
1828 domain->name, nt_errstr(result)));
1830 /* older samba3 DCs will return DCERPC_FAULT_OP_RNG_ERROR for
1831 * every opcode on the DSSETUP pipe, continue with
1832 * no_dssetup mode here as well to get domain->initialized
1833 * set - gd */
1835 if (NT_STATUS_V(result) == DCERPC_FAULT_OP_RNG_ERROR) {
1836 goto no_dssetup;
1839 TALLOC_FREE(mem_ctx);
1840 return;
1843 if ((info.basic.flags & DS_ROLE_PRIMARY_DS_RUNNING) &&
1844 !(info.basic.flags & DS_ROLE_PRIMARY_DS_MIXED_MODE)) {
1845 domain->native_mode = True;
1846 } else {
1847 domain->native_mode = False;
1850 no_dssetup:
1851 result = cli_rpc_pipe_open_noauth(domain->conn.cli,
1852 &ndr_table_lsarpc.syntax_id, &cli);
1854 if (!NT_STATUS_IS_OK(result)) {
1855 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
1856 "PI_LSARPC on domain %s: (%s)\n",
1857 domain->name, nt_errstr(result)));
1858 TALLOC_FREE(cli);
1859 TALLOC_FREE(mem_ctx);
1860 return;
1863 result = rpccli_lsa_open_policy2(cli, mem_ctx, True,
1864 SEC_FLAG_MAXIMUM_ALLOWED, &pol);
1866 if (NT_STATUS_IS_OK(result)) {
1867 /* This particular query is exactly what Win2k clients use
1868 to determine that the DC is active directory */
1869 result = rpccli_lsa_QueryInfoPolicy2(cli, mem_ctx,
1870 &pol,
1871 LSA_POLICY_INFO_DNS,
1872 &lsa_info);
1875 if (NT_STATUS_IS_OK(result)) {
1876 domain->active_directory = True;
1878 if (lsa_info->dns.name.string) {
1879 fstrcpy(domain->name, lsa_info->dns.name.string);
1882 if (lsa_info->dns.dns_domain.string) {
1883 fstrcpy(domain->alt_name,
1884 lsa_info->dns.dns_domain.string);
1887 /* See if we can set some domain trust flags about
1888 ourself */
1890 if (lsa_info->dns.dns_forest.string) {
1891 fstrcpy(domain->forest_name,
1892 lsa_info->dns.dns_forest.string);
1894 if (strequal(domain->forest_name, domain->alt_name)) {
1895 domain->domain_flags |= NETR_TRUST_FLAG_TREEROOT;
1899 if (lsa_info->dns.sid) {
1900 sid_copy(&domain->sid, lsa_info->dns.sid);
1902 } else {
1903 domain->active_directory = False;
1905 result = rpccli_lsa_open_policy(cli, mem_ctx, True,
1906 SEC_FLAG_MAXIMUM_ALLOWED,
1907 &pol);
1909 if (!NT_STATUS_IS_OK(result)) {
1910 goto done;
1913 result = rpccli_lsa_QueryInfoPolicy(cli, mem_ctx,
1914 &pol,
1915 LSA_POLICY_INFO_ACCOUNT_DOMAIN,
1916 &lsa_info);
1918 if (NT_STATUS_IS_OK(result)) {
1920 if (lsa_info->account_domain.name.string) {
1921 fstrcpy(domain->name,
1922 lsa_info->account_domain.name.string);
1925 if (lsa_info->account_domain.sid) {
1926 sid_copy(&domain->sid, lsa_info->account_domain.sid);
1930 done:
1932 DEBUG(5, ("set_dc_type_and_flags_connect: domain %s is %sin native mode.\n",
1933 domain->name, domain->native_mode ? "" : "NOT "));
1935 DEBUG(5,("set_dc_type_and_flags_connect: domain %s is %srunning active directory.\n",
1936 domain->name, domain->active_directory ? "" : "NOT "));
1938 TALLOC_FREE(cli);
1940 TALLOC_FREE(mem_ctx);
1942 domain->initialized = True;
1945 /**********************************************************************
1946 Set the domain_flags (trust attributes, domain operating modes, etc...
1947 ***********************************************************************/
1949 static void set_dc_type_and_flags( struct winbindd_domain *domain )
1951 /* we always have to contact our primary domain */
1953 if ( domain->primary ) {
1954 DEBUG(10,("set_dc_type_and_flags: setting up flags for "
1955 "primary domain\n"));
1956 set_dc_type_and_flags_connect( domain );
1957 return;
1960 /* Use our DC to get the information if possible */
1962 if ( !set_dc_type_and_flags_trustinfo( domain ) ) {
1963 /* Otherwise, fallback to contacting the
1964 domain directly */
1965 set_dc_type_and_flags_connect( domain );
1968 return;
1973 /**********************************************************************
1974 ***********************************************************************/
1976 static bool cm_get_schannel_creds(struct winbindd_domain *domain,
1977 struct netlogon_creds_CredentialState **ppdc)
1979 NTSTATUS result;
1980 struct rpc_pipe_client *netlogon_pipe;
1982 if (lp_client_schannel() == False) {
1983 return False;
1986 result = cm_connect_netlogon(domain, &netlogon_pipe);
1987 if (!NT_STATUS_IS_OK(result)) {
1988 return False;
1991 /* Return a pointer to the struct netlogon_creds_CredentialState from the
1992 netlogon pipe. */
1994 if (!domain->conn.netlogon_pipe->dc) {
1995 return false;
1998 *ppdc = domain->conn.netlogon_pipe->dc;
1999 return True;
2002 NTSTATUS cm_connect_sam(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2003 struct rpc_pipe_client **cli, struct policy_handle *sam_handle)
2005 struct winbindd_cm_conn *conn;
2006 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2007 struct netlogon_creds_CredentialState *p_creds;
2008 char *machine_password = NULL;
2009 char *machine_account = NULL;
2010 char *domain_name = NULL;
2012 result = init_dc_connection(domain);
2013 if (!NT_STATUS_IS_OK(result)) {
2014 return result;
2017 conn = &domain->conn;
2019 if (conn->samr_pipe != NULL) {
2020 goto done;
2025 * No SAMR pipe yet. Attempt to get an NTLMSSP SPNEGO authenticated
2026 * sign and sealed pipe using the machine account password by
2027 * preference. If we can't - try schannel, if that fails, try
2028 * anonymous.
2031 if ((conn->cli->user_name[0] == '\0') ||
2032 (conn->cli->domain[0] == '\0') ||
2033 (conn->cli->password == NULL || conn->cli->password[0] == '\0'))
2035 result = get_trust_creds(domain, &machine_password,
2036 &machine_account, NULL);
2037 if (!NT_STATUS_IS_OK(result)) {
2038 DEBUG(10, ("cm_connect_sam: No no user available for "
2039 "domain %s, trying schannel\n", conn->cli->domain));
2040 goto schannel;
2042 domain_name = domain->name;
2043 } else {
2044 machine_password = SMB_STRDUP(conn->cli->password);
2045 machine_account = SMB_STRDUP(conn->cli->user_name);
2046 domain_name = conn->cli->domain;
2049 if (!machine_password || !machine_account) {
2050 result = NT_STATUS_NO_MEMORY;
2051 goto done;
2054 /* We have an authenticated connection. Use a NTLMSSP SPNEGO
2055 authenticated SAMR pipe with sign & seal. */
2056 result = cli_rpc_pipe_open_spnego_ntlmssp(conn->cli,
2057 &ndr_table_samr.syntax_id,
2058 NCACN_NP,
2059 DCERPC_AUTH_LEVEL_PRIVACY,
2060 domain_name,
2061 machine_account,
2062 machine_password,
2063 &conn->samr_pipe);
2065 if (!NT_STATUS_IS_OK(result)) {
2066 DEBUG(10,("cm_connect_sam: failed to connect to SAMR "
2067 "pipe for domain %s using NTLMSSP "
2068 "authenticated pipe: user %s\\%s. Error was "
2069 "%s\n", domain->name, domain_name,
2070 machine_account, nt_errstr(result)));
2071 goto schannel;
2074 DEBUG(10,("cm_connect_sam: connected to SAMR pipe for "
2075 "domain %s using NTLMSSP authenticated "
2076 "pipe: user %s\\%s\n", domain->name,
2077 domain_name, machine_account));
2079 result = rpccli_samr_Connect2(conn->samr_pipe, mem_ctx,
2080 conn->samr_pipe->desthost,
2081 SEC_FLAG_MAXIMUM_ALLOWED,
2082 &conn->sam_connect_handle);
2083 if (NT_STATUS_IS_OK(result)) {
2084 goto open_domain;
2086 DEBUG(10,("cm_connect_sam: ntlmssp-sealed rpccli_samr_Connect2 "
2087 "failed for domain %s, error was %s. Trying schannel\n",
2088 domain->name, nt_errstr(result) ));
2089 TALLOC_FREE(conn->samr_pipe);
2091 schannel:
2093 /* Fall back to schannel if it's a W2K pre-SP1 box. */
2095 if (!cm_get_schannel_creds(domain, &p_creds)) {
2096 /* If this call fails - conn->cli can now be NULL ! */
2097 DEBUG(10, ("cm_connect_sam: Could not get schannel auth info "
2098 "for domain %s, trying anon\n", domain->name));
2099 goto anonymous;
2101 result = cli_rpc_pipe_open_schannel_with_key
2102 (conn->cli, &ndr_table_samr.syntax_id, NCACN_NP,
2103 DCERPC_AUTH_LEVEL_PRIVACY,
2104 domain->name, &p_creds, &conn->samr_pipe);
2106 if (!NT_STATUS_IS_OK(result)) {
2107 DEBUG(10,("cm_connect_sam: failed to connect to SAMR pipe for "
2108 "domain %s using schannel. Error was %s\n",
2109 domain->name, nt_errstr(result) ));
2110 goto anonymous;
2112 DEBUG(10,("cm_connect_sam: connected to SAMR pipe for domain %s using "
2113 "schannel.\n", domain->name ));
2115 result = rpccli_samr_Connect2(conn->samr_pipe, mem_ctx,
2116 conn->samr_pipe->desthost,
2117 SEC_FLAG_MAXIMUM_ALLOWED,
2118 &conn->sam_connect_handle);
2119 if (NT_STATUS_IS_OK(result)) {
2120 goto open_domain;
2122 DEBUG(10,("cm_connect_sam: schannel-sealed rpccli_samr_Connect2 failed "
2123 "for domain %s, error was %s. Trying anonymous\n",
2124 domain->name, nt_errstr(result) ));
2125 TALLOC_FREE(conn->samr_pipe);
2127 anonymous:
2129 /* Finally fall back to anonymous. */
2130 result = cli_rpc_pipe_open_noauth(conn->cli, &ndr_table_samr.syntax_id,
2131 &conn->samr_pipe);
2133 if (!NT_STATUS_IS_OK(result)) {
2134 goto done;
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 DEBUG(10,("cm_connect_sam: rpccli_samr_Connect2 failed "
2143 "for domain %s Error was %s\n",
2144 domain->name, nt_errstr(result) ));
2145 goto done;
2148 open_domain:
2149 result = rpccli_samr_OpenDomain(conn->samr_pipe,
2150 mem_ctx,
2151 &conn->sam_connect_handle,
2152 SEC_FLAG_MAXIMUM_ALLOWED,
2153 &domain->sid,
2154 &conn->sam_domain_handle);
2156 done:
2158 if (!NT_STATUS_IS_OK(result)) {
2159 invalidate_cm_connection(conn);
2160 return result;
2163 *cli = conn->samr_pipe;
2164 *sam_handle = conn->sam_domain_handle;
2165 SAFE_FREE(machine_password);
2166 SAFE_FREE(machine_account);
2167 return result;
2170 NTSTATUS cm_connect_lsa(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2171 struct rpc_pipe_client **cli, struct policy_handle *lsa_policy)
2173 struct winbindd_cm_conn *conn;
2174 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2175 struct netlogon_creds_CredentialState *p_creds;
2177 result = init_dc_connection(domain);
2178 if (!NT_STATUS_IS_OK(result))
2179 return result;
2181 conn = &domain->conn;
2183 if (conn->lsa_pipe != NULL) {
2184 goto done;
2187 if ((conn->cli->user_name[0] == '\0') ||
2188 (conn->cli->domain[0] == '\0') ||
2189 (conn->cli->password == NULL || conn->cli->password[0] == '\0')) {
2190 DEBUG(10, ("cm_connect_lsa: No no user available for "
2191 "domain %s, trying schannel\n", conn->cli->domain));
2192 goto schannel;
2195 /* We have an authenticated connection. Use a NTLMSSP SPNEGO
2196 * authenticated LSA pipe with sign & seal. */
2197 result = cli_rpc_pipe_open_spnego_ntlmssp
2198 (conn->cli, &ndr_table_lsarpc.syntax_id, NCACN_NP,
2199 DCERPC_AUTH_LEVEL_PRIVACY,
2200 conn->cli->domain, conn->cli->user_name, conn->cli->password,
2201 &conn->lsa_pipe);
2203 if (!NT_STATUS_IS_OK(result)) {
2204 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
2205 "domain %s using NTLMSSP authenticated pipe: user "
2206 "%s\\%s. Error was %s. Trying schannel.\n",
2207 domain->name, conn->cli->domain,
2208 conn->cli->user_name, nt_errstr(result)));
2209 goto schannel;
2212 DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
2213 "NTLMSSP authenticated pipe: user %s\\%s\n",
2214 domain->name, conn->cli->domain, conn->cli->user_name ));
2216 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2217 SEC_FLAG_MAXIMUM_ALLOWED,
2218 &conn->lsa_policy);
2219 if (NT_STATUS_IS_OK(result)) {
2220 goto done;
2223 DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
2224 "schannel\n"));
2226 TALLOC_FREE(conn->lsa_pipe);
2228 schannel:
2230 /* Fall back to schannel if it's a W2K pre-SP1 box. */
2232 if (!cm_get_schannel_creds(domain, &p_creds)) {
2233 /* If this call fails - conn->cli can now be NULL ! */
2234 DEBUG(10, ("cm_connect_lsa: Could not get schannel auth info "
2235 "for domain %s, trying anon\n", domain->name));
2236 goto anonymous;
2238 result = cli_rpc_pipe_open_schannel_with_key
2239 (conn->cli, &ndr_table_lsarpc.syntax_id, NCACN_NP,
2240 DCERPC_AUTH_LEVEL_PRIVACY,
2241 domain->name, &p_creds, &conn->lsa_pipe);
2243 if (!NT_STATUS_IS_OK(result)) {
2244 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
2245 "domain %s using schannel. Error was %s\n",
2246 domain->name, nt_errstr(result) ));
2247 goto anonymous;
2249 DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
2250 "schannel.\n", domain->name ));
2252 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2253 SEC_FLAG_MAXIMUM_ALLOWED,
2254 &conn->lsa_policy);
2255 if (NT_STATUS_IS_OK(result)) {
2256 goto done;
2259 DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
2260 "anonymous\n"));
2262 TALLOC_FREE(conn->lsa_pipe);
2264 anonymous:
2266 result = cli_rpc_pipe_open_noauth(conn->cli,
2267 &ndr_table_lsarpc.syntax_id,
2268 &conn->lsa_pipe);
2269 if (!NT_STATUS_IS_OK(result)) {
2270 result = NT_STATUS_PIPE_NOT_AVAILABLE;
2271 goto done;
2274 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2275 SEC_FLAG_MAXIMUM_ALLOWED,
2276 &conn->lsa_policy);
2277 done:
2278 if (!NT_STATUS_IS_OK(result)) {
2279 invalidate_cm_connection(conn);
2280 return result;
2283 *cli = conn->lsa_pipe;
2284 *lsa_policy = conn->lsa_policy;
2285 return result;
2288 /****************************************************************************
2289 Open the netlogon pipe to this DC. Use schannel if specified in client conf.
2290 session key stored in conn->netlogon_pipe->dc->sess_key.
2291 ****************************************************************************/
2293 NTSTATUS cm_connect_netlogon(struct winbindd_domain *domain,
2294 struct rpc_pipe_client **cli)
2296 struct winbindd_cm_conn *conn;
2297 NTSTATUS result;
2299 uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS;
2300 uint8 mach_pwd[16];
2301 uint32 sec_chan_type;
2302 const char *account_name;
2303 struct rpc_pipe_client *netlogon_pipe = NULL;
2305 *cli = NULL;
2307 result = init_dc_connection(domain);
2308 if (!NT_STATUS_IS_OK(result)) {
2309 return result;
2312 conn = &domain->conn;
2314 if (conn->netlogon_pipe != NULL) {
2315 *cli = conn->netlogon_pipe;
2316 return NT_STATUS_OK;
2319 result = cli_rpc_pipe_open_noauth(conn->cli,
2320 &ndr_table_netlogon.syntax_id,
2321 &netlogon_pipe);
2322 if (!NT_STATUS_IS_OK(result)) {
2323 return result;
2326 if ((!IS_DC) && (!domain->primary)) {
2327 /* Clear the schannel request bit and drop down */
2328 neg_flags &= ~NETLOGON_NEG_SCHANNEL;
2329 goto no_schannel;
2332 if (lp_client_schannel() != False) {
2333 neg_flags |= NETLOGON_NEG_SCHANNEL;
2336 if (!get_trust_pw_hash(domain->name, mach_pwd, &account_name,
2337 &sec_chan_type))
2339 TALLOC_FREE(netlogon_pipe);
2340 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2343 result = rpccli_netlogon_setup_creds(
2344 netlogon_pipe,
2345 domain->dcname, /* server name. */
2346 domain->name, /* domain name */
2347 global_myname(), /* client name */
2348 account_name, /* machine account */
2349 mach_pwd, /* machine password */
2350 sec_chan_type, /* from get_trust_pw */
2351 &neg_flags);
2353 if (!NT_STATUS_IS_OK(result)) {
2354 TALLOC_FREE(netlogon_pipe);
2355 return result;
2358 if ((lp_client_schannel() == True) &&
2359 ((neg_flags & NETLOGON_NEG_SCHANNEL) == 0)) {
2360 DEBUG(3, ("Server did not offer schannel\n"));
2361 TALLOC_FREE(netlogon_pipe);
2362 return NT_STATUS_ACCESS_DENIED;
2365 no_schannel:
2366 if ((lp_client_schannel() == False) ||
2367 ((neg_flags & NETLOGON_NEG_SCHANNEL) == 0)) {
2369 * NetSamLogonEx only works for schannel
2371 domain->can_do_samlogon_ex = False;
2373 /* We're done - just keep the existing connection to NETLOGON
2374 * open */
2375 conn->netlogon_pipe = netlogon_pipe;
2376 *cli = conn->netlogon_pipe;
2377 return NT_STATUS_OK;
2380 /* Using the credentials from the first pipe, open a signed and sealed
2381 second netlogon pipe. The session key is stored in the schannel
2382 part of the new pipe auth struct.
2385 result = cli_rpc_pipe_open_schannel_with_key(
2386 conn->cli, &ndr_table_netlogon.syntax_id, NCACN_NP,
2387 DCERPC_AUTH_LEVEL_PRIVACY, domain->name, &netlogon_pipe->dc,
2388 &conn->netlogon_pipe);
2390 /* We can now close the initial netlogon pipe. */
2391 TALLOC_FREE(netlogon_pipe);
2393 if (!NT_STATUS_IS_OK(result)) {
2394 DEBUG(3, ("Could not open schannel'ed NETLOGON pipe. Error "
2395 "was %s\n", nt_errstr(result)));
2397 /* make sure we return something besides OK */
2398 return !NT_STATUS_IS_OK(result) ? result : NT_STATUS_PIPE_NOT_AVAILABLE;
2402 * Try NetSamLogonEx for AD domains
2404 domain->can_do_samlogon_ex = domain->active_directory;
2406 *cli = conn->netlogon_pipe;
2407 return NT_STATUS_OK;