s3-rpc_client: Migrate to cli_rpc_pipe_open_generic_auth and remove cli_rpc_pipe_open...
[Samba.git] / source3 / winbindd / winbindd_cm.c
blob96c457756282fc6b7ad6e93ad89b0fc686a26acf
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 "lib/param/loadparm.h"
82 #include "libcli/auth/netlogon_creds_cli.h"
83 #include "auth.h"
84 #include "rpc_server/rpc_ncacn_np.h"
86 #undef DBGC_CLASS
87 #define DBGC_CLASS DBGC_WINBIND
89 struct dc_name_ip {
90 fstring name;
91 struct sockaddr_storage ss;
94 extern struct winbindd_methods reconnect_methods;
95 extern bool override_logfile;
97 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain, bool need_rw_dc);
98 static void set_dc_type_and_flags( struct winbindd_domain *domain );
99 static bool set_dc_type_and_flags_trustinfo( struct winbindd_domain *domain );
100 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
101 struct dc_name_ip **dcs, int *num_dcs);
103 /****************************************************************
104 Child failed to find DC's. Reschedule check.
105 ****************************************************************/
107 static void msg_failed_to_go_online(struct messaging_context *msg,
108 void *private_data,
109 uint32_t msg_type,
110 struct server_id server_id,
111 DATA_BLOB *data)
113 struct winbindd_domain *domain;
114 const char *domainname = (const char *)data->data;
116 if (data->data == NULL || data->length == 0) {
117 return;
120 DEBUG(5,("msg_fail_to_go_online: received for domain %s.\n", domainname));
122 for (domain = domain_list(); domain; domain = domain->next) {
123 if (domain->internal) {
124 continue;
127 if (strequal(domain->name, domainname)) {
128 if (domain->online) {
129 /* We're already online, ignore. */
130 DEBUG(5,("msg_fail_to_go_online: domain %s "
131 "already online.\n", domainname));
132 continue;
135 /* Reschedule the online check. */
136 set_domain_offline(domain);
137 break;
142 /****************************************************************
143 Actually cause a reconnect from a message.
144 ****************************************************************/
146 static void msg_try_to_go_online(struct messaging_context *msg,
147 void *private_data,
148 uint32_t msg_type,
149 struct server_id server_id,
150 DATA_BLOB *data)
152 struct winbindd_domain *domain;
153 const char *domainname = (const char *)data->data;
155 if (data->data == NULL || data->length == 0) {
156 return;
159 DEBUG(5,("msg_try_to_go_online: received for domain %s.\n", domainname));
161 for (domain = domain_list(); domain; domain = domain->next) {
162 if (domain->internal) {
163 continue;
166 if (strequal(domain->name, domainname)) {
168 if (domain->online) {
169 /* We're already online, ignore. */
170 DEBUG(5,("msg_try_to_go_online: domain %s "
171 "already online.\n", domainname));
172 continue;
175 /* This call takes care of setting the online
176 flag to true if we connected, or re-adding
177 the offline handler if false. Bypasses online
178 check so always does network calls. */
180 init_dc_connection_network(domain, true);
181 break;
186 /****************************************************************
187 Fork a child to try and contact a DC. Do this as contacting a
188 DC requires blocking lookups and we don't want to block our
189 parent.
190 ****************************************************************/
192 static bool fork_child_dc_connect(struct winbindd_domain *domain)
194 struct dc_name_ip *dcs = NULL;
195 int num_dcs = 0;
196 TALLOC_CTX *mem_ctx = NULL;
197 pid_t parent_pid = getpid();
198 char *lfile = NULL;
199 NTSTATUS status;
201 if (domain->dc_probe_pid != (pid_t)-1) {
203 * We might already have a DC probe
204 * child working, check.
206 if (process_exists_by_pid(domain->dc_probe_pid)) {
207 DEBUG(10,("fork_child_dc_connect: pid %u already "
208 "checking for DC's.\n",
209 (unsigned int)domain->dc_probe_pid));
210 return true;
212 domain->dc_probe_pid = (pid_t)-1;
215 domain->dc_probe_pid = fork();
217 if (domain->dc_probe_pid == (pid_t)-1) {
218 DEBUG(0, ("fork_child_dc_connect: Could not fork: %s\n", strerror(errno)));
219 return False;
222 if (domain->dc_probe_pid != (pid_t)0) {
223 /* Parent */
224 messaging_register(winbind_messaging_context(), NULL,
225 MSG_WINBIND_TRY_TO_GO_ONLINE,
226 msg_try_to_go_online);
227 messaging_register(winbind_messaging_context(), NULL,
228 MSG_WINBIND_FAILED_TO_GO_ONLINE,
229 msg_failed_to_go_online);
230 return True;
233 /* Child. */
235 /* Leave messages blocked - we will never process one. */
237 if (!override_logfile) {
238 if (asprintf(&lfile, "%s/log.winbindd-dc-connect", get_dyn_LOGFILEBASE()) == -1) {
239 DEBUG(0, ("fork_child_dc_connect: out of memory.\n"));
240 _exit(1);
244 status = winbindd_reinit_after_fork(NULL, lfile);
245 if (!NT_STATUS_IS_OK(status)) {
246 DEBUG(1, ("winbindd_reinit_after_fork failed: %s\n",
247 nt_errstr(status)));
248 messaging_send_buf(winbind_messaging_context(),
249 pid_to_procid(parent_pid),
250 MSG_WINBIND_FAILED_TO_GO_ONLINE,
251 (const uint8_t *)domain->name,
252 strlen(domain->name)+1);
253 _exit(1);
255 SAFE_FREE(lfile);
257 mem_ctx = talloc_init("fork_child_dc_connect");
258 if (!mem_ctx) {
259 DEBUG(0,("talloc_init failed.\n"));
260 messaging_send_buf(winbind_messaging_context(),
261 pid_to_procid(parent_pid),
262 MSG_WINBIND_FAILED_TO_GO_ONLINE,
263 (const uint8_t *)domain->name,
264 strlen(domain->name)+1);
265 _exit(1);
268 if ((!get_dcs(mem_ctx, domain, &dcs, &num_dcs)) || (num_dcs == 0)) {
269 /* Still offline ? Can't find DC's. */
270 messaging_send_buf(winbind_messaging_context(),
271 pid_to_procid(parent_pid),
272 MSG_WINBIND_FAILED_TO_GO_ONLINE,
273 (const uint8_t *)domain->name,
274 strlen(domain->name)+1);
275 _exit(0);
278 /* We got a DC. Send a message to our parent to get it to
279 try and do the same. */
281 messaging_send_buf(winbind_messaging_context(),
282 pid_to_procid(parent_pid),
283 MSG_WINBIND_TRY_TO_GO_ONLINE,
284 (const uint8_t *)domain->name,
285 strlen(domain->name)+1);
286 _exit(0);
289 /****************************************************************
290 Handler triggered if we're offline to try and detect a DC.
291 ****************************************************************/
293 static void check_domain_online_handler(struct tevent_context *ctx,
294 struct tevent_timer *te,
295 struct timeval now,
296 void *private_data)
298 struct winbindd_domain *domain =
299 (struct winbindd_domain *)private_data;
301 DEBUG(10,("check_domain_online_handler: called for domain "
302 "%s (online = %s)\n", domain->name,
303 domain->online ? "True" : "False" ));
305 TALLOC_FREE(domain->check_online_event);
307 /* Are we still in "startup" mode ? */
309 if (domain->startup && (time_mono(NULL) > domain->startup_time + 30)) {
310 /* No longer in "startup" mode. */
311 DEBUG(10,("check_domain_online_handler: domain %s no longer in 'startup' mode.\n",
312 domain->name ));
313 domain->startup = False;
316 /* We've been told to stay offline, so stay
317 that way. */
319 if (get_global_winbindd_state_offline()) {
320 DEBUG(10,("check_domain_online_handler: domain %s remaining globally offline\n",
321 domain->name ));
322 return;
325 /* Fork a child to test if it can contact a DC.
326 If it can then send ourselves a message to
327 cause a reconnect. */
329 fork_child_dc_connect(domain);
332 /****************************************************************
333 If we're still offline setup the timeout check.
334 ****************************************************************/
336 static void calc_new_online_timeout_check(struct winbindd_domain *domain)
338 int wbr = lp_winbind_reconnect_delay();
340 if (domain->startup) {
341 domain->check_online_timeout = 10;
342 } else if (domain->check_online_timeout < wbr) {
343 domain->check_online_timeout = wbr;
347 void winbind_msg_domain_offline(struct messaging_context *msg_ctx,
348 void *private_data,
349 uint32_t msg_type,
350 struct server_id server_id,
351 DATA_BLOB *data)
353 const char *domain_name = (const char *)data->data;
354 struct winbindd_domain *domain;
356 domain = find_domain_from_name_noinit(domain_name);
357 if (domain == NULL) {
358 return;
361 domain->online = false;
363 DEBUG(10, ("Domain %s is marked as offline now.\n",
364 domain_name));
367 void winbind_msg_domain_online(struct messaging_context *msg_ctx,
368 void *private_data,
369 uint32_t msg_type,
370 struct server_id server_id,
371 DATA_BLOB *data)
373 const char *domain_name = (const char *)data->data;
374 struct winbindd_domain *domain;
376 domain = find_domain_from_name_noinit(domain_name);
377 if (domain == NULL) {
378 return;
381 domain->online = true;
383 DEBUG(10, ("Domain %s is marked as online now.\n",
384 domain_name));
387 /****************************************************************
388 Set domain offline and also add handler to put us back online
389 if we detect a DC.
390 ****************************************************************/
392 void set_domain_offline(struct winbindd_domain *domain)
394 pid_t parent_pid = getppid();
396 DEBUG(10,("set_domain_offline: called for domain %s\n",
397 domain->name ));
399 TALLOC_FREE(domain->check_online_event);
401 if (domain->internal) {
402 DEBUG(3,("set_domain_offline: domain %s is internal - logic error.\n",
403 domain->name ));
404 return;
407 domain->online = False;
409 /* Offline domains are always initialized. They're
410 re-initialized when they go back online. */
412 domain->initialized = True;
414 /* We only add the timeout handler that checks and
415 allows us to go back online when we've not
416 been told to remain offline. */
418 if (get_global_winbindd_state_offline()) {
419 DEBUG(10,("set_domain_offline: domain %s remaining globally offline\n",
420 domain->name ));
421 return;
424 /* If we're in startup mode, check again in 10 seconds, not in
425 lp_winbind_reconnect_delay() seconds (which is 30 seconds by default). */
427 calc_new_online_timeout_check(domain);
429 domain->check_online_event = tevent_add_timer(winbind_event_context(),
430 NULL,
431 timeval_current_ofs(domain->check_online_timeout,0),
432 check_domain_online_handler,
433 domain);
435 /* The above *has* to succeed for winbindd to work. */
436 if (!domain->check_online_event) {
437 smb_panic("set_domain_offline: failed to add online handler");
440 DEBUG(10,("set_domain_offline: added event handler for domain %s\n",
441 domain->name ));
443 /* Send a message to the parent that the domain is offline. */
444 if (parent_pid > 1 && !domain->internal) {
445 messaging_send_buf(winbind_messaging_context(),
446 pid_to_procid(parent_pid),
447 MSG_WINBIND_DOMAIN_OFFLINE,
448 (uint8 *)domain->name,
449 strlen(domain->name) + 1);
452 /* Send an offline message to the idmap child when our
453 primary domain goes offline */
455 if ( domain->primary ) {
456 struct winbindd_child *idmap = idmap_child();
458 if ( idmap->pid != 0 ) {
459 messaging_send_buf(winbind_messaging_context(),
460 pid_to_procid(idmap->pid),
461 MSG_WINBIND_OFFLINE,
462 (const uint8_t *)domain->name,
463 strlen(domain->name)+1);
467 return;
470 /****************************************************************
471 Set domain online - if allowed.
472 ****************************************************************/
474 static void set_domain_online(struct winbindd_domain *domain)
476 pid_t parent_pid = getppid();
478 DEBUG(10,("set_domain_online: called for domain %s\n",
479 domain->name ));
481 if (domain->internal) {
482 DEBUG(3,("set_domain_online: domain %s is internal - logic error.\n",
483 domain->name ));
484 return;
487 if (get_global_winbindd_state_offline()) {
488 DEBUG(10,("set_domain_online: domain %s remaining globally offline\n",
489 domain->name ));
490 return;
493 winbindd_set_locator_kdc_envs(domain);
495 /* If we are waiting to get a krb5 ticket, trigger immediately. */
496 ccache_regain_all_now();
498 /* Ok, we're out of any startup mode now... */
499 domain->startup = False;
501 if (domain->online == False) {
502 /* We were offline - now we're online. We default to
503 using the MS-RPC backend if we started offline,
504 and if we're going online for the first time we
505 should really re-initialize the backends and the
506 checks to see if we're talking to an AD or NT domain.
509 domain->initialized = False;
511 /* 'reconnect_methods' is the MS-RPC backend. */
512 if (domain->backend == &reconnect_methods) {
513 domain->backend = NULL;
517 /* Ensure we have no online timeout checks. */
518 domain->check_online_timeout = 0;
519 TALLOC_FREE(domain->check_online_event);
521 /* Ensure we ignore any pending child messages. */
522 messaging_deregister(winbind_messaging_context(),
523 MSG_WINBIND_TRY_TO_GO_ONLINE, NULL);
524 messaging_deregister(winbind_messaging_context(),
525 MSG_WINBIND_FAILED_TO_GO_ONLINE, NULL);
527 domain->online = True;
529 /* Send a message to the parent that the domain is online. */
530 if (parent_pid > 1 && !domain->internal) {
531 messaging_send_buf(winbind_messaging_context(),
532 pid_to_procid(parent_pid),
533 MSG_WINBIND_DOMAIN_ONLINE,
534 (uint8 *)domain->name,
535 strlen(domain->name) + 1);
538 /* Send an online message to the idmap child when our
539 primary domain comes online */
541 if ( domain->primary ) {
542 struct winbindd_child *idmap = idmap_child();
544 if ( idmap->pid != 0 ) {
545 messaging_send_buf(winbind_messaging_context(),
546 pid_to_procid(idmap->pid),
547 MSG_WINBIND_ONLINE,
548 (const uint8_t *)domain->name,
549 strlen(domain->name)+1);
553 return;
556 /****************************************************************
557 Requested to set a domain online.
558 ****************************************************************/
560 void set_domain_online_request(struct winbindd_domain *domain)
562 struct timeval tev;
564 DEBUG(10,("set_domain_online_request: called for domain %s\n",
565 domain->name ));
567 if (get_global_winbindd_state_offline()) {
568 DEBUG(10,("set_domain_online_request: domain %s remaining globally offline\n",
569 domain->name ));
570 return;
573 if (domain->internal) {
574 DEBUG(10, ("set_domain_online_request: Internal domains are "
575 "always online\n"));
576 return;
579 /* We've been told it's safe to go online and
580 try and connect to a DC. But I don't believe it
581 because network manager seems to lie.
582 Wait at least 5 seconds. Heuristics suck... */
585 GetTimeOfDay(&tev);
587 /* Go into "startup" mode again. */
588 domain->startup_time = time_mono(NULL);
589 domain->startup = True;
591 tev.tv_sec += 5;
593 if (!domain->check_online_event) {
594 /* If we've come from being globally offline we
595 don't have a check online event handler set.
596 We need to add one now we're trying to go
597 back online. */
599 DEBUG(10,("set_domain_online_request: domain %s was globally offline.\n",
600 domain->name ));
603 TALLOC_FREE(domain->check_online_event);
605 domain->check_online_event = tevent_add_timer(winbind_event_context(),
606 NULL,
607 tev,
608 check_domain_online_handler,
609 domain);
611 /* The above *has* to succeed for winbindd to work. */
612 if (!domain->check_online_event) {
613 smb_panic("set_domain_online_request: failed to add online handler");
617 /****************************************************************
618 Add -ve connection cache entries for domain and realm.
619 ****************************************************************/
621 static void winbind_add_failed_connection_entry(
622 const struct winbindd_domain *domain,
623 const char *server,
624 NTSTATUS result)
626 add_failed_connection_entry(domain->name, server, result);
627 /* If this was the saf name for the last thing we talked to,
628 remove it. */
629 saf_delete(domain->name);
630 if (domain->alt_name != NULL) {
631 add_failed_connection_entry(domain->alt_name, server, result);
632 saf_delete(domain->alt_name);
634 winbindd_unset_locator_kdc_env(domain);
637 /* Choose between anonymous or authenticated connections. We need to use
638 an authenticated connection if DCs have the RestrictAnonymous registry
639 entry set > 0, or the "Additional restrictions for anonymous
640 connections" set in the win2k Local Security Policy.
642 Caller to free() result in domain, username, password
645 static void cm_get_ipc_userpass(char **username, char **domain, char **password)
647 *username = (char *)secrets_fetch(SECRETS_AUTH_USER, NULL);
648 *domain = (char *)secrets_fetch(SECRETS_AUTH_DOMAIN, NULL);
649 *password = (char *)secrets_fetch(SECRETS_AUTH_PASSWORD, NULL);
651 if (*username && **username) {
653 if (!*domain || !**domain)
654 *domain = smb_xstrdup(lp_workgroup());
656 if (!*password || !**password)
657 *password = smb_xstrdup("");
659 DEBUG(3, ("cm_get_ipc_userpass: Retrieved auth-user from secrets.tdb [%s\\%s]\n",
660 *domain, *username));
662 } else {
663 DEBUG(3, ("cm_get_ipc_userpass: No auth-user defined\n"));
664 *username = smb_xstrdup("");
665 *domain = smb_xstrdup("");
666 *password = smb_xstrdup("");
670 static bool get_dc_name_via_netlogon(struct winbindd_domain *domain,
671 fstring dcname,
672 struct sockaddr_storage *dc_ss)
674 struct winbindd_domain *our_domain = NULL;
675 struct rpc_pipe_client *netlogon_pipe = NULL;
676 NTSTATUS result;
677 WERROR werr;
678 TALLOC_CTX *mem_ctx;
679 unsigned int orig_timeout;
680 const char *tmp = NULL;
681 const char *p;
682 struct dcerpc_binding_handle *b;
684 /* Hmmmm. We can only open one connection to the NETLOGON pipe at the
685 * moment.... */
687 if (IS_DC) {
688 return False;
691 if (domain->primary) {
692 return False;
695 our_domain = find_our_domain();
697 if ((mem_ctx = talloc_init("get_dc_name_via_netlogon")) == NULL) {
698 return False;
701 result = cm_connect_netlogon(our_domain, &netlogon_pipe);
702 if (!NT_STATUS_IS_OK(result)) {
703 talloc_destroy(mem_ctx);
704 return False;
707 b = netlogon_pipe->binding_handle;
709 /* This call can take a long time - allow the server to time out.
710 35 seconds should do it. */
712 orig_timeout = rpccli_set_timeout(netlogon_pipe, 35000);
714 if (our_domain->active_directory) {
715 struct netr_DsRGetDCNameInfo *domain_info = NULL;
717 result = dcerpc_netr_DsRGetDCName(b,
718 mem_ctx,
719 our_domain->dcname,
720 domain->name,
721 NULL,
722 NULL,
723 DS_RETURN_DNS_NAME,
724 &domain_info,
725 &werr);
726 if (NT_STATUS_IS_OK(result) && W_ERROR_IS_OK(werr)) {
727 tmp = talloc_strdup(
728 mem_ctx, domain_info->dc_unc);
729 if (tmp == NULL) {
730 DEBUG(0, ("talloc_strdup failed\n"));
731 talloc_destroy(mem_ctx);
732 return false;
734 if (domain->alt_name == NULL) {
735 domain->alt_name = talloc_strdup(domain,
736 domain_info->domain_name);
737 if (domain->alt_name == NULL) {
738 DEBUG(0, ("talloc_strdup failed\n"));
739 talloc_destroy(mem_ctx);
740 return false;
743 if (domain->forest_name == NULL) {
744 domain->forest_name = talloc_strdup(domain,
745 domain_info->forest_name);
746 if (domain->forest_name == NULL) {
747 DEBUG(0, ("talloc_strdup failed\n"));
748 talloc_destroy(mem_ctx);
749 return false;
753 } else {
754 result = dcerpc_netr_GetAnyDCName(b, mem_ctx,
755 our_domain->dcname,
756 domain->name,
757 &tmp,
758 &werr);
761 /* And restore our original timeout. */
762 rpccli_set_timeout(netlogon_pipe, orig_timeout);
764 if (!NT_STATUS_IS_OK(result)) {
765 DEBUG(10,("dcerpc_netr_GetAnyDCName failed: %s\n",
766 nt_errstr(result)));
767 talloc_destroy(mem_ctx);
768 return false;
771 if (!W_ERROR_IS_OK(werr)) {
772 DEBUG(10,("dcerpc_netr_GetAnyDCName failed: %s\n",
773 win_errstr(werr)));
774 talloc_destroy(mem_ctx);
775 return false;
778 /* dcerpc_netr_GetAnyDCName gives us a name with \\ */
779 p = strip_hostname(tmp);
781 fstrcpy(dcname, p);
783 talloc_destroy(mem_ctx);
785 DEBUG(10,("dcerpc_netr_GetAnyDCName returned %s\n", dcname));
787 if (!resolve_name(dcname, dc_ss, 0x20, true)) {
788 return False;
791 return True;
795 * Helper function to assemble trust password and account name
797 static NTSTATUS get_trust_creds(const struct winbindd_domain *domain,
798 char **machine_password,
799 char **machine_account,
800 char **machine_krb5_principal)
802 const char *account_name;
803 const char *name = NULL;
805 /* If we are a DC and this is not our own domain */
807 if (IS_DC) {
808 name = domain->name;
809 } else {
810 struct winbindd_domain *our_domain = find_our_domain();
812 if (!our_domain)
813 return NT_STATUS_INVALID_SERVER_STATE;
815 name = our_domain->name;
818 if (!get_trust_pw_clear(name, machine_password,
819 &account_name, NULL))
821 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
824 if ((machine_account != NULL) &&
825 (asprintf(machine_account, "%s$", account_name) == -1))
827 return NT_STATUS_NO_MEMORY;
830 /* For now assume our machine account only exists in our domain */
832 if (machine_krb5_principal != NULL)
834 struct winbindd_domain *our_domain = find_our_domain();
836 if (!our_domain) {
837 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
840 if (our_domain->alt_name == NULL) {
841 return NT_STATUS_INVALID_PARAMETER;
844 if (asprintf(machine_krb5_principal, "%s$@%s",
845 account_name, our_domain->alt_name) == -1)
847 return NT_STATUS_NO_MEMORY;
850 if (!strupper_m(*machine_krb5_principal)) {
851 SAFE_FREE(*machine_krb5_principal);
852 return NT_STATUS_INVALID_PARAMETER;
856 return NT_STATUS_OK;
859 /************************************************************************
860 Given a fd with a just-connected TCP connection to a DC, open a connection
861 to the pipe.
862 ************************************************************************/
864 static NTSTATUS cm_prepare_connection(const struct winbindd_domain *domain,
865 const int sockfd,
866 const char *controller,
867 struct cli_state **cli,
868 bool *retry)
870 bool try_spnego = false;
871 bool try_ipc_auth = false;
872 char *machine_password = NULL;
873 char *machine_krb5_principal = NULL;
874 char *machine_account = NULL;
875 char *ipc_username = NULL;
876 char *ipc_domain = NULL;
877 char *ipc_password = NULL;
878 int flags = 0;
879 uint16_t sec_mode = 0;
881 struct named_mutex *mutex;
883 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
885 enum smb_signing_setting smb_sign_client_connections = lp_client_signing();
887 if (smb_sign_client_connections == SMB_SIGNING_DEFAULT) {
889 * If we are connecting to our own AD domain, require
890 * smb signing to disrupt MITM attacks
892 if (domain->primary && lp_security() == SEC_ADS) {
893 smb_sign_client_connections = SMB_SIGNING_REQUIRED;
895 * If we are in or are an AD domain and connecting to another
896 * AD domain in our forest
897 * then require smb signing to disrupt MITM attacks
899 } else if ((lp_security() == SEC_ADS ||
900 lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC)
901 && domain->active_directory
902 && (domain->domain_trust_attribs
903 & LSA_TRUST_ATTRIBUTE_WITHIN_FOREST)) {
904 smb_sign_client_connections = SMB_SIGNING_REQUIRED;
908 DEBUG(10,("cm_prepare_connection: connecting to DC %s for domain %s\n",
909 controller, domain->name ));
911 *retry = True;
913 mutex = grab_named_mutex(talloc_tos(), controller,
914 WINBIND_SERVER_MUTEX_WAIT_TIME);
915 if (mutex == NULL) {
916 close(sockfd);
917 DEBUG(0,("cm_prepare_connection: mutex grab failed for %s\n",
918 controller));
919 result = NT_STATUS_POSSIBLE_DEADLOCK;
920 goto done;
923 flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
925 *cli = cli_state_create(NULL, sockfd,
926 controller, domain->alt_name,
927 smb_sign_client_connections, flags);
928 if (*cli == NULL) {
929 close(sockfd);
930 DEBUG(1, ("Could not cli_initialize\n"));
931 result = NT_STATUS_NO_MEMORY;
932 goto done;
935 cli_set_timeout(*cli, 10000); /* 10 seconds */
937 result = smbXcli_negprot((*cli)->conn, (*cli)->timeout,
938 lp_client_min_protocol(),
939 lp_winbindd_max_protocol());
941 if (!NT_STATUS_IS_OK(result)) {
942 DEBUG(1, ("cli_negprot failed: %s\n", nt_errstr(result)));
943 goto done;
946 if (smbXcli_conn_protocol((*cli)->conn) >= PROTOCOL_NT1 &&
947 smb1cli_conn_capabilities((*cli)->conn) & CAP_EXTENDED_SECURITY) {
948 try_spnego = true;
949 } else if (smbXcli_conn_protocol((*cli)->conn) >= PROTOCOL_SMB2_02) {
950 try_spnego = true;
953 if (!is_dc_trusted_domain_situation(domain->name) && try_spnego) {
954 result = get_trust_creds(domain, &machine_password,
955 &machine_account,
956 &machine_krb5_principal);
957 if (!NT_STATUS_IS_OK(result)) {
958 goto anon_fallback;
961 if (lp_security() == SEC_ADS) {
963 /* Try a krb5 session */
965 (*cli)->use_kerberos = True;
966 DEBUG(5, ("connecting to %s from %s with kerberos principal "
967 "[%s] and realm [%s]\n", controller, lp_netbios_name(),
968 machine_krb5_principal, domain->alt_name));
970 winbindd_set_locator_kdc_envs(domain);
972 result = cli_session_setup(*cli,
973 machine_krb5_principal,
974 machine_password,
975 strlen(machine_password)+1,
976 machine_password,
977 strlen(machine_password)+1,
978 lp_workgroup());
980 if (!NT_STATUS_IS_OK(result)) {
981 DEBUG(4,("failed kerberos session setup with %s\n",
982 nt_errstr(result)));
985 if (NT_STATUS_IS_OK(result)) {
986 /* Ensure creds are stored for NTLMSSP authenticated pipe access. */
987 result = cli_init_creds(*cli, machine_account, lp_workgroup(), machine_password);
988 if (!NT_STATUS_IS_OK(result)) {
989 goto done;
991 goto session_setup_done;
995 /* Fall back to non-kerberos session setup using NTLMSSP SPNEGO with the machine account. */
996 (*cli)->use_kerberos = False;
998 DEBUG(5, ("connecting to %s from %s with username "
999 "[%s]\\[%s]\n", controller, lp_netbios_name(),
1000 lp_workgroup(), machine_account));
1002 result = cli_session_setup(*cli,
1003 machine_account,
1004 machine_password,
1005 strlen(machine_password)+1,
1006 machine_password,
1007 strlen(machine_password)+1,
1008 lp_workgroup());
1009 if (!NT_STATUS_IS_OK(result)) {
1010 DEBUG(4, ("authenticated session setup failed with %s\n",
1011 nt_errstr(result)));
1014 if (NT_STATUS_IS_OK(result)) {
1015 /* Ensure creds are stored for NTLMSSP authenticated pipe access. */
1016 result = cli_init_creds(*cli, machine_account, lp_workgroup(), machine_password);
1017 if (!NT_STATUS_IS_OK(result)) {
1018 goto done;
1020 goto session_setup_done;
1024 /* Fall back to non-kerberos session setup with auth_user */
1026 (*cli)->use_kerberos = False;
1028 cm_get_ipc_userpass(&ipc_username, &ipc_domain, &ipc_password);
1030 sec_mode = smb1cli_conn_server_security_mode((*cli)->conn);
1032 try_ipc_auth = false;
1033 if (try_spnego) {
1034 try_ipc_auth = true;
1035 } else if (sec_mode & NEGOTIATE_SECURITY_CHALLENGE_RESPONSE) {
1036 try_ipc_auth = true;
1039 if (try_ipc_auth && (strlen(ipc_username) > 0)) {
1041 /* Only try authenticated if we have a username */
1043 DEBUG(5, ("connecting to %s from %s with username "
1044 "[%s]\\[%s]\n", controller, lp_netbios_name(),
1045 ipc_domain, ipc_username));
1047 if (NT_STATUS_IS_OK(cli_session_setup(
1048 *cli, ipc_username,
1049 ipc_password, strlen(ipc_password)+1,
1050 ipc_password, strlen(ipc_password)+1,
1051 ipc_domain))) {
1052 /* Successful logon with given username. */
1053 result = cli_init_creds(*cli, ipc_username, ipc_domain, ipc_password);
1054 if (!NT_STATUS_IS_OK(result)) {
1055 goto done;
1057 goto session_setup_done;
1058 } else {
1059 DEBUG(4, ("authenticated session setup with user %s\\%s failed.\n",
1060 ipc_domain, ipc_username ));
1064 anon_fallback:
1066 /* Fall back to anonymous connection, this might fail later */
1067 DEBUG(10,("cm_prepare_connection: falling back to anonymous "
1068 "connection for DC %s\n",
1069 controller ));
1071 result = cli_session_setup(*cli, "", NULL, 0, NULL, 0, "");
1072 if (NT_STATUS_IS_OK(result)) {
1073 DEBUG(5, ("Connected anonymously\n"));
1074 result = cli_init_creds(*cli, "", "", "");
1075 if (!NT_STATUS_IS_OK(result)) {
1076 goto done;
1078 goto session_setup_done;
1081 /* We can't session setup */
1082 goto done;
1084 session_setup_done:
1087 * This should be a short term hack until
1088 * dynamic re-authentication is implemented.
1090 * See Bug 9175 - winbindd doesn't recover from
1091 * NT_STATUS_NETWORK_SESSION_EXPIRED
1093 if (smbXcli_conn_protocol((*cli)->conn) >= PROTOCOL_SMB2_02) {
1094 smbXcli_session_set_disconnect_expired((*cli)->smb2.session);
1097 /* cache the server name for later connections */
1099 saf_store(domain->name, controller);
1100 if (domain->alt_name && (*cli)->use_kerberos) {
1101 saf_store(domain->alt_name, controller);
1104 winbindd_set_locator_kdc_envs(domain);
1106 result = cli_tree_connect(*cli, "IPC$", "IPC", "", 0);
1108 if (!NT_STATUS_IS_OK(result)) {
1109 DEBUG(1,("failed tcon_X with %s\n", nt_errstr(result)));
1110 goto done;
1113 TALLOC_FREE(mutex);
1114 *retry = False;
1116 /* set the domain if empty; needed for schannel connections */
1117 if ( !(*cli)->domain[0] ) {
1118 result = cli_set_domain((*cli), domain->name);
1119 if (!NT_STATUS_IS_OK(result)) {
1120 SAFE_FREE(ipc_username);
1121 SAFE_FREE(ipc_domain);
1122 SAFE_FREE(ipc_password);
1123 return result;
1127 result = NT_STATUS_OK;
1129 done:
1130 TALLOC_FREE(mutex);
1131 SAFE_FREE(machine_account);
1132 SAFE_FREE(machine_password);
1133 SAFE_FREE(machine_krb5_principal);
1134 SAFE_FREE(ipc_username);
1135 SAFE_FREE(ipc_domain);
1136 SAFE_FREE(ipc_password);
1138 if (!NT_STATUS_IS_OK(result)) {
1139 winbind_add_failed_connection_entry(domain, controller, result);
1140 if ((*cli) != NULL) {
1141 cli_shutdown(*cli);
1142 *cli = NULL;
1146 return result;
1149 /*******************************************************************
1150 Add a dcname and sockaddr_storage pair to the end of a dc_name_ip
1151 array.
1153 Keeps the list unique by not adding duplicate entries.
1155 @param[in] mem_ctx talloc memory context to allocate from
1156 @param[in] domain_name domain of the DC
1157 @param[in] dcname name of the DC to add to the list
1158 @param[in] pss Internet address and port pair to add to the list
1159 @param[in,out] dcs array of dc_name_ip structures to add to
1160 @param[in,out] num_dcs number of dcs returned in the dcs array
1161 @return true if the list was added to, false otherwise
1162 *******************************************************************/
1164 static bool add_one_dc_unique(TALLOC_CTX *mem_ctx, const char *domain_name,
1165 const char *dcname, struct sockaddr_storage *pss,
1166 struct dc_name_ip **dcs, int *num)
1168 int i = 0;
1170 if (!NT_STATUS_IS_OK(check_negative_conn_cache(domain_name, dcname))) {
1171 DEBUG(10, ("DC %s was in the negative conn cache\n", dcname));
1172 return False;
1175 /* Make sure there's no duplicates in the list */
1176 for (i=0; i<*num; i++)
1177 if (sockaddr_equal(
1178 (struct sockaddr *)(void *)&(*dcs)[i].ss,
1179 (struct sockaddr *)(void *)pss))
1180 return False;
1182 *dcs = talloc_realloc(mem_ctx, *dcs, struct dc_name_ip, (*num)+1);
1184 if (*dcs == NULL)
1185 return False;
1187 fstrcpy((*dcs)[*num].name, dcname);
1188 (*dcs)[*num].ss = *pss;
1189 *num += 1;
1190 return True;
1193 static bool add_sockaddr_to_array(TALLOC_CTX *mem_ctx,
1194 struct sockaddr_storage *pss, uint16 port,
1195 struct sockaddr_storage **addrs, int *num)
1197 *addrs = talloc_realloc(mem_ctx, *addrs, struct sockaddr_storage, (*num)+1);
1199 if (*addrs == NULL) {
1200 *num = 0;
1201 return False;
1204 (*addrs)[*num] = *pss;
1205 set_sockaddr_port((struct sockaddr *)&(*addrs)[*num], port);
1207 *num += 1;
1208 return True;
1211 /*******************************************************************
1212 convert an ip to a name
1213 *******************************************************************/
1215 static bool dcip_to_name(TALLOC_CTX *mem_ctx,
1216 const struct winbindd_domain *domain,
1217 struct sockaddr_storage *pss,
1218 char **name)
1220 struct ip_service ip_list;
1221 uint32_t nt_version = NETLOGON_NT_VERSION_1;
1222 NTSTATUS status;
1223 const char *dc_name;
1224 fstring nbtname;
1226 ip_list.ss = *pss;
1227 ip_list.port = 0;
1229 #ifdef HAVE_ADS
1230 /* For active directory servers, try to get the ldap server name.
1231 None of these failures should be considered critical for now */
1233 if ((lp_security() == SEC_ADS) && (domain->alt_name != NULL)) {
1234 ADS_STRUCT *ads;
1235 ADS_STATUS ads_status;
1236 char addr[INET6_ADDRSTRLEN];
1238 print_sockaddr(addr, sizeof(addr), pss);
1240 ads = ads_init(domain->alt_name, domain->name, addr);
1241 ads->auth.flags |= ADS_AUTH_NO_BIND;
1243 ads_status = ads_connect(ads);
1244 if (ADS_ERR_OK(ads_status)) {
1245 /* We got a cldap packet. */
1246 *name = talloc_strdup(mem_ctx,
1247 ads->config.ldap_server_name);
1248 if (*name == NULL) {
1249 return false;
1251 namecache_store(*name, 0x20, 1, &ip_list);
1253 DEBUG(10,("dcip_to_name: flags = 0x%x\n", (unsigned int)ads->config.flags));
1255 if (domain->primary && (ads->config.flags & NBT_SERVER_KDC)) {
1256 if (ads_closest_dc(ads)) {
1257 char *sitename = sitename_fetch(mem_ctx, ads->config.realm);
1259 /* We're going to use this KDC for this realm/domain.
1260 If we are using sites, then force the krb5 libs
1261 to use this KDC. */
1263 create_local_private_krb5_conf_for_domain(domain->alt_name,
1264 domain->name,
1265 sitename,
1266 pss);
1268 TALLOC_FREE(sitename);
1269 } else {
1270 /* use an off site KDC */
1271 create_local_private_krb5_conf_for_domain(domain->alt_name,
1272 domain->name,
1273 NULL,
1274 pss);
1276 winbindd_set_locator_kdc_envs(domain);
1278 /* Ensure we contact this DC also. */
1279 saf_store(domain->name, *name);
1280 saf_store(domain->alt_name, *name);
1283 ads_destroy( &ads );
1284 return True;
1287 ads_destroy( &ads );
1288 return false;
1290 #endif
1292 status = nbt_getdc(winbind_messaging_context(), 10, pss, domain->name,
1293 &domain->sid, nt_version, mem_ctx, &nt_version,
1294 &dc_name, NULL);
1295 if (NT_STATUS_IS_OK(status)) {
1296 *name = talloc_strdup(mem_ctx, dc_name);
1297 if (*name == NULL) {
1298 return false;
1300 namecache_store(*name, 0x20, 1, &ip_list);
1301 return True;
1304 /* try node status request */
1306 if (name_status_find(domain->name, 0x1c, 0x20, pss, nbtname) ) {
1307 namecache_store(nbtname, 0x20, 1, &ip_list);
1309 if (name != NULL) {
1310 *name = talloc_strdup(mem_ctx, nbtname);
1311 if (*name == NULL) {
1312 return false;
1316 return true;
1318 return False;
1321 /*******************************************************************
1322 Retrieve a list of IP addresses for domain controllers.
1324 The array is sorted in the preferred connection order.
1326 @param[in] mem_ctx talloc memory context to allocate from
1327 @param[in] domain domain to retrieve DCs for
1328 @param[out] dcs array of dcs that will be returned
1329 @param[out] num_dcs number of dcs returned in the dcs array
1330 @return always true
1331 *******************************************************************/
1333 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
1334 struct dc_name_ip **dcs, int *num_dcs)
1336 fstring dcname;
1337 struct sockaddr_storage ss;
1338 struct ip_service *ip_list = NULL;
1339 int iplist_size = 0;
1340 int i;
1341 bool is_our_domain;
1342 enum security_types sec = (enum security_types)lp_security();
1344 is_our_domain = strequal(domain->name, lp_workgroup());
1346 /* If not our domain, get the preferred DC, by asking our primary DC */
1347 if ( !is_our_domain
1348 && get_dc_name_via_netlogon(domain, dcname, &ss)
1349 && add_one_dc_unique(mem_ctx, domain->name, dcname, &ss, dcs,
1350 num_dcs) )
1352 char addr[INET6_ADDRSTRLEN];
1353 print_sockaddr(addr, sizeof(addr), &ss);
1354 DEBUG(10, ("Retrieved DC %s at %s via netlogon\n",
1355 dcname, addr));
1356 return True;
1359 if ((sec == SEC_ADS) && (domain->alt_name != NULL)) {
1360 char *sitename = NULL;
1362 /* We need to make sure we know the local site before
1363 doing any DNS queries, as this will restrict the
1364 get_sorted_dc_list() call below to only fetching
1365 DNS records for the correct site. */
1367 /* Find any DC to get the site record.
1368 We deliberately don't care about the
1369 return here. */
1371 get_dc_name(domain->name, domain->alt_name, dcname, &ss);
1373 sitename = sitename_fetch(mem_ctx, domain->alt_name);
1374 if (sitename) {
1376 /* Do the site-specific AD dns lookup first. */
1377 get_sorted_dc_list(domain->alt_name, sitename, &ip_list,
1378 &iplist_size, True);
1380 /* Add ips to the DC array. We don't look up the name
1381 of the DC in this function, but we fill in the char*
1382 of the ip now to make the failed connection cache
1383 work */
1384 for ( i=0; i<iplist_size; i++ ) {
1385 char addr[INET6_ADDRSTRLEN];
1386 print_sockaddr(addr, sizeof(addr),
1387 &ip_list[i].ss);
1388 add_one_dc_unique(mem_ctx,
1389 domain->name,
1390 addr,
1391 &ip_list[i].ss,
1392 dcs,
1393 num_dcs);
1396 SAFE_FREE(ip_list);
1397 TALLOC_FREE(sitename);
1398 iplist_size = 0;
1401 /* Now we add DCs from the main AD DNS lookup. */
1402 get_sorted_dc_list(domain->alt_name, NULL, &ip_list,
1403 &iplist_size, True);
1405 for ( i=0; i<iplist_size; i++ ) {
1406 char addr[INET6_ADDRSTRLEN];
1407 print_sockaddr(addr, sizeof(addr),
1408 &ip_list[i].ss);
1409 add_one_dc_unique(mem_ctx,
1410 domain->name,
1411 addr,
1412 &ip_list[i].ss,
1413 dcs,
1414 num_dcs);
1417 SAFE_FREE(ip_list);
1418 iplist_size = 0;
1421 /* Try standard netbios queries if no ADS and fall back to DNS queries
1422 * if alt_name is available */
1423 if (*num_dcs == 0) {
1424 get_sorted_dc_list(domain->name, NULL, &ip_list, &iplist_size,
1425 false);
1426 if (iplist_size == 0) {
1427 if (domain->alt_name != NULL) {
1428 get_sorted_dc_list(domain->alt_name, NULL, &ip_list,
1429 &iplist_size, true);
1433 for ( i=0; i<iplist_size; i++ ) {
1434 char addr[INET6_ADDRSTRLEN];
1435 print_sockaddr(addr, sizeof(addr),
1436 &ip_list[i].ss);
1437 add_one_dc_unique(mem_ctx,
1438 domain->name,
1439 addr,
1440 &ip_list[i].ss,
1441 dcs,
1442 num_dcs);
1445 SAFE_FREE(ip_list);
1446 iplist_size = 0;
1449 return True;
1452 /*******************************************************************
1453 Find and make a connection to a DC in the given domain.
1455 @param[in] mem_ctx talloc memory context to allocate from
1456 @param[in] domain domain to find a dc in
1457 @param[out] dcname NetBIOS or FQDN of DC that's connected to
1458 @param[out] pss DC Internet address and port
1459 @param[out] fd fd of the open socket connected to the newly found dc
1460 @return true when a DC connection is made, false otherwise
1461 *******************************************************************/
1463 static bool find_new_dc(TALLOC_CTX *mem_ctx,
1464 struct winbindd_domain *domain,
1465 char **dcname, struct sockaddr_storage *pss, int *fd)
1467 struct dc_name_ip *dcs = NULL;
1468 int num_dcs = 0;
1470 const char **dcnames = NULL;
1471 int num_dcnames = 0;
1473 struct sockaddr_storage *addrs = NULL;
1474 int num_addrs = 0;
1476 int i;
1477 size_t fd_index;
1479 NTSTATUS status;
1481 *fd = -1;
1483 again:
1484 if (!get_dcs(mem_ctx, domain, &dcs, &num_dcs) || (num_dcs == 0))
1485 return False;
1487 for (i=0; i<num_dcs; i++) {
1489 if (!add_string_to_array(mem_ctx, dcs[i].name,
1490 &dcnames, &num_dcnames)) {
1491 return False;
1493 if (!add_sockaddr_to_array(mem_ctx, &dcs[i].ss, TCP_SMB_PORT,
1494 &addrs, &num_addrs)) {
1495 return False;
1499 if ((num_dcnames == 0) || (num_dcnames != num_addrs))
1500 return False;
1502 if ((addrs == NULL) || (dcnames == NULL))
1503 return False;
1505 status = smbsock_any_connect(addrs, dcnames, NULL, NULL, NULL,
1506 num_addrs, 0, 10, fd, &fd_index, NULL);
1507 if (!NT_STATUS_IS_OK(status)) {
1508 for (i=0; i<num_dcs; i++) {
1509 char ab[INET6_ADDRSTRLEN];
1510 print_sockaddr(ab, sizeof(ab), &dcs[i].ss);
1511 DEBUG(10, ("find_new_dc: smbsock_any_connect failed for "
1512 "domain %s address %s. Error was %s\n",
1513 domain->name, ab, nt_errstr(status) ));
1514 winbind_add_failed_connection_entry(domain,
1515 dcs[i].name, NT_STATUS_UNSUCCESSFUL);
1517 return False;
1520 *pss = addrs[fd_index];
1522 if (*dcnames[fd_index] != '\0' && !is_ipaddress(dcnames[fd_index])) {
1523 /* Ok, we've got a name for the DC */
1524 *dcname = talloc_strdup(mem_ctx, dcnames[fd_index]);
1525 if (*dcname == NULL) {
1526 return false;
1528 return true;
1531 /* Try to figure out the name */
1532 if (dcip_to_name(mem_ctx, domain, pss, dcname)) {
1533 return True;
1536 /* We can not continue without the DC's name */
1537 winbind_add_failed_connection_entry(domain, dcs[fd_index].name,
1538 NT_STATUS_UNSUCCESSFUL);
1540 /* Throw away all arrays as we're doing this again. */
1541 TALLOC_FREE(dcs);
1542 num_dcs = 0;
1544 TALLOC_FREE(dcnames);
1545 num_dcnames = 0;
1547 TALLOC_FREE(addrs);
1548 num_addrs = 0;
1550 close(*fd);
1551 *fd = -1;
1553 goto again;
1556 static char *current_dc_key(TALLOC_CTX *mem_ctx, const char *domain_name)
1558 return talloc_asprintf_strupper_m(mem_ctx, "CURRENT_DCNAME/%s",
1559 domain_name);
1562 static void store_current_dc_in_gencache(const char *domain_name,
1563 const char *dc_name,
1564 struct cli_state *cli)
1566 char addr[INET6_ADDRSTRLEN];
1567 char *key = NULL;
1568 char *value = NULL;
1570 if (!cli_state_is_connected(cli)) {
1571 return;
1574 print_sockaddr(addr, sizeof(addr),
1575 smbXcli_conn_remote_sockaddr(cli->conn));
1577 key = current_dc_key(talloc_tos(), domain_name);
1578 if (key == NULL) {
1579 goto done;
1582 value = talloc_asprintf(talloc_tos(), "%s %s", addr, dc_name);
1583 if (value == NULL) {
1584 goto done;
1587 gencache_set(key, value, 0x7fffffff);
1588 done:
1589 TALLOC_FREE(value);
1590 TALLOC_FREE(key);
1593 bool fetch_current_dc_from_gencache(TALLOC_CTX *mem_ctx,
1594 const char *domain_name,
1595 char **p_dc_name, char **p_dc_ip)
1597 char *key, *p;
1598 char *value = NULL;
1599 bool ret = false;
1600 char *dc_name = NULL;
1601 char *dc_ip = NULL;
1603 key = current_dc_key(talloc_tos(), domain_name);
1604 if (key == NULL) {
1605 goto done;
1607 if (!gencache_get(key, mem_ctx, &value, NULL)) {
1608 goto done;
1610 p = strchr(value, ' ');
1611 if (p == NULL) {
1612 goto done;
1614 dc_ip = talloc_strndup(mem_ctx, value, p - value);
1615 if (dc_ip == NULL) {
1616 goto done;
1618 dc_name = talloc_strdup(mem_ctx, p+1);
1619 if (dc_name == NULL) {
1620 goto done;
1623 if (p_dc_ip != NULL) {
1624 *p_dc_ip = dc_ip;
1625 dc_ip = NULL;
1627 if (p_dc_name != NULL) {
1628 *p_dc_name = dc_name;
1629 dc_name = NULL;
1631 ret = true;
1632 done:
1633 TALLOC_FREE(dc_name);
1634 TALLOC_FREE(dc_ip);
1635 TALLOC_FREE(key);
1636 TALLOC_FREE(value);
1637 return ret;
1640 NTSTATUS wb_open_internal_pipe(TALLOC_CTX *mem_ctx,
1641 const struct ndr_interface_table *table,
1642 struct rpc_pipe_client **ret_pipe)
1644 struct rpc_pipe_client *cli = NULL;
1645 const struct auth_session_info *session_info;
1646 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1649 session_info = get_session_info_system();
1650 SMB_ASSERT(session_info != NULL);
1652 /* create a connection to the specified pipe */
1653 if (lp_parm_bool(-1, "winbindd", "use external pipes", false)) {
1654 status = rpc_pipe_open_interface(mem_ctx,
1655 table,
1656 session_info,
1657 NULL,
1658 winbind_messaging_context(),
1659 &cli);
1660 } else {
1661 status = rpc_pipe_open_internal(mem_ctx,
1662 &table->syntax_id,
1663 session_info,
1664 NULL,
1665 winbind_messaging_context(),
1666 &cli);
1668 if (!NT_STATUS_IS_OK(status)) {
1669 DEBUG(0, ("open_internal_pipe: Could not connect to %s pipe: %s\n",
1670 table->name, nt_errstr(status)));
1671 return status;
1674 if (ret_pipe) {
1675 *ret_pipe = cli;
1678 return NT_STATUS_OK;
1681 static NTSTATUS cm_open_connection(struct winbindd_domain *domain,
1682 struct winbindd_cm_conn *new_conn)
1684 TALLOC_CTX *mem_ctx;
1685 NTSTATUS result;
1686 char *saf_servername;
1687 int retries;
1689 if ((mem_ctx = talloc_init("cm_open_connection")) == NULL) {
1690 set_domain_offline(domain);
1691 return NT_STATUS_NO_MEMORY;
1694 saf_servername = saf_fetch(mem_ctx, domain->name );
1696 /* we have to check the server affinity cache here since
1697 later we select a DC based on response time and not preference */
1699 /* Check the negative connection cache
1700 before talking to it. It going down may have
1701 triggered the reconnection. */
1703 if ( saf_servername && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, saf_servername))) {
1705 DEBUG(10,("cm_open_connection: saf_servername is '%s' for domain %s\n",
1706 saf_servername, domain->name ));
1708 /* convert an ip address to a name */
1709 if (is_ipaddress( saf_servername ) ) {
1710 char *dcname = NULL;
1711 struct sockaddr_storage ss;
1713 if (!interpret_string_addr(&ss, saf_servername,
1714 AI_NUMERICHOST)) {
1715 TALLOC_FREE(mem_ctx);
1716 return NT_STATUS_UNSUCCESSFUL;
1718 if (dcip_to_name(mem_ctx, domain, &ss, &dcname)) {
1719 domain->dcname = talloc_strdup(domain,
1720 dcname);
1721 if (domain->dcname == NULL) {
1722 TALLOC_FREE(mem_ctx);
1723 return NT_STATUS_NO_MEMORY;
1725 } else {
1726 winbind_add_failed_connection_entry(
1727 domain, saf_servername,
1728 NT_STATUS_UNSUCCESSFUL);
1730 } else {
1731 domain->dcname = talloc_strdup(domain, saf_servername);
1732 if (domain->dcname == NULL) {
1733 TALLOC_FREE(mem_ctx);
1734 return NT_STATUS_NO_MEMORY;
1739 for (retries = 0; retries < 3; retries++) {
1740 int fd = -1;
1741 bool retry = False;
1742 char *dcname = NULL;
1744 result = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1746 DEBUG(10,("cm_open_connection: dcname is '%s' for domain %s\n",
1747 domain->dcname ? domain->dcname : "", domain->name ));
1749 if (domain->dcname != NULL
1750 && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, domain->dcname))
1751 && (resolve_name(domain->dcname, &domain->dcaddr, 0x20, true)))
1753 NTSTATUS status;
1755 status = smbsock_connect(&domain->dcaddr, 0,
1756 NULL, -1, NULL, -1,
1757 &fd, NULL, 10);
1758 if (!NT_STATUS_IS_OK(status)) {
1759 fd = -1;
1763 if ((fd == -1) &&
1764 !find_new_dc(mem_ctx, domain, &dcname, &domain->dcaddr, &fd))
1766 /* This is the one place where we will
1767 set the global winbindd offline state
1768 to true, if a "WINBINDD_OFFLINE" entry
1769 is found in the winbindd cache. */
1770 set_global_winbindd_state_offline();
1771 break;
1773 if (dcname != NULL) {
1774 talloc_free(domain->dcname);
1776 domain->dcname = talloc_move(domain, &dcname);
1777 if (domain->dcname == NULL) {
1778 result = NT_STATUS_NO_MEMORY;
1779 break;
1783 new_conn->cli = NULL;
1785 result = cm_prepare_connection(domain, fd, domain->dcname,
1786 &new_conn->cli, &retry);
1787 if (!NT_STATUS_IS_OK(result)) {
1788 /* Don't leak the smb connection socket */
1789 close(fd);
1792 if (!retry)
1793 break;
1796 if (NT_STATUS_IS_OK(result)) {
1797 bool seal_pipes = true;
1799 winbindd_set_locator_kdc_envs(domain);
1801 if (domain->online == False) {
1802 /* We're changing state from offline to online. */
1803 set_global_winbindd_state_online();
1805 set_domain_online(domain);
1808 * Much as I hate global state, this seems to be the point
1809 * where we can be certain that we have a proper connection to
1810 * a DC. wbinfo --dc-info needs that information, store it in
1811 * gencache with a looong timeout. This will need revisiting
1812 * once we start to connect to multiple DCs, wbcDcInfo is
1813 * already prepared for that.
1815 store_current_dc_in_gencache(domain->name, domain->dcname,
1816 new_conn->cli);
1818 seal_pipes = lp_winbind_sealed_pipes();
1819 seal_pipes = lp_parm_bool(-1, "winbind sealed pipes",
1820 domain->name,
1821 seal_pipes);
1823 if (seal_pipes) {
1824 new_conn->auth_level = DCERPC_AUTH_LEVEL_PRIVACY;
1825 } else {
1826 new_conn->auth_level = DCERPC_AUTH_LEVEL_INTEGRITY;
1828 } else {
1829 /* Ensure we setup the retry handler. */
1830 set_domain_offline(domain);
1833 talloc_destroy(mem_ctx);
1834 return result;
1837 /* Close down all open pipes on a connection. */
1839 void invalidate_cm_connection(struct winbindd_domain *domain)
1841 NTSTATUS result;
1842 struct winbindd_cm_conn *conn = &domain->conn;
1844 /* We're closing down a possibly dead
1845 connection. Don't have impossibly long (10s) timeouts. */
1847 if (conn->cli) {
1848 cli_set_timeout(conn->cli, 1000); /* 1 second. */
1851 if (conn->samr_pipe != NULL) {
1852 if (is_valid_policy_hnd(&conn->sam_connect_handle)) {
1853 dcerpc_samr_Close(conn->samr_pipe->binding_handle,
1854 talloc_tos(),
1855 &conn->sam_connect_handle,
1856 &result);
1858 TALLOC_FREE(conn->samr_pipe);
1859 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1860 if (conn->cli) {
1861 cli_set_timeout(conn->cli, 500);
1865 if (conn->lsa_pipe != NULL) {
1866 if (is_valid_policy_hnd(&conn->lsa_policy)) {
1867 dcerpc_lsa_Close(conn->lsa_pipe->binding_handle,
1868 talloc_tos(),
1869 &conn->lsa_policy,
1870 &result);
1872 TALLOC_FREE(conn->lsa_pipe);
1873 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1874 if (conn->cli) {
1875 cli_set_timeout(conn->cli, 500);
1879 if (conn->lsa_pipe_tcp != NULL) {
1880 if (is_valid_policy_hnd(&conn->lsa_policy)) {
1881 dcerpc_lsa_Close(conn->lsa_pipe_tcp->binding_handle,
1882 talloc_tos(),
1883 &conn->lsa_policy,
1884 &result);
1886 TALLOC_FREE(conn->lsa_pipe_tcp);
1887 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1888 if (conn->cli) {
1889 cli_set_timeout(conn->cli, 500);
1893 if (conn->netlogon_pipe != NULL) {
1894 TALLOC_FREE(conn->netlogon_pipe);
1895 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1896 if (conn->cli) {
1897 cli_set_timeout(conn->cli, 500);
1901 conn->auth_level = DCERPC_AUTH_LEVEL_PRIVACY;
1902 conn->netlogon_force_reauth = false;
1903 conn->netlogon_flags = 0;
1904 TALLOC_FREE(conn->netlogon_creds);
1906 if (conn->cli) {
1907 cli_shutdown(conn->cli);
1910 conn->cli = NULL;
1913 void close_conns_after_fork(void)
1915 struct winbindd_domain *domain;
1916 struct winbindd_cli_state *cli_state;
1918 for (domain = domain_list(); domain; domain = domain->next) {
1920 * first close the low level SMB TCP connection
1921 * so that we don't generate any SMBclose
1922 * requests in invalidate_cm_connection()
1924 if (cli_state_is_connected(domain->conn.cli)) {
1925 smbXcli_conn_disconnect(domain->conn.cli->conn, NT_STATUS_OK);
1928 invalidate_cm_connection(domain);
1931 for (cli_state = winbindd_client_list();
1932 cli_state != NULL;
1933 cli_state = cli_state->next) {
1934 if (cli_state->sock >= 0) {
1935 close(cli_state->sock);
1936 cli_state->sock = -1;
1941 static bool connection_ok(struct winbindd_domain *domain)
1943 bool ok;
1945 ok = cli_state_is_connected(domain->conn.cli);
1946 if (!ok) {
1947 DEBUG(3, ("connection_ok: Connection to %s for domain %s is not connected\n",
1948 domain->dcname, domain->name));
1949 return False;
1952 if (domain->online == False) {
1953 DEBUG(3, ("connection_ok: Domain %s is offline\n", domain->name));
1954 return False;
1957 return True;
1960 /* Initialize a new connection up to the RPC BIND.
1961 Bypass online status check so always does network calls. */
1963 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain, bool need_rw_dc)
1965 NTSTATUS result;
1966 bool skip_connection = domain->internal;
1967 if (need_rw_dc && domain->rodc) {
1968 skip_connection = false;
1971 /* Internal connections never use the network. */
1972 if (dom_sid_equal(&domain->sid, &global_sid_Builtin)) {
1973 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1976 /* Still ask the internal LSA and SAMR server about the local domain */
1977 if (skip_connection || connection_ok(domain)) {
1978 if (!domain->initialized) {
1979 set_dc_type_and_flags(domain);
1981 return NT_STATUS_OK;
1984 invalidate_cm_connection(domain);
1986 if (!domain->primary && !domain->initialized) {
1988 * Before we connect to a trust, work out if it is an
1989 * AD domain by asking our own domain.
1991 set_dc_type_and_flags_trustinfo(domain);
1994 result = cm_open_connection(domain, &domain->conn);
1996 if (NT_STATUS_IS_OK(result) && !domain->initialized) {
1997 set_dc_type_and_flags(domain);
2000 return result;
2003 NTSTATUS init_dc_connection(struct winbindd_domain *domain, bool need_rw_dc)
2005 if (dom_sid_equal(&domain->sid, &global_sid_Builtin)) {
2006 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2009 if (domain->initialized && !domain->online) {
2010 /* We check for online status elsewhere. */
2011 return NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
2014 return init_dc_connection_network(domain, need_rw_dc);
2017 static NTSTATUS init_dc_connection_rpc(struct winbindd_domain *domain, bool need_rw_dc)
2019 NTSTATUS status;
2021 status = init_dc_connection(domain, need_rw_dc);
2022 if (!NT_STATUS_IS_OK(status)) {
2023 return status;
2026 if (!domain->internal && domain->conn.cli == NULL) {
2027 /* happens for trusted domains without inbound trust */
2028 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2031 return NT_STATUS_OK;
2034 /******************************************************************************
2035 Set the trust flags (direction and forest location) for a domain
2036 ******************************************************************************/
2038 static bool set_dc_type_and_flags_trustinfo( struct winbindd_domain *domain )
2040 struct winbindd_domain *our_domain;
2041 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2042 WERROR werr;
2043 struct netr_DomainTrustList trusts;
2044 int i;
2045 uint32 flags = (NETR_TRUST_FLAG_IN_FOREST |
2046 NETR_TRUST_FLAG_OUTBOUND |
2047 NETR_TRUST_FLAG_INBOUND);
2048 struct rpc_pipe_client *cli;
2049 TALLOC_CTX *mem_ctx = NULL;
2050 struct dcerpc_binding_handle *b;
2052 DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s\n", domain->name ));
2054 /* Our primary domain doesn't need to worry about trust flags.
2055 Force it to go through the network setup */
2056 if ( domain->primary ) {
2057 return False;
2060 mem_ctx = talloc_stackframe();
2061 our_domain = find_our_domain();
2062 if (our_domain->internal) {
2063 result = init_dc_connection(our_domain, false);
2064 if (!NT_STATUS_IS_OK(result)) {
2065 DEBUG(3,("set_dc_type_and_flags_trustinfo: "
2066 "Not able to make a connection to our domain: %s\n",
2067 nt_errstr(result)));
2068 TALLOC_FREE(mem_ctx);
2069 return false;
2073 /* This won't work unless our domain is AD */
2074 if ( !our_domain->active_directory ) {
2075 TALLOC_FREE(mem_ctx);
2076 return False;
2079 if (our_domain->internal) {
2080 result = wb_open_internal_pipe(mem_ctx, &ndr_table_netlogon, &cli);
2081 } else if (!connection_ok(our_domain)) {
2082 DEBUG(3,("set_dc_type_and_flags_trustinfo: "
2083 "No connection to our domain!\n"));
2084 TALLOC_FREE(mem_ctx);
2085 return False;
2086 } else {
2087 result = cm_connect_netlogon(our_domain, &cli);
2090 if (!NT_STATUS_IS_OK(result)) {
2091 DEBUG(5, ("set_dc_type_and_flags_trustinfo: Could not open "
2092 "a connection to %s for PIPE_NETLOGON (%s)\n",
2093 domain->name, nt_errstr(result)));
2094 TALLOC_FREE(mem_ctx);
2095 return False;
2097 b = cli->binding_handle;
2099 /* Use DsEnumerateDomainTrusts to get us the trust direction and type. */
2100 result = dcerpc_netr_DsrEnumerateDomainTrusts(b, mem_ctx,
2101 cli->desthost,
2102 flags,
2103 &trusts,
2104 &werr);
2105 if (!NT_STATUS_IS_OK(result)) {
2106 DEBUG(0,("set_dc_type_and_flags_trustinfo: "
2107 "failed to query trusted domain list: %s\n",
2108 nt_errstr(result)));
2109 TALLOC_FREE(mem_ctx);
2110 return false;
2112 if (!W_ERROR_IS_OK(werr)) {
2113 DEBUG(0,("set_dc_type_and_flags_trustinfo: "
2114 "failed to query trusted domain list: %s\n",
2115 win_errstr(werr)));
2116 TALLOC_FREE(mem_ctx);
2117 return false;
2120 /* Now find the domain name and get the flags */
2122 for ( i=0; i<trusts.count; i++ ) {
2123 if ( strequal( domain->name, trusts.array[i].netbios_name) ) {
2124 domain->domain_flags = trusts.array[i].trust_flags;
2125 domain->domain_type = trusts.array[i].trust_type;
2126 domain->domain_trust_attribs = trusts.array[i].trust_attributes;
2128 if ( domain->domain_type == LSA_TRUST_TYPE_UPLEVEL )
2129 domain->active_directory = True;
2131 /* This flag is only set if the domain is *our*
2132 primary domain and the primary domain is in
2133 native mode */
2135 domain->native_mode = (domain->domain_flags & NETR_TRUST_FLAG_NATIVE);
2137 DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s is %sin "
2138 "native mode.\n", domain->name,
2139 domain->native_mode ? "" : "NOT "));
2141 DEBUG(5,("set_dc_type_and_flags_trustinfo: domain %s is %s"
2142 "running active directory.\n", domain->name,
2143 domain->active_directory ? "" : "NOT "));
2145 domain->can_do_ncacn_ip_tcp = domain->active_directory;
2147 domain->initialized = True;
2149 break;
2153 TALLOC_FREE(mem_ctx);
2155 return domain->initialized;
2158 /******************************************************************************
2159 We can 'sense' certain things about the DC by it's replies to certain
2160 questions.
2162 This tells us if this particular remote server is Active Directory, and if it
2163 is native mode.
2164 ******************************************************************************/
2166 static void set_dc_type_and_flags_connect( struct winbindd_domain *domain )
2168 NTSTATUS status, result;
2169 WERROR werr;
2170 TALLOC_CTX *mem_ctx = NULL;
2171 struct rpc_pipe_client *cli = NULL;
2172 struct policy_handle pol;
2173 union dssetup_DsRoleInfo info;
2174 union lsa_PolicyInformation *lsa_info = NULL;
2176 if (!domain->internal && !connection_ok(domain)) {
2177 return;
2180 mem_ctx = talloc_init("set_dc_type_and_flags on domain %s\n",
2181 domain->name);
2182 if (!mem_ctx) {
2183 DEBUG(1, ("set_dc_type_and_flags_connect: talloc_init() failed\n"));
2184 return;
2187 DEBUG(5, ("set_dc_type_and_flags_connect: domain %s\n", domain->name ));
2189 if (domain->internal) {
2190 status = wb_open_internal_pipe(mem_ctx,
2191 &ndr_table_dssetup,
2192 &cli);
2193 } else {
2194 status = cli_rpc_pipe_open_noauth(domain->conn.cli,
2195 &ndr_table_dssetup,
2196 &cli);
2199 if (!NT_STATUS_IS_OK(status)) {
2200 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
2201 "PI_DSSETUP on domain %s: (%s)\n",
2202 domain->name, nt_errstr(status)));
2204 /* if this is just a non-AD domain we need to continue
2205 * identifying so that we can in the end return with
2206 * domain->initialized = True - gd */
2208 goto no_dssetup;
2211 status = dcerpc_dssetup_DsRoleGetPrimaryDomainInformation(cli->binding_handle, mem_ctx,
2212 DS_ROLE_BASIC_INFORMATION,
2213 &info,
2214 &werr);
2215 TALLOC_FREE(cli);
2217 if (NT_STATUS_IS_OK(status)) {
2218 result = werror_to_ntstatus(werr);
2220 if (!NT_STATUS_IS_OK(status)) {
2221 DEBUG(5, ("set_dc_type_and_flags_connect: rpccli_ds_getprimarydominfo "
2222 "on domain %s failed: (%s)\n",
2223 domain->name, nt_errstr(status)));
2225 /* older samba3 DCs will return DCERPC_FAULT_OP_RNG_ERROR for
2226 * every opcode on the DSSETUP pipe, continue with
2227 * no_dssetup mode here as well to get domain->initialized
2228 * set - gd */
2230 if (NT_STATUS_EQUAL(status, NT_STATUS_RPC_PROCNUM_OUT_OF_RANGE)) {
2231 goto no_dssetup;
2234 TALLOC_FREE(mem_ctx);
2235 return;
2238 if ((info.basic.flags & DS_ROLE_PRIMARY_DS_RUNNING) &&
2239 !(info.basic.flags & DS_ROLE_PRIMARY_DS_MIXED_MODE)) {
2240 domain->native_mode = True;
2241 } else {
2242 domain->native_mode = False;
2245 no_dssetup:
2246 if (domain->internal) {
2247 status = wb_open_internal_pipe(mem_ctx,
2248 &ndr_table_lsarpc,
2249 &cli);
2250 } else {
2251 status = cli_rpc_pipe_open_noauth(domain->conn.cli,
2252 &ndr_table_lsarpc, &cli);
2254 if (!NT_STATUS_IS_OK(status)) {
2255 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
2256 "PI_LSARPC on domain %s: (%s)\n",
2257 domain->name, nt_errstr(status)));
2258 TALLOC_FREE(cli);
2259 TALLOC_FREE(mem_ctx);
2260 return;
2263 status = rpccli_lsa_open_policy2(cli, mem_ctx, True,
2264 SEC_FLAG_MAXIMUM_ALLOWED, &pol);
2266 if (NT_STATUS_IS_OK(status)) {
2267 /* This particular query is exactly what Win2k clients use
2268 to determine that the DC is active directory */
2269 status = dcerpc_lsa_QueryInfoPolicy2(cli->binding_handle, mem_ctx,
2270 &pol,
2271 LSA_POLICY_INFO_DNS,
2272 &lsa_info,
2273 &result);
2276 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2277 domain->active_directory = True;
2279 if (lsa_info->dns.name.string) {
2280 if (!strequal(domain->name, lsa_info->dns.name.string))
2282 DEBUG(1, ("set_dc_type_and_flags_connect: DC "
2283 "for domain %s claimed it was a DC "
2284 "for domain %s, refusing to "
2285 "initialize\n",
2286 domain->name,
2287 lsa_info->dns.name.string));
2288 TALLOC_FREE(cli);
2289 TALLOC_FREE(mem_ctx);
2290 return;
2292 talloc_free(domain->name);
2293 domain->name = talloc_strdup(domain,
2294 lsa_info->dns.name.string);
2295 if (domain->name == NULL) {
2296 goto done;
2300 if (lsa_info->dns.dns_domain.string) {
2301 if (domain->alt_name != NULL &&
2302 !strequal(domain->alt_name,
2303 lsa_info->dns.dns_domain.string))
2305 DEBUG(1, ("set_dc_type_and_flags_connect: DC "
2306 "for domain %s (%s) claimed it was "
2307 "a DC for domain %s, refusing to "
2308 "initialize\n",
2309 domain->alt_name, domain->name,
2310 lsa_info->dns.dns_domain.string));
2311 TALLOC_FREE(cli);
2312 TALLOC_FREE(mem_ctx);
2313 return;
2315 talloc_free(domain->alt_name);
2316 domain->alt_name =
2317 talloc_strdup(domain,
2318 lsa_info->dns.dns_domain.string);
2319 if (domain->alt_name == NULL) {
2320 goto done;
2324 /* See if we can set some domain trust flags about
2325 ourself */
2327 if (lsa_info->dns.dns_forest.string) {
2328 talloc_free(domain->forest_name);
2329 domain->forest_name =
2330 talloc_strdup(domain,
2331 lsa_info->dns.dns_forest.string);
2332 if (domain->forest_name == NULL) {
2333 goto done;
2336 if (strequal(domain->forest_name, domain->alt_name)) {
2337 domain->domain_flags |= NETR_TRUST_FLAG_TREEROOT;
2341 if (lsa_info->dns.sid) {
2342 if (!is_null_sid(&domain->sid) &&
2343 !dom_sid_equal(&domain->sid,
2344 lsa_info->dns.sid))
2346 DEBUG(1, ("set_dc_type_and_flags_connect: DC "
2347 "for domain %s (%s) claimed it was "
2348 "a DC for domain %s, refusing to "
2349 "initialize\n",
2350 dom_sid_string(talloc_tos(),
2351 &domain->sid),
2352 domain->name,
2353 dom_sid_string(talloc_tos(),
2354 lsa_info->dns.sid)));
2355 TALLOC_FREE(cli);
2356 TALLOC_FREE(mem_ctx);
2357 return;
2359 sid_copy(&domain->sid, lsa_info->dns.sid);
2361 } else {
2362 domain->active_directory = False;
2364 status = rpccli_lsa_open_policy(cli, mem_ctx, True,
2365 SEC_FLAG_MAXIMUM_ALLOWED,
2366 &pol);
2368 if (!NT_STATUS_IS_OK(status)) {
2369 goto done;
2372 status = dcerpc_lsa_QueryInfoPolicy(cli->binding_handle, mem_ctx,
2373 &pol,
2374 LSA_POLICY_INFO_ACCOUNT_DOMAIN,
2375 &lsa_info,
2376 &result);
2377 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2379 if (lsa_info->account_domain.name.string) {
2380 if (!strequal(domain->name,
2381 lsa_info->account_domain.name.string))
2383 DEBUG(1,
2384 ("set_dc_type_and_flags_connect: "
2385 "DC for domain %s claimed it was"
2386 " a DC for domain %s, refusing "
2387 "to initialize\n", domain->name,
2388 lsa_info->
2389 account_domain.name.string));
2390 TALLOC_FREE(cli);
2391 TALLOC_FREE(mem_ctx);
2392 return;
2394 talloc_free(domain->name);
2395 domain->name =
2396 talloc_strdup(domain,
2397 lsa_info->account_domain.name.string);
2400 if (lsa_info->account_domain.sid) {
2401 if (!is_null_sid(&domain->sid) &&
2402 !dom_sid_equal(&domain->sid,
2403 lsa_info->account_domain.sid))
2405 DEBUG(1,
2406 ("set_dc_type_and_flags_connect: "
2407 "DC for domain %s (%s) claimed "
2408 "it was a DC for domain %s, "
2409 "refusing to initialize\n",
2410 dom_sid_string(talloc_tos(),
2411 &domain->sid),
2412 domain->name,
2413 dom_sid_string(talloc_tos(),
2414 lsa_info->account_domain.sid)));
2415 TALLOC_FREE(cli);
2416 TALLOC_FREE(mem_ctx);
2417 return;
2419 sid_copy(&domain->sid, lsa_info->account_domain.sid);
2423 done:
2425 DEBUG(5, ("set_dc_type_and_flags_connect: domain %s is %sin native mode.\n",
2426 domain->name, domain->native_mode ? "" : "NOT "));
2428 DEBUG(5,("set_dc_type_and_flags_connect: domain %s is %srunning active directory.\n",
2429 domain->name, domain->active_directory ? "" : "NOT "));
2431 domain->can_do_ncacn_ip_tcp = domain->active_directory;
2433 TALLOC_FREE(cli);
2435 TALLOC_FREE(mem_ctx);
2437 domain->initialized = True;
2440 /**********************************************************************
2441 Set the domain_flags (trust attributes, domain operating modes, etc...
2442 ***********************************************************************/
2444 static void set_dc_type_and_flags( struct winbindd_domain *domain )
2446 /* we always have to contact our primary domain */
2448 if ( domain->primary || domain->internal) {
2449 DEBUG(10,("set_dc_type_and_flags: setting up flags for "
2450 "primary or internal domain\n"));
2451 set_dc_type_and_flags_connect( domain );
2452 return;
2455 /* Use our DC to get the information if possible */
2457 if ( !set_dc_type_and_flags_trustinfo( domain ) ) {
2458 /* Otherwise, fallback to contacting the
2459 domain directly */
2460 set_dc_type_and_flags_connect( domain );
2463 return;
2468 /**********************************************************************
2469 ***********************************************************************/
2471 static NTSTATUS cm_get_schannel_creds(struct winbindd_domain *domain,
2472 struct netlogon_creds_cli_context **ppdc)
2474 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2475 struct rpc_pipe_client *netlogon_pipe;
2477 *ppdc = NULL;
2479 if ((!IS_DC) && (!domain->primary)) {
2480 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2483 if (domain->conn.netlogon_creds != NULL) {
2484 if (!(domain->conn.netlogon_flags & NETLOGON_NEG_AUTHENTICATED_RPC)) {
2485 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2487 *ppdc = domain->conn.netlogon_creds;
2488 return NT_STATUS_OK;
2491 result = cm_connect_netlogon(domain, &netlogon_pipe);
2492 if (!NT_STATUS_IS_OK(result)) {
2493 return result;
2496 if (domain->conn.netlogon_creds == NULL) {
2497 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2500 if (!(domain->conn.netlogon_flags & NETLOGON_NEG_AUTHENTICATED_RPC)) {
2501 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2504 *ppdc = domain->conn.netlogon_creds;
2505 return NT_STATUS_OK;
2508 NTSTATUS cm_connect_sam(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2509 bool need_rw_dc,
2510 struct rpc_pipe_client **cli, struct policy_handle *sam_handle)
2512 struct winbindd_cm_conn *conn;
2513 NTSTATUS status, result;
2514 struct netlogon_creds_cli_context *p_creds;
2515 char *machine_password = NULL;
2516 char *machine_account = NULL;
2517 const char *domain_name = NULL;
2519 if (sid_check_is_our_sam(&domain->sid)) {
2520 if (domain->rodc == false || need_rw_dc == false) {
2521 return open_internal_samr_conn(mem_ctx, domain, cli, sam_handle);
2525 status = init_dc_connection_rpc(domain, need_rw_dc);
2526 if (!NT_STATUS_IS_OK(status)) {
2527 return status;
2530 conn = &domain->conn;
2532 if (rpccli_is_connected(conn->samr_pipe)) {
2533 goto done;
2536 TALLOC_FREE(conn->samr_pipe);
2539 * No SAMR pipe yet. Attempt to get an NTLMSSP SPNEGO authenticated
2540 * sign and sealed pipe using the machine account password by
2541 * preference. If we can't - try schannel, if that fails, try
2542 * anonymous.
2545 if ((conn->cli->user_name[0] == '\0') ||
2546 (conn->cli->domain[0] == '\0') ||
2547 (conn->cli->password == NULL || conn->cli->password[0] == '\0'))
2549 status = get_trust_creds(domain, &machine_password,
2550 &machine_account, NULL);
2551 if (!NT_STATUS_IS_OK(status)) {
2552 DEBUG(10, ("cm_connect_sam: No no user available for "
2553 "domain %s, trying schannel\n", conn->cli->domain));
2554 goto schannel;
2556 domain_name = domain->name;
2557 } else {
2558 machine_password = SMB_STRDUP(conn->cli->password);
2559 machine_account = SMB_STRDUP(conn->cli->user_name);
2560 domain_name = conn->cli->domain;
2563 if (!machine_password || !machine_account) {
2564 status = NT_STATUS_NO_MEMORY;
2565 goto done;
2568 /* We have an authenticated connection. Use a NTLMSSP SPNEGO
2569 authenticated SAMR pipe with sign & seal. */
2570 status = cli_rpc_pipe_open_generic_auth(conn->cli,
2571 &ndr_table_samr,
2572 NCACN_NP,
2573 CRED_DONT_USE_KERBEROS,
2574 DCERPC_AUTH_TYPE_SPNEGO,
2575 conn->auth_level,
2576 smbXcli_conn_remote_name(conn->cli->conn),
2577 domain_name,
2578 machine_account,
2579 machine_password,
2580 &conn->samr_pipe);
2582 if (!NT_STATUS_IS_OK(status)) {
2583 DEBUG(10,("cm_connect_sam: failed to connect to SAMR "
2584 "pipe for domain %s using NTLMSSP "
2585 "authenticated pipe: user %s\\%s. Error was "
2586 "%s\n", domain->name, domain_name,
2587 machine_account, nt_errstr(status)));
2588 goto schannel;
2591 DEBUG(10,("cm_connect_sam: connected to SAMR pipe for "
2592 "domain %s using NTLMSSP authenticated "
2593 "pipe: user %s\\%s\n", domain->name,
2594 domain_name, machine_account));
2596 status = dcerpc_samr_Connect2(conn->samr_pipe->binding_handle, mem_ctx,
2597 conn->samr_pipe->desthost,
2598 SEC_FLAG_MAXIMUM_ALLOWED,
2599 &conn->sam_connect_handle,
2600 &result);
2601 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2602 goto open_domain;
2604 if (NT_STATUS_IS_OK(status)) {
2605 status = result;
2608 DEBUG(10,("cm_connect_sam: ntlmssp-sealed dcerpc_samr_Connect2 "
2609 "failed for domain %s, error was %s. Trying schannel\n",
2610 domain->name, nt_errstr(status) ));
2611 TALLOC_FREE(conn->samr_pipe);
2613 schannel:
2615 /* Fall back to schannel if it's a W2K pre-SP1 box. */
2617 status = cm_get_schannel_creds(domain, &p_creds);
2618 if (!NT_STATUS_IS_OK(status)) {
2619 /* If this call fails - conn->cli can now be NULL ! */
2620 DEBUG(10, ("cm_connect_sam: Could not get schannel auth info "
2621 "for domain %s (error %s), trying anon\n",
2622 domain->name,
2623 nt_errstr(status) ));
2624 goto anonymous;
2626 status = cli_rpc_pipe_open_schannel_with_key
2627 (conn->cli, &ndr_table_samr, NCACN_NP,
2628 domain->name, p_creds, &conn->samr_pipe);
2630 if (!NT_STATUS_IS_OK(status)) {
2631 DEBUG(10,("cm_connect_sam: failed to connect to SAMR pipe for "
2632 "domain %s using schannel. Error was %s\n",
2633 domain->name, nt_errstr(status) ));
2634 goto anonymous;
2636 DEBUG(10,("cm_connect_sam: connected to SAMR pipe for domain %s using "
2637 "schannel.\n", domain->name ));
2639 status = dcerpc_samr_Connect2(conn->samr_pipe->binding_handle, mem_ctx,
2640 conn->samr_pipe->desthost,
2641 SEC_FLAG_MAXIMUM_ALLOWED,
2642 &conn->sam_connect_handle,
2643 &result);
2644 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2645 goto open_domain;
2647 if (NT_STATUS_IS_OK(status)) {
2648 status = result;
2650 DEBUG(10,("cm_connect_sam: schannel-sealed dcerpc_samr_Connect2 failed "
2651 "for domain %s, error was %s. Trying anonymous\n",
2652 domain->name, nt_errstr(status) ));
2653 TALLOC_FREE(conn->samr_pipe);
2655 anonymous:
2657 /* Finally fall back to anonymous. */
2658 if (lp_winbind_sealed_pipes() || lp_require_strong_key()) {
2659 status = NT_STATUS_DOWNGRADE_DETECTED;
2660 DEBUG(1, ("Unwilling to make SAMR connection to domain %s"
2661 "without connection level security, "
2662 "must set 'winbind sealed pipes = false' and "
2663 "'require strong key = false' to proceed: %s\n",
2664 domain->name, nt_errstr(status)));
2665 goto done;
2667 status = cli_rpc_pipe_open_noauth(conn->cli, &ndr_table_samr,
2668 &conn->samr_pipe);
2670 if (!NT_STATUS_IS_OK(status)) {
2671 goto done;
2674 status = dcerpc_samr_Connect2(conn->samr_pipe->binding_handle, mem_ctx,
2675 conn->samr_pipe->desthost,
2676 SEC_FLAG_MAXIMUM_ALLOWED,
2677 &conn->sam_connect_handle,
2678 &result);
2679 if (!NT_STATUS_IS_OK(status)) {
2680 DEBUG(10,("cm_connect_sam: rpccli_samr_Connect2 failed "
2681 "for domain %s Error was %s\n",
2682 domain->name, nt_errstr(status) ));
2683 goto done;
2685 if (!NT_STATUS_IS_OK(result)) {
2686 status = result;
2687 DEBUG(10,("cm_connect_sam: dcerpc_samr_Connect2 failed "
2688 "for domain %s Error was %s\n",
2689 domain->name, nt_errstr(result)));
2690 goto done;
2693 open_domain:
2694 status = dcerpc_samr_OpenDomain(conn->samr_pipe->binding_handle,
2695 mem_ctx,
2696 &conn->sam_connect_handle,
2697 SEC_FLAG_MAXIMUM_ALLOWED,
2698 &domain->sid,
2699 &conn->sam_domain_handle,
2700 &result);
2701 if (!NT_STATUS_IS_OK(status)) {
2702 goto done;
2705 status = result;
2706 done:
2708 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
2710 * if we got access denied, we might just have no access rights
2711 * to talk to the remote samr server server (e.g. when we are a
2712 * PDC and we are connecting a w2k8 pdc via an interdomain
2713 * trust). In that case do not invalidate the whole connection
2714 * stack
2716 TALLOC_FREE(conn->samr_pipe);
2717 ZERO_STRUCT(conn->sam_domain_handle);
2718 return status;
2719 } else if (!NT_STATUS_IS_OK(status)) {
2720 invalidate_cm_connection(domain);
2721 return status;
2724 *cli = conn->samr_pipe;
2725 *sam_handle = conn->sam_domain_handle;
2726 SAFE_FREE(machine_password);
2727 SAFE_FREE(machine_account);
2728 return status;
2731 /**********************************************************************
2732 open an schanneld ncacn_ip_tcp connection to LSA
2733 ***********************************************************************/
2735 static NTSTATUS cm_connect_lsa_tcp(struct winbindd_domain *domain,
2736 TALLOC_CTX *mem_ctx,
2737 struct rpc_pipe_client **cli)
2739 struct winbindd_cm_conn *conn;
2740 struct netlogon_creds_cli_context *creds;
2741 NTSTATUS status;
2743 DEBUG(10,("cm_connect_lsa_tcp\n"));
2745 status = init_dc_connection_rpc(domain, false);
2746 if (!NT_STATUS_IS_OK(status)) {
2747 return status;
2750 conn = &domain->conn;
2752 if (conn->lsa_pipe_tcp &&
2753 conn->lsa_pipe_tcp->transport->transport == NCACN_IP_TCP &&
2754 conn->lsa_pipe_tcp->auth->auth_level >= DCERPC_AUTH_LEVEL_INTEGRITY &&
2755 rpccli_is_connected(conn->lsa_pipe_tcp)) {
2756 goto done;
2759 TALLOC_FREE(conn->lsa_pipe_tcp);
2761 status = cm_get_schannel_creds(domain, &creds);
2762 if (!NT_STATUS_IS_OK(status)) {
2763 goto done;
2766 status = cli_rpc_pipe_open_schannel_with_key(conn->cli,
2767 &ndr_table_lsarpc,
2768 NCACN_IP_TCP,
2769 domain->name,
2770 creds,
2771 &conn->lsa_pipe_tcp);
2772 if (!NT_STATUS_IS_OK(status)) {
2773 DEBUG(10,("cli_rpc_pipe_open_schannel_with_key failed: %s\n",
2774 nt_errstr(status)));
2775 goto done;
2778 done:
2779 if (!NT_STATUS_IS_OK(status)) {
2780 TALLOC_FREE(conn->lsa_pipe_tcp);
2781 return status;
2784 *cli = conn->lsa_pipe_tcp;
2786 return status;
2789 NTSTATUS cm_connect_lsa(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2790 struct rpc_pipe_client **cli, struct policy_handle *lsa_policy)
2792 struct winbindd_cm_conn *conn;
2793 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2794 struct netlogon_creds_cli_context *p_creds;
2796 result = init_dc_connection_rpc(domain, false);
2797 if (!NT_STATUS_IS_OK(result))
2798 return result;
2800 conn = &domain->conn;
2802 if (rpccli_is_connected(conn->lsa_pipe)) {
2803 goto done;
2806 TALLOC_FREE(conn->lsa_pipe);
2808 if ((conn->cli->user_name[0] == '\0') ||
2809 (conn->cli->domain[0] == '\0') ||
2810 (conn->cli->password == NULL || conn->cli->password[0] == '\0')) {
2811 DEBUG(10, ("cm_connect_lsa: No no user available for "
2812 "domain %s, trying schannel\n", conn->cli->domain));
2813 goto schannel;
2816 /* We have an authenticated connection. Use a NTLMSSP SPNEGO
2817 * authenticated LSA pipe with sign & seal. */
2818 result = cli_rpc_pipe_open_generic_auth
2819 (conn->cli, &ndr_table_lsarpc, NCACN_NP,
2820 CRED_DONT_USE_KERBEROS,
2821 DCERPC_AUTH_TYPE_SPNEGO,
2822 conn->auth_level,
2823 smbXcli_conn_remote_name(conn->cli->conn),
2824 conn->cli->domain, conn->cli->user_name, conn->cli->password,
2825 &conn->lsa_pipe);
2827 if (!NT_STATUS_IS_OK(result)) {
2828 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
2829 "domain %s using NTLMSSP authenticated pipe: user "
2830 "%s\\%s. Error was %s. Trying schannel.\n",
2831 domain->name, conn->cli->domain,
2832 conn->cli->user_name, nt_errstr(result)));
2833 goto schannel;
2836 DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
2837 "NTLMSSP authenticated pipe: user %s\\%s\n",
2838 domain->name, conn->cli->domain, conn->cli->user_name ));
2840 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2841 SEC_FLAG_MAXIMUM_ALLOWED,
2842 &conn->lsa_policy);
2843 if (NT_STATUS_IS_OK(result)) {
2844 goto done;
2847 DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
2848 "schannel\n"));
2850 TALLOC_FREE(conn->lsa_pipe);
2852 schannel:
2854 /* Fall back to schannel if it's a W2K pre-SP1 box. */
2856 result = cm_get_schannel_creds(domain, &p_creds);
2857 if (!NT_STATUS_IS_OK(result)) {
2858 /* If this call fails - conn->cli can now be NULL ! */
2859 DEBUG(10, ("cm_connect_lsa: Could not get schannel auth info "
2860 "for domain %s (error %s), trying anon\n",
2861 domain->name,
2862 nt_errstr(result) ));
2863 goto anonymous;
2865 result = cli_rpc_pipe_open_schannel_with_key
2866 (conn->cli, &ndr_table_lsarpc, NCACN_NP,
2867 domain->name, p_creds, &conn->lsa_pipe);
2869 if (!NT_STATUS_IS_OK(result)) {
2870 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
2871 "domain %s using schannel. Error was %s\n",
2872 domain->name, nt_errstr(result) ));
2873 goto anonymous;
2875 DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
2876 "schannel.\n", domain->name ));
2878 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2879 SEC_FLAG_MAXIMUM_ALLOWED,
2880 &conn->lsa_policy);
2881 if (NT_STATUS_IS_OK(result)) {
2882 goto done;
2885 DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
2886 "anonymous\n"));
2888 TALLOC_FREE(conn->lsa_pipe);
2890 anonymous:
2892 if (lp_winbind_sealed_pipes() || lp_require_strong_key()) {
2893 result = NT_STATUS_DOWNGRADE_DETECTED;
2894 DEBUG(1, ("Unwilling to make LSA connection to domain %s"
2895 "without connection level security, "
2896 "must set 'winbind sealed pipes = false' and "
2897 "'require strong key = false' to proceed: %s\n",
2898 domain->name, nt_errstr(result)));
2899 goto done;
2902 result = cli_rpc_pipe_open_noauth(conn->cli,
2903 &ndr_table_lsarpc,
2904 &conn->lsa_pipe);
2905 if (!NT_STATUS_IS_OK(result)) {
2906 goto done;
2909 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2910 SEC_FLAG_MAXIMUM_ALLOWED,
2911 &conn->lsa_policy);
2912 done:
2913 if (!NT_STATUS_IS_OK(result)) {
2914 invalidate_cm_connection(domain);
2915 return result;
2918 *cli = conn->lsa_pipe;
2919 *lsa_policy = conn->lsa_policy;
2920 return result;
2923 /****************************************************************************
2924 Open a LSA connection to a DC, suiteable for LSA lookup calls.
2925 ****************************************************************************/
2927 NTSTATUS cm_connect_lsat(struct winbindd_domain *domain,
2928 TALLOC_CTX *mem_ctx,
2929 struct rpc_pipe_client **cli,
2930 struct policy_handle *lsa_policy)
2932 NTSTATUS status;
2934 if (domain->can_do_ncacn_ip_tcp) {
2935 status = cm_connect_lsa_tcp(domain, mem_ctx, cli);
2936 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED) ||
2937 NT_STATUS_EQUAL(status, NT_STATUS_RPC_SEC_PKG_ERROR) ||
2938 NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_ACCESS_DENIED)) {
2939 invalidate_cm_connection(domain);
2940 status = cm_connect_lsa_tcp(domain, mem_ctx, cli);
2942 if (NT_STATUS_IS_OK(status)) {
2943 return status;
2947 * we tried twice to connect via ncan_ip_tcp and schannel and
2948 * failed - maybe it is a trusted domain we can't connect to ?
2949 * do not try tcp next time - gd
2951 domain->can_do_ncacn_ip_tcp = false;
2954 status = cm_connect_lsa(domain, mem_ctx, cli, lsa_policy);
2956 return status;
2959 /****************************************************************************
2960 Open the netlogon pipe to this DC. Use schannel if specified in client conf.
2961 session key stored in conn->netlogon_pipe->dc->sess_key.
2962 ****************************************************************************/
2964 NTSTATUS cm_connect_netlogon(struct winbindd_domain *domain,
2965 struct rpc_pipe_client **cli)
2967 struct messaging_context *msg_ctx = winbind_messaging_context();
2968 struct winbindd_cm_conn *conn;
2969 NTSTATUS result;
2970 enum netr_SchannelType sec_chan_type;
2971 const char *_account_name;
2972 const char *account_name;
2973 struct samr_Password current_nt_hash;
2974 struct samr_Password *previous_nt_hash = NULL;
2975 struct netlogon_creds_CredentialState *creds = NULL;
2976 bool ok;
2978 *cli = NULL;
2980 result = init_dc_connection_rpc(domain, true);
2981 if (!NT_STATUS_IS_OK(result)) {
2982 return result;
2985 conn = &domain->conn;
2987 if (rpccli_is_connected(conn->netlogon_pipe)) {
2988 *cli = conn->netlogon_pipe;
2989 return NT_STATUS_OK;
2992 TALLOC_FREE(conn->netlogon_pipe);
2993 conn->netlogon_flags = 0;
2994 TALLOC_FREE(conn->netlogon_creds);
2996 if ((!IS_DC) && (!domain->primary)) {
2997 goto no_schannel;
3000 ok = get_trust_pw_hash(domain->name,
3001 current_nt_hash.hash,
3002 &_account_name,
3003 &sec_chan_type);
3004 if (!ok) {
3005 DEBUG(1, ("get_trust_pw_hash failed for %s, "
3006 "unable to get NETLOGON credentials\n",
3007 domain->name));
3008 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3011 account_name = talloc_asprintf(talloc_tos(), "%s$", _account_name);
3012 if (account_name == NULL) {
3013 return NT_STATUS_NO_MEMORY;
3016 result = rpccli_create_netlogon_creds(domain->dcname,
3017 domain->name,
3018 account_name,
3019 sec_chan_type,
3020 msg_ctx,
3021 domain,
3022 &conn->netlogon_creds);
3023 if (!NT_STATUS_IS_OK(result)) {
3024 DEBUG(1, ("rpccli_create_netlogon_creds failed for %s, "
3025 "unable to create NETLOGON credentials: %s\n",
3026 domain->name, nt_errstr(result)));
3027 SAFE_FREE(previous_nt_hash);
3028 return result;
3031 result = rpccli_setup_netlogon_creds(conn->cli,
3032 conn->netlogon_creds,
3033 conn->netlogon_force_reauth,
3034 current_nt_hash,
3035 previous_nt_hash);
3036 conn->netlogon_force_reauth = false;
3037 SAFE_FREE(previous_nt_hash);
3038 if (!NT_STATUS_IS_OK(result)) {
3039 DEBUG(1, ("rpccli_setup_netlogon_creds failed for %s, "
3040 "unable to setup NETLOGON credentials: %s\n",
3041 domain->name, nt_errstr(result)));
3042 return result;
3045 result = netlogon_creds_cli_get(conn->netlogon_creds,
3046 talloc_tos(),
3047 &creds);
3048 if (!NT_STATUS_IS_OK(result)) {
3049 DEBUG(1, ("netlogon_creds_cli_get failed for %s, "
3050 "unable to get NETLOGON credentials: %s\n",
3051 domain->name, nt_errstr(result)));
3052 return result;
3054 conn->netlogon_flags = creds->negotiate_flags;
3055 TALLOC_FREE(creds);
3057 no_schannel:
3058 if (!(conn->netlogon_flags & NETLOGON_NEG_AUTHENTICATED_RPC)) {
3059 if (lp_winbind_sealed_pipes() || lp_require_strong_key()) {
3060 result = NT_STATUS_DOWNGRADE_DETECTED;
3061 DEBUG(1, ("Unwilling to make connection to domain %s"
3062 "without connection level security, "
3063 "must set 'winbind sealed pipes = false' and "
3064 "'require strong key = false' to proceed: %s\n",
3065 domain->name, nt_errstr(result)));
3066 invalidate_cm_connection(domain);
3067 return result;
3069 result = cli_rpc_pipe_open_noauth(conn->cli,
3070 &ndr_table_netlogon,
3071 &conn->netlogon_pipe);
3072 if (!NT_STATUS_IS_OK(result)) {
3073 invalidate_cm_connection(domain);
3074 return result;
3077 *cli = conn->netlogon_pipe;
3078 return NT_STATUS_OK;
3081 /* Using the credentials from the first pipe, open a signed and sealed
3082 second netlogon pipe. The session key is stored in the schannel
3083 part of the new pipe auth struct.
3086 result = cli_rpc_pipe_open_schannel_with_key(
3087 conn->cli, &ndr_table_netlogon, NCACN_NP,
3088 domain->name,
3089 conn->netlogon_creds,
3090 &conn->netlogon_pipe);
3091 if (!NT_STATUS_IS_OK(result)) {
3092 DEBUG(3, ("Could not open schannel'ed NETLOGON pipe. Error "
3093 "was %s\n", nt_errstr(result)));
3095 invalidate_cm_connection(domain);
3096 return result;
3099 *cli = conn->netlogon_pipe;
3100 return NT_STATUS_OK;
3103 void winbind_msg_ip_dropped(struct messaging_context *msg_ctx,
3104 void *private_data,
3105 uint32_t msg_type,
3106 struct server_id server_id,
3107 DATA_BLOB *data)
3109 struct winbindd_domain *domain;
3110 char *freeit = NULL;
3111 char *addr;
3113 if ((data == NULL)
3114 || (data->data == NULL)
3115 || (data->length == 0)
3116 || (data->data[data->length-1] != '\0')) {
3117 DEBUG(1, ("invalid msg_ip_dropped message: not a valid "
3118 "string\n"));
3119 return;
3122 addr = (char *)data->data;
3123 DEBUG(10, ("IP %s dropped\n", addr));
3125 if (!is_ipaddress(addr)) {
3126 char *slash;
3128 * Some code sends us ip addresses with the /netmask
3129 * suffix
3131 slash = strchr(addr, '/');
3132 if (slash == NULL) {
3133 DEBUG(1, ("invalid msg_ip_dropped message: %s",
3134 addr));
3135 return;
3137 freeit = talloc_strndup(talloc_tos(), addr, slash-addr);
3138 if (freeit == NULL) {
3139 DEBUG(1, ("talloc failed\n"));
3140 return;
3142 addr = freeit;
3143 DEBUG(10, ("Stripped /netmask to IP %s\n", addr));
3146 for (domain = domain_list(); domain != NULL; domain = domain->next) {
3147 char sockaddr[INET6_ADDRSTRLEN];
3149 if (!cli_state_is_connected(domain->conn.cli)) {
3150 continue;
3153 print_sockaddr(sockaddr, sizeof(sockaddr),
3154 smbXcli_conn_local_sockaddr(domain->conn.cli->conn));
3156 if (strequal(sockaddr, addr)) {
3157 smbXcli_conn_disconnect(domain->conn.cli->conn, NT_STATUS_OK);
3160 TALLOC_FREE(freeit);