s4:nbt_server: avoid str_list related const warning
[Samba.git] / source3 / winbindd / winbindd_cm.c
blob52e3fa1b362d38d712b92ea07e2a2e042452cfd4
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 *)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 *)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;
906 /* If we are a DC and this is not our own domain */
908 if (IS_DC && netlogon) {
909 creds_domain = domain;
910 } else {
911 creds_domain = find_our_domain();
912 if (creds_domain == NULL) {
913 return NT_STATUS_INVALID_SERVER_STATE;
917 status = pdb_get_trust_credentials(creds_domain->name,
918 creds_domain->alt_name,
919 mem_ctx,
920 &creds);
921 if (!NT_STATUS_IS_OK(status)) {
922 goto ipc_fallback;
925 if (lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC) {
926 cli_credentials_set_kerberos_state(creds,
927 CRED_MUST_USE_KERBEROS);
930 if (domain->primary && lp_security() == SEC_ADS) {
931 cli_credentials_set_kerberos_state(creds,
932 CRED_AUTO_USE_KERBEROS);
933 } else if (!domain->active_directory) {
934 cli_credentials_set_kerberos_state(creds,
935 CRED_DONT_USE_KERBEROS);
938 if (creds_domain != domain) {
940 * We can only use schannel against a direct trust
942 cli_credentials_set_secure_channel_type(creds,
943 SEC_CHAN_NULL);
946 *_creds = creds;
947 return NT_STATUS_OK;
949 ipc_fallback:
950 if (netlogon) {
951 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
954 status = cm_get_ipc_credentials(mem_ctx, &creds);
955 if (!NT_STATUS_IS_OK(status)) {
956 return status;
959 *_creds = creds;
960 return NT_STATUS_OK;
963 /************************************************************************
964 Given a fd with a just-connected TCP connection to a DC, open a connection
965 to the pipe.
966 ************************************************************************/
968 static NTSTATUS cm_prepare_connection(struct winbindd_domain *domain,
969 const int sockfd,
970 const char *controller,
971 struct cli_state **cli,
972 bool *retry)
974 bool try_ipc_auth = false;
975 const char *machine_password = NULL;
976 const char *machine_krb5_principal = NULL;
977 const char *machine_account = NULL;
978 const char *machine_domain = NULL;
979 int flags = 0;
980 struct cli_credentials *creds = NULL;
981 enum credentials_use_kerberos krb5_state;
983 struct named_mutex *mutex;
985 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
987 enum smb_signing_setting smb_sign_client_connections = lp_client_signing();
989 if (smb_sign_client_connections == SMB_SIGNING_DEFAULT) {
991 * If we are connecting to our own AD domain, require
992 * smb signing to disrupt MITM attacks
994 if (domain->primary && lp_security() == SEC_ADS) {
995 smb_sign_client_connections = SMB_SIGNING_REQUIRED;
997 * If we are in or are an AD domain and connecting to another
998 * AD domain in our forest
999 * then require smb signing to disrupt MITM attacks
1001 } else if ((lp_security() == SEC_ADS ||
1002 lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC)
1003 && domain->active_directory
1004 && (domain->domain_trust_attribs
1005 & LSA_TRUST_ATTRIBUTE_WITHIN_FOREST)) {
1006 smb_sign_client_connections = SMB_SIGNING_REQUIRED;
1010 DEBUG(10,("cm_prepare_connection: connecting to DC %s for domain %s\n",
1011 controller, domain->name ));
1013 *retry = True;
1015 mutex = grab_named_mutex(talloc_tos(), controller,
1016 WINBIND_SERVER_MUTEX_WAIT_TIME);
1017 if (mutex == NULL) {
1018 close(sockfd);
1019 DEBUG(0,("cm_prepare_connection: mutex grab failed for %s\n",
1020 controller));
1021 result = NT_STATUS_POSSIBLE_DEADLOCK;
1022 goto done;
1025 flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
1027 *cli = cli_state_create(NULL, sockfd,
1028 controller, domain->alt_name,
1029 smb_sign_client_connections, flags);
1030 if (*cli == NULL) {
1031 close(sockfd);
1032 DEBUG(1, ("Could not cli_initialize\n"));
1033 result = NT_STATUS_NO_MEMORY;
1034 goto done;
1037 cli_set_timeout(*cli, 10000); /* 10 seconds */
1039 result = smbXcli_negprot((*cli)->conn, (*cli)->timeout,
1040 lp_client_min_protocol(),
1041 lp_winbindd_max_protocol());
1043 if (!NT_STATUS_IS_OK(result)) {
1044 DEBUG(1, ("cli_negprot failed: %s\n", nt_errstr(result)));
1045 goto done;
1048 if (smbXcli_conn_protocol((*cli)->conn) >= PROTOCOL_NT1 &&
1049 smb1cli_conn_capabilities((*cli)->conn) & CAP_EXTENDED_SECURITY) {
1050 try_ipc_auth = true;
1051 } else if (smbXcli_conn_protocol((*cli)->conn) >= PROTOCOL_SMB2_02) {
1052 try_ipc_auth = true;
1053 } else if (smb_sign_client_connections == SMB_SIGNING_REQUIRED) {
1055 * If we are forcing on SMB signing, then we must
1056 * require authentication unless this is a one-way
1057 * trust, and we have no stored user/password
1059 try_ipc_auth = true;
1062 if (try_ipc_auth) {
1063 result = get_trust_credentials(domain, talloc_tos(), false, &creds);
1064 if (!NT_STATUS_IS_OK(result)) {
1065 DEBUG(1, ("get_trust_credentials(%s) failed: %s\n",
1066 domain->name, nt_errstr(result)));
1067 goto done;
1069 } else {
1071 * Without SPNEGO or NTLMSSP (perhaps via SMB2) we
1072 * would try and authentication with our machine
1073 * account password and fail. This is very rare in
1074 * the modern world however
1076 creds = cli_credentials_init_anon(talloc_tos());
1077 if (creds == NULL) {
1078 result = NT_STATUS_NO_MEMORY;
1079 DEBUG(1, ("cli_credentials_init_anon(%s) failed: %s\n",
1080 domain->name, nt_errstr(result)));
1081 goto done;
1085 krb5_state = cli_credentials_get_kerberos_state(creds);
1087 machine_krb5_principal = cli_credentials_get_principal(creds,
1088 talloc_tos());
1089 if (machine_krb5_principal == NULL) {
1090 krb5_state = CRED_DONT_USE_KERBEROS;
1093 machine_account = cli_credentials_get_username(creds);
1094 machine_password = cli_credentials_get_password(creds);
1095 machine_domain = cli_credentials_get_domain(creds);
1097 if (krb5_state != CRED_DONT_USE_KERBEROS) {
1099 /* Try a krb5 session */
1101 (*cli)->use_kerberos = True;
1102 DEBUG(5, ("connecting to %s from %s with kerberos principal "
1103 "[%s] and realm [%s]\n", controller, lp_netbios_name(),
1104 machine_krb5_principal, domain->alt_name));
1106 winbindd_set_locator_kdc_envs(domain);
1108 result = cli_session_setup(*cli,
1109 machine_krb5_principal,
1110 machine_password,
1111 strlen(machine_password)+1,
1112 machine_password,
1113 strlen(machine_password)+1,
1114 machine_domain);
1116 if (NT_STATUS_IS_OK(result)) {
1117 goto session_setup_done;
1120 DEBUG(4,("failed kerberos session setup with %s\n",
1121 nt_errstr(result)));
1124 if (krb5_state != CRED_MUST_USE_KERBEROS) {
1125 /* Fall back to non-kerberos session setup using NTLMSSP SPNEGO with the machine account. */
1126 (*cli)->use_kerberos = False;
1128 DEBUG(5, ("connecting to %s from %s using NTLMSSP with username "
1129 "[%s]\\[%s]\n", controller, lp_netbios_name(),
1130 machine_domain, machine_account));
1132 result = cli_session_setup(*cli,
1133 machine_account,
1134 machine_password,
1135 strlen(machine_password)+1,
1136 machine_password,
1137 strlen(machine_password)+1,
1138 machine_domain);
1141 if (NT_STATUS_IS_OK(result)) {
1142 goto session_setup_done;
1146 * If we are not going to validiate the conneciton
1147 * with SMB signing, then allow us to fall back to
1148 * anonymous
1150 if (NT_STATUS_EQUAL(result, NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT)
1151 || NT_STATUS_EQUAL(result, NT_STATUS_TRUSTED_DOMAIN_FAILURE)
1152 || NT_STATUS_EQUAL(result, NT_STATUS_LOGON_FAILURE))
1154 if (cli_credentials_is_anonymous(creds)) {
1155 goto done;
1158 if (!cm_is_ipc_credentials(creds)) {
1159 goto ipc_fallback;
1162 if (smb_sign_client_connections == SMB_SIGNING_REQUIRED) {
1163 goto done;
1166 goto anon_fallback;
1169 DEBUG(4, ("authenticated session setup failed with %s\n",
1170 nt_errstr(result)));
1172 goto done;
1174 ipc_fallback:
1175 result = cm_get_ipc_credentials(talloc_tos(), &creds);
1176 if (!NT_STATUS_IS_OK(result)) {
1177 goto done;
1180 if (cli_credentials_is_anonymous(creds)) {
1181 TALLOC_FREE(creds);
1182 goto anon_fallback;
1185 machine_account = cli_credentials_get_username(creds);
1186 machine_password = cli_credentials_get_password(creds);
1187 machine_domain = cli_credentials_get_domain(creds);
1189 /* Fall back to non-kerberos session setup using NTLMSSP SPNEGO with the ipc creds. */
1190 (*cli)->use_kerberos = False;
1192 DEBUG(5, ("connecting to %s from %s using NTLMSSP with username "
1193 "[%s]\\[%s]\n", controller, lp_netbios_name(),
1194 machine_domain, machine_account));
1196 result = cli_session_setup(*cli,
1197 machine_account,
1198 machine_password,
1199 strlen(machine_password)+1,
1200 machine_password,
1201 strlen(machine_password)+1,
1202 machine_domain);
1204 if (NT_STATUS_IS_OK(result)) {
1205 goto session_setup_done;
1209 * If we are not going to validiate the conneciton
1210 * with SMB signing, then allow us to fall back to
1211 * anonymous
1213 if (NT_STATUS_EQUAL(result, NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT)
1214 || NT_STATUS_EQUAL(result, NT_STATUS_TRUSTED_DOMAIN_FAILURE)
1215 || NT_STATUS_EQUAL(result, NT_STATUS_LOGON_FAILURE))
1217 goto anon_fallback;
1220 DEBUG(4, ("authenticated session setup failed with %s\n",
1221 nt_errstr(result)));
1223 goto done;
1225 anon_fallback:
1227 if (smb_sign_client_connections == SMB_SIGNING_REQUIRED) {
1228 goto done;
1231 creds = cli_credentials_init_anon(talloc_tos());
1232 if (creds == NULL) {
1233 result = NT_STATUS_NO_MEMORY;
1234 goto done;
1237 machine_account = cli_credentials_get_username(creds);
1238 machine_password = cli_credentials_get_password(creds);
1239 machine_domain = cli_credentials_get_domain(creds);
1241 /* Fall back to anonymous connection, this might fail later */
1242 DEBUG(10,("cm_prepare_connection: falling back to anonymous "
1243 "connection for DC %s\n",
1244 controller ));
1246 (*cli)->use_kerberos = False;
1248 result = cli_session_setup(*cli,
1249 machine_account,
1250 machine_password,
1251 strlen(machine_password)+1,
1252 machine_password,
1253 strlen(machine_password)+1,
1254 machine_domain);
1256 if (NT_STATUS_IS_OK(result)) {
1257 DEBUG(5, ("Connected anonymously\n"));
1258 goto session_setup_done;
1261 /* We can't session setup */
1262 goto done;
1264 session_setup_done:
1267 * This should be a short term hack until
1268 * dynamic re-authentication is implemented.
1270 * See Bug 9175 - winbindd doesn't recover from
1271 * NT_STATUS_NETWORK_SESSION_EXPIRED
1273 if (smbXcli_conn_protocol((*cli)->conn) >= PROTOCOL_SMB2_02) {
1274 smbXcli_session_set_disconnect_expired((*cli)->smb2.session);
1277 result = cli_tree_connect(*cli, "IPC$", "IPC", "", 0);
1279 if (!NT_STATUS_IS_OK(result)) {
1280 DEBUG(1,("failed tcon_X with %s\n", nt_errstr(result)));
1281 goto done;
1284 /* cache the server name for later connections */
1286 saf_store(domain->name, controller);
1287 if (domain->alt_name && (*cli)->use_kerberos) {
1288 saf_store(domain->alt_name, controller);
1291 winbindd_set_locator_kdc_envs(domain);
1293 TALLOC_FREE(mutex);
1294 *retry = False;
1296 result = NT_STATUS_OK;
1298 done:
1299 TALLOC_FREE(mutex);
1301 if (!NT_STATUS_IS_OK(result)) {
1302 winbind_add_failed_connection_entry(domain, controller, result);
1303 if ((*cli) != NULL) {
1304 cli_shutdown(*cli);
1305 *cli = NULL;
1309 return result;
1312 /*******************************************************************
1313 Add a dcname and sockaddr_storage pair to the end of a dc_name_ip
1314 array.
1316 Keeps the list unique by not adding duplicate entries.
1318 @param[in] mem_ctx talloc memory context to allocate from
1319 @param[in] domain_name domain of the DC
1320 @param[in] dcname name of the DC to add to the list
1321 @param[in] pss Internet address and port pair to add to the list
1322 @param[in,out] dcs array of dc_name_ip structures to add to
1323 @param[in,out] num_dcs number of dcs returned in the dcs array
1324 @return true if the list was added to, false otherwise
1325 *******************************************************************/
1327 static bool add_one_dc_unique(TALLOC_CTX *mem_ctx, const char *domain_name,
1328 const char *dcname, struct sockaddr_storage *pss,
1329 struct dc_name_ip **dcs, int *num)
1331 int i = 0;
1333 if (!NT_STATUS_IS_OK(check_negative_conn_cache(domain_name, dcname))) {
1334 DEBUG(10, ("DC %s was in the negative conn cache\n", dcname));
1335 return False;
1338 /* Make sure there's no duplicates in the list */
1339 for (i=0; i<*num; i++)
1340 if (sockaddr_equal(
1341 (struct sockaddr *)(void *)&(*dcs)[i].ss,
1342 (struct sockaddr *)(void *)pss))
1343 return False;
1345 *dcs = talloc_realloc(mem_ctx, *dcs, struct dc_name_ip, (*num)+1);
1347 if (*dcs == NULL)
1348 return False;
1350 fstrcpy((*dcs)[*num].name, dcname);
1351 (*dcs)[*num].ss = *pss;
1352 *num += 1;
1353 return True;
1356 static bool add_sockaddr_to_array(TALLOC_CTX *mem_ctx,
1357 struct sockaddr_storage *pss, uint16 port,
1358 struct sockaddr_storage **addrs, int *num)
1360 *addrs = talloc_realloc(mem_ctx, *addrs, struct sockaddr_storage, (*num)+1);
1362 if (*addrs == NULL) {
1363 *num = 0;
1364 return False;
1367 (*addrs)[*num] = *pss;
1368 set_sockaddr_port((struct sockaddr *)&(*addrs)[*num], port);
1370 *num += 1;
1371 return True;
1374 /*******************************************************************
1375 convert an ip to a name
1376 *******************************************************************/
1378 static bool dcip_to_name(TALLOC_CTX *mem_ctx,
1379 const struct winbindd_domain *domain,
1380 struct sockaddr_storage *pss,
1381 char **name)
1383 struct ip_service ip_list;
1384 uint32_t nt_version = NETLOGON_NT_VERSION_1;
1385 NTSTATUS status;
1386 const char *dc_name;
1387 fstring nbtname;
1389 ip_list.ss = *pss;
1390 ip_list.port = 0;
1392 #ifdef HAVE_ADS
1393 /* For active directory servers, try to get the ldap server name.
1394 None of these failures should be considered critical for now */
1396 if ((lp_security() == SEC_ADS) && (domain->alt_name != NULL)) {
1397 ADS_STRUCT *ads;
1398 ADS_STATUS ads_status;
1399 char addr[INET6_ADDRSTRLEN];
1401 print_sockaddr(addr, sizeof(addr), pss);
1403 ads = ads_init(domain->alt_name, domain->name, addr);
1404 ads->auth.flags |= ADS_AUTH_NO_BIND;
1406 ads_status = ads_connect(ads);
1407 if (ADS_ERR_OK(ads_status)) {
1408 /* We got a cldap packet. */
1409 *name = talloc_strdup(mem_ctx,
1410 ads->config.ldap_server_name);
1411 if (*name == NULL) {
1412 return false;
1414 namecache_store(*name, 0x20, 1, &ip_list);
1416 DEBUG(10,("dcip_to_name: flags = 0x%x\n", (unsigned int)ads->config.flags));
1418 if (domain->primary && (ads->config.flags & NBT_SERVER_KDC)) {
1419 if (ads_closest_dc(ads)) {
1420 char *sitename = sitename_fetch(mem_ctx, ads->config.realm);
1422 /* We're going to use this KDC for this realm/domain.
1423 If we are using sites, then force the krb5 libs
1424 to use this KDC. */
1426 create_local_private_krb5_conf_for_domain(domain->alt_name,
1427 domain->name,
1428 sitename,
1429 pss);
1431 TALLOC_FREE(sitename);
1432 } else {
1433 /* use an off site KDC */
1434 create_local_private_krb5_conf_for_domain(domain->alt_name,
1435 domain->name,
1436 NULL,
1437 pss);
1439 winbindd_set_locator_kdc_envs(domain);
1441 /* Ensure we contact this DC also. */
1442 saf_store(domain->name, *name);
1443 saf_store(domain->alt_name, *name);
1446 ads_destroy( &ads );
1447 return True;
1450 ads_destroy( &ads );
1451 return false;
1453 #endif
1455 status = nbt_getdc(winbind_messaging_context(), 10, pss, domain->name,
1456 &domain->sid, nt_version, mem_ctx, &nt_version,
1457 &dc_name, NULL);
1458 if (NT_STATUS_IS_OK(status)) {
1459 *name = talloc_strdup(mem_ctx, dc_name);
1460 if (*name == NULL) {
1461 return false;
1463 namecache_store(*name, 0x20, 1, &ip_list);
1464 return True;
1467 /* try node status request */
1469 if (name_status_find(domain->name, 0x1c, 0x20, pss, nbtname) ) {
1470 namecache_store(nbtname, 0x20, 1, &ip_list);
1472 if (name != NULL) {
1473 *name = talloc_strdup(mem_ctx, nbtname);
1474 if (*name == NULL) {
1475 return false;
1479 return true;
1481 return False;
1484 /*******************************************************************
1485 Retrieve a list of IP addresses for domain controllers.
1487 The array is sorted in the preferred connection order.
1489 @param[in] mem_ctx talloc memory context to allocate from
1490 @param[in] domain domain to retrieve DCs for
1491 @param[out] dcs array of dcs that will be returned
1492 @param[out] num_dcs number of dcs returned in the dcs array
1493 @return always true
1494 *******************************************************************/
1496 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
1497 struct dc_name_ip **dcs, int *num_dcs)
1499 fstring dcname;
1500 struct sockaddr_storage ss;
1501 struct ip_service *ip_list = NULL;
1502 int iplist_size = 0;
1503 int i;
1504 bool is_our_domain;
1505 enum security_types sec = (enum security_types)lp_security();
1507 is_our_domain = strequal(domain->name, lp_workgroup());
1509 /* If not our domain, get the preferred DC, by asking our primary DC */
1510 if ( !is_our_domain
1511 && get_dc_name_via_netlogon(domain, dcname, &ss)
1512 && add_one_dc_unique(mem_ctx, domain->name, dcname, &ss, dcs,
1513 num_dcs) )
1515 char addr[INET6_ADDRSTRLEN];
1516 print_sockaddr(addr, sizeof(addr), &ss);
1517 DEBUG(10, ("Retrieved DC %s at %s via netlogon\n",
1518 dcname, addr));
1519 return True;
1522 if ((sec == SEC_ADS) && (domain->alt_name != NULL)) {
1523 char *sitename = NULL;
1525 /* We need to make sure we know the local site before
1526 doing any DNS queries, as this will restrict the
1527 get_sorted_dc_list() call below to only fetching
1528 DNS records for the correct site. */
1530 /* Find any DC to get the site record.
1531 We deliberately don't care about the
1532 return here. */
1534 get_dc_name(domain->name, domain->alt_name, dcname, &ss);
1536 sitename = sitename_fetch(mem_ctx, domain->alt_name);
1537 if (sitename) {
1539 /* Do the site-specific AD dns lookup first. */
1540 get_sorted_dc_list(domain->alt_name, sitename, &ip_list,
1541 &iplist_size, True);
1543 /* Add ips to the DC array. We don't look up the name
1544 of the DC in this function, but we fill in the char*
1545 of the ip now to make the failed connection cache
1546 work */
1547 for ( i=0; i<iplist_size; i++ ) {
1548 char addr[INET6_ADDRSTRLEN];
1549 print_sockaddr(addr, sizeof(addr),
1550 &ip_list[i].ss);
1551 add_one_dc_unique(mem_ctx,
1552 domain->name,
1553 addr,
1554 &ip_list[i].ss,
1555 dcs,
1556 num_dcs);
1559 SAFE_FREE(ip_list);
1560 TALLOC_FREE(sitename);
1561 iplist_size = 0;
1564 /* Now we add DCs from the main AD DNS lookup. */
1565 get_sorted_dc_list(domain->alt_name, NULL, &ip_list,
1566 &iplist_size, True);
1568 for ( i=0; i<iplist_size; i++ ) {
1569 char addr[INET6_ADDRSTRLEN];
1570 print_sockaddr(addr, sizeof(addr),
1571 &ip_list[i].ss);
1572 add_one_dc_unique(mem_ctx,
1573 domain->name,
1574 addr,
1575 &ip_list[i].ss,
1576 dcs,
1577 num_dcs);
1580 SAFE_FREE(ip_list);
1581 iplist_size = 0;
1584 /* Try standard netbios queries if no ADS and fall back to DNS queries
1585 * if alt_name is available */
1586 if (*num_dcs == 0) {
1587 get_sorted_dc_list(domain->name, NULL, &ip_list, &iplist_size,
1588 false);
1589 if (iplist_size == 0) {
1590 if (domain->alt_name != NULL) {
1591 get_sorted_dc_list(domain->alt_name, NULL, &ip_list,
1592 &iplist_size, true);
1596 for ( i=0; i<iplist_size; i++ ) {
1597 char addr[INET6_ADDRSTRLEN];
1598 print_sockaddr(addr, sizeof(addr),
1599 &ip_list[i].ss);
1600 add_one_dc_unique(mem_ctx,
1601 domain->name,
1602 addr,
1603 &ip_list[i].ss,
1604 dcs,
1605 num_dcs);
1608 SAFE_FREE(ip_list);
1609 iplist_size = 0;
1612 return True;
1615 /*******************************************************************
1616 Find and make a connection to a DC in the given domain.
1618 @param[in] mem_ctx talloc memory context to allocate from
1619 @param[in] domain domain to find a dc in
1620 @param[out] dcname NetBIOS or FQDN of DC that's connected to
1621 @param[out] pss DC Internet address and port
1622 @param[out] fd fd of the open socket connected to the newly found dc
1623 @return true when a DC connection is made, false otherwise
1624 *******************************************************************/
1626 static bool find_new_dc(TALLOC_CTX *mem_ctx,
1627 struct winbindd_domain *domain,
1628 char **dcname, struct sockaddr_storage *pss, int *fd)
1630 struct dc_name_ip *dcs = NULL;
1631 int num_dcs = 0;
1633 const char **dcnames = NULL;
1634 size_t num_dcnames = 0;
1636 struct sockaddr_storage *addrs = NULL;
1637 int num_addrs = 0;
1639 int i;
1640 size_t fd_index;
1642 NTSTATUS status;
1644 *fd = -1;
1646 again:
1647 if (!get_dcs(mem_ctx, domain, &dcs, &num_dcs) || (num_dcs == 0))
1648 return False;
1650 for (i=0; i<num_dcs; i++) {
1652 if (!add_string_to_array(mem_ctx, dcs[i].name,
1653 &dcnames, &num_dcnames)) {
1654 return False;
1656 if (!add_sockaddr_to_array(mem_ctx, &dcs[i].ss, TCP_SMB_PORT,
1657 &addrs, &num_addrs)) {
1658 return False;
1662 if ((num_dcnames == 0) || (num_dcnames != num_addrs))
1663 return False;
1665 if ((addrs == NULL) || (dcnames == NULL))
1666 return False;
1668 status = smbsock_any_connect(addrs, dcnames, NULL, NULL, NULL,
1669 num_addrs, 0, 10, fd, &fd_index, NULL);
1670 if (!NT_STATUS_IS_OK(status)) {
1671 for (i=0; i<num_dcs; i++) {
1672 char ab[INET6_ADDRSTRLEN];
1673 print_sockaddr(ab, sizeof(ab), &dcs[i].ss);
1674 DEBUG(10, ("find_new_dc: smbsock_any_connect failed for "
1675 "domain %s address %s. Error was %s\n",
1676 domain->name, ab, nt_errstr(status) ));
1677 winbind_add_failed_connection_entry(domain,
1678 dcs[i].name, NT_STATUS_UNSUCCESSFUL);
1680 return False;
1683 *pss = addrs[fd_index];
1685 if (*dcnames[fd_index] != '\0' && !is_ipaddress(dcnames[fd_index])) {
1686 /* Ok, we've got a name for the DC */
1687 *dcname = talloc_strdup(mem_ctx, dcnames[fd_index]);
1688 if (*dcname == NULL) {
1689 return false;
1691 return true;
1694 /* Try to figure out the name */
1695 if (dcip_to_name(mem_ctx, domain, pss, dcname)) {
1696 return True;
1699 /* We can not continue without the DC's name */
1700 winbind_add_failed_connection_entry(domain, dcs[fd_index].name,
1701 NT_STATUS_UNSUCCESSFUL);
1703 /* Throw away all arrays as we're doing this again. */
1704 TALLOC_FREE(dcs);
1705 num_dcs = 0;
1707 TALLOC_FREE(dcnames);
1708 num_dcnames = 0;
1710 TALLOC_FREE(addrs);
1711 num_addrs = 0;
1713 close(*fd);
1714 *fd = -1;
1716 goto again;
1719 static char *current_dc_key(TALLOC_CTX *mem_ctx, const char *domain_name)
1721 return talloc_asprintf_strupper_m(mem_ctx, "CURRENT_DCNAME/%s",
1722 domain_name);
1725 static void store_current_dc_in_gencache(const char *domain_name,
1726 const char *dc_name,
1727 struct cli_state *cli)
1729 char addr[INET6_ADDRSTRLEN];
1730 char *key = NULL;
1731 char *value = NULL;
1733 if (!cli_state_is_connected(cli)) {
1734 return;
1737 print_sockaddr(addr, sizeof(addr),
1738 smbXcli_conn_remote_sockaddr(cli->conn));
1740 key = current_dc_key(talloc_tos(), domain_name);
1741 if (key == NULL) {
1742 goto done;
1745 value = talloc_asprintf(talloc_tos(), "%s %s", addr, dc_name);
1746 if (value == NULL) {
1747 goto done;
1750 gencache_set(key, value, 0x7fffffff);
1751 done:
1752 TALLOC_FREE(value);
1753 TALLOC_FREE(key);
1756 bool fetch_current_dc_from_gencache(TALLOC_CTX *mem_ctx,
1757 const char *domain_name,
1758 char **p_dc_name, char **p_dc_ip)
1760 char *key, *p;
1761 char *value = NULL;
1762 bool ret = false;
1763 char *dc_name = NULL;
1764 char *dc_ip = NULL;
1766 key = current_dc_key(talloc_tos(), domain_name);
1767 if (key == NULL) {
1768 goto done;
1770 if (!gencache_get(key, mem_ctx, &value, NULL)) {
1771 goto done;
1773 p = strchr(value, ' ');
1774 if (p == NULL) {
1775 goto done;
1777 dc_ip = talloc_strndup(mem_ctx, value, p - value);
1778 if (dc_ip == NULL) {
1779 goto done;
1781 dc_name = talloc_strdup(mem_ctx, p+1);
1782 if (dc_name == NULL) {
1783 goto done;
1786 if (p_dc_ip != NULL) {
1787 *p_dc_ip = dc_ip;
1788 dc_ip = NULL;
1790 if (p_dc_name != NULL) {
1791 *p_dc_name = dc_name;
1792 dc_name = NULL;
1794 ret = true;
1795 done:
1796 TALLOC_FREE(dc_name);
1797 TALLOC_FREE(dc_ip);
1798 TALLOC_FREE(key);
1799 TALLOC_FREE(value);
1800 return ret;
1803 NTSTATUS wb_open_internal_pipe(TALLOC_CTX *mem_ctx,
1804 const struct ndr_interface_table *table,
1805 struct rpc_pipe_client **ret_pipe)
1807 struct rpc_pipe_client *cli = NULL;
1808 const struct auth_session_info *session_info;
1809 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1812 session_info = get_session_info_system();
1813 SMB_ASSERT(session_info != NULL);
1815 /* create a connection to the specified pipe */
1816 if (lp_parm_bool(-1, "winbindd", "use external pipes", false)) {
1817 status = rpc_pipe_open_interface(mem_ctx,
1818 table,
1819 session_info,
1820 NULL,
1821 winbind_messaging_context(),
1822 &cli);
1823 } else {
1824 status = rpc_pipe_open_internal(mem_ctx,
1825 &table->syntax_id,
1826 session_info,
1827 NULL,
1828 winbind_messaging_context(),
1829 &cli);
1831 if (!NT_STATUS_IS_OK(status)) {
1832 DEBUG(0, ("open_internal_pipe: Could not connect to %s pipe: %s\n",
1833 table->name, nt_errstr(status)));
1834 return status;
1837 if (ret_pipe) {
1838 *ret_pipe = cli;
1841 return NT_STATUS_OK;
1844 static NTSTATUS cm_open_connection(struct winbindd_domain *domain,
1845 struct winbindd_cm_conn *new_conn)
1847 TALLOC_CTX *mem_ctx;
1848 NTSTATUS result;
1849 char *saf_servername;
1850 int retries;
1852 if ((mem_ctx = talloc_init("cm_open_connection")) == NULL) {
1853 set_domain_offline(domain);
1854 return NT_STATUS_NO_MEMORY;
1857 saf_servername = saf_fetch(mem_ctx, domain->name );
1859 /* we have to check the server affinity cache here since
1860 later we select a DC based on response time and not preference */
1862 /* Check the negative connection cache
1863 before talking to it. It going down may have
1864 triggered the reconnection. */
1866 if ( saf_servername && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, saf_servername))) {
1868 DEBUG(10,("cm_open_connection: saf_servername is '%s' for domain %s\n",
1869 saf_servername, domain->name ));
1871 /* convert an ip address to a name */
1872 if (is_ipaddress( saf_servername ) ) {
1873 char *dcname = NULL;
1874 struct sockaddr_storage ss;
1876 if (!interpret_string_addr(&ss, saf_servername,
1877 AI_NUMERICHOST)) {
1878 TALLOC_FREE(mem_ctx);
1879 return NT_STATUS_UNSUCCESSFUL;
1881 if (dcip_to_name(mem_ctx, domain, &ss, &dcname)) {
1882 domain->dcname = talloc_strdup(domain,
1883 dcname);
1884 if (domain->dcname == NULL) {
1885 TALLOC_FREE(mem_ctx);
1886 return NT_STATUS_NO_MEMORY;
1888 } else {
1889 winbind_add_failed_connection_entry(
1890 domain, saf_servername,
1891 NT_STATUS_UNSUCCESSFUL);
1893 } else {
1894 domain->dcname = talloc_strdup(domain, saf_servername);
1895 if (domain->dcname == NULL) {
1896 TALLOC_FREE(mem_ctx);
1897 return NT_STATUS_NO_MEMORY;
1902 for (retries = 0; retries < 3; retries++) {
1903 int fd = -1;
1904 bool retry = False;
1905 char *dcname = NULL;
1907 result = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1909 DEBUG(10,("cm_open_connection: dcname is '%s' for domain %s\n",
1910 domain->dcname ? domain->dcname : "", domain->name ));
1912 if (domain->dcname != NULL
1913 && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, domain->dcname))
1914 && (resolve_name(domain->dcname, &domain->dcaddr, 0x20, true)))
1916 NTSTATUS status;
1918 status = smbsock_connect(&domain->dcaddr, 0,
1919 NULL, -1, NULL, -1,
1920 &fd, NULL, 10);
1921 if (!NT_STATUS_IS_OK(status)) {
1922 fd = -1;
1926 if ((fd == -1) &&
1927 !find_new_dc(mem_ctx, domain, &dcname, &domain->dcaddr, &fd))
1929 /* This is the one place where we will
1930 set the global winbindd offline state
1931 to true, if a "WINBINDD_OFFLINE" entry
1932 is found in the winbindd cache. */
1933 set_global_winbindd_state_offline();
1934 break;
1936 if (dcname != NULL) {
1937 talloc_free(domain->dcname);
1939 domain->dcname = talloc_move(domain, &dcname);
1940 if (domain->dcname == NULL) {
1941 result = NT_STATUS_NO_MEMORY;
1942 break;
1946 new_conn->cli = NULL;
1948 result = cm_prepare_connection(domain, fd, domain->dcname,
1949 &new_conn->cli, &retry);
1950 if (!NT_STATUS_IS_OK(result)) {
1951 /* Don't leak the smb connection socket */
1952 close(fd);
1955 if (!retry)
1956 break;
1959 if (NT_STATUS_IS_OK(result)) {
1960 bool seal_pipes = true;
1962 winbindd_set_locator_kdc_envs(domain);
1964 if (domain->online == False) {
1965 /* We're changing state from offline to online. */
1966 set_global_winbindd_state_online();
1968 set_domain_online(domain);
1971 * Much as I hate global state, this seems to be the point
1972 * where we can be certain that we have a proper connection to
1973 * a DC. wbinfo --dc-info needs that information, store it in
1974 * gencache with a looong timeout. This will need revisiting
1975 * once we start to connect to multiple DCs, wbcDcInfo is
1976 * already prepared for that.
1978 store_current_dc_in_gencache(domain->name, domain->dcname,
1979 new_conn->cli);
1981 seal_pipes = lp_winbind_sealed_pipes();
1982 seal_pipes = lp_parm_bool(-1, "winbind sealed pipes",
1983 domain->name,
1984 seal_pipes);
1986 if (seal_pipes) {
1987 new_conn->auth_level = DCERPC_AUTH_LEVEL_PRIVACY;
1988 } else {
1989 new_conn->auth_level = DCERPC_AUTH_LEVEL_INTEGRITY;
1991 } else {
1992 /* Ensure we setup the retry handler. */
1993 set_domain_offline(domain);
1996 talloc_destroy(mem_ctx);
1997 return result;
2000 /* Close down all open pipes on a connection. */
2002 void invalidate_cm_connection(struct winbindd_domain *domain)
2004 NTSTATUS result;
2005 struct winbindd_cm_conn *conn = &domain->conn;
2007 /* We're closing down a possibly dead
2008 connection. Don't have impossibly long (10s) timeouts. */
2010 if (conn->cli) {
2011 cli_set_timeout(conn->cli, 1000); /* 1 second. */
2014 if (conn->samr_pipe != NULL) {
2015 if (is_valid_policy_hnd(&conn->sam_connect_handle)) {
2016 dcerpc_samr_Close(conn->samr_pipe->binding_handle,
2017 talloc_tos(),
2018 &conn->sam_connect_handle,
2019 &result);
2021 TALLOC_FREE(conn->samr_pipe);
2022 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
2023 if (conn->cli) {
2024 cli_set_timeout(conn->cli, 500);
2028 if (conn->lsa_pipe != NULL) {
2029 if (is_valid_policy_hnd(&conn->lsa_policy)) {
2030 dcerpc_lsa_Close(conn->lsa_pipe->binding_handle,
2031 talloc_tos(),
2032 &conn->lsa_policy,
2033 &result);
2035 TALLOC_FREE(conn->lsa_pipe);
2036 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
2037 if (conn->cli) {
2038 cli_set_timeout(conn->cli, 500);
2042 if (conn->lsa_pipe_tcp != NULL) {
2043 if (is_valid_policy_hnd(&conn->lsa_policy)) {
2044 dcerpc_lsa_Close(conn->lsa_pipe_tcp->binding_handle,
2045 talloc_tos(),
2046 &conn->lsa_policy,
2047 &result);
2049 TALLOC_FREE(conn->lsa_pipe_tcp);
2050 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
2051 if (conn->cli) {
2052 cli_set_timeout(conn->cli, 500);
2056 if (conn->netlogon_pipe != NULL) {
2057 TALLOC_FREE(conn->netlogon_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 conn->auth_level = DCERPC_AUTH_LEVEL_PRIVACY;
2065 conn->netlogon_force_reauth = false;
2066 conn->netlogon_flags = 0;
2067 TALLOC_FREE(conn->netlogon_creds);
2069 if (conn->cli) {
2070 cli_shutdown(conn->cli);
2073 conn->cli = NULL;
2076 void close_conns_after_fork(void)
2078 struct winbindd_domain *domain;
2079 struct winbindd_cli_state *cli_state;
2081 for (domain = domain_list(); domain; domain = domain->next) {
2083 * first close the low level SMB TCP connection
2084 * so that we don't generate any SMBclose
2085 * requests in invalidate_cm_connection()
2087 if (cli_state_is_connected(domain->conn.cli)) {
2088 smbXcli_conn_disconnect(domain->conn.cli->conn, NT_STATUS_OK);
2091 invalidate_cm_connection(domain);
2094 for (cli_state = winbindd_client_list();
2095 cli_state != NULL;
2096 cli_state = cli_state->next) {
2097 if (cli_state->sock >= 0) {
2098 close(cli_state->sock);
2099 cli_state->sock = -1;
2104 static bool connection_ok(struct winbindd_domain *domain)
2106 bool ok;
2108 ok = cli_state_is_connected(domain->conn.cli);
2109 if (!ok) {
2110 DEBUG(3, ("connection_ok: Connection to %s for domain %s is not connected\n",
2111 domain->dcname, domain->name));
2112 return False;
2115 if (domain->online == False) {
2116 DEBUG(3, ("connection_ok: Domain %s is offline\n", domain->name));
2117 return False;
2120 return True;
2123 /* Initialize a new connection up to the RPC BIND.
2124 Bypass online status check so always does network calls. */
2126 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain, bool need_rw_dc)
2128 NTSTATUS result;
2129 bool skip_connection = domain->internal;
2130 if (need_rw_dc && domain->rodc) {
2131 skip_connection = false;
2134 /* Internal connections never use the network. */
2135 if (dom_sid_equal(&domain->sid, &global_sid_Builtin)) {
2136 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2139 /* Still ask the internal LSA and SAMR server about the local domain */
2140 if (skip_connection || connection_ok(domain)) {
2141 if (!domain->initialized) {
2142 set_dc_type_and_flags(domain);
2144 return NT_STATUS_OK;
2147 invalidate_cm_connection(domain);
2149 if (!domain->primary && !domain->initialized) {
2151 * Before we connect to a trust, work out if it is an
2152 * AD domain by asking our own domain.
2154 set_dc_type_and_flags_trustinfo(domain);
2157 result = cm_open_connection(domain, &domain->conn);
2159 if (NT_STATUS_IS_OK(result) && !domain->initialized) {
2160 set_dc_type_and_flags(domain);
2163 return result;
2166 NTSTATUS init_dc_connection(struct winbindd_domain *domain, bool need_rw_dc)
2168 if (dom_sid_equal(&domain->sid, &global_sid_Builtin)) {
2169 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2172 if (domain->initialized && !domain->online) {
2173 /* We check for online status elsewhere. */
2174 return NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
2177 return init_dc_connection_network(domain, need_rw_dc);
2180 static NTSTATUS init_dc_connection_rpc(struct winbindd_domain *domain, bool need_rw_dc)
2182 NTSTATUS status;
2184 status = init_dc_connection(domain, need_rw_dc);
2185 if (!NT_STATUS_IS_OK(status)) {
2186 return status;
2189 if (!domain->internal && domain->conn.cli == NULL) {
2190 /* happens for trusted domains without inbound trust */
2191 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2194 return NT_STATUS_OK;
2197 /******************************************************************************
2198 Set the trust flags (direction and forest location) for a domain
2199 ******************************************************************************/
2201 static bool set_dc_type_and_flags_trustinfo( struct winbindd_domain *domain )
2203 struct winbindd_domain *our_domain;
2204 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2205 WERROR werr;
2206 struct netr_DomainTrustList trusts;
2207 int i;
2208 uint32 flags = (NETR_TRUST_FLAG_IN_FOREST |
2209 NETR_TRUST_FLAG_OUTBOUND |
2210 NETR_TRUST_FLAG_INBOUND);
2211 struct rpc_pipe_client *cli;
2212 TALLOC_CTX *mem_ctx = NULL;
2213 struct dcerpc_binding_handle *b;
2215 DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s\n", domain->name ));
2217 /* Our primary domain doesn't need to worry about trust flags.
2218 Force it to go through the network setup */
2219 if ( domain->primary ) {
2220 return False;
2223 mem_ctx = talloc_stackframe();
2224 our_domain = find_our_domain();
2225 if (our_domain->internal) {
2226 result = init_dc_connection(our_domain, false);
2227 if (!NT_STATUS_IS_OK(result)) {
2228 DEBUG(3,("set_dc_type_and_flags_trustinfo: "
2229 "Not able to make a connection to our domain: %s\n",
2230 nt_errstr(result)));
2231 TALLOC_FREE(mem_ctx);
2232 return false;
2236 /* This won't work unless our domain is AD */
2237 if ( !our_domain->active_directory ) {
2238 TALLOC_FREE(mem_ctx);
2239 return False;
2242 if (our_domain->internal) {
2243 result = wb_open_internal_pipe(mem_ctx, &ndr_table_netlogon, &cli);
2244 } else if (!connection_ok(our_domain)) {
2245 DEBUG(3,("set_dc_type_and_flags_trustinfo: "
2246 "No connection to our domain!\n"));
2247 TALLOC_FREE(mem_ctx);
2248 return False;
2249 } else {
2250 result = cm_connect_netlogon(our_domain, &cli);
2253 if (!NT_STATUS_IS_OK(result)) {
2254 DEBUG(5, ("set_dc_type_and_flags_trustinfo: Could not open "
2255 "a connection to %s for PIPE_NETLOGON (%s)\n",
2256 domain->name, nt_errstr(result)));
2257 TALLOC_FREE(mem_ctx);
2258 return False;
2260 b = cli->binding_handle;
2262 /* Use DsEnumerateDomainTrusts to get us the trust direction and type. */
2263 result = dcerpc_netr_DsrEnumerateDomainTrusts(b, mem_ctx,
2264 cli->desthost,
2265 flags,
2266 &trusts,
2267 &werr);
2268 if (!NT_STATUS_IS_OK(result)) {
2269 DEBUG(0,("set_dc_type_and_flags_trustinfo: "
2270 "failed to query trusted domain list: %s\n",
2271 nt_errstr(result)));
2272 TALLOC_FREE(mem_ctx);
2273 return false;
2275 if (!W_ERROR_IS_OK(werr)) {
2276 DEBUG(0,("set_dc_type_and_flags_trustinfo: "
2277 "failed to query trusted domain list: %s\n",
2278 win_errstr(werr)));
2279 TALLOC_FREE(mem_ctx);
2280 return false;
2283 /* Now find the domain name and get the flags */
2285 for ( i=0; i<trusts.count; i++ ) {
2286 if ( strequal( domain->name, trusts.array[i].netbios_name) ) {
2287 domain->domain_flags = trusts.array[i].trust_flags;
2288 domain->domain_type = trusts.array[i].trust_type;
2289 domain->domain_trust_attribs = trusts.array[i].trust_attributes;
2291 if ( domain->domain_type == LSA_TRUST_TYPE_UPLEVEL )
2292 domain->active_directory = True;
2294 /* This flag is only set if the domain is *our*
2295 primary domain and the primary domain is in
2296 native mode */
2298 domain->native_mode = (domain->domain_flags & NETR_TRUST_FLAG_NATIVE);
2300 DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s is %sin "
2301 "native mode.\n", domain->name,
2302 domain->native_mode ? "" : "NOT "));
2304 DEBUG(5,("set_dc_type_and_flags_trustinfo: domain %s is %s"
2305 "running active directory.\n", domain->name,
2306 domain->active_directory ? "" : "NOT "));
2308 domain->can_do_ncacn_ip_tcp = domain->active_directory;
2310 domain->initialized = True;
2312 break;
2316 TALLOC_FREE(mem_ctx);
2318 return domain->initialized;
2321 /******************************************************************************
2322 We can 'sense' certain things about the DC by it's replies to certain
2323 questions.
2325 This tells us if this particular remote server is Active Directory, and if it
2326 is native mode.
2327 ******************************************************************************/
2329 static void set_dc_type_and_flags_connect( struct winbindd_domain *domain )
2331 NTSTATUS status, result;
2332 WERROR werr;
2333 TALLOC_CTX *mem_ctx = NULL;
2334 struct rpc_pipe_client *cli = NULL;
2335 struct policy_handle pol;
2336 union dssetup_DsRoleInfo info;
2337 union lsa_PolicyInformation *lsa_info = NULL;
2339 if (!domain->internal && !connection_ok(domain)) {
2340 return;
2343 mem_ctx = talloc_init("set_dc_type_and_flags on domain %s\n",
2344 domain->name);
2345 if (!mem_ctx) {
2346 DEBUG(1, ("set_dc_type_and_flags_connect: talloc_init() failed\n"));
2347 return;
2350 DEBUG(5, ("set_dc_type_and_flags_connect: domain %s\n", domain->name ));
2352 if (domain->internal) {
2353 status = wb_open_internal_pipe(mem_ctx,
2354 &ndr_table_dssetup,
2355 &cli);
2356 } else {
2357 status = cli_rpc_pipe_open_noauth(domain->conn.cli,
2358 &ndr_table_dssetup,
2359 &cli);
2362 if (!NT_STATUS_IS_OK(status)) {
2363 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
2364 "PI_DSSETUP on domain %s: (%s)\n",
2365 domain->name, nt_errstr(status)));
2367 /* if this is just a non-AD domain we need to continue
2368 * identifying so that we can in the end return with
2369 * domain->initialized = True - gd */
2371 goto no_dssetup;
2374 status = dcerpc_dssetup_DsRoleGetPrimaryDomainInformation(cli->binding_handle, mem_ctx,
2375 DS_ROLE_BASIC_INFORMATION,
2376 &info,
2377 &werr);
2378 TALLOC_FREE(cli);
2380 if (NT_STATUS_IS_OK(status)) {
2381 result = werror_to_ntstatus(werr);
2383 if (!NT_STATUS_IS_OK(status)) {
2384 DEBUG(5, ("set_dc_type_and_flags_connect: rpccli_ds_getprimarydominfo "
2385 "on domain %s failed: (%s)\n",
2386 domain->name, nt_errstr(status)));
2388 /* older samba3 DCs will return DCERPC_FAULT_OP_RNG_ERROR for
2389 * every opcode on the DSSETUP pipe, continue with
2390 * no_dssetup mode here as well to get domain->initialized
2391 * set - gd */
2393 if (NT_STATUS_EQUAL(status, NT_STATUS_RPC_PROCNUM_OUT_OF_RANGE)) {
2394 goto no_dssetup;
2397 TALLOC_FREE(mem_ctx);
2398 return;
2401 if ((info.basic.flags & DS_ROLE_PRIMARY_DS_RUNNING) &&
2402 !(info.basic.flags & DS_ROLE_PRIMARY_DS_MIXED_MODE)) {
2403 domain->native_mode = True;
2404 } else {
2405 domain->native_mode = False;
2408 no_dssetup:
2409 if (domain->internal) {
2410 status = wb_open_internal_pipe(mem_ctx,
2411 &ndr_table_lsarpc,
2412 &cli);
2413 } else {
2414 status = cli_rpc_pipe_open_noauth(domain->conn.cli,
2415 &ndr_table_lsarpc, &cli);
2417 if (!NT_STATUS_IS_OK(status)) {
2418 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
2419 "PI_LSARPC on domain %s: (%s)\n",
2420 domain->name, nt_errstr(status)));
2421 TALLOC_FREE(cli);
2422 TALLOC_FREE(mem_ctx);
2423 return;
2426 status = rpccli_lsa_open_policy2(cli, mem_ctx, True,
2427 SEC_FLAG_MAXIMUM_ALLOWED, &pol);
2429 if (NT_STATUS_IS_OK(status)) {
2430 /* This particular query is exactly what Win2k clients use
2431 to determine that the DC is active directory */
2432 status = dcerpc_lsa_QueryInfoPolicy2(cli->binding_handle, mem_ctx,
2433 &pol,
2434 LSA_POLICY_INFO_DNS,
2435 &lsa_info,
2436 &result);
2439 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2440 domain->active_directory = True;
2442 if (lsa_info->dns.name.string) {
2443 if (!strequal(domain->name, lsa_info->dns.name.string))
2445 DEBUG(1, ("set_dc_type_and_flags_connect: DC "
2446 "for domain %s claimed it was a DC "
2447 "for domain %s, refusing to "
2448 "initialize\n",
2449 domain->name,
2450 lsa_info->dns.name.string));
2451 TALLOC_FREE(cli);
2452 TALLOC_FREE(mem_ctx);
2453 return;
2455 talloc_free(domain->name);
2456 domain->name = talloc_strdup(domain,
2457 lsa_info->dns.name.string);
2458 if (domain->name == NULL) {
2459 goto done;
2463 if (lsa_info->dns.dns_domain.string) {
2464 if (domain->alt_name != NULL &&
2465 !strequal(domain->alt_name,
2466 lsa_info->dns.dns_domain.string))
2468 DEBUG(1, ("set_dc_type_and_flags_connect: DC "
2469 "for domain %s (%s) claimed it was "
2470 "a DC for domain %s, refusing to "
2471 "initialize\n",
2472 domain->alt_name, domain->name,
2473 lsa_info->dns.dns_domain.string));
2474 TALLOC_FREE(cli);
2475 TALLOC_FREE(mem_ctx);
2476 return;
2478 talloc_free(domain->alt_name);
2479 domain->alt_name =
2480 talloc_strdup(domain,
2481 lsa_info->dns.dns_domain.string);
2482 if (domain->alt_name == NULL) {
2483 goto done;
2487 /* See if we can set some domain trust flags about
2488 ourself */
2490 if (lsa_info->dns.dns_forest.string) {
2491 talloc_free(domain->forest_name);
2492 domain->forest_name =
2493 talloc_strdup(domain,
2494 lsa_info->dns.dns_forest.string);
2495 if (domain->forest_name == NULL) {
2496 goto done;
2499 if (strequal(domain->forest_name, domain->alt_name)) {
2500 domain->domain_flags |= NETR_TRUST_FLAG_TREEROOT;
2504 if (lsa_info->dns.sid) {
2505 if (!is_null_sid(&domain->sid) &&
2506 !dom_sid_equal(&domain->sid,
2507 lsa_info->dns.sid))
2509 DEBUG(1, ("set_dc_type_and_flags_connect: DC "
2510 "for domain %s (%s) claimed it was "
2511 "a DC for domain %s, refusing to "
2512 "initialize\n",
2513 dom_sid_string(talloc_tos(),
2514 &domain->sid),
2515 domain->name,
2516 dom_sid_string(talloc_tos(),
2517 lsa_info->dns.sid)));
2518 TALLOC_FREE(cli);
2519 TALLOC_FREE(mem_ctx);
2520 return;
2522 sid_copy(&domain->sid, lsa_info->dns.sid);
2524 } else {
2525 domain->active_directory = False;
2527 status = rpccli_lsa_open_policy(cli, mem_ctx, True,
2528 SEC_FLAG_MAXIMUM_ALLOWED,
2529 &pol);
2531 if (!NT_STATUS_IS_OK(status)) {
2532 goto done;
2535 status = dcerpc_lsa_QueryInfoPolicy(cli->binding_handle, mem_ctx,
2536 &pol,
2537 LSA_POLICY_INFO_ACCOUNT_DOMAIN,
2538 &lsa_info,
2539 &result);
2540 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2542 if (lsa_info->account_domain.name.string) {
2543 if (!strequal(domain->name,
2544 lsa_info->account_domain.name.string))
2546 DEBUG(1,
2547 ("set_dc_type_and_flags_connect: "
2548 "DC for domain %s claimed it was"
2549 " a DC for domain %s, refusing "
2550 "to initialize\n", domain->name,
2551 lsa_info->
2552 account_domain.name.string));
2553 TALLOC_FREE(cli);
2554 TALLOC_FREE(mem_ctx);
2555 return;
2557 talloc_free(domain->name);
2558 domain->name =
2559 talloc_strdup(domain,
2560 lsa_info->account_domain.name.string);
2563 if (lsa_info->account_domain.sid) {
2564 if (!is_null_sid(&domain->sid) &&
2565 !dom_sid_equal(&domain->sid,
2566 lsa_info->account_domain.sid))
2568 DEBUG(1,
2569 ("set_dc_type_and_flags_connect: "
2570 "DC for domain %s (%s) claimed "
2571 "it was a DC for domain %s, "
2572 "refusing to initialize\n",
2573 dom_sid_string(talloc_tos(),
2574 &domain->sid),
2575 domain->name,
2576 dom_sid_string(talloc_tos(),
2577 lsa_info->account_domain.sid)));
2578 TALLOC_FREE(cli);
2579 TALLOC_FREE(mem_ctx);
2580 return;
2582 sid_copy(&domain->sid, lsa_info->account_domain.sid);
2586 done:
2588 DEBUG(5, ("set_dc_type_and_flags_connect: domain %s is %sin native mode.\n",
2589 domain->name, domain->native_mode ? "" : "NOT "));
2591 DEBUG(5,("set_dc_type_and_flags_connect: domain %s is %srunning active directory.\n",
2592 domain->name, domain->active_directory ? "" : "NOT "));
2594 domain->can_do_ncacn_ip_tcp = domain->active_directory;
2596 TALLOC_FREE(cli);
2598 TALLOC_FREE(mem_ctx);
2600 domain->initialized = True;
2603 /**********************************************************************
2604 Set the domain_flags (trust attributes, domain operating modes, etc...
2605 ***********************************************************************/
2607 static void set_dc_type_and_flags( struct winbindd_domain *domain )
2609 /* we always have to contact our primary domain */
2611 if ( domain->primary || domain->internal) {
2612 DEBUG(10,("set_dc_type_and_flags: setting up flags for "
2613 "primary or internal domain\n"));
2614 set_dc_type_and_flags_connect( domain );
2615 return;
2618 /* Use our DC to get the information if possible */
2620 if ( !set_dc_type_and_flags_trustinfo( domain ) ) {
2621 /* Otherwise, fallback to contacting the
2622 domain directly */
2623 set_dc_type_and_flags_connect( domain );
2626 return;
2631 /**********************************************************************
2632 ***********************************************************************/
2634 static NTSTATUS cm_get_schannel_creds(struct winbindd_domain *domain,
2635 struct netlogon_creds_cli_context **ppdc)
2637 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2638 struct rpc_pipe_client *netlogon_pipe;
2640 *ppdc = NULL;
2642 if ((!IS_DC) && (!domain->primary)) {
2643 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2646 if (domain->conn.netlogon_creds != NULL) {
2647 if (!(domain->conn.netlogon_flags & NETLOGON_NEG_AUTHENTICATED_RPC)) {
2648 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2650 *ppdc = domain->conn.netlogon_creds;
2651 return NT_STATUS_OK;
2654 result = cm_connect_netlogon(domain, &netlogon_pipe);
2655 if (!NT_STATUS_IS_OK(result)) {
2656 return result;
2659 if (domain->conn.netlogon_creds == NULL) {
2660 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2663 if (!(domain->conn.netlogon_flags & NETLOGON_NEG_AUTHENTICATED_RPC)) {
2664 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2667 *ppdc = domain->conn.netlogon_creds;
2668 return NT_STATUS_OK;
2671 NTSTATUS cm_connect_sam(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2672 bool need_rw_dc,
2673 struct rpc_pipe_client **cli, struct policy_handle *sam_handle)
2675 struct winbindd_cm_conn *conn;
2676 NTSTATUS status, result;
2677 struct netlogon_creds_cli_context *p_creds;
2678 struct cli_credentials *creds = NULL;
2680 if (sid_check_is_our_sam(&domain->sid)) {
2681 if (domain->rodc == false || need_rw_dc == false) {
2682 return open_internal_samr_conn(mem_ctx, domain, cli, sam_handle);
2686 status = init_dc_connection_rpc(domain, need_rw_dc);
2687 if (!NT_STATUS_IS_OK(status)) {
2688 return status;
2691 conn = &domain->conn;
2693 if (rpccli_is_connected(conn->samr_pipe)) {
2694 goto done;
2697 TALLOC_FREE(conn->samr_pipe);
2700 * No SAMR pipe yet. Attempt to get an NTLMSSP SPNEGO authenticated
2701 * sign and sealed pipe using the machine account password by
2702 * preference. If we can't - try schannel, if that fails, try
2703 * anonymous.
2706 result = get_trust_credentials(domain, talloc_tos(), false, &creds);
2707 if (!NT_STATUS_IS_OK(result)) {
2708 DEBUG(10, ("cm_connect_sam: No no user available for "
2709 "domain %s, trying schannel\n", domain->name));
2710 goto schannel;
2713 if (cli_credentials_is_anonymous(creds)) {
2714 goto anonymous;
2718 * We have an authenticated connection. Use a SPNEGO
2719 * authenticated SAMR pipe with sign & seal.
2721 status = cli_rpc_pipe_open_with_creds(conn->cli,
2722 &ndr_table_samr,
2723 NCACN_NP,
2724 DCERPC_AUTH_TYPE_SPNEGO,
2725 conn->auth_level,
2726 smbXcli_conn_remote_name(conn->cli->conn),
2727 creds,
2728 &conn->samr_pipe);
2729 if (!NT_STATUS_IS_OK(status)) {
2730 DEBUG(10,("cm_connect_sam: failed to connect to SAMR "
2731 "pipe for domain %s using NTLMSSP "
2732 "authenticated pipe: user %s. Error was "
2733 "%s\n", domain->name,
2734 cli_credentials_get_unparsed_name(creds, talloc_tos()),
2735 nt_errstr(status)));
2736 goto schannel;
2739 DEBUG(10,("cm_connect_sam: connected to SAMR pipe for "
2740 "domain %s using NTLMSSP authenticated "
2741 "pipe: user %s\n", domain->name,
2742 cli_credentials_get_unparsed_name(creds, talloc_tos())));
2744 status = dcerpc_samr_Connect2(conn->samr_pipe->binding_handle, mem_ctx,
2745 conn->samr_pipe->desthost,
2746 SEC_FLAG_MAXIMUM_ALLOWED,
2747 &conn->sam_connect_handle,
2748 &result);
2749 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2750 goto open_domain;
2752 if (NT_STATUS_IS_OK(status)) {
2753 status = result;
2756 DEBUG(10,("cm_connect_sam: ntlmssp-sealed dcerpc_samr_Connect2 "
2757 "failed for domain %s, error was %s. Trying schannel\n",
2758 domain->name, nt_errstr(status) ));
2759 TALLOC_FREE(conn->samr_pipe);
2761 schannel:
2763 /* Fall back to schannel if it's a W2K pre-SP1 box. */
2765 status = cm_get_schannel_creds(domain, &p_creds);
2766 if (!NT_STATUS_IS_OK(status)) {
2767 /* If this call fails - conn->cli can now be NULL ! */
2768 DEBUG(10, ("cm_connect_sam: Could not get schannel auth info "
2769 "for domain %s (error %s), trying anon\n",
2770 domain->name,
2771 nt_errstr(status) ));
2772 goto anonymous;
2774 status = cli_rpc_pipe_open_schannel_with_key
2775 (conn->cli, &ndr_table_samr, NCACN_NP,
2776 domain->name, p_creds, &conn->samr_pipe);
2778 if (!NT_STATUS_IS_OK(status)) {
2779 DEBUG(10,("cm_connect_sam: failed to connect to SAMR pipe for "
2780 "domain %s using schannel. Error was %s\n",
2781 domain->name, nt_errstr(status) ));
2782 goto anonymous;
2784 DEBUG(10,("cm_connect_sam: connected to SAMR pipe for domain %s using "
2785 "schannel.\n", domain->name ));
2787 status = dcerpc_samr_Connect2(conn->samr_pipe->binding_handle, mem_ctx,
2788 conn->samr_pipe->desthost,
2789 SEC_FLAG_MAXIMUM_ALLOWED,
2790 &conn->sam_connect_handle,
2791 &result);
2792 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2793 goto open_domain;
2795 if (NT_STATUS_IS_OK(status)) {
2796 status = result;
2798 DEBUG(10,("cm_connect_sam: schannel-sealed dcerpc_samr_Connect2 failed "
2799 "for domain %s, error was %s. Trying anonymous\n",
2800 domain->name, nt_errstr(status) ));
2801 TALLOC_FREE(conn->samr_pipe);
2803 anonymous:
2805 /* Finally fall back to anonymous. */
2806 if (lp_winbind_sealed_pipes() || lp_require_strong_key()) {
2807 status = NT_STATUS_DOWNGRADE_DETECTED;
2808 DEBUG(1, ("Unwilling to make SAMR connection to domain %s"
2809 "without connection level security, "
2810 "must set 'winbind sealed pipes = false' and "
2811 "'require strong key = false' to proceed: %s\n",
2812 domain->name, nt_errstr(status)));
2813 goto done;
2815 status = cli_rpc_pipe_open_noauth(conn->cli, &ndr_table_samr,
2816 &conn->samr_pipe);
2818 if (!NT_STATUS_IS_OK(status)) {
2819 goto done;
2822 status = dcerpc_samr_Connect2(conn->samr_pipe->binding_handle, mem_ctx,
2823 conn->samr_pipe->desthost,
2824 SEC_FLAG_MAXIMUM_ALLOWED,
2825 &conn->sam_connect_handle,
2826 &result);
2827 if (!NT_STATUS_IS_OK(status)) {
2828 DEBUG(10,("cm_connect_sam: rpccli_samr_Connect2 failed "
2829 "for domain %s Error was %s\n",
2830 domain->name, nt_errstr(status) ));
2831 goto done;
2833 if (!NT_STATUS_IS_OK(result)) {
2834 status = result;
2835 DEBUG(10,("cm_connect_sam: dcerpc_samr_Connect2 failed "
2836 "for domain %s Error was %s\n",
2837 domain->name, nt_errstr(result)));
2838 goto done;
2841 open_domain:
2842 status = dcerpc_samr_OpenDomain(conn->samr_pipe->binding_handle,
2843 mem_ctx,
2844 &conn->sam_connect_handle,
2845 SEC_FLAG_MAXIMUM_ALLOWED,
2846 &domain->sid,
2847 &conn->sam_domain_handle,
2848 &result);
2849 if (!NT_STATUS_IS_OK(status)) {
2850 goto done;
2853 status = result;
2854 done:
2856 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
2858 * if we got access denied, we might just have no access rights
2859 * to talk to the remote samr server server (e.g. when we are a
2860 * PDC and we are connecting a w2k8 pdc via an interdomain
2861 * trust). In that case do not invalidate the whole connection
2862 * stack
2864 TALLOC_FREE(conn->samr_pipe);
2865 ZERO_STRUCT(conn->sam_domain_handle);
2866 return status;
2867 } else if (!NT_STATUS_IS_OK(status)) {
2868 invalidate_cm_connection(domain);
2869 return status;
2872 *cli = conn->samr_pipe;
2873 *sam_handle = conn->sam_domain_handle;
2874 return status;
2877 /**********************************************************************
2878 open an schanneld ncacn_ip_tcp connection to LSA
2879 ***********************************************************************/
2881 static NTSTATUS cm_connect_lsa_tcp(struct winbindd_domain *domain,
2882 TALLOC_CTX *mem_ctx,
2883 struct rpc_pipe_client **cli)
2885 struct winbindd_cm_conn *conn;
2886 struct netlogon_creds_cli_context *creds;
2887 NTSTATUS status;
2889 DEBUG(10,("cm_connect_lsa_tcp\n"));
2891 status = init_dc_connection_rpc(domain, false);
2892 if (!NT_STATUS_IS_OK(status)) {
2893 return status;
2896 conn = &domain->conn;
2898 if (conn->lsa_pipe_tcp &&
2899 conn->lsa_pipe_tcp->transport->transport == NCACN_IP_TCP &&
2900 conn->lsa_pipe_tcp->auth->auth_level >= DCERPC_AUTH_LEVEL_INTEGRITY &&
2901 rpccli_is_connected(conn->lsa_pipe_tcp)) {
2902 goto done;
2905 TALLOC_FREE(conn->lsa_pipe_tcp);
2907 status = cm_get_schannel_creds(domain, &creds);
2908 if (!NT_STATUS_IS_OK(status)) {
2909 goto done;
2912 status = cli_rpc_pipe_open_schannel_with_key(conn->cli,
2913 &ndr_table_lsarpc,
2914 NCACN_IP_TCP,
2915 domain->name,
2916 creds,
2917 &conn->lsa_pipe_tcp);
2918 if (!NT_STATUS_IS_OK(status)) {
2919 DEBUG(10,("cli_rpc_pipe_open_schannel_with_key failed: %s\n",
2920 nt_errstr(status)));
2921 goto done;
2924 done:
2925 if (!NT_STATUS_IS_OK(status)) {
2926 TALLOC_FREE(conn->lsa_pipe_tcp);
2927 return status;
2930 *cli = conn->lsa_pipe_tcp;
2932 return status;
2935 NTSTATUS cm_connect_lsa(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2936 struct rpc_pipe_client **cli, struct policy_handle *lsa_policy)
2938 struct winbindd_cm_conn *conn;
2939 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2940 struct netlogon_creds_cli_context *p_creds;
2941 struct cli_credentials *creds = NULL;
2943 result = init_dc_connection_rpc(domain, false);
2944 if (!NT_STATUS_IS_OK(result))
2945 return result;
2947 conn = &domain->conn;
2949 if (rpccli_is_connected(conn->lsa_pipe)) {
2950 goto done;
2953 TALLOC_FREE(conn->lsa_pipe);
2955 result = get_trust_credentials(domain, talloc_tos(), false, &creds);
2956 if (!NT_STATUS_IS_OK(result)) {
2957 DEBUG(10, ("cm_connect_sam: No no user available for "
2958 "domain %s, trying schannel\n", domain->name));
2959 goto schannel;
2962 if (cli_credentials_is_anonymous(creds)) {
2963 goto anonymous;
2967 * We have an authenticated connection. Use a SPNEGO
2968 * authenticated LSA pipe with sign & seal.
2970 result = cli_rpc_pipe_open_with_creds
2971 (conn->cli, &ndr_table_lsarpc, NCACN_NP,
2972 DCERPC_AUTH_TYPE_SPNEGO,
2973 conn->auth_level,
2974 smbXcli_conn_remote_name(conn->cli->conn),
2975 creds,
2976 &conn->lsa_pipe);
2977 if (!NT_STATUS_IS_OK(result)) {
2978 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
2979 "domain %s using NTLMSSP authenticated pipe: user "
2980 "%s. Error was %s. Trying schannel.\n",
2981 domain->name,
2982 cli_credentials_get_unparsed_name(creds, talloc_tos()),
2983 nt_errstr(result)));
2984 goto schannel;
2987 DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
2988 "NTLMSSP authenticated pipe: user %s\n",
2989 domain->name, cli_credentials_get_unparsed_name(creds, talloc_tos())));
2991 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2992 SEC_FLAG_MAXIMUM_ALLOWED,
2993 &conn->lsa_policy);
2994 if (NT_STATUS_IS_OK(result)) {
2995 goto done;
2998 DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
2999 "schannel\n"));
3001 TALLOC_FREE(conn->lsa_pipe);
3003 schannel:
3005 /* Fall back to schannel if it's a W2K pre-SP1 box. */
3007 result = cm_get_schannel_creds(domain, &p_creds);
3008 if (!NT_STATUS_IS_OK(result)) {
3009 /* If this call fails - conn->cli can now be NULL ! */
3010 DEBUG(10, ("cm_connect_lsa: Could not get schannel auth info "
3011 "for domain %s (error %s), trying anon\n",
3012 domain->name,
3013 nt_errstr(result) ));
3014 goto anonymous;
3016 result = cli_rpc_pipe_open_schannel_with_key
3017 (conn->cli, &ndr_table_lsarpc, NCACN_NP,
3018 domain->name, p_creds, &conn->lsa_pipe);
3020 if (!NT_STATUS_IS_OK(result)) {
3021 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
3022 "domain %s using schannel. Error was %s\n",
3023 domain->name, nt_errstr(result) ));
3024 goto anonymous;
3026 DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
3027 "schannel.\n", domain->name ));
3029 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
3030 SEC_FLAG_MAXIMUM_ALLOWED,
3031 &conn->lsa_policy);
3032 if (NT_STATUS_IS_OK(result)) {
3033 goto done;
3036 DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
3037 "anonymous\n"));
3039 TALLOC_FREE(conn->lsa_pipe);
3041 anonymous:
3043 if (lp_winbind_sealed_pipes() || lp_require_strong_key()) {
3044 result = NT_STATUS_DOWNGRADE_DETECTED;
3045 DEBUG(1, ("Unwilling to make LSA connection to domain %s"
3046 "without connection level security, "
3047 "must set 'winbind sealed pipes = false' and "
3048 "'require strong key = false' to proceed: %s\n",
3049 domain->name, nt_errstr(result)));
3050 goto done;
3053 result = cli_rpc_pipe_open_noauth(conn->cli,
3054 &ndr_table_lsarpc,
3055 &conn->lsa_pipe);
3056 if (!NT_STATUS_IS_OK(result)) {
3057 goto done;
3060 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
3061 SEC_FLAG_MAXIMUM_ALLOWED,
3062 &conn->lsa_policy);
3063 done:
3064 if (!NT_STATUS_IS_OK(result)) {
3065 invalidate_cm_connection(domain);
3066 return result;
3069 *cli = conn->lsa_pipe;
3070 *lsa_policy = conn->lsa_policy;
3071 return result;
3074 /****************************************************************************
3075 Open a LSA connection to a DC, suiteable for LSA lookup calls.
3076 ****************************************************************************/
3078 NTSTATUS cm_connect_lsat(struct winbindd_domain *domain,
3079 TALLOC_CTX *mem_ctx,
3080 struct rpc_pipe_client **cli,
3081 struct policy_handle *lsa_policy)
3083 NTSTATUS status;
3085 if (domain->can_do_ncacn_ip_tcp) {
3086 status = cm_connect_lsa_tcp(domain, mem_ctx, cli);
3087 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED) ||
3088 NT_STATUS_EQUAL(status, NT_STATUS_RPC_SEC_PKG_ERROR) ||
3089 NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_ACCESS_DENIED)) {
3090 invalidate_cm_connection(domain);
3091 status = cm_connect_lsa_tcp(domain, mem_ctx, cli);
3093 if (NT_STATUS_IS_OK(status)) {
3094 return status;
3098 * we tried twice to connect via ncan_ip_tcp and schannel and
3099 * failed - maybe it is a trusted domain we can't connect to ?
3100 * do not try tcp next time - gd
3102 * This also prevents NETLOGON over TCP
3104 domain->can_do_ncacn_ip_tcp = false;
3107 status = cm_connect_lsa(domain, mem_ctx, cli, lsa_policy);
3109 return status;
3112 /****************************************************************************
3113 Open the netlogon pipe to this DC. Use schannel if specified in client conf.
3114 session key stored in conn->netlogon_pipe->dc->sess_key.
3115 ****************************************************************************/
3117 static NTSTATUS cm_connect_netlogon_transport(struct winbindd_domain *domain,
3118 enum dcerpc_transport_t transport,
3119 struct rpc_pipe_client **cli)
3121 struct messaging_context *msg_ctx = winbind_messaging_context();
3122 struct winbindd_cm_conn *conn;
3123 NTSTATUS result;
3124 enum netr_SchannelType sec_chan_type;
3125 const char *account_name;
3126 const char *domain_name;
3127 const struct samr_Password *current_nt_hash = NULL;
3128 const struct samr_Password *previous_nt_hash = NULL;
3129 struct netlogon_creds_CredentialState *netlogon_creds = NULL;
3130 struct cli_credentials *creds = NULL;
3132 *cli = NULL;
3134 result = init_dc_connection_rpc(domain, true);
3135 if (!NT_STATUS_IS_OK(result)) {
3136 return result;
3139 conn = &domain->conn;
3141 if (rpccli_is_connected(conn->netlogon_pipe)) {
3142 *cli = conn->netlogon_pipe;
3143 return NT_STATUS_OK;
3146 TALLOC_FREE(conn->netlogon_pipe);
3147 conn->netlogon_flags = 0;
3148 TALLOC_FREE(conn->netlogon_creds);
3150 result = get_trust_credentials(domain, talloc_tos(), true, &creds);
3151 if (!NT_STATUS_IS_OK(result)) {
3152 DEBUG(10, ("cm_connect_sam: No no user available for "
3153 "domain %s when trying schannel\n", domain->name));
3154 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3157 if (cli_credentials_is_anonymous(creds)) {
3158 DEBUG(1, ("get_trust_credential only gave anonymous for %s, unable to make get NETLOGON credentials\n",
3159 domain->name));
3160 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3163 sec_chan_type = cli_credentials_get_secure_channel_type(creds);
3164 if (sec_chan_type == SEC_CHAN_NULL) {
3165 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3166 goto no_schannel;
3169 account_name = cli_credentials_get_username(creds);
3170 domain_name = cli_credentials_get_domain(creds);
3171 current_nt_hash = cli_credentials_get_nt_hash(creds, talloc_tos());
3172 if (current_nt_hash == NULL) {
3173 return NT_STATUS_NO_MEMORY;
3176 result = rpccli_create_netlogon_creds(domain->dcname,
3177 domain_name,
3178 account_name,
3179 sec_chan_type,
3180 msg_ctx,
3181 domain,
3182 &conn->netlogon_creds);
3183 if (!NT_STATUS_IS_OK(result)) {
3184 DEBUG(1, ("rpccli_create_netlogon_creds failed for %s, "
3185 "unable to create NETLOGON credentials: %s\n",
3186 domain->name, nt_errstr(result)));
3187 return result;
3190 result = rpccli_setup_netlogon_creds(conn->cli, transport,
3191 conn->netlogon_creds,
3192 conn->netlogon_force_reauth,
3193 *current_nt_hash,
3194 previous_nt_hash);
3195 conn->netlogon_force_reauth = false;
3196 if (!NT_STATUS_IS_OK(result)) {
3197 DEBUG(1, ("rpccli_setup_netlogon_creds failed for %s, "
3198 "unable to setup NETLOGON credentials: %s\n",
3199 domain->name, nt_errstr(result)));
3200 return result;
3203 result = netlogon_creds_cli_get(conn->netlogon_creds,
3204 talloc_tos(),
3205 &netlogon_creds);
3206 if (!NT_STATUS_IS_OK(result)) {
3207 DEBUG(1, ("netlogon_creds_cli_get failed for %s, "
3208 "unable to get NETLOGON credentials: %s\n",
3209 domain->name, nt_errstr(result)));
3210 return result;
3212 conn->netlogon_flags = netlogon_creds->negotiate_flags;
3213 TALLOC_FREE(netlogon_creds);
3215 no_schannel:
3216 if (!(conn->netlogon_flags & NETLOGON_NEG_AUTHENTICATED_RPC)) {
3217 if (lp_winbind_sealed_pipes() || lp_require_strong_key()) {
3218 result = NT_STATUS_DOWNGRADE_DETECTED;
3219 DEBUG(1, ("Unwilling to make connection to domain %s"
3220 "without connection level security, "
3221 "must set 'winbind sealed pipes = false' and "
3222 "'require strong key = false' to proceed: %s\n",
3223 domain->name, nt_errstr(result)));
3224 invalidate_cm_connection(domain);
3225 return result;
3227 result = cli_rpc_pipe_open_noauth_transport(conn->cli,
3228 transport,
3229 &ndr_table_netlogon,
3230 &conn->netlogon_pipe);
3231 if (!NT_STATUS_IS_OK(result)) {
3232 invalidate_cm_connection(domain);
3233 return result;
3236 *cli = conn->netlogon_pipe;
3237 return NT_STATUS_OK;
3240 /* Using the credentials from the first pipe, open a signed and sealed
3241 second netlogon pipe. The session key is stored in the schannel
3242 part of the new pipe auth struct.
3245 result = cli_rpc_pipe_open_schannel_with_key(
3246 conn->cli, &ndr_table_netlogon, transport,
3247 domain->name,
3248 conn->netlogon_creds,
3249 &conn->netlogon_pipe);
3250 if (!NT_STATUS_IS_OK(result)) {
3251 DEBUG(3, ("Could not open schannel'ed NETLOGON pipe. Error "
3252 "was %s\n", nt_errstr(result)));
3254 invalidate_cm_connection(domain);
3255 return result;
3258 *cli = conn->netlogon_pipe;
3259 return NT_STATUS_OK;
3262 /****************************************************************************
3263 Open a LSA connection to a DC, suiteable for LSA lookup calls.
3264 ****************************************************************************/
3266 NTSTATUS cm_connect_netlogon(struct winbindd_domain *domain,
3267 struct rpc_pipe_client **cli)
3269 NTSTATUS status;
3271 if (domain->active_directory && domain->can_do_ncacn_ip_tcp) {
3272 status = cm_connect_netlogon_transport(domain, NCACN_IP_TCP, cli);
3273 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED) ||
3274 NT_STATUS_EQUAL(status, NT_STATUS_RPC_SEC_PKG_ERROR) ||
3275 NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_ACCESS_DENIED)) {
3276 invalidate_cm_connection(domain);
3277 status = cm_connect_netlogon_transport(domain, NCACN_IP_TCP, cli);
3279 if (NT_STATUS_IS_OK(status)) {
3280 return status;
3284 * we tried twice to connect via ncan_ip_tcp and schannel and
3285 * failed - maybe it is a trusted domain we can't connect to ?
3286 * do not try tcp next time - gd
3288 * This also prevents LSA over TCP
3290 domain->can_do_ncacn_ip_tcp = false;
3293 status = cm_connect_netlogon_transport(domain, NCACN_NP, cli);
3295 return status;
3298 void winbind_msg_ip_dropped(struct messaging_context *msg_ctx,
3299 void *private_data,
3300 uint32_t msg_type,
3301 struct server_id server_id,
3302 DATA_BLOB *data)
3304 struct winbindd_domain *domain;
3305 char *freeit = NULL;
3306 char *addr;
3308 if ((data == NULL)
3309 || (data->data == NULL)
3310 || (data->length == 0)
3311 || (data->data[data->length-1] != '\0')) {
3312 DEBUG(1, ("invalid msg_ip_dropped message: not a valid "
3313 "string\n"));
3314 return;
3317 addr = (char *)data->data;
3318 DEBUG(10, ("IP %s dropped\n", addr));
3320 if (!is_ipaddress(addr)) {
3321 char *slash;
3323 * Some code sends us ip addresses with the /netmask
3324 * suffix
3326 slash = strchr(addr, '/');
3327 if (slash == NULL) {
3328 DEBUG(1, ("invalid msg_ip_dropped message: %s",
3329 addr));
3330 return;
3332 freeit = talloc_strndup(talloc_tos(), addr, slash-addr);
3333 if (freeit == NULL) {
3334 DEBUG(1, ("talloc failed\n"));
3335 return;
3337 addr = freeit;
3338 DEBUG(10, ("Stripped /netmask to IP %s\n", addr));
3341 for (domain = domain_list(); domain != NULL; domain = domain->next) {
3342 char sockaddr[INET6_ADDRSTRLEN];
3344 if (!cli_state_is_connected(domain->conn.cli)) {
3345 continue;
3348 print_sockaddr(sockaddr, sizeof(sockaddr),
3349 smbXcli_conn_local_sockaddr(domain->conn.cli->conn));
3351 if (strequal(sockaddr, addr)) {
3352 smbXcli_conn_disconnect(domain->conn.cli->conn, NT_STATUS_OK);
3355 TALLOC_FREE(freeit);