s3:winbindd: add more debugging to cm_prepare_connection()
[Samba.git] / source3 / winbindd / winbindd_cm.c
blobf8e4607a8456cf10fe79459fbd68dedea9829d77
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/ndr_netlogon_c.h"
65 #include "rpc_client/cli_pipe.h"
66 #include "rpc_client/cli_netlogon.h"
67 #include "../librpc/gen_ndr/ndr_samr_c.h"
68 #include "../librpc/gen_ndr/ndr_lsa_c.h"
69 #include "rpc_client/cli_lsarpc.h"
70 #include "../librpc/gen_ndr/ndr_dssetup_c.h"
71 #include "libads/sitename_cache.h"
72 #include "libsmb/libsmb.h"
73 #include "libsmb/clidgram.h"
74 #include "ads.h"
75 #include "secrets.h"
76 #include "../libcli/security/security.h"
77 #include "passdb.h"
78 #include "messages.h"
79 #include "auth/gensec/gensec.h"
80 #include "../libcli/smb/smbXcli_base.h"
81 #include "libcli/auth/netlogon_creds_cli.h"
82 #include "auth.h"
83 #include "rpc_server/rpc_ncacn_np.h"
84 #include "auth/credentials/credentials.h"
85 #include "lib/param/param.h"
87 #undef DBGC_CLASS
88 #define DBGC_CLASS DBGC_WINBIND
90 struct dc_name_ip {
91 fstring name;
92 struct sockaddr_storage ss;
95 extern struct winbindd_methods reconnect_methods;
96 extern bool override_logfile;
98 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain, bool need_rw_dc);
99 static void set_dc_type_and_flags( struct winbindd_domain *domain );
100 static bool set_dc_type_and_flags_trustinfo( struct winbindd_domain *domain );
101 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
102 struct dc_name_ip **dcs, int *num_dcs);
104 /****************************************************************
105 Child failed to find DC's. Reschedule check.
106 ****************************************************************/
108 static void msg_failed_to_go_online(struct messaging_context *msg,
109 void *private_data,
110 uint32_t msg_type,
111 struct server_id server_id,
112 DATA_BLOB *data)
114 struct winbindd_domain *domain;
115 const char *domainname = (const char *)data->data;
117 if (data->data == NULL || data->length == 0) {
118 return;
121 DEBUG(5,("msg_fail_to_go_online: received for domain %s.\n", domainname));
123 for (domain = domain_list(); domain; domain = domain->next) {
124 if (domain->internal) {
125 continue;
128 if (strequal(domain->name, domainname)) {
129 if (domain->online) {
130 /* We're already online, ignore. */
131 DEBUG(5,("msg_fail_to_go_online: domain %s "
132 "already online.\n", domainname));
133 continue;
136 /* Reschedule the online check. */
137 set_domain_offline(domain);
138 break;
143 /****************************************************************
144 Actually cause a reconnect from a message.
145 ****************************************************************/
147 static void msg_try_to_go_online(struct messaging_context *msg,
148 void *private_data,
149 uint32_t msg_type,
150 struct server_id server_id,
151 DATA_BLOB *data)
153 struct winbindd_domain *domain;
154 const char *domainname = (const char *)data->data;
156 if (data->data == NULL || data->length == 0) {
157 return;
160 DEBUG(5,("msg_try_to_go_online: received for domain %s.\n", domainname));
162 for (domain = domain_list(); domain; domain = domain->next) {
163 if (domain->internal) {
164 continue;
167 if (strequal(domain->name, domainname)) {
169 if (domain->online) {
170 /* We're already online, ignore. */
171 DEBUG(5,("msg_try_to_go_online: domain %s "
172 "already online.\n", domainname));
173 continue;
176 /* This call takes care of setting the online
177 flag to true if we connected, or re-adding
178 the offline handler if false. Bypasses online
179 check so always does network calls. */
181 init_dc_connection_network(domain, true);
182 break;
187 /****************************************************************
188 Fork a child to try and contact a DC. Do this as contacting a
189 DC requires blocking lookups and we don't want to block our
190 parent.
191 ****************************************************************/
193 static bool fork_child_dc_connect(struct winbindd_domain *domain)
195 struct dc_name_ip *dcs = NULL;
196 int num_dcs = 0;
197 TALLOC_CTX *mem_ctx = NULL;
198 pid_t parent_pid = getpid();
199 char *lfile = NULL;
200 NTSTATUS status;
202 if (domain->dc_probe_pid != (pid_t)-1) {
204 * We might already have a DC probe
205 * child working, check.
207 if (process_exists_by_pid(domain->dc_probe_pid)) {
208 DEBUG(10,("fork_child_dc_connect: pid %u already "
209 "checking for DC's.\n",
210 (unsigned int)domain->dc_probe_pid));
211 return true;
213 domain->dc_probe_pid = (pid_t)-1;
216 domain->dc_probe_pid = fork();
218 if (domain->dc_probe_pid == (pid_t)-1) {
219 DEBUG(0, ("fork_child_dc_connect: Could not fork: %s\n", strerror(errno)));
220 return False;
223 if (domain->dc_probe_pid != (pid_t)0) {
224 /* Parent */
225 messaging_register(winbind_messaging_context(), NULL,
226 MSG_WINBIND_TRY_TO_GO_ONLINE,
227 msg_try_to_go_online);
228 messaging_register(winbind_messaging_context(), NULL,
229 MSG_WINBIND_FAILED_TO_GO_ONLINE,
230 msg_failed_to_go_online);
231 return True;
234 /* Child. */
236 /* Leave messages blocked - we will never process one. */
238 if (!override_logfile) {
239 if (asprintf(&lfile, "%s/log.winbindd-dc-connect", get_dyn_LOGFILEBASE()) == -1) {
240 DEBUG(0, ("fork_child_dc_connect: out of memory.\n"));
241 _exit(1);
245 status = winbindd_reinit_after_fork(NULL, lfile);
246 if (!NT_STATUS_IS_OK(status)) {
247 DEBUG(1, ("winbindd_reinit_after_fork failed: %s\n",
248 nt_errstr(status)));
249 messaging_send_buf(winbind_messaging_context(),
250 pid_to_procid(parent_pid),
251 MSG_WINBIND_FAILED_TO_GO_ONLINE,
252 (const uint8_t *)domain->name,
253 strlen(domain->name)+1);
254 _exit(1);
256 SAFE_FREE(lfile);
258 mem_ctx = talloc_init("fork_child_dc_connect");
259 if (!mem_ctx) {
260 DEBUG(0,("talloc_init failed.\n"));
261 messaging_send_buf(winbind_messaging_context(),
262 pid_to_procid(parent_pid),
263 MSG_WINBIND_FAILED_TO_GO_ONLINE,
264 (const uint8_t *)domain->name,
265 strlen(domain->name)+1);
266 _exit(1);
269 if ((!get_dcs(mem_ctx, domain, &dcs, &num_dcs)) || (num_dcs == 0)) {
270 /* Still offline ? Can't find DC's. */
271 messaging_send_buf(winbind_messaging_context(),
272 pid_to_procid(parent_pid),
273 MSG_WINBIND_FAILED_TO_GO_ONLINE,
274 (const uint8_t *)domain->name,
275 strlen(domain->name)+1);
276 _exit(0);
279 /* We got a DC. Send a message to our parent to get it to
280 try and do the same. */
282 messaging_send_buf(winbind_messaging_context(),
283 pid_to_procid(parent_pid),
284 MSG_WINBIND_TRY_TO_GO_ONLINE,
285 (const uint8_t *)domain->name,
286 strlen(domain->name)+1);
287 _exit(0);
290 /****************************************************************
291 Handler triggered if we're offline to try and detect a DC.
292 ****************************************************************/
294 static void check_domain_online_handler(struct tevent_context *ctx,
295 struct tevent_timer *te,
296 struct timeval now,
297 void *private_data)
299 struct winbindd_domain *domain =
300 (struct winbindd_domain *)private_data;
302 DEBUG(10,("check_domain_online_handler: called for domain "
303 "%s (online = %s)\n", domain->name,
304 domain->online ? "True" : "False" ));
306 TALLOC_FREE(domain->check_online_event);
308 /* Are we still in "startup" mode ? */
310 if (domain->startup && (time_mono(NULL) > domain->startup_time + 30)) {
311 /* No longer in "startup" mode. */
312 DEBUG(10,("check_domain_online_handler: domain %s no longer in 'startup' mode.\n",
313 domain->name ));
314 domain->startup = False;
317 /* We've been told to stay offline, so stay
318 that way. */
320 if (get_global_winbindd_state_offline()) {
321 DEBUG(10,("check_domain_online_handler: domain %s remaining globally offline\n",
322 domain->name ));
323 return;
326 /* Fork a child to test if it can contact a DC.
327 If it can then send ourselves a message to
328 cause a reconnect. */
330 fork_child_dc_connect(domain);
333 /****************************************************************
334 If we're still offline setup the timeout check.
335 ****************************************************************/
337 static void calc_new_online_timeout_check(struct winbindd_domain *domain)
339 int wbr = lp_winbind_reconnect_delay();
341 if (domain->startup) {
342 domain->check_online_timeout = 10;
343 } else if (domain->check_online_timeout < wbr) {
344 domain->check_online_timeout = wbr;
348 void winbind_msg_domain_offline(struct messaging_context *msg_ctx,
349 void *private_data,
350 uint32_t msg_type,
351 struct server_id server_id,
352 DATA_BLOB *data)
354 const char *domain_name = (const char *)data->data;
355 struct winbindd_domain *domain;
357 domain = find_domain_from_name_noinit(domain_name);
358 if (domain == NULL) {
359 return;
362 domain->online = false;
364 DEBUG(10, ("Domain %s is marked as offline now.\n",
365 domain_name));
368 void winbind_msg_domain_online(struct messaging_context *msg_ctx,
369 void *private_data,
370 uint32_t msg_type,
371 struct server_id server_id,
372 DATA_BLOB *data)
374 const char *domain_name = (const char *)data->data;
375 struct winbindd_domain *domain;
377 domain = find_domain_from_name_noinit(domain_name);
378 if (domain == NULL) {
379 return;
382 domain->online = true;
384 DEBUG(10, ("Domain %s is marked as online now.\n",
385 domain_name));
388 /****************************************************************
389 Set domain offline and also add handler to put us back online
390 if we detect a DC.
391 ****************************************************************/
393 void set_domain_offline(struct winbindd_domain *domain)
395 pid_t parent_pid = getppid();
397 DEBUG(10,("set_domain_offline: called for domain %s\n",
398 domain->name ));
400 TALLOC_FREE(domain->check_online_event);
402 if (domain->internal) {
403 DEBUG(3,("set_domain_offline: domain %s is internal - logic error.\n",
404 domain->name ));
405 return;
408 domain->online = False;
410 /* Offline domains are always initialized. They're
411 re-initialized when they go back online. */
413 domain->initialized = True;
415 /* We only add the timeout handler that checks and
416 allows us to go back online when we've not
417 been told to remain offline. */
419 if (get_global_winbindd_state_offline()) {
420 DEBUG(10,("set_domain_offline: domain %s remaining globally offline\n",
421 domain->name ));
422 return;
425 /* If we're in startup mode, check again in 10 seconds, not in
426 lp_winbind_reconnect_delay() seconds (which is 30 seconds by default). */
428 calc_new_online_timeout_check(domain);
430 domain->check_online_event = tevent_add_timer(winbind_event_context(),
431 NULL,
432 timeval_current_ofs(domain->check_online_timeout,0),
433 check_domain_online_handler,
434 domain);
436 /* The above *has* to succeed for winbindd to work. */
437 if (!domain->check_online_event) {
438 smb_panic("set_domain_offline: failed to add online handler");
441 DEBUG(10,("set_domain_offline: added event handler for domain %s\n",
442 domain->name ));
444 /* Send a message to the parent that the domain is offline. */
445 if (parent_pid > 1 && !domain->internal) {
446 messaging_send_buf(winbind_messaging_context(),
447 pid_to_procid(parent_pid),
448 MSG_WINBIND_DOMAIN_OFFLINE,
449 (uint8_t *)domain->name,
450 strlen(domain->name) + 1);
453 /* Send an offline message to the idmap child when our
454 primary domain goes offline */
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_OFFLINE,
463 (const uint8_t *)domain->name,
464 strlen(domain->name)+1);
468 return;
471 /****************************************************************
472 Set domain online - if allowed.
473 ****************************************************************/
475 static void set_domain_online(struct winbindd_domain *domain)
477 pid_t parent_pid = getppid();
479 DEBUG(10,("set_domain_online: called for domain %s\n",
480 domain->name ));
482 if (domain->internal) {
483 DEBUG(3,("set_domain_online: domain %s is internal - logic error.\n",
484 domain->name ));
485 return;
488 if (get_global_winbindd_state_offline()) {
489 DEBUG(10,("set_domain_online: domain %s remaining globally offline\n",
490 domain->name ));
491 return;
494 winbindd_set_locator_kdc_envs(domain);
496 /* If we are waiting to get a krb5 ticket, trigger immediately. */
497 ccache_regain_all_now();
499 /* Ok, we're out of any startup mode now... */
500 domain->startup = False;
502 if (domain->online == False) {
503 /* We were offline - now we're online. We default to
504 using the MS-RPC backend if we started offline,
505 and if we're going online for the first time we
506 should really re-initialize the backends and the
507 checks to see if we're talking to an AD or NT domain.
510 domain->initialized = False;
512 /* 'reconnect_methods' is the MS-RPC backend. */
513 if (domain->backend == &reconnect_methods) {
514 domain->backend = NULL;
518 /* Ensure we have no online timeout checks. */
519 domain->check_online_timeout = 0;
520 TALLOC_FREE(domain->check_online_event);
522 /* Ensure we ignore any pending child messages. */
523 messaging_deregister(winbind_messaging_context(),
524 MSG_WINBIND_TRY_TO_GO_ONLINE, NULL);
525 messaging_deregister(winbind_messaging_context(),
526 MSG_WINBIND_FAILED_TO_GO_ONLINE, NULL);
528 domain->online = True;
530 /* Send a message to the parent that the domain is online. */
531 if (parent_pid > 1 && !domain->internal) {
532 messaging_send_buf(winbind_messaging_context(),
533 pid_to_procid(parent_pid),
534 MSG_WINBIND_DOMAIN_ONLINE,
535 (uint8_t *)domain->name,
536 strlen(domain->name) + 1);
539 /* Send an online message to the idmap child when our
540 primary domain comes online */
542 if ( domain->primary ) {
543 struct winbindd_child *idmap = idmap_child();
545 if ( idmap->pid != 0 ) {
546 messaging_send_buf(winbind_messaging_context(),
547 pid_to_procid(idmap->pid),
548 MSG_WINBIND_ONLINE,
549 (const uint8_t *)domain->name,
550 strlen(domain->name)+1);
554 return;
557 /****************************************************************
558 Requested to set a domain online.
559 ****************************************************************/
561 void set_domain_online_request(struct winbindd_domain *domain)
563 struct timeval tev;
565 DEBUG(10,("set_domain_online_request: called for domain %s\n",
566 domain->name ));
568 if (get_global_winbindd_state_offline()) {
569 DEBUG(10,("set_domain_online_request: domain %s remaining globally offline\n",
570 domain->name ));
571 return;
574 if (domain->internal) {
575 DEBUG(10, ("set_domain_online_request: Internal domains are "
576 "always online\n"));
577 return;
580 /* We've been told it's safe to go online and
581 try and connect to a DC. But I don't believe it
582 because network manager seems to lie.
583 Wait at least 5 seconds. Heuristics suck... */
586 GetTimeOfDay(&tev);
588 /* Go into "startup" mode again. */
589 domain->startup_time = time_mono(NULL);
590 domain->startup = True;
592 tev.tv_sec += 5;
594 if (!domain->check_online_event) {
595 /* If we've come from being globally offline we
596 don't have a check online event handler set.
597 We need to add one now we're trying to go
598 back online. */
600 DEBUG(10,("set_domain_online_request: domain %s was globally offline.\n",
601 domain->name ));
604 TALLOC_FREE(domain->check_online_event);
606 domain->check_online_event = tevent_add_timer(winbind_event_context(),
607 NULL,
608 tev,
609 check_domain_online_handler,
610 domain);
612 /* The above *has* to succeed for winbindd to work. */
613 if (!domain->check_online_event) {
614 smb_panic("set_domain_online_request: failed to add online handler");
618 /****************************************************************
619 Add -ve connection cache entries for domain and realm.
620 ****************************************************************/
622 static void winbind_add_failed_connection_entry(
623 const struct winbindd_domain *domain,
624 const char *server,
625 NTSTATUS result)
627 add_failed_connection_entry(domain->name, server, result);
628 /* If this was the saf name for the last thing we talked to,
629 remove it. */
630 saf_delete(domain->name);
631 if (domain->alt_name != NULL) {
632 add_failed_connection_entry(domain->alt_name, server, result);
633 saf_delete(domain->alt_name);
635 winbindd_unset_locator_kdc_env(domain);
638 /* Choose between anonymous or authenticated connections. We need to use
639 an authenticated connection if DCs have the RestrictAnonymous registry
640 entry set > 0, or the "Additional restrictions for anonymous
641 connections" set in the win2k Local Security Policy.
643 Caller to free() result in domain, username, password
646 static void cm_get_ipc_userpass(char **username, char **domain, char **password)
648 *username = (char *)secrets_fetch(SECRETS_AUTH_USER, NULL);
649 *domain = (char *)secrets_fetch(SECRETS_AUTH_DOMAIN, NULL);
650 *password = (char *)secrets_fetch(SECRETS_AUTH_PASSWORD, NULL);
652 if (*username && **username) {
654 if (!*domain || !**domain)
655 *domain = smb_xstrdup(lp_workgroup());
657 if (!*password || !**password)
658 *password = smb_xstrdup("");
660 DEBUG(3, ("cm_get_ipc_userpass: Retrieved auth-user from secrets.tdb [%s\\%s]\n",
661 *domain, *username));
663 } else {
664 DEBUG(3, ("cm_get_ipc_userpass: No auth-user defined\n"));
665 *username = smb_xstrdup("");
666 *domain = smb_xstrdup("");
667 *password = smb_xstrdup("");
671 static NTSTATUS cm_get_ipc_credentials(TALLOC_CTX *mem_ctx,
672 struct cli_credentials **_creds)
675 TALLOC_CTX *frame = talloc_stackframe();
676 NTSTATUS status = NT_STATUS_INTERNAL_ERROR;
677 struct loadparm_context *lp_ctx;
678 char *username = NULL;
679 char *netbios_domain = NULL;
680 char *password = NULL;
681 struct cli_credentials *creds = NULL;
682 bool ok;
684 cm_get_ipc_userpass(&username, &netbios_domain, &password);
686 lp_ctx = loadparm_init_s3(frame, loadparm_s3_helpers());
687 if (lp_ctx == NULL) {
688 DEBUG(1, ("loadparm_init_s3 failed\n"));
689 status = NT_STATUS_INTERNAL_ERROR;
690 goto fail;
693 creds = cli_credentials_init(mem_ctx);
694 if (creds == NULL) {
695 status = NT_STATUS_NO_MEMORY;
696 goto fail;
699 cli_credentials_set_conf(creds, lp_ctx);
700 cli_credentials_set_kerberos_state(creds, CRED_DONT_USE_KERBEROS);
702 ok = cli_credentials_set_domain(creds, netbios_domain, CRED_SPECIFIED);
703 if (!ok) {
704 status = NT_STATUS_NO_MEMORY;
705 goto fail;
708 ok = cli_credentials_set_username(creds, username, CRED_SPECIFIED);
709 if (!ok) {
710 status = NT_STATUS_NO_MEMORY;
711 goto fail;
714 ok = cli_credentials_set_password(creds, password, CRED_SPECIFIED);
715 if (!ok) {
716 status = NT_STATUS_NO_MEMORY;
717 goto fail;
720 *_creds = creds;
721 creds = NULL;
722 status = NT_STATUS_OK;
723 fail:
724 TALLOC_FREE(creds);
725 SAFE_FREE(username);
726 SAFE_FREE(netbios_domain);
727 SAFE_FREE(password);
728 TALLOC_FREE(frame);
729 return status;
732 static bool cm_is_ipc_credentials(struct cli_credentials *creds)
734 TALLOC_CTX *frame = talloc_stackframe();
735 char *ipc_account = NULL;
736 char *ipc_domain = NULL;
737 char *ipc_password = NULL;
738 const char *creds_account = NULL;
739 const char *creds_domain = NULL;
740 const char *creds_password = NULL;
741 bool ret = false;
743 cm_get_ipc_userpass(&ipc_account, &ipc_domain, &ipc_password);
745 creds_account = cli_credentials_get_username(creds);
746 creds_domain = cli_credentials_get_domain(creds);
747 creds_password = cli_credentials_get_password(creds);
749 if (!strequal(ipc_domain, creds_domain)) {
750 goto done;
753 if (!strequal(ipc_account, creds_account)) {
754 goto done;
757 if (!strcsequal(ipc_password, creds_password)) {
758 goto done;
761 ret = true;
762 done:
763 SAFE_FREE(ipc_account);
764 SAFE_FREE(ipc_domain);
765 SAFE_FREE(ipc_password);
766 TALLOC_FREE(frame);
767 return ret;
770 static bool get_dc_name_via_netlogon(struct winbindd_domain *domain,
771 fstring dcname,
772 struct sockaddr_storage *dc_ss)
774 struct winbindd_domain *our_domain = NULL;
775 struct rpc_pipe_client *netlogon_pipe = NULL;
776 NTSTATUS result;
777 WERROR werr;
778 TALLOC_CTX *mem_ctx;
779 unsigned int orig_timeout;
780 const char *tmp = NULL;
781 const char *p;
782 struct dcerpc_binding_handle *b;
784 /* Hmmmm. We can only open one connection to the NETLOGON pipe at the
785 * moment.... */
787 if (IS_DC) {
788 return False;
791 if (domain->primary) {
792 return False;
795 our_domain = find_our_domain();
797 if ((mem_ctx = talloc_init("get_dc_name_via_netlogon")) == NULL) {
798 return False;
801 result = cm_connect_netlogon(our_domain, &netlogon_pipe);
802 if (!NT_STATUS_IS_OK(result)) {
803 talloc_destroy(mem_ctx);
804 return False;
807 b = netlogon_pipe->binding_handle;
809 /* This call can take a long time - allow the server to time out.
810 35 seconds should do it. */
812 orig_timeout = rpccli_set_timeout(netlogon_pipe, 35000);
814 if (our_domain->active_directory) {
815 struct netr_DsRGetDCNameInfo *domain_info = NULL;
817 result = dcerpc_netr_DsRGetDCName(b,
818 mem_ctx,
819 our_domain->dcname,
820 domain->name,
821 NULL,
822 NULL,
823 DS_RETURN_DNS_NAME,
824 &domain_info,
825 &werr);
826 if (NT_STATUS_IS_OK(result) && W_ERROR_IS_OK(werr)) {
827 tmp = talloc_strdup(
828 mem_ctx, domain_info->dc_unc);
829 if (tmp == NULL) {
830 DEBUG(0, ("talloc_strdup failed\n"));
831 talloc_destroy(mem_ctx);
832 return false;
834 if (domain->alt_name == NULL) {
835 domain->alt_name = talloc_strdup(domain,
836 domain_info->domain_name);
837 if (domain->alt_name == NULL) {
838 DEBUG(0, ("talloc_strdup failed\n"));
839 talloc_destroy(mem_ctx);
840 return false;
843 if (domain->forest_name == NULL) {
844 domain->forest_name = talloc_strdup(domain,
845 domain_info->forest_name);
846 if (domain->forest_name == NULL) {
847 DEBUG(0, ("talloc_strdup failed\n"));
848 talloc_destroy(mem_ctx);
849 return false;
853 } else {
854 result = dcerpc_netr_GetAnyDCName(b, mem_ctx,
855 our_domain->dcname,
856 domain->name,
857 &tmp,
858 &werr);
861 /* And restore our original timeout. */
862 rpccli_set_timeout(netlogon_pipe, orig_timeout);
864 if (!NT_STATUS_IS_OK(result)) {
865 DEBUG(10,("dcerpc_netr_GetAnyDCName failed: %s\n",
866 nt_errstr(result)));
867 talloc_destroy(mem_ctx);
868 return false;
871 if (!W_ERROR_IS_OK(werr)) {
872 DEBUG(10,("dcerpc_netr_GetAnyDCName failed: %s\n",
873 win_errstr(werr)));
874 talloc_destroy(mem_ctx);
875 return false;
878 /* dcerpc_netr_GetAnyDCName gives us a name with \\ */
879 p = strip_hostname(tmp);
881 fstrcpy(dcname, p);
883 talloc_destroy(mem_ctx);
885 DEBUG(10,("dcerpc_netr_GetAnyDCName returned %s\n", dcname));
887 if (!resolve_name(dcname, dc_ss, 0x20, true)) {
888 return False;
891 return True;
895 * Helper function to assemble trust password and account name
897 static NTSTATUS get_trust_credentials(struct winbindd_domain *domain,
898 TALLOC_CTX *mem_ctx,
899 bool netlogon,
900 struct cli_credentials **_creds)
902 const struct winbindd_domain *creds_domain = NULL;
903 struct cli_credentials *creds;
904 NTSTATUS status;
905 bool force_machine_account = false;
907 /* If we are a DC and this is not our own domain */
909 if (!domain->active_directory) {
910 if (!netlogon) {
912 * For non active directory domains
913 * we can only use NTLMSSP for SMB.
915 * But the trust account is not allowed
916 * to use SMB with NTLMSSP.
918 force_machine_account = true;
922 if (IS_DC && !force_machine_account) {
923 creds_domain = domain;
924 } else {
925 creds_domain = find_our_domain();
926 if (creds_domain == NULL) {
927 return NT_STATUS_INVALID_SERVER_STATE;
931 status = pdb_get_trust_credentials(creds_domain->name,
932 creds_domain->alt_name,
933 mem_ctx,
934 &creds);
935 if (!NT_STATUS_IS_OK(status)) {
936 goto ipc_fallback;
939 if (domain->primary && lp_security() == SEC_ADS) {
940 cli_credentials_set_kerberos_state(creds,
941 CRED_AUTO_USE_KERBEROS);
942 } else if (domain->active_directory) {
943 cli_credentials_set_kerberos_state(creds,
944 CRED_MUST_USE_KERBEROS);
945 } else {
946 cli_credentials_set_kerberos_state(creds,
947 CRED_DONT_USE_KERBEROS);
950 if (creds_domain != domain) {
952 * We can only use schannel against a direct trust
954 cli_credentials_set_secure_channel_type(creds,
955 SEC_CHAN_NULL);
958 *_creds = creds;
959 return NT_STATUS_OK;
961 ipc_fallback:
962 if (netlogon) {
963 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
966 status = cm_get_ipc_credentials(mem_ctx, &creds);
967 if (!NT_STATUS_IS_OK(status)) {
968 return status;
971 *_creds = creds;
972 return NT_STATUS_OK;
975 /************************************************************************
976 Given a fd with a just-connected TCP connection to a DC, open a connection
977 to the pipe.
978 ************************************************************************/
980 static NTSTATUS cm_prepare_connection(struct winbindd_domain *domain,
981 const int sockfd,
982 const char *controller,
983 struct cli_state **cli,
984 bool *retry)
986 bool try_ipc_auth = false;
987 const char *machine_password = NULL;
988 const char *machine_krb5_principal = NULL;
989 const char *machine_account = NULL;
990 const char *machine_domain = NULL;
991 int flags = 0;
992 struct cli_credentials *creds = NULL;
993 enum credentials_use_kerberos krb5_state;
995 struct named_mutex *mutex;
997 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
998 NTSTATUS tmp_status;
999 NTSTATUS tcon_status = NT_STATUS_NETWORK_NAME_DELETED;
1001 enum smb_signing_setting smb_sign_client_connections = lp_client_ipc_signing();
1003 if (smb_sign_client_connections == SMB_SIGNING_DEFAULT) {
1005 * If we are connecting to our own AD domain, require
1006 * smb signing to disrupt MITM attacks
1008 if (domain->primary && lp_security() == SEC_ADS) {
1009 smb_sign_client_connections = SMB_SIGNING_REQUIRED;
1011 * If we are in or are an AD domain and connecting to another
1012 * AD domain in our forest
1013 * then require smb signing to disrupt MITM attacks
1015 } else if ((lp_security() == SEC_ADS ||
1016 lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC)
1017 && domain->active_directory
1018 && (domain->domain_trust_attribs
1019 & LSA_TRUST_ATTRIBUTE_WITHIN_FOREST)) {
1020 smb_sign_client_connections = SMB_SIGNING_REQUIRED;
1024 DEBUG(10,("cm_prepare_connection: connecting to DC %s for domain %s\n",
1025 controller, domain->name ));
1027 *retry = True;
1029 mutex = grab_named_mutex(talloc_tos(), controller,
1030 WINBIND_SERVER_MUTEX_WAIT_TIME);
1031 if (mutex == NULL) {
1032 close(sockfd);
1033 DEBUG(0,("cm_prepare_connection: mutex grab failed for %s\n",
1034 controller));
1035 result = NT_STATUS_POSSIBLE_DEADLOCK;
1036 goto done;
1039 flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
1041 *cli = cli_state_create(NULL, sockfd,
1042 controller, domain->alt_name,
1043 smb_sign_client_connections, flags);
1044 if (*cli == NULL) {
1045 close(sockfd);
1046 DEBUG(1, ("Could not cli_initialize\n"));
1047 result = NT_STATUS_NO_MEMORY;
1048 goto done;
1051 cli_set_timeout(*cli, 10000); /* 10 seconds */
1053 result = smbXcli_negprot((*cli)->conn, (*cli)->timeout,
1054 lp_client_ipc_min_protocol(),
1055 lp_client_ipc_max_protocol());
1057 if (!NT_STATUS_IS_OK(result)) {
1058 DEBUG(1, ("cli_negprot failed: %s\n", nt_errstr(result)));
1059 goto done;
1062 if (smbXcli_conn_protocol((*cli)->conn) >= PROTOCOL_NT1 &&
1063 smb1cli_conn_capabilities((*cli)->conn) & CAP_EXTENDED_SECURITY) {
1064 try_ipc_auth = true;
1065 } else if (smbXcli_conn_protocol((*cli)->conn) >= PROTOCOL_SMB2_02) {
1066 try_ipc_auth = true;
1067 } else if (smb_sign_client_connections == SMB_SIGNING_REQUIRED) {
1069 * If we are forcing on SMB signing, then we must
1070 * require authentication unless this is a one-way
1071 * trust, and we have no stored user/password
1073 try_ipc_auth = true;
1076 if (try_ipc_auth) {
1077 result = get_trust_credentials(domain, talloc_tos(), false, &creds);
1078 if (!NT_STATUS_IS_OK(result)) {
1079 DEBUG(1, ("get_trust_credentials(%s) failed: %s\n",
1080 domain->name, nt_errstr(result)));
1081 goto done;
1083 } else {
1085 * Without SPNEGO or NTLMSSP (perhaps via SMB2) we
1086 * would try and authentication with our machine
1087 * account password and fail. This is very rare in
1088 * the modern world however
1090 creds = cli_credentials_init_anon(talloc_tos());
1091 if (creds == NULL) {
1092 result = NT_STATUS_NO_MEMORY;
1093 DEBUG(1, ("cli_credentials_init_anon(%s) failed: %s\n",
1094 domain->name, nt_errstr(result)));
1095 goto done;
1099 if (cli_credentials_is_anonymous(creds)) {
1100 goto anon_fallback;
1103 krb5_state = cli_credentials_get_kerberos_state(creds);
1105 machine_krb5_principal = cli_credentials_get_principal(creds,
1106 talloc_tos());
1107 if (machine_krb5_principal == NULL) {
1108 krb5_state = CRED_DONT_USE_KERBEROS;
1111 machine_account = cli_credentials_get_username(creds);
1112 machine_password = cli_credentials_get_password(creds);
1113 machine_domain = cli_credentials_get_domain(creds);
1115 if (krb5_state != CRED_DONT_USE_KERBEROS) {
1117 /* Try a krb5 session */
1119 (*cli)->use_kerberos = True;
1120 DEBUG(5, ("connecting to %s from %s with kerberos principal "
1121 "[%s] and realm [%s]\n", controller, lp_netbios_name(),
1122 machine_krb5_principal, domain->alt_name));
1124 winbindd_set_locator_kdc_envs(domain);
1126 result = cli_session_setup(*cli,
1127 machine_krb5_principal,
1128 machine_password,
1129 strlen(machine_password)+1,
1130 machine_password,
1131 strlen(machine_password)+1,
1132 machine_domain);
1134 if (NT_STATUS_IS_OK(result)) {
1135 goto session_setup_done;
1138 DEBUG(1, ("Failed to use kerberos connecting to %s from %s "
1139 "with kerberos principal [%s]\n",
1140 controller, lp_netbios_name(),
1141 machine_krb5_principal));
1144 if (krb5_state != CRED_MUST_USE_KERBEROS) {
1145 /* Fall back to non-kerberos session setup using NTLMSSP SPNEGO with the machine account. */
1146 (*cli)->use_kerberos = False;
1148 DEBUG(5, ("connecting to %s from %s using NTLMSSP with username "
1149 "[%s]\\[%s]\n", controller, lp_netbios_name(),
1150 machine_domain, machine_account));
1152 result = cli_session_setup(*cli,
1153 machine_account,
1154 machine_password,
1155 strlen(machine_password)+1,
1156 machine_password,
1157 strlen(machine_password)+1,
1158 machine_domain);
1160 if (NT_STATUS_IS_OK(result)) {
1161 goto session_setup_done;
1164 DEBUG(1, ("Failed to use NTLMSSP connecting to %s from %s "
1165 "with username [%s]\\[%s]\n",
1166 controller, lp_netbios_name(),
1167 machine_domain, machine_account));
1171 * If we are not going to validiate the conneciton
1172 * with SMB signing, then allow us to fall back to
1173 * anonymous
1175 if (NT_STATUS_EQUAL(result, NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT)
1176 || NT_STATUS_EQUAL(result, NT_STATUS_TRUSTED_DOMAIN_FAILURE)
1177 || NT_STATUS_EQUAL(result, NT_STATUS_INVALID_ACCOUNT_NAME)
1178 || NT_STATUS_EQUAL(result, NT_STATUS_NO_LOGON_SERVERS)
1179 || NT_STATUS_EQUAL(result, NT_STATUS_LOGON_FAILURE))
1181 if (!cm_is_ipc_credentials(creds)) {
1182 goto ipc_fallback;
1185 if (smb_sign_client_connections == SMB_SIGNING_REQUIRED) {
1186 goto done;
1189 goto anon_fallback;
1192 DEBUG(1, ("authenticated session setup to %s using %s failed with %s\n",
1193 controller,
1194 cli_credentials_get_unparsed_name(creds, talloc_tos()),
1195 nt_errstr(result)));
1197 goto done;
1199 ipc_fallback:
1200 TALLOC_FREE(creds);
1201 tmp_status = cm_get_ipc_credentials(talloc_tos(), &creds);
1202 if (!NT_STATUS_IS_OK(tmp_status)) {
1203 result = tmp_status;
1204 goto done;
1207 if (cli_credentials_is_anonymous(creds)) {
1208 goto anon_fallback;
1211 machine_account = cli_credentials_get_username(creds);
1212 machine_password = cli_credentials_get_password(creds);
1213 machine_domain = cli_credentials_get_domain(creds);
1215 /* Fall back to non-kerberos session setup using NTLMSSP SPNEGO with the ipc creds. */
1216 (*cli)->use_kerberos = False;
1218 DEBUG(5, ("connecting to %s from %s using NTLMSSP with username "
1219 "[%s]\\[%s]\n", controller, lp_netbios_name(),
1220 machine_domain, machine_account));
1222 result = cli_session_setup(*cli,
1223 machine_account,
1224 machine_password,
1225 strlen(machine_password)+1,
1226 machine_password,
1227 strlen(machine_password)+1,
1228 machine_domain);
1230 if (NT_STATUS_IS_OK(result)) {
1231 goto session_setup_done;
1234 DEBUG(1, ("Failed to use NTLMSSP connecting to %s from %s "
1235 "with username "
1236 "[%s]\\[%s]\n", controller, lp_netbios_name(),
1237 machine_domain, machine_account));
1240 * If we are not going to validiate the conneciton
1241 * with SMB signing, then allow us to fall back to
1242 * anonymous
1244 if (NT_STATUS_EQUAL(result, NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT)
1245 || NT_STATUS_EQUAL(result, NT_STATUS_TRUSTED_DOMAIN_FAILURE)
1246 || NT_STATUS_EQUAL(result, NT_STATUS_INVALID_ACCOUNT_NAME)
1247 || NT_STATUS_EQUAL(result, NT_STATUS_NO_LOGON_SERVERS)
1248 || NT_STATUS_EQUAL(result, NT_STATUS_LOGON_FAILURE))
1250 goto anon_fallback;
1253 DEBUG(1, ("authenticated session setup to %s using %s failed with %s\n",
1254 controller,
1255 cli_credentials_get_unparsed_name(creds, talloc_tos()),
1256 nt_errstr(result)));
1258 goto done;
1260 anon_fallback:
1261 TALLOC_FREE(creds);
1263 if (smb_sign_client_connections == SMB_SIGNING_REQUIRED) {
1264 goto done;
1267 /* Fall back to anonymous connection, this might fail later */
1268 DEBUG(5,("cm_prepare_connection: falling back to anonymous "
1269 "connection for DC %s\n",
1270 controller ));
1272 (*cli)->use_kerberos = False;
1274 result = cli_session_setup(*cli, "", "", 0, "", 0, "");
1275 if (NT_STATUS_IS_OK(result)) {
1276 DEBUG(5, ("Connected anonymously\n"));
1277 goto session_setup_done;
1280 DEBUG(1, ("anonymous session setup to %s failed with %s\n",
1281 controller, nt_errstr(result)));
1283 /* We can't session setup */
1284 goto done;
1286 session_setup_done:
1289 * This should be a short term hack until
1290 * dynamic re-authentication is implemented.
1292 * See Bug 9175 - winbindd doesn't recover from
1293 * NT_STATUS_NETWORK_SESSION_EXPIRED
1295 if (smbXcli_conn_protocol((*cli)->conn) >= PROTOCOL_SMB2_02) {
1296 smbXcli_session_set_disconnect_expired((*cli)->smb2.session);
1299 result = cli_tree_connect(*cli, "IPC$", "IPC", "", 0);
1300 if (!NT_STATUS_IS_OK(result)) {
1301 DEBUG(1,("failed tcon_X with %s\n", nt_errstr(result)));
1302 goto done;
1304 tcon_status = result;
1306 /* cache the server name for later connections */
1308 saf_store(domain->name, controller);
1309 if (domain->alt_name && (*cli)->use_kerberos) {
1310 saf_store(domain->alt_name, controller);
1313 winbindd_set_locator_kdc_envs(domain);
1315 TALLOC_FREE(mutex);
1316 *retry = False;
1318 result = NT_STATUS_OK;
1320 done:
1321 TALLOC_FREE(mutex);
1323 if (NT_STATUS_IS_OK(result)) {
1324 result = tcon_status;
1327 if (!NT_STATUS_IS_OK(result)) {
1328 DEBUG(1, ("Failed to prepare SMB connection to %s: %s\n",
1329 controller, nt_errstr(result)));
1330 winbind_add_failed_connection_entry(domain, controller, result);
1331 if ((*cli) != NULL) {
1332 cli_shutdown(*cli);
1333 *cli = NULL;
1337 return result;
1340 /*******************************************************************
1341 Add a dcname and sockaddr_storage pair to the end of a dc_name_ip
1342 array.
1344 Keeps the list unique by not adding duplicate entries.
1346 @param[in] mem_ctx talloc memory context to allocate from
1347 @param[in] domain_name domain of the DC
1348 @param[in] dcname name of the DC to add to the list
1349 @param[in] pss Internet address and port pair to add to the list
1350 @param[in,out] dcs array of dc_name_ip structures to add to
1351 @param[in,out] num_dcs number of dcs returned in the dcs array
1352 @return true if the list was added to, false otherwise
1353 *******************************************************************/
1355 static bool add_one_dc_unique(TALLOC_CTX *mem_ctx, const char *domain_name,
1356 const char *dcname, struct sockaddr_storage *pss,
1357 struct dc_name_ip **dcs, int *num)
1359 int i = 0;
1361 if (!NT_STATUS_IS_OK(check_negative_conn_cache(domain_name, dcname))) {
1362 DEBUG(10, ("DC %s was in the negative conn cache\n", dcname));
1363 return False;
1366 /* Make sure there's no duplicates in the list */
1367 for (i=0; i<*num; i++)
1368 if (sockaddr_equal(
1369 (struct sockaddr *)(void *)&(*dcs)[i].ss,
1370 (struct sockaddr *)(void *)pss))
1371 return False;
1373 *dcs = talloc_realloc(mem_ctx, *dcs, struct dc_name_ip, (*num)+1);
1375 if (*dcs == NULL)
1376 return False;
1378 fstrcpy((*dcs)[*num].name, dcname);
1379 (*dcs)[*num].ss = *pss;
1380 *num += 1;
1381 return True;
1384 static bool add_sockaddr_to_array(TALLOC_CTX *mem_ctx,
1385 struct sockaddr_storage *pss, uint16_t port,
1386 struct sockaddr_storage **addrs, int *num)
1388 *addrs = talloc_realloc(mem_ctx, *addrs, struct sockaddr_storage, (*num)+1);
1390 if (*addrs == NULL) {
1391 *num = 0;
1392 return False;
1395 (*addrs)[*num] = *pss;
1396 set_sockaddr_port((struct sockaddr *)&(*addrs)[*num], port);
1398 *num += 1;
1399 return True;
1402 /*******************************************************************
1403 convert an ip to a name
1404 *******************************************************************/
1406 static bool dcip_to_name(TALLOC_CTX *mem_ctx,
1407 const struct winbindd_domain *domain,
1408 struct sockaddr_storage *pss,
1409 char **name)
1411 struct ip_service ip_list;
1412 uint32_t nt_version = NETLOGON_NT_VERSION_1;
1413 NTSTATUS status;
1414 const char *dc_name;
1415 fstring nbtname;
1416 #ifdef HAVE_ADS
1417 bool is_ad_domain = false;
1418 #endif
1419 ip_list.ss = *pss;
1420 ip_list.port = 0;
1422 #ifdef HAVE_ADS
1423 /* For active directory servers, try to get the ldap server name.
1424 None of these failures should be considered critical for now */
1426 if ((lp_security() == SEC_ADS) && (domain->alt_name != NULL)) {
1427 is_ad_domain = true;
1428 } else if (lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC) {
1429 is_ad_domain = domain->active_directory;
1432 if (is_ad_domain) {
1433 ADS_STRUCT *ads;
1434 ADS_STATUS ads_status;
1435 char addr[INET6_ADDRSTRLEN];
1437 print_sockaddr(addr, sizeof(addr), pss);
1439 ads = ads_init(domain->alt_name, domain->name, addr);
1440 ads->auth.flags |= ADS_AUTH_NO_BIND;
1442 ads_status = ads_connect(ads);
1443 if (ADS_ERR_OK(ads_status)) {
1444 /* We got a cldap packet. */
1445 *name = talloc_strdup(mem_ctx,
1446 ads->config.ldap_server_name);
1447 if (*name == NULL) {
1448 return false;
1450 namecache_store(*name, 0x20, 1, &ip_list);
1452 DEBUG(10,("dcip_to_name: flags = 0x%x\n", (unsigned int)ads->config.flags));
1454 if (domain->primary && (ads->config.flags & NBT_SERVER_KDC)) {
1455 if (ads_closest_dc(ads)) {
1456 char *sitename = sitename_fetch(mem_ctx, ads->config.realm);
1458 /* We're going to use this KDC for this realm/domain.
1459 If we are using sites, then force the krb5 libs
1460 to use this KDC. */
1462 create_local_private_krb5_conf_for_domain(domain->alt_name,
1463 domain->name,
1464 sitename,
1465 pss);
1467 TALLOC_FREE(sitename);
1468 } else {
1469 /* use an off site KDC */
1470 create_local_private_krb5_conf_for_domain(domain->alt_name,
1471 domain->name,
1472 NULL,
1473 pss);
1475 winbindd_set_locator_kdc_envs(domain);
1477 /* Ensure we contact this DC also. */
1478 saf_store(domain->name, *name);
1479 saf_store(domain->alt_name, *name);
1482 ads_destroy( &ads );
1483 return True;
1486 ads_destroy( &ads );
1487 return false;
1489 #endif
1491 status = nbt_getdc(winbind_messaging_context(), 10, pss, domain->name,
1492 &domain->sid, nt_version, mem_ctx, &nt_version,
1493 &dc_name, NULL);
1494 if (NT_STATUS_IS_OK(status)) {
1495 *name = talloc_strdup(mem_ctx, dc_name);
1496 if (*name == NULL) {
1497 return false;
1499 namecache_store(*name, 0x20, 1, &ip_list);
1500 return True;
1503 /* try node status request */
1505 if (name_status_find(domain->name, 0x1c, 0x20, pss, nbtname) ) {
1506 namecache_store(nbtname, 0x20, 1, &ip_list);
1508 if (name != NULL) {
1509 *name = talloc_strdup(mem_ctx, nbtname);
1510 if (*name == NULL) {
1511 return false;
1515 return true;
1517 return False;
1520 /*******************************************************************
1521 Retrieve a list of IP addresses for domain controllers.
1523 The array is sorted in the preferred connection order.
1525 @param[in] mem_ctx talloc memory context to allocate from
1526 @param[in] domain domain to retrieve DCs for
1527 @param[out] dcs array of dcs that will be returned
1528 @param[out] num_dcs number of dcs returned in the dcs array
1529 @return always true
1530 *******************************************************************/
1532 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
1533 struct dc_name_ip **dcs, int *num_dcs)
1535 fstring dcname;
1536 struct sockaddr_storage ss;
1537 struct ip_service *ip_list = NULL;
1538 int iplist_size = 0;
1539 int i;
1540 bool is_our_domain;
1541 enum security_types sec = (enum security_types)lp_security();
1543 is_our_domain = strequal(domain->name, lp_workgroup());
1545 /* If not our domain, get the preferred DC, by asking our primary DC */
1546 if ( !is_our_domain
1547 && get_dc_name_via_netlogon(domain, dcname, &ss)
1548 && add_one_dc_unique(mem_ctx, domain->name, dcname, &ss, dcs,
1549 num_dcs) )
1551 char addr[INET6_ADDRSTRLEN];
1552 print_sockaddr(addr, sizeof(addr), &ss);
1553 DEBUG(10, ("Retrieved DC %s at %s via netlogon\n",
1554 dcname, addr));
1555 return True;
1558 if ((sec == SEC_ADS) && (domain->alt_name != NULL)) {
1559 char *sitename = NULL;
1561 /* We need to make sure we know the local site before
1562 doing any DNS queries, as this will restrict the
1563 get_sorted_dc_list() call below to only fetching
1564 DNS records for the correct site. */
1566 /* Find any DC to get the site record.
1567 We deliberately don't care about the
1568 return here. */
1570 get_dc_name(domain->name, domain->alt_name, dcname, &ss);
1572 sitename = sitename_fetch(mem_ctx, domain->alt_name);
1573 if (sitename) {
1575 /* Do the site-specific AD dns lookup first. */
1576 get_sorted_dc_list(domain->alt_name, sitename, &ip_list,
1577 &iplist_size, True);
1579 /* Add ips to the DC array. We don't look up the name
1580 of the DC in this function, but we fill in the char*
1581 of the ip now to make the failed connection cache
1582 work */
1583 for ( i=0; i<iplist_size; i++ ) {
1584 char addr[INET6_ADDRSTRLEN];
1585 print_sockaddr(addr, sizeof(addr),
1586 &ip_list[i].ss);
1587 add_one_dc_unique(mem_ctx,
1588 domain->name,
1589 addr,
1590 &ip_list[i].ss,
1591 dcs,
1592 num_dcs);
1595 SAFE_FREE(ip_list);
1596 TALLOC_FREE(sitename);
1597 iplist_size = 0;
1600 /* Now we add DCs from the main AD DNS lookup. */
1601 get_sorted_dc_list(domain->alt_name, NULL, &ip_list,
1602 &iplist_size, True);
1604 for ( i=0; i<iplist_size; i++ ) {
1605 char addr[INET6_ADDRSTRLEN];
1606 print_sockaddr(addr, sizeof(addr),
1607 &ip_list[i].ss);
1608 add_one_dc_unique(mem_ctx,
1609 domain->name,
1610 addr,
1611 &ip_list[i].ss,
1612 dcs,
1613 num_dcs);
1616 SAFE_FREE(ip_list);
1617 iplist_size = 0;
1620 /* Try standard netbios queries if no ADS and fall back to DNS queries
1621 * if alt_name is available */
1622 if (*num_dcs == 0) {
1623 get_sorted_dc_list(domain->name, NULL, &ip_list, &iplist_size,
1624 false);
1625 if (iplist_size == 0) {
1626 if (domain->alt_name != NULL) {
1627 get_sorted_dc_list(domain->alt_name, NULL, &ip_list,
1628 &iplist_size, true);
1632 for ( i=0; i<iplist_size; i++ ) {
1633 char addr[INET6_ADDRSTRLEN];
1634 print_sockaddr(addr, sizeof(addr),
1635 &ip_list[i].ss);
1636 add_one_dc_unique(mem_ctx,
1637 domain->name,
1638 addr,
1639 &ip_list[i].ss,
1640 dcs,
1641 num_dcs);
1644 SAFE_FREE(ip_list);
1645 iplist_size = 0;
1648 return True;
1651 /*******************************************************************
1652 Find and make a connection to a DC in the given domain.
1654 @param[in] mem_ctx talloc memory context to allocate from
1655 @param[in] domain domain to find a dc in
1656 @param[out] dcname NetBIOS or FQDN of DC that's connected to
1657 @param[out] pss DC Internet address and port
1658 @param[out] fd fd of the open socket connected to the newly found dc
1659 @return true when a DC connection is made, false otherwise
1660 *******************************************************************/
1662 static bool find_new_dc(TALLOC_CTX *mem_ctx,
1663 struct winbindd_domain *domain,
1664 char **dcname, struct sockaddr_storage *pss, int *fd)
1666 struct dc_name_ip *dcs = NULL;
1667 int num_dcs = 0;
1669 const char **dcnames = NULL;
1670 size_t num_dcnames = 0;
1672 struct sockaddr_storage *addrs = NULL;
1673 int num_addrs = 0;
1675 int i;
1676 size_t fd_index;
1678 NTSTATUS status;
1680 *fd = -1;
1682 again:
1683 if (!get_dcs(mem_ctx, domain, &dcs, &num_dcs) || (num_dcs == 0))
1684 return False;
1686 for (i=0; i<num_dcs; i++) {
1688 if (!add_string_to_array(mem_ctx, dcs[i].name,
1689 &dcnames, &num_dcnames)) {
1690 return False;
1692 if (!add_sockaddr_to_array(mem_ctx, &dcs[i].ss, TCP_SMB_PORT,
1693 &addrs, &num_addrs)) {
1694 return False;
1698 if ((num_dcnames == 0) || (num_dcnames != num_addrs))
1699 return False;
1701 if ((addrs == NULL) || (dcnames == NULL))
1702 return False;
1704 status = smbsock_any_connect(addrs, dcnames, NULL, NULL, NULL,
1705 num_addrs, 0, 10, fd, &fd_index, NULL);
1706 if (!NT_STATUS_IS_OK(status)) {
1707 for (i=0; i<num_dcs; i++) {
1708 char ab[INET6_ADDRSTRLEN];
1709 print_sockaddr(ab, sizeof(ab), &dcs[i].ss);
1710 DEBUG(10, ("find_new_dc: smbsock_any_connect failed for "
1711 "domain %s address %s. Error was %s\n",
1712 domain->name, ab, nt_errstr(status) ));
1713 winbind_add_failed_connection_entry(domain,
1714 dcs[i].name, NT_STATUS_UNSUCCESSFUL);
1716 return False;
1719 *pss = addrs[fd_index];
1721 if (*dcnames[fd_index] != '\0' && !is_ipaddress(dcnames[fd_index])) {
1722 /* Ok, we've got a name for the DC */
1723 *dcname = talloc_strdup(mem_ctx, dcnames[fd_index]);
1724 if (*dcname == NULL) {
1725 return false;
1727 return true;
1730 /* Try to figure out the name */
1731 if (dcip_to_name(mem_ctx, domain, pss, dcname)) {
1732 return True;
1735 /* We can not continue without the DC's name */
1736 winbind_add_failed_connection_entry(domain, dcs[fd_index].name,
1737 NT_STATUS_UNSUCCESSFUL);
1739 /* Throw away all arrays as we're doing this again. */
1740 TALLOC_FREE(dcs);
1741 num_dcs = 0;
1743 TALLOC_FREE(dcnames);
1744 num_dcnames = 0;
1746 TALLOC_FREE(addrs);
1747 num_addrs = 0;
1749 close(*fd);
1750 *fd = -1;
1752 goto again;
1755 static char *current_dc_key(TALLOC_CTX *mem_ctx, const char *domain_name)
1757 return talloc_asprintf_strupper_m(mem_ctx, "CURRENT_DCNAME/%s",
1758 domain_name);
1761 static void store_current_dc_in_gencache(const char *domain_name,
1762 const char *dc_name,
1763 struct cli_state *cli)
1765 char addr[INET6_ADDRSTRLEN];
1766 char *key = NULL;
1767 char *value = NULL;
1769 if (!cli_state_is_connected(cli)) {
1770 return;
1773 print_sockaddr(addr, sizeof(addr),
1774 smbXcli_conn_remote_sockaddr(cli->conn));
1776 key = current_dc_key(talloc_tos(), domain_name);
1777 if (key == NULL) {
1778 goto done;
1781 value = talloc_asprintf(talloc_tos(), "%s %s", addr, dc_name);
1782 if (value == NULL) {
1783 goto done;
1786 gencache_set(key, value, 0x7fffffff);
1787 done:
1788 TALLOC_FREE(value);
1789 TALLOC_FREE(key);
1792 bool fetch_current_dc_from_gencache(TALLOC_CTX *mem_ctx,
1793 const char *domain_name,
1794 char **p_dc_name, char **p_dc_ip)
1796 char *key, *p;
1797 char *value = NULL;
1798 bool ret = false;
1799 char *dc_name = NULL;
1800 char *dc_ip = NULL;
1802 key = current_dc_key(talloc_tos(), domain_name);
1803 if (key == NULL) {
1804 goto done;
1806 if (!gencache_get(key, mem_ctx, &value, NULL)) {
1807 goto done;
1809 p = strchr(value, ' ');
1810 if (p == NULL) {
1811 goto done;
1813 dc_ip = talloc_strndup(mem_ctx, value, p - value);
1814 if (dc_ip == NULL) {
1815 goto done;
1817 dc_name = talloc_strdup(mem_ctx, p+1);
1818 if (dc_name == NULL) {
1819 goto done;
1822 if (p_dc_ip != NULL) {
1823 *p_dc_ip = dc_ip;
1824 dc_ip = NULL;
1826 if (p_dc_name != NULL) {
1827 *p_dc_name = dc_name;
1828 dc_name = NULL;
1830 ret = true;
1831 done:
1832 TALLOC_FREE(dc_name);
1833 TALLOC_FREE(dc_ip);
1834 TALLOC_FREE(key);
1835 TALLOC_FREE(value);
1836 return ret;
1839 NTSTATUS wb_open_internal_pipe(TALLOC_CTX *mem_ctx,
1840 const struct ndr_interface_table *table,
1841 struct rpc_pipe_client **ret_pipe)
1843 struct rpc_pipe_client *cli = NULL;
1844 const struct auth_session_info *session_info;
1845 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1848 session_info = get_session_info_system();
1849 SMB_ASSERT(session_info != NULL);
1851 /* create a connection to the specified pipe */
1852 if (lp_parm_bool(-1, "winbindd", "use external pipes", false)) {
1853 status = rpc_pipe_open_interface(mem_ctx,
1854 table,
1855 session_info,
1856 NULL,
1857 winbind_messaging_context(),
1858 &cli);
1859 } else {
1860 status = rpc_pipe_open_internal(mem_ctx,
1861 &table->syntax_id,
1862 session_info,
1863 NULL,
1864 winbind_messaging_context(),
1865 &cli);
1867 if (!NT_STATUS_IS_OK(status)) {
1868 DEBUG(0, ("open_internal_pipe: Could not connect to %s pipe: %s\n",
1869 table->name, nt_errstr(status)));
1870 return status;
1873 if (ret_pipe) {
1874 *ret_pipe = cli;
1877 return NT_STATUS_OK;
1880 static NTSTATUS cm_open_connection(struct winbindd_domain *domain,
1881 struct winbindd_cm_conn *new_conn)
1883 TALLOC_CTX *mem_ctx;
1884 NTSTATUS result;
1885 char *saf_servername;
1886 int retries;
1888 if ((mem_ctx = talloc_init("cm_open_connection")) == NULL) {
1889 set_domain_offline(domain);
1890 return NT_STATUS_NO_MEMORY;
1893 saf_servername = saf_fetch(mem_ctx, domain->name );
1895 /* we have to check the server affinity cache here since
1896 later we select a DC based on response time and not preference */
1898 /* Check the negative connection cache
1899 before talking to it. It going down may have
1900 triggered the reconnection. */
1902 if ( saf_servername && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, saf_servername))) {
1904 DEBUG(10,("cm_open_connection: saf_servername is '%s' for domain %s\n",
1905 saf_servername, domain->name ));
1907 /* convert an ip address to a name */
1908 if (is_ipaddress( saf_servername ) ) {
1909 char *dcname = NULL;
1910 struct sockaddr_storage ss;
1912 if (!interpret_string_addr(&ss, saf_servername,
1913 AI_NUMERICHOST)) {
1914 TALLOC_FREE(mem_ctx);
1915 return NT_STATUS_UNSUCCESSFUL;
1917 if (dcip_to_name(mem_ctx, domain, &ss, &dcname)) {
1918 domain->dcname = talloc_strdup(domain,
1919 dcname);
1920 if (domain->dcname == NULL) {
1921 TALLOC_FREE(mem_ctx);
1922 return NT_STATUS_NO_MEMORY;
1924 } else {
1925 winbind_add_failed_connection_entry(
1926 domain, saf_servername,
1927 NT_STATUS_UNSUCCESSFUL);
1929 } else {
1930 domain->dcname = talloc_strdup(domain, saf_servername);
1931 if (domain->dcname == NULL) {
1932 TALLOC_FREE(mem_ctx);
1933 return NT_STATUS_NO_MEMORY;
1938 for (retries = 0; retries < 3; retries++) {
1939 int fd = -1;
1940 bool retry = False;
1941 char *dcname = NULL;
1943 result = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1945 DEBUG(10,("cm_open_connection: dcname is '%s' for domain %s\n",
1946 domain->dcname ? domain->dcname : "", domain->name ));
1948 if (domain->dcname != NULL
1949 && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, domain->dcname))
1950 && (resolve_name(domain->dcname, &domain->dcaddr, 0x20, true)))
1952 NTSTATUS status;
1954 status = smbsock_connect(&domain->dcaddr, 0,
1955 NULL, -1, NULL, -1,
1956 &fd, NULL, 10);
1957 if (!NT_STATUS_IS_OK(status)) {
1958 fd = -1;
1962 if ((fd == -1) &&
1963 !find_new_dc(mem_ctx, domain, &dcname, &domain->dcaddr, &fd))
1965 /* This is the one place where we will
1966 set the global winbindd offline state
1967 to true, if a "WINBINDD_OFFLINE" entry
1968 is found in the winbindd cache. */
1969 set_global_winbindd_state_offline();
1970 break;
1972 if (dcname != NULL) {
1973 talloc_free(domain->dcname);
1975 domain->dcname = talloc_move(domain, &dcname);
1976 if (domain->dcname == NULL) {
1977 result = NT_STATUS_NO_MEMORY;
1978 break;
1982 new_conn->cli = NULL;
1984 result = cm_prepare_connection(domain, fd, domain->dcname,
1985 &new_conn->cli, &retry);
1986 if (!NT_STATUS_IS_OK(result)) {
1987 /* Don't leak the smb connection socket */
1988 close(fd);
1991 if (!retry)
1992 break;
1995 if (NT_STATUS_IS_OK(result)) {
1996 bool seal_pipes = true;
1998 winbindd_set_locator_kdc_envs(domain);
2000 if (domain->online == False) {
2001 /* We're changing state from offline to online. */
2002 set_global_winbindd_state_online();
2004 set_domain_online(domain);
2007 * Much as I hate global state, this seems to be the point
2008 * where we can be certain that we have a proper connection to
2009 * a DC. wbinfo --dc-info needs that information, store it in
2010 * gencache with a looong timeout. This will need revisiting
2011 * once we start to connect to multiple DCs, wbcDcInfo is
2012 * already prepared for that.
2014 store_current_dc_in_gencache(domain->name, domain->dcname,
2015 new_conn->cli);
2017 seal_pipes = lp_winbind_sealed_pipes();
2018 seal_pipes = lp_parm_bool(-1, "winbind sealed pipes",
2019 domain->name,
2020 seal_pipes);
2022 if (seal_pipes) {
2023 new_conn->auth_level = DCERPC_AUTH_LEVEL_PRIVACY;
2024 } else {
2025 new_conn->auth_level = DCERPC_AUTH_LEVEL_INTEGRITY;
2027 } else {
2028 /* Ensure we setup the retry handler. */
2029 set_domain_offline(domain);
2032 talloc_destroy(mem_ctx);
2033 return result;
2036 /* Close down all open pipes on a connection. */
2038 void invalidate_cm_connection(struct winbindd_domain *domain)
2040 NTSTATUS result;
2041 struct winbindd_cm_conn *conn = &domain->conn;
2043 /* We're closing down a possibly dead
2044 connection. Don't have impossibly long (10s) timeouts. */
2046 if (conn->cli) {
2047 cli_set_timeout(conn->cli, 1000); /* 1 second. */
2050 if (conn->samr_pipe != NULL) {
2051 if (is_valid_policy_hnd(&conn->sam_connect_handle)) {
2052 dcerpc_samr_Close(conn->samr_pipe->binding_handle,
2053 talloc_tos(),
2054 &conn->sam_connect_handle,
2055 &result);
2057 TALLOC_FREE(conn->samr_pipe);
2058 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
2059 if (conn->cli) {
2060 cli_set_timeout(conn->cli, 500);
2064 if (conn->lsa_pipe != NULL) {
2065 if (is_valid_policy_hnd(&conn->lsa_policy)) {
2066 dcerpc_lsa_Close(conn->lsa_pipe->binding_handle,
2067 talloc_tos(),
2068 &conn->lsa_policy,
2069 &result);
2071 TALLOC_FREE(conn->lsa_pipe);
2072 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
2073 if (conn->cli) {
2074 cli_set_timeout(conn->cli, 500);
2078 if (conn->lsa_pipe_tcp != NULL) {
2079 if (is_valid_policy_hnd(&conn->lsa_policy)) {
2080 dcerpc_lsa_Close(conn->lsa_pipe_tcp->binding_handle,
2081 talloc_tos(),
2082 &conn->lsa_policy,
2083 &result);
2085 TALLOC_FREE(conn->lsa_pipe_tcp);
2086 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
2087 if (conn->cli) {
2088 cli_set_timeout(conn->cli, 500);
2092 if (conn->netlogon_pipe != NULL) {
2093 TALLOC_FREE(conn->netlogon_pipe);
2094 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
2095 if (conn->cli) {
2096 cli_set_timeout(conn->cli, 500);
2100 conn->auth_level = DCERPC_AUTH_LEVEL_PRIVACY;
2101 conn->netlogon_force_reauth = false;
2102 conn->netlogon_flags = 0;
2103 TALLOC_FREE(conn->netlogon_creds);
2105 if (conn->cli) {
2106 cli_shutdown(conn->cli);
2109 conn->cli = NULL;
2112 void close_conns_after_fork(void)
2114 struct winbindd_domain *domain;
2115 struct winbindd_cli_state *cli_state;
2117 for (domain = domain_list(); domain; domain = domain->next) {
2119 * first close the low level SMB TCP connection
2120 * so that we don't generate any SMBclose
2121 * requests in invalidate_cm_connection()
2123 if (cli_state_is_connected(domain->conn.cli)) {
2124 smbXcli_conn_disconnect(domain->conn.cli->conn, NT_STATUS_OK);
2127 invalidate_cm_connection(domain);
2130 for (cli_state = winbindd_client_list();
2131 cli_state != NULL;
2132 cli_state = cli_state->next) {
2133 if (cli_state->sock >= 0) {
2134 close(cli_state->sock);
2135 cli_state->sock = -1;
2140 static bool connection_ok(struct winbindd_domain *domain)
2142 bool ok;
2144 ok = cli_state_is_connected(domain->conn.cli);
2145 if (!ok) {
2146 DEBUG(3, ("connection_ok: Connection to %s for domain %s is not connected\n",
2147 domain->dcname, domain->name));
2148 return False;
2151 if (domain->online == False) {
2152 DEBUG(3, ("connection_ok: Domain %s is offline\n", domain->name));
2153 return False;
2156 return True;
2159 /* Initialize a new connection up to the RPC BIND.
2160 Bypass online status check so always does network calls. */
2162 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain, bool need_rw_dc)
2164 NTSTATUS result;
2165 bool skip_connection = domain->internal;
2166 if (need_rw_dc && domain->rodc) {
2167 skip_connection = false;
2170 /* Internal connections never use the network. */
2171 if (dom_sid_equal(&domain->sid, &global_sid_Builtin)) {
2172 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2175 /* Still ask the internal LSA and SAMR server about the local domain */
2176 if (skip_connection || connection_ok(domain)) {
2177 if (!domain->initialized) {
2178 set_dc_type_and_flags(domain);
2180 return NT_STATUS_OK;
2183 invalidate_cm_connection(domain);
2185 if (!domain->primary && !domain->initialized) {
2187 * Before we connect to a trust, work out if it is an
2188 * AD domain by asking our own domain.
2190 set_dc_type_and_flags_trustinfo(domain);
2193 result = cm_open_connection(domain, &domain->conn);
2195 if (NT_STATUS_IS_OK(result) && !domain->initialized) {
2196 set_dc_type_and_flags(domain);
2199 return result;
2202 NTSTATUS init_dc_connection(struct winbindd_domain *domain, bool need_rw_dc)
2204 if (dom_sid_equal(&domain->sid, &global_sid_Builtin)) {
2205 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2208 if (domain->initialized && !domain->online) {
2209 /* We check for online status elsewhere. */
2210 return NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
2213 return init_dc_connection_network(domain, need_rw_dc);
2216 static NTSTATUS init_dc_connection_rpc(struct winbindd_domain *domain, bool need_rw_dc)
2218 NTSTATUS status;
2220 status = init_dc_connection(domain, need_rw_dc);
2221 if (!NT_STATUS_IS_OK(status)) {
2222 return status;
2225 if (!domain->internal && domain->conn.cli == NULL) {
2226 /* happens for trusted domains without inbound trust */
2227 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2230 return NT_STATUS_OK;
2233 /******************************************************************************
2234 Set the trust flags (direction and forest location) for a domain
2235 ******************************************************************************/
2237 static bool set_dc_type_and_flags_trustinfo( struct winbindd_domain *domain )
2239 struct winbindd_domain *our_domain;
2240 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2241 WERROR werr;
2242 struct netr_DomainTrustList trusts;
2243 int i;
2244 uint32_t flags = (NETR_TRUST_FLAG_IN_FOREST |
2245 NETR_TRUST_FLAG_OUTBOUND |
2246 NETR_TRUST_FLAG_INBOUND);
2247 struct rpc_pipe_client *cli;
2248 TALLOC_CTX *mem_ctx = NULL;
2249 struct dcerpc_binding_handle *b;
2251 DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s\n", domain->name ));
2253 /* Our primary domain doesn't need to worry about trust flags.
2254 Force it to go through the network setup */
2255 if ( domain->primary ) {
2256 return False;
2259 mem_ctx = talloc_stackframe();
2260 our_domain = find_our_domain();
2261 if (our_domain->internal) {
2262 result = init_dc_connection(our_domain, false);
2263 if (!NT_STATUS_IS_OK(result)) {
2264 DEBUG(3,("set_dc_type_and_flags_trustinfo: "
2265 "Not able to make a connection to our domain: %s\n",
2266 nt_errstr(result)));
2267 TALLOC_FREE(mem_ctx);
2268 return false;
2272 /* This won't work unless our domain is AD */
2273 if ( !our_domain->active_directory ) {
2274 TALLOC_FREE(mem_ctx);
2275 return False;
2278 if (our_domain->internal) {
2279 result = wb_open_internal_pipe(mem_ctx, &ndr_table_netlogon, &cli);
2280 } else if (!connection_ok(our_domain)) {
2281 DEBUG(3,("set_dc_type_and_flags_trustinfo: "
2282 "No connection to our domain!\n"));
2283 TALLOC_FREE(mem_ctx);
2284 return False;
2285 } else {
2286 result = cm_connect_netlogon(our_domain, &cli);
2289 if (!NT_STATUS_IS_OK(result)) {
2290 DEBUG(5, ("set_dc_type_and_flags_trustinfo: Could not open "
2291 "a connection to %s for PIPE_NETLOGON (%s)\n",
2292 domain->name, nt_errstr(result)));
2293 TALLOC_FREE(mem_ctx);
2294 return False;
2296 b = cli->binding_handle;
2298 /* Use DsEnumerateDomainTrusts to get us the trust direction and type. */
2299 result = dcerpc_netr_DsrEnumerateDomainTrusts(b, mem_ctx,
2300 cli->desthost,
2301 flags,
2302 &trusts,
2303 &werr);
2304 if (!NT_STATUS_IS_OK(result)) {
2305 DEBUG(0,("set_dc_type_and_flags_trustinfo: "
2306 "failed to query trusted domain list: %s\n",
2307 nt_errstr(result)));
2308 TALLOC_FREE(mem_ctx);
2309 return false;
2311 if (!W_ERROR_IS_OK(werr)) {
2312 DEBUG(0,("set_dc_type_and_flags_trustinfo: "
2313 "failed to query trusted domain list: %s\n",
2314 win_errstr(werr)));
2315 TALLOC_FREE(mem_ctx);
2316 return false;
2319 /* Now find the domain name and get the flags */
2321 for ( i=0; i<trusts.count; i++ ) {
2322 if ( strequal( domain->name, trusts.array[i].netbios_name) ) {
2323 domain->domain_flags = trusts.array[i].trust_flags;
2324 domain->domain_type = trusts.array[i].trust_type;
2325 domain->domain_trust_attribs = trusts.array[i].trust_attributes;
2327 if ( domain->domain_type == LSA_TRUST_TYPE_UPLEVEL )
2328 domain->active_directory = True;
2330 /* This flag is only set if the domain is *our*
2331 primary domain and the primary domain is in
2332 native mode */
2334 domain->native_mode = (domain->domain_flags & NETR_TRUST_FLAG_NATIVE);
2336 DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s is %sin "
2337 "native mode.\n", domain->name,
2338 domain->native_mode ? "" : "NOT "));
2340 DEBUG(5,("set_dc_type_and_flags_trustinfo: domain %s is %s"
2341 "running active directory.\n", domain->name,
2342 domain->active_directory ? "" : "NOT "));
2344 domain->can_do_ncacn_ip_tcp = domain->active_directory;
2346 domain->initialized = True;
2348 break;
2352 TALLOC_FREE(mem_ctx);
2354 return domain->initialized;
2357 /******************************************************************************
2358 We can 'sense' certain things about the DC by it's replies to certain
2359 questions.
2361 This tells us if this particular remote server is Active Directory, and if it
2362 is native mode.
2363 ******************************************************************************/
2365 static void set_dc_type_and_flags_connect( struct winbindd_domain *domain )
2367 NTSTATUS status, result;
2368 WERROR werr;
2369 TALLOC_CTX *mem_ctx = NULL;
2370 struct rpc_pipe_client *cli = NULL;
2371 struct policy_handle pol;
2372 union dssetup_DsRoleInfo info;
2373 union lsa_PolicyInformation *lsa_info = NULL;
2375 if (!domain->internal && !connection_ok(domain)) {
2376 return;
2379 mem_ctx = talloc_init("set_dc_type_and_flags on domain %s\n",
2380 domain->name);
2381 if (!mem_ctx) {
2382 DEBUG(1, ("set_dc_type_and_flags_connect: talloc_init() failed\n"));
2383 return;
2386 DEBUG(5, ("set_dc_type_and_flags_connect: domain %s\n", domain->name ));
2388 if (domain->internal) {
2389 status = wb_open_internal_pipe(mem_ctx,
2390 &ndr_table_dssetup,
2391 &cli);
2392 } else {
2393 status = cli_rpc_pipe_open_noauth(domain->conn.cli,
2394 &ndr_table_dssetup,
2395 &cli);
2398 if (!NT_STATUS_IS_OK(status)) {
2399 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
2400 "PI_DSSETUP on domain %s: (%s)\n",
2401 domain->name, nt_errstr(status)));
2403 /* if this is just a non-AD domain we need to continue
2404 * identifying so that we can in the end return with
2405 * domain->initialized = True - gd */
2407 goto no_dssetup;
2410 status = dcerpc_dssetup_DsRoleGetPrimaryDomainInformation(cli->binding_handle, mem_ctx,
2411 DS_ROLE_BASIC_INFORMATION,
2412 &info,
2413 &werr);
2414 TALLOC_FREE(cli);
2416 if (NT_STATUS_IS_OK(status)) {
2417 result = werror_to_ntstatus(werr);
2419 if (!NT_STATUS_IS_OK(status)) {
2420 DEBUG(5, ("set_dc_type_and_flags_connect: rpccli_ds_getprimarydominfo "
2421 "on domain %s failed: (%s)\n",
2422 domain->name, nt_errstr(status)));
2424 /* older samba3 DCs will return DCERPC_FAULT_OP_RNG_ERROR for
2425 * every opcode on the DSSETUP pipe, continue with
2426 * no_dssetup mode here as well to get domain->initialized
2427 * set - gd */
2429 if (NT_STATUS_EQUAL(status, NT_STATUS_RPC_PROCNUM_OUT_OF_RANGE)) {
2430 goto no_dssetup;
2433 TALLOC_FREE(mem_ctx);
2434 return;
2437 if ((info.basic.flags & DS_ROLE_PRIMARY_DS_RUNNING) &&
2438 !(info.basic.flags & DS_ROLE_PRIMARY_DS_MIXED_MODE)) {
2439 domain->native_mode = True;
2440 } else {
2441 domain->native_mode = False;
2444 no_dssetup:
2445 if (domain->internal) {
2446 status = wb_open_internal_pipe(mem_ctx,
2447 &ndr_table_lsarpc,
2448 &cli);
2449 } else {
2450 status = cli_rpc_pipe_open_noauth(domain->conn.cli,
2451 &ndr_table_lsarpc, &cli);
2453 if (!NT_STATUS_IS_OK(status)) {
2454 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
2455 "PI_LSARPC on domain %s: (%s)\n",
2456 domain->name, nt_errstr(status)));
2457 TALLOC_FREE(cli);
2458 TALLOC_FREE(mem_ctx);
2459 return;
2462 status = rpccli_lsa_open_policy2(cli, mem_ctx, True,
2463 SEC_FLAG_MAXIMUM_ALLOWED, &pol);
2465 if (NT_STATUS_IS_OK(status)) {
2466 /* This particular query is exactly what Win2k clients use
2467 to determine that the DC is active directory */
2468 status = dcerpc_lsa_QueryInfoPolicy2(cli->binding_handle, mem_ctx,
2469 &pol,
2470 LSA_POLICY_INFO_DNS,
2471 &lsa_info,
2472 &result);
2475 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2476 domain->active_directory = True;
2478 if (lsa_info->dns.name.string) {
2479 if (!strequal(domain->name, lsa_info->dns.name.string))
2481 DEBUG(1, ("set_dc_type_and_flags_connect: DC "
2482 "for domain %s claimed it was a DC "
2483 "for domain %s, refusing to "
2484 "initialize\n",
2485 domain->name,
2486 lsa_info->dns.name.string));
2487 TALLOC_FREE(cli);
2488 TALLOC_FREE(mem_ctx);
2489 return;
2491 talloc_free(domain->name);
2492 domain->name = talloc_strdup(domain,
2493 lsa_info->dns.name.string);
2494 if (domain->name == NULL) {
2495 goto done;
2499 if (lsa_info->dns.dns_domain.string) {
2500 if (domain->alt_name != NULL &&
2501 !strequal(domain->alt_name,
2502 lsa_info->dns.dns_domain.string))
2504 DEBUG(1, ("set_dc_type_and_flags_connect: DC "
2505 "for domain %s (%s) claimed it was "
2506 "a DC for domain %s, refusing to "
2507 "initialize\n",
2508 domain->alt_name, domain->name,
2509 lsa_info->dns.dns_domain.string));
2510 TALLOC_FREE(cli);
2511 TALLOC_FREE(mem_ctx);
2512 return;
2514 talloc_free(domain->alt_name);
2515 domain->alt_name =
2516 talloc_strdup(domain,
2517 lsa_info->dns.dns_domain.string);
2518 if (domain->alt_name == NULL) {
2519 goto done;
2523 /* See if we can set some domain trust flags about
2524 ourself */
2526 if (lsa_info->dns.dns_forest.string) {
2527 talloc_free(domain->forest_name);
2528 domain->forest_name =
2529 talloc_strdup(domain,
2530 lsa_info->dns.dns_forest.string);
2531 if (domain->forest_name == NULL) {
2532 goto done;
2535 if (strequal(domain->forest_name, domain->alt_name)) {
2536 domain->domain_flags |= NETR_TRUST_FLAG_TREEROOT;
2540 if (lsa_info->dns.sid) {
2541 if (!is_null_sid(&domain->sid) &&
2542 !dom_sid_equal(&domain->sid,
2543 lsa_info->dns.sid))
2545 DEBUG(1, ("set_dc_type_and_flags_connect: DC "
2546 "for domain %s (%s) claimed it was "
2547 "a DC for domain %s, refusing to "
2548 "initialize\n",
2549 dom_sid_string(talloc_tos(),
2550 &domain->sid),
2551 domain->name,
2552 dom_sid_string(talloc_tos(),
2553 lsa_info->dns.sid)));
2554 TALLOC_FREE(cli);
2555 TALLOC_FREE(mem_ctx);
2556 return;
2558 sid_copy(&domain->sid, lsa_info->dns.sid);
2560 } else {
2561 domain->active_directory = False;
2563 status = rpccli_lsa_open_policy(cli, mem_ctx, True,
2564 SEC_FLAG_MAXIMUM_ALLOWED,
2565 &pol);
2567 if (!NT_STATUS_IS_OK(status)) {
2568 goto done;
2571 status = dcerpc_lsa_QueryInfoPolicy(cli->binding_handle, mem_ctx,
2572 &pol,
2573 LSA_POLICY_INFO_ACCOUNT_DOMAIN,
2574 &lsa_info,
2575 &result);
2576 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2578 if (lsa_info->account_domain.name.string) {
2579 if (!strequal(domain->name,
2580 lsa_info->account_domain.name.string))
2582 DEBUG(1,
2583 ("set_dc_type_and_flags_connect: "
2584 "DC for domain %s claimed it was"
2585 " a DC for domain %s, refusing "
2586 "to initialize\n", domain->name,
2587 lsa_info->
2588 account_domain.name.string));
2589 TALLOC_FREE(cli);
2590 TALLOC_FREE(mem_ctx);
2591 return;
2593 talloc_free(domain->name);
2594 domain->name =
2595 talloc_strdup(domain,
2596 lsa_info->account_domain.name.string);
2599 if (lsa_info->account_domain.sid) {
2600 if (!is_null_sid(&domain->sid) &&
2601 !dom_sid_equal(&domain->sid,
2602 lsa_info->account_domain.sid))
2604 DEBUG(1,
2605 ("set_dc_type_and_flags_connect: "
2606 "DC for domain %s (%s) claimed "
2607 "it was a DC for domain %s, "
2608 "refusing to initialize\n",
2609 dom_sid_string(talloc_tos(),
2610 &domain->sid),
2611 domain->name,
2612 dom_sid_string(talloc_tos(),
2613 lsa_info->account_domain.sid)));
2614 TALLOC_FREE(cli);
2615 TALLOC_FREE(mem_ctx);
2616 return;
2618 sid_copy(&domain->sid, lsa_info->account_domain.sid);
2622 done:
2624 DEBUG(5, ("set_dc_type_and_flags_connect: domain %s is %sin native mode.\n",
2625 domain->name, domain->native_mode ? "" : "NOT "));
2627 DEBUG(5,("set_dc_type_and_flags_connect: domain %s is %srunning active directory.\n",
2628 domain->name, domain->active_directory ? "" : "NOT "));
2630 domain->can_do_ncacn_ip_tcp = domain->active_directory;
2632 TALLOC_FREE(cli);
2634 TALLOC_FREE(mem_ctx);
2636 domain->initialized = True;
2639 /**********************************************************************
2640 Set the domain_flags (trust attributes, domain operating modes, etc...
2641 ***********************************************************************/
2643 static void set_dc_type_and_flags( struct winbindd_domain *domain )
2645 /* we always have to contact our primary domain */
2647 if ( domain->primary || domain->internal) {
2648 DEBUG(10,("set_dc_type_and_flags: setting up flags for "
2649 "primary or internal domain\n"));
2650 set_dc_type_and_flags_connect( domain );
2651 return;
2654 /* Use our DC to get the information if possible */
2656 if ( !set_dc_type_and_flags_trustinfo( domain ) ) {
2657 /* Otherwise, fallback to contacting the
2658 domain directly */
2659 set_dc_type_and_flags_connect( domain );
2662 return;
2667 /**********************************************************************
2668 ***********************************************************************/
2670 static NTSTATUS cm_get_schannel_creds(struct winbindd_domain *domain,
2671 struct netlogon_creds_cli_context **ppdc)
2673 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2674 struct rpc_pipe_client *netlogon_pipe;
2676 *ppdc = NULL;
2678 if ((!IS_DC) && (!domain->primary)) {
2679 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2682 if (domain->conn.netlogon_creds != NULL) {
2683 if (!(domain->conn.netlogon_flags & NETLOGON_NEG_AUTHENTICATED_RPC)) {
2684 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2686 *ppdc = domain->conn.netlogon_creds;
2687 return NT_STATUS_OK;
2690 result = cm_connect_netlogon(domain, &netlogon_pipe);
2691 if (!NT_STATUS_IS_OK(result)) {
2692 return result;
2695 if (domain->conn.netlogon_creds == NULL) {
2696 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2699 if (!(domain->conn.netlogon_flags & NETLOGON_NEG_AUTHENTICATED_RPC)) {
2700 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2703 *ppdc = domain->conn.netlogon_creds;
2704 return NT_STATUS_OK;
2707 NTSTATUS cm_connect_sam(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2708 bool need_rw_dc,
2709 struct rpc_pipe_client **cli, struct policy_handle *sam_handle)
2711 struct winbindd_cm_conn *conn;
2712 NTSTATUS status, result;
2713 struct netlogon_creds_cli_context *p_creds;
2714 struct cli_credentials *creds = NULL;
2715 bool retry = false; /* allow one retry attempt for expired session */
2717 if (sid_check_is_our_sam(&domain->sid)) {
2718 if (domain->rodc == false || need_rw_dc == false) {
2719 return open_internal_samr_conn(mem_ctx, domain, cli, sam_handle);
2723 retry:
2724 status = init_dc_connection_rpc(domain, need_rw_dc);
2725 if (!NT_STATUS_IS_OK(status)) {
2726 return status;
2729 conn = &domain->conn;
2731 if (rpccli_is_connected(conn->samr_pipe)) {
2732 goto done;
2735 TALLOC_FREE(conn->samr_pipe);
2738 * No SAMR pipe yet. Attempt to get an NTLMSSP SPNEGO authenticated
2739 * sign and sealed pipe using the machine account password by
2740 * preference. If we can't - try schannel, if that fails, try
2741 * anonymous.
2744 result = get_trust_credentials(domain, talloc_tos(), false, &creds);
2745 if (!NT_STATUS_IS_OK(result)) {
2746 DEBUG(10, ("cm_connect_sam: No user available for "
2747 "domain %s, trying schannel\n", domain->name));
2748 goto schannel;
2751 if (cli_credentials_is_anonymous(creds)) {
2752 goto anonymous;
2756 * We have an authenticated connection. Use a SPNEGO
2757 * authenticated SAMR pipe with sign & seal.
2759 status = cli_rpc_pipe_open_with_creds(conn->cli,
2760 &ndr_table_samr,
2761 NCACN_NP,
2762 DCERPC_AUTH_TYPE_SPNEGO,
2763 conn->auth_level,
2764 smbXcli_conn_remote_name(conn->cli->conn),
2765 creds,
2766 &conn->samr_pipe);
2768 if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_SESSION_EXPIRED)
2769 && !retry) {
2770 invalidate_cm_connection(domain);
2771 retry = true;
2772 goto retry;
2775 if (!NT_STATUS_IS_OK(status)) {
2776 DEBUG(10,("cm_connect_sam: failed to connect to SAMR "
2777 "pipe for domain %s using NTLMSSP "
2778 "authenticated pipe: user %s. Error was "
2779 "%s\n", domain->name,
2780 cli_credentials_get_unparsed_name(creds, talloc_tos()),
2781 nt_errstr(status)));
2782 goto schannel;
2785 DEBUG(10,("cm_connect_sam: connected to SAMR pipe for "
2786 "domain %s using NTLMSSP authenticated "
2787 "pipe: user %s\n", domain->name,
2788 cli_credentials_get_unparsed_name(creds, talloc_tos())));
2790 status = dcerpc_samr_Connect2(conn->samr_pipe->binding_handle, mem_ctx,
2791 conn->samr_pipe->desthost,
2792 SEC_FLAG_MAXIMUM_ALLOWED,
2793 &conn->sam_connect_handle,
2794 &result);
2796 if (NT_STATUS_EQUAL(status, NT_STATUS_IO_DEVICE_ERROR) && !retry) {
2797 invalidate_cm_connection(domain);
2798 TALLOC_FREE(conn->samr_pipe);
2799 retry = true;
2800 goto retry;
2803 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2804 goto open_domain;
2806 if (NT_STATUS_IS_OK(status)) {
2807 status = result;
2810 DEBUG(10,("cm_connect_sam: ntlmssp-sealed dcerpc_samr_Connect2 "
2811 "failed for domain %s, error was %s. Trying schannel\n",
2812 domain->name, nt_errstr(status) ));
2813 TALLOC_FREE(conn->samr_pipe);
2815 schannel:
2817 /* Fall back to schannel if it's a W2K pre-SP1 box. */
2819 status = cm_get_schannel_creds(domain, &p_creds);
2820 if (!NT_STATUS_IS_OK(status)) {
2821 /* If this call fails - conn->cli can now be NULL ! */
2822 DEBUG(10, ("cm_connect_sam: Could not get schannel auth info "
2823 "for domain %s (error %s), trying anon\n",
2824 domain->name,
2825 nt_errstr(status) ));
2826 goto anonymous;
2828 TALLOC_FREE(creds);
2829 result = get_trust_credentials(domain, talloc_tos(), true, &creds);
2830 if (!NT_STATUS_IS_OK(result)) {
2831 DEBUG(10, ("cm_connect_sam: No user available for "
2832 "domain %s (error %s), trying anon\n", domain->name,
2833 nt_errstr(result)));
2834 goto anonymous;
2836 status = cli_rpc_pipe_open_schannel_with_creds
2837 (conn->cli, &ndr_table_samr, NCACN_NP,
2838 creds, p_creds, &conn->samr_pipe);
2840 if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_SESSION_EXPIRED)
2841 && !retry) {
2842 invalidate_cm_connection(domain);
2843 retry = true;
2844 goto retry;
2847 if (!NT_STATUS_IS_OK(status)) {
2848 DEBUG(10,("cm_connect_sam: failed to connect to SAMR pipe for "
2849 "domain %s using schannel. Error was %s\n",
2850 domain->name, nt_errstr(status) ));
2851 goto anonymous;
2853 DEBUG(10,("cm_connect_sam: connected to SAMR pipe for domain %s using "
2854 "schannel.\n", domain->name ));
2856 status = dcerpc_samr_Connect2(conn->samr_pipe->binding_handle, mem_ctx,
2857 conn->samr_pipe->desthost,
2858 SEC_FLAG_MAXIMUM_ALLOWED,
2859 &conn->sam_connect_handle,
2860 &result);
2862 if (NT_STATUS_EQUAL(status, NT_STATUS_IO_DEVICE_ERROR) && !retry) {
2863 invalidate_cm_connection(domain);
2864 TALLOC_FREE(conn->samr_pipe);
2865 retry = true;
2866 goto retry;
2869 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2870 goto open_domain;
2872 if (NT_STATUS_IS_OK(status)) {
2873 status = result;
2875 DEBUG(10,("cm_connect_sam: schannel-sealed dcerpc_samr_Connect2 failed "
2876 "for domain %s, error was %s. Trying anonymous\n",
2877 domain->name, nt_errstr(status) ));
2878 TALLOC_FREE(conn->samr_pipe);
2880 anonymous:
2882 /* Finally fall back to anonymous. */
2883 if (lp_winbind_sealed_pipes() || lp_require_strong_key()) {
2884 status = NT_STATUS_DOWNGRADE_DETECTED;
2885 DEBUG(1, ("Unwilling to make SAMR connection to domain %s"
2886 "without connection level security, "
2887 "must set 'winbind sealed pipes = false' and "
2888 "'require strong key = false' to proceed: %s\n",
2889 domain->name, nt_errstr(status)));
2890 goto done;
2892 status = cli_rpc_pipe_open_noauth(conn->cli, &ndr_table_samr,
2893 &conn->samr_pipe);
2895 if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_SESSION_EXPIRED)
2896 && !retry) {
2897 invalidate_cm_connection(domain);
2898 retry = true;
2899 goto retry;
2902 if (!NT_STATUS_IS_OK(status)) {
2903 goto done;
2906 status = dcerpc_samr_Connect2(conn->samr_pipe->binding_handle, mem_ctx,
2907 conn->samr_pipe->desthost,
2908 SEC_FLAG_MAXIMUM_ALLOWED,
2909 &conn->sam_connect_handle,
2910 &result);
2912 if (NT_STATUS_EQUAL(status, NT_STATUS_IO_DEVICE_ERROR) && !retry) {
2913 invalidate_cm_connection(domain);
2914 TALLOC_FREE(conn->samr_pipe);
2915 retry = true;
2916 goto retry;
2919 if (!NT_STATUS_IS_OK(status)) {
2920 DEBUG(10,("cm_connect_sam: rpccli_samr_Connect2 failed "
2921 "for domain %s Error was %s\n",
2922 domain->name, nt_errstr(status) ));
2923 goto done;
2925 if (!NT_STATUS_IS_OK(result)) {
2926 status = result;
2927 DEBUG(10,("cm_connect_sam: dcerpc_samr_Connect2 failed "
2928 "for domain %s Error was %s\n",
2929 domain->name, nt_errstr(result)));
2930 goto done;
2933 open_domain:
2934 status = dcerpc_samr_OpenDomain(conn->samr_pipe->binding_handle,
2935 mem_ctx,
2936 &conn->sam_connect_handle,
2937 SEC_FLAG_MAXIMUM_ALLOWED,
2938 &domain->sid,
2939 &conn->sam_domain_handle,
2940 &result);
2941 if (!NT_STATUS_IS_OK(status)) {
2942 goto done;
2945 status = result;
2946 done:
2948 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
2950 * if we got access denied, we might just have no access rights
2951 * to talk to the remote samr server server (e.g. when we are a
2952 * PDC and we are connecting a w2k8 pdc via an interdomain
2953 * trust). In that case do not invalidate the whole connection
2954 * stack
2956 TALLOC_FREE(conn->samr_pipe);
2957 ZERO_STRUCT(conn->sam_domain_handle);
2958 return status;
2959 } else if (!NT_STATUS_IS_OK(status)) {
2960 invalidate_cm_connection(domain);
2961 return status;
2964 *cli = conn->samr_pipe;
2965 *sam_handle = conn->sam_domain_handle;
2966 return status;
2969 /**********************************************************************
2970 open an schanneld ncacn_ip_tcp connection to LSA
2971 ***********************************************************************/
2973 static NTSTATUS cm_connect_lsa_tcp(struct winbindd_domain *domain,
2974 TALLOC_CTX *mem_ctx,
2975 struct rpc_pipe_client **cli)
2977 struct winbindd_cm_conn *conn;
2978 struct netlogon_creds_cli_context *p_creds = NULL;
2979 struct cli_credentials *creds = NULL;
2980 NTSTATUS status;
2982 DEBUG(10,("cm_connect_lsa_tcp\n"));
2984 status = init_dc_connection_rpc(domain, false);
2985 if (!NT_STATUS_IS_OK(status)) {
2986 return status;
2989 conn = &domain->conn;
2991 if (conn->lsa_pipe_tcp &&
2992 conn->lsa_pipe_tcp->transport->transport == NCACN_IP_TCP &&
2993 conn->lsa_pipe_tcp->auth->auth_level >= DCERPC_AUTH_LEVEL_INTEGRITY &&
2994 rpccli_is_connected(conn->lsa_pipe_tcp)) {
2995 goto done;
2998 TALLOC_FREE(conn->lsa_pipe_tcp);
3000 status = cm_get_schannel_creds(domain, &p_creds);
3001 if (!NT_STATUS_IS_OK(status)) {
3002 goto done;
3005 status = get_trust_credentials(domain, talloc_tos(), true, &creds);
3006 if (!NT_STATUS_IS_OK(status)) {
3007 goto done;
3010 status = cli_rpc_pipe_open_schannel_with_creds(conn->cli,
3011 &ndr_table_lsarpc,
3012 NCACN_IP_TCP,
3013 creds,
3014 p_creds,
3015 &conn->lsa_pipe_tcp);
3016 if (!NT_STATUS_IS_OK(status)) {
3017 DEBUG(10,("cli_rpc_pipe_open_schannel_with_key failed: %s\n",
3018 nt_errstr(status)));
3019 goto done;
3022 done:
3023 if (!NT_STATUS_IS_OK(status)) {
3024 TALLOC_FREE(conn->lsa_pipe_tcp);
3025 return status;
3028 *cli = conn->lsa_pipe_tcp;
3030 return status;
3033 NTSTATUS cm_connect_lsa(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
3034 struct rpc_pipe_client **cli, struct policy_handle *lsa_policy)
3036 struct winbindd_cm_conn *conn;
3037 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
3038 struct netlogon_creds_cli_context *p_creds;
3039 struct cli_credentials *creds = NULL;
3040 bool retry = false; /* allow one retry attempt for expired session */
3042 retry:
3043 result = init_dc_connection_rpc(domain, false);
3044 if (!NT_STATUS_IS_OK(result))
3045 return result;
3047 conn = &domain->conn;
3049 if (rpccli_is_connected(conn->lsa_pipe)) {
3050 goto done;
3053 TALLOC_FREE(conn->lsa_pipe);
3055 result = get_trust_credentials(domain, talloc_tos(), false, &creds);
3056 if (!NT_STATUS_IS_OK(result)) {
3057 DEBUG(10, ("cm_connect_lsa: No user available for "
3058 "domain %s, trying schannel\n", domain->name));
3059 goto schannel;
3062 if (cli_credentials_is_anonymous(creds)) {
3063 goto anonymous;
3067 * We have an authenticated connection. Use a SPNEGO
3068 * authenticated LSA pipe with sign & seal.
3070 result = cli_rpc_pipe_open_with_creds
3071 (conn->cli, &ndr_table_lsarpc, NCACN_NP,
3072 DCERPC_AUTH_TYPE_SPNEGO,
3073 conn->auth_level,
3074 smbXcli_conn_remote_name(conn->cli->conn),
3075 creds,
3076 &conn->lsa_pipe);
3078 if (NT_STATUS_EQUAL(result, NT_STATUS_NETWORK_SESSION_EXPIRED)
3079 && !retry) {
3080 invalidate_cm_connection(domain);
3081 retry = true;
3082 goto retry;
3085 if (!NT_STATUS_IS_OK(result)) {
3086 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
3087 "domain %s using NTLMSSP authenticated pipe: user "
3088 "%s. Error was %s. Trying schannel.\n",
3089 domain->name,
3090 cli_credentials_get_unparsed_name(creds, talloc_tos()),
3091 nt_errstr(result)));
3092 goto schannel;
3095 DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
3096 "NTLMSSP authenticated pipe: user %s\n",
3097 domain->name, cli_credentials_get_unparsed_name(creds, talloc_tos())));
3099 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
3100 SEC_FLAG_MAXIMUM_ALLOWED,
3101 &conn->lsa_policy);
3102 if (NT_STATUS_EQUAL(result, NT_STATUS_IO_DEVICE_ERROR) && !retry) {
3103 invalidate_cm_connection(domain);
3104 TALLOC_FREE(conn->lsa_pipe);
3105 retry = true;
3106 goto retry;
3109 if (NT_STATUS_IS_OK(result)) {
3110 goto done;
3113 DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
3114 "schannel\n"));
3116 TALLOC_FREE(conn->lsa_pipe);
3118 schannel:
3120 /* Fall back to schannel if it's a W2K pre-SP1 box. */
3122 result = cm_get_schannel_creds(domain, &p_creds);
3123 if (!NT_STATUS_IS_OK(result)) {
3124 /* If this call fails - conn->cli can now be NULL ! */
3125 DEBUG(10, ("cm_connect_lsa: Could not get schannel auth info "
3126 "for domain %s (error %s), trying anon\n",
3127 domain->name,
3128 nt_errstr(result) ));
3129 goto anonymous;
3132 TALLOC_FREE(creds);
3133 result = get_trust_credentials(domain, talloc_tos(), true, &creds);
3134 if (!NT_STATUS_IS_OK(result)) {
3135 DEBUG(10, ("cm_connect_lsa: No user available for "
3136 "domain %s (error %s), trying anon\n", domain->name,
3137 nt_errstr(result)));
3138 goto anonymous;
3140 result = cli_rpc_pipe_open_schannel_with_creds
3141 (conn->cli, &ndr_table_lsarpc, NCACN_NP,
3142 creds, p_creds, &conn->lsa_pipe);
3144 if (NT_STATUS_EQUAL(result, NT_STATUS_NETWORK_SESSION_EXPIRED)
3145 && !retry) {
3146 invalidate_cm_connection(domain);
3147 retry = true;
3148 goto retry;
3151 if (!NT_STATUS_IS_OK(result)) {
3152 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
3153 "domain %s using schannel. Error was %s\n",
3154 domain->name, nt_errstr(result) ));
3155 goto anonymous;
3157 DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
3158 "schannel.\n", domain->name ));
3160 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
3161 SEC_FLAG_MAXIMUM_ALLOWED,
3162 &conn->lsa_policy);
3164 if (NT_STATUS_EQUAL(result, NT_STATUS_IO_DEVICE_ERROR) && !retry) {
3165 invalidate_cm_connection(domain);
3166 TALLOC_FREE(conn->lsa_pipe);
3167 retry = true;
3168 goto retry;
3171 if (NT_STATUS_IS_OK(result)) {
3172 goto done;
3175 DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
3176 "anonymous\n"));
3178 TALLOC_FREE(conn->lsa_pipe);
3180 anonymous:
3182 if (lp_winbind_sealed_pipes() || lp_require_strong_key()) {
3183 result = NT_STATUS_DOWNGRADE_DETECTED;
3184 DEBUG(1, ("Unwilling to make LSA connection to domain %s "
3185 "without connection level security, "
3186 "must set 'winbind sealed pipes = false' and "
3187 "'require strong key = false' to proceed: %s\n",
3188 domain->name, nt_errstr(result)));
3189 goto done;
3192 result = cli_rpc_pipe_open_noauth(conn->cli,
3193 &ndr_table_lsarpc,
3194 &conn->lsa_pipe);
3196 if (NT_STATUS_EQUAL(result, NT_STATUS_NETWORK_SESSION_EXPIRED)
3197 && !retry) {
3198 invalidate_cm_connection(domain);
3199 retry = true;
3200 goto retry;
3203 if (!NT_STATUS_IS_OK(result)) {
3204 goto done;
3207 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
3208 SEC_FLAG_MAXIMUM_ALLOWED,
3209 &conn->lsa_policy);
3211 if (NT_STATUS_EQUAL(result, NT_STATUS_IO_DEVICE_ERROR) && !retry) {
3212 invalidate_cm_connection(domain);
3213 TALLOC_FREE(conn->lsa_pipe);
3214 retry = true;
3215 goto retry;
3218 done:
3219 if (!NT_STATUS_IS_OK(result)) {
3220 invalidate_cm_connection(domain);
3221 return result;
3224 *cli = conn->lsa_pipe;
3225 *lsa_policy = conn->lsa_policy;
3226 return result;
3229 /****************************************************************************
3230 Open a LSA connection to a DC, suiteable for LSA lookup calls.
3231 ****************************************************************************/
3233 NTSTATUS cm_connect_lsat(struct winbindd_domain *domain,
3234 TALLOC_CTX *mem_ctx,
3235 struct rpc_pipe_client **cli,
3236 struct policy_handle *lsa_policy)
3238 NTSTATUS status;
3240 if (domain->can_do_ncacn_ip_tcp) {
3241 status = cm_connect_lsa_tcp(domain, mem_ctx, cli);
3242 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED) ||
3243 NT_STATUS_EQUAL(status, NT_STATUS_RPC_SEC_PKG_ERROR) ||
3244 NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_ACCESS_DENIED)) {
3245 invalidate_cm_connection(domain);
3246 status = cm_connect_lsa_tcp(domain, mem_ctx, cli);
3248 if (NT_STATUS_IS_OK(status)) {
3249 return status;
3253 * we tried twice to connect via ncan_ip_tcp and schannel and
3254 * failed - maybe it is a trusted domain we can't connect to ?
3255 * do not try tcp next time - gd
3257 * This also prevents NETLOGON over TCP
3259 domain->can_do_ncacn_ip_tcp = false;
3262 status = cm_connect_lsa(domain, mem_ctx, cli, lsa_policy);
3264 return status;
3267 /****************************************************************************
3268 Open the netlogon pipe to this DC. Use schannel if specified in client conf.
3269 session key stored in conn->netlogon_pipe->dc->sess_key.
3270 ****************************************************************************/
3272 static NTSTATUS cm_connect_netlogon_transport(struct winbindd_domain *domain,
3273 enum dcerpc_transport_t transport,
3274 struct rpc_pipe_client **cli)
3276 struct messaging_context *msg_ctx = winbind_messaging_context();
3277 struct winbindd_cm_conn *conn;
3278 NTSTATUS result;
3279 enum netr_SchannelType sec_chan_type;
3280 struct netlogon_creds_CredentialState *netlogon_creds = NULL;
3281 struct cli_credentials *creds = NULL;
3283 *cli = NULL;
3285 result = init_dc_connection_rpc(domain, domain->rodc);
3286 if (!NT_STATUS_IS_OK(result)) {
3287 return result;
3290 conn = &domain->conn;
3292 if (rpccli_is_connected(conn->netlogon_pipe)) {
3293 *cli = conn->netlogon_pipe;
3294 return NT_STATUS_OK;
3297 TALLOC_FREE(conn->netlogon_pipe);
3298 conn->netlogon_flags = 0;
3299 TALLOC_FREE(conn->netlogon_creds);
3301 result = get_trust_credentials(domain, talloc_tos(), true, &creds);
3302 if (!NT_STATUS_IS_OK(result)) {
3303 DEBUG(10, ("cm_connect_sam: No user available for "
3304 "domain %s when trying schannel\n", domain->name));
3305 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3308 if (cli_credentials_is_anonymous(creds)) {
3309 DEBUG(1, ("get_trust_credential only gave anonymous for %s, unable to make get NETLOGON credentials\n",
3310 domain->name));
3311 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3314 sec_chan_type = cli_credentials_get_secure_channel_type(creds);
3315 if (sec_chan_type == SEC_CHAN_NULL) {
3316 if (transport == NCACN_IP_TCP) {
3317 DBG_NOTICE("get_secure_channel_type gave SEC_CHAN_NULL for %s, "
3318 " deny NCACN_IP_TCP and let the caller fallback to NCACN_NP.\n",
3319 domain->name);
3320 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3323 DBG_NOTICE("get_secure_channel_type gave SEC_CHAN_NULL for %s, "
3324 "fallback to noauth on NCACN_NP.\n",
3325 domain->name);
3327 result = cli_rpc_pipe_open_noauth_transport(conn->cli,
3328 transport,
3329 &ndr_table_netlogon,
3330 &conn->netlogon_pipe);
3331 if (!NT_STATUS_IS_OK(result)) {
3332 invalidate_cm_connection(domain);
3333 return result;
3336 *cli = conn->netlogon_pipe;
3337 return NT_STATUS_OK;
3340 result = rpccli_create_netlogon_creds_with_creds(creds,
3341 domain->dcname,
3342 msg_ctx,
3343 domain,
3344 &conn->netlogon_creds);
3345 if (!NT_STATUS_IS_OK(result)) {
3346 DEBUG(1, ("rpccli_create_netlogon_creds failed for %s, "
3347 "unable to create NETLOGON credentials: %s\n",
3348 domain->name, nt_errstr(result)));
3349 return result;
3352 result = rpccli_setup_netlogon_creds_with_creds(conn->cli, transport,
3353 conn->netlogon_creds,
3354 conn->netlogon_force_reauth,
3355 creds);
3356 conn->netlogon_force_reauth = false;
3357 if (!NT_STATUS_IS_OK(result)) {
3358 DEBUG(1, ("rpccli_setup_netlogon_creds failed for %s, "
3359 "unable to setup NETLOGON credentials: %s\n",
3360 domain->name, nt_errstr(result)));
3361 return result;
3364 result = netlogon_creds_cli_get(conn->netlogon_creds,
3365 talloc_tos(),
3366 &netlogon_creds);
3367 if (!NT_STATUS_IS_OK(result)) {
3368 DEBUG(1, ("netlogon_creds_cli_get failed for %s, "
3369 "unable to get NETLOGON credentials: %s\n",
3370 domain->name, nt_errstr(result)));
3371 return result;
3373 conn->netlogon_flags = netlogon_creds->negotiate_flags;
3374 TALLOC_FREE(netlogon_creds);
3376 if (!(conn->netlogon_flags & NETLOGON_NEG_AUTHENTICATED_RPC)) {
3377 if (lp_winbind_sealed_pipes() || lp_require_strong_key()) {
3378 result = NT_STATUS_DOWNGRADE_DETECTED;
3379 DEBUG(1, ("Unwilling to make connection to domain %s"
3380 "without connection level security, "
3381 "must set 'winbind sealed pipes = false' and "
3382 "'require strong key = false' to proceed: %s\n",
3383 domain->name, nt_errstr(result)));
3384 invalidate_cm_connection(domain);
3385 return result;
3387 result = cli_rpc_pipe_open_noauth_transport(conn->cli,
3388 transport,
3389 &ndr_table_netlogon,
3390 &conn->netlogon_pipe);
3391 if (!NT_STATUS_IS_OK(result)) {
3392 invalidate_cm_connection(domain);
3393 return result;
3396 *cli = conn->netlogon_pipe;
3397 return NT_STATUS_OK;
3400 /* Using the credentials from the first pipe, open a signed and sealed
3401 second netlogon pipe. The session key is stored in the schannel
3402 part of the new pipe auth struct.
3405 result = cli_rpc_pipe_open_schannel_with_creds(
3406 conn->cli, &ndr_table_netlogon, transport,
3407 creds,
3408 conn->netlogon_creds,
3409 &conn->netlogon_pipe);
3410 if (!NT_STATUS_IS_OK(result)) {
3411 DEBUG(3, ("Could not open schannel'ed NETLOGON pipe. Error "
3412 "was %s\n", nt_errstr(result)));
3414 invalidate_cm_connection(domain);
3415 return result;
3418 *cli = conn->netlogon_pipe;
3419 return NT_STATUS_OK;
3422 /****************************************************************************
3423 Open a LSA connection to a DC, suiteable for LSA lookup calls.
3424 ****************************************************************************/
3426 NTSTATUS cm_connect_netlogon(struct winbindd_domain *domain,
3427 struct rpc_pipe_client **cli)
3429 NTSTATUS status;
3431 status = init_dc_connection_rpc(domain, domain->rodc);
3432 if (!NT_STATUS_IS_OK(status)) {
3433 return status;
3436 if (domain->active_directory && domain->can_do_ncacn_ip_tcp) {
3437 status = cm_connect_netlogon_transport(domain, NCACN_IP_TCP, cli);
3438 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED) ||
3439 NT_STATUS_EQUAL(status, NT_STATUS_RPC_SEC_PKG_ERROR) ||
3440 NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_ACCESS_DENIED)) {
3441 invalidate_cm_connection(domain);
3442 status = cm_connect_netlogon_transport(domain, NCACN_IP_TCP, cli);
3444 if (NT_STATUS_IS_OK(status)) {
3445 return status;
3449 * we tried twice to connect via ncan_ip_tcp and schannel and
3450 * failed - maybe it is a trusted domain we can't connect to ?
3451 * do not try tcp next time - gd
3453 * This also prevents LSA over TCP
3455 domain->can_do_ncacn_ip_tcp = false;
3458 status = cm_connect_netlogon_transport(domain, NCACN_NP, cli);
3459 if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_SESSION_EXPIRED)) {
3461 * SMB2 session expired, needs reauthentication. Drop
3462 * connection and retry.
3464 invalidate_cm_connection(domain);
3465 status = cm_connect_netlogon_transport(domain, NCACN_NP, cli);
3468 return status;
3471 void winbind_msg_ip_dropped(struct messaging_context *msg_ctx,
3472 void *private_data,
3473 uint32_t msg_type,
3474 struct server_id server_id,
3475 DATA_BLOB *data)
3477 struct winbindd_domain *domain;
3478 char *freeit = NULL;
3479 char *addr;
3481 if ((data == NULL)
3482 || (data->data == NULL)
3483 || (data->length == 0)
3484 || (data->data[data->length-1] != '\0')) {
3485 DEBUG(1, ("invalid msg_ip_dropped message: not a valid "
3486 "string\n"));
3487 return;
3490 addr = (char *)data->data;
3491 DEBUG(10, ("IP %s dropped\n", addr));
3493 if (!is_ipaddress(addr)) {
3494 char *slash;
3496 * Some code sends us ip addresses with the /netmask
3497 * suffix
3499 slash = strchr(addr, '/');
3500 if (slash == NULL) {
3501 DEBUG(1, ("invalid msg_ip_dropped message: %s",
3502 addr));
3503 return;
3505 freeit = talloc_strndup(talloc_tos(), addr, slash-addr);
3506 if (freeit == NULL) {
3507 DEBUG(1, ("talloc failed\n"));
3508 return;
3510 addr = freeit;
3511 DEBUG(10, ("Stripped /netmask to IP %s\n", addr));
3514 for (domain = domain_list(); domain != NULL; domain = domain->next) {
3515 char sockaddr[INET6_ADDRSTRLEN];
3517 if (!cli_state_is_connected(domain->conn.cli)) {
3518 continue;
3521 print_sockaddr(sockaddr, sizeof(sockaddr),
3522 smbXcli_conn_local_sockaddr(domain->conn.cli->conn));
3524 if (strequal(sockaddr, addr)) {
3525 smbXcli_conn_disconnect(domain->conn.cli->conn, NT_STATUS_OK);
3528 TALLOC_FREE(freeit);