s3:winbindd_cm: use rpccli_is_connected() helper function
[Samba.git] / source3 / winbindd / winbindd_cm.c
blob73f431a44913c19467e1ab6342b80a83b2cf8ce0
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"
64 #undef DBGC_CLASS
65 #define DBGC_CLASS DBGC_WINBIND
67 struct dc_name_ip {
68 fstring name;
69 struct sockaddr_storage ss;
72 extern struct winbindd_methods reconnect_methods;
73 extern bool override_logfile;
75 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain);
76 static void set_dc_type_and_flags( struct winbindd_domain *domain );
77 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
78 struct dc_name_ip **dcs, int *num_dcs);
80 /****************************************************************
81 Child failed to find DC's. Reschedule check.
82 ****************************************************************/
84 static void msg_failed_to_go_online(struct messaging_context *msg,
85 void *private_data,
86 uint32_t msg_type,
87 struct server_id server_id,
88 DATA_BLOB *data)
90 struct winbindd_domain *domain;
91 const char *domainname = (const char *)data->data;
93 if (data->data == NULL || data->length == 0) {
94 return;
97 DEBUG(5,("msg_fail_to_go_online: received for domain %s.\n", domainname));
99 for (domain = domain_list(); domain; domain = domain->next) {
100 if (domain->internal) {
101 continue;
104 if (strequal(domain->name, domainname)) {
105 if (domain->online) {
106 /* We're already online, ignore. */
107 DEBUG(5,("msg_fail_to_go_online: domain %s "
108 "already online.\n", domainname));
109 continue;
112 /* Reschedule the online check. */
113 set_domain_offline(domain);
114 break;
119 /****************************************************************
120 Actually cause a reconnect from a message.
121 ****************************************************************/
123 static void msg_try_to_go_online(struct messaging_context *msg,
124 void *private_data,
125 uint32_t msg_type,
126 struct server_id server_id,
127 DATA_BLOB *data)
129 struct winbindd_domain *domain;
130 const char *domainname = (const char *)data->data;
132 if (data->data == NULL || data->length == 0) {
133 return;
136 DEBUG(5,("msg_try_to_go_online: received for domain %s.\n", domainname));
138 for (domain = domain_list(); domain; domain = domain->next) {
139 if (domain->internal) {
140 continue;
143 if (strequal(domain->name, domainname)) {
145 if (domain->online) {
146 /* We're already online, ignore. */
147 DEBUG(5,("msg_try_to_go_online: domain %s "
148 "already online.\n", domainname));
149 continue;
152 /* This call takes care of setting the online
153 flag to true if we connected, or re-adding
154 the offline handler if false. Bypasses online
155 check so always does network calls. */
157 init_dc_connection_network(domain);
158 break;
163 /****************************************************************
164 Fork a child to try and contact a DC. Do this as contacting a
165 DC requires blocking lookups and we don't want to block our
166 parent.
167 ****************************************************************/
169 static bool fork_child_dc_connect(struct winbindd_domain *domain)
171 struct dc_name_ip *dcs = NULL;
172 int num_dcs = 0;
173 TALLOC_CTX *mem_ctx = NULL;
174 pid_t parent_pid = sys_getpid();
175 char *lfile = NULL;
177 /* Stop zombies */
178 CatchChild();
180 if (domain->dc_probe_pid != (pid_t)-1) {
182 * We might already have a DC probe
183 * child working, check.
185 if (process_exists_by_pid(domain->dc_probe_pid)) {
186 DEBUG(10,("fork_child_dc_connect: pid %u already "
187 "checking for DC's.\n",
188 (unsigned int)domain->dc_probe_pid));
189 return true;
191 domain->dc_probe_pid = (pid_t)-1;
194 domain->dc_probe_pid = sys_fork();
196 if (domain->dc_probe_pid == (pid_t)-1) {
197 DEBUG(0, ("fork_child_dc_connect: Could not fork: %s\n", strerror(errno)));
198 return False;
201 if (domain->dc_probe_pid != (pid_t)0) {
202 /* Parent */
203 messaging_register(winbind_messaging_context(), NULL,
204 MSG_WINBIND_TRY_TO_GO_ONLINE,
205 msg_try_to_go_online);
206 messaging_register(winbind_messaging_context(), NULL,
207 MSG_WINBIND_FAILED_TO_GO_ONLINE,
208 msg_failed_to_go_online);
209 return True;
212 /* Child. */
214 /* Leave messages blocked - we will never process one. */
216 if (!override_logfile) {
217 if (asprintf(&lfile, "%s/log.winbindd-dc-connect", get_dyn_LOGFILEBASE()) == -1) {
218 DEBUG(0, ("fork_child_dc_connect: out of memory.\n"));
219 _exit(1);
223 if (!winbindd_reinit_after_fork(lfile)) {
224 messaging_send_buf(winbind_messaging_context(),
225 pid_to_procid(parent_pid),
226 MSG_WINBIND_FAILED_TO_GO_ONLINE,
227 (uint8 *)domain->name,
228 strlen(domain->name)+1);
229 _exit(1);
231 SAFE_FREE(lfile);
233 mem_ctx = talloc_init("fork_child_dc_connect");
234 if (!mem_ctx) {
235 DEBUG(0,("talloc_init failed.\n"));
236 messaging_send_buf(winbind_messaging_context(),
237 pid_to_procid(parent_pid),
238 MSG_WINBIND_FAILED_TO_GO_ONLINE,
239 (uint8 *)domain->name,
240 strlen(domain->name)+1);
241 _exit(1);
244 if ((!get_dcs(mem_ctx, domain, &dcs, &num_dcs)) || (num_dcs == 0)) {
245 /* Still offline ? Can't find DC's. */
246 messaging_send_buf(winbind_messaging_context(),
247 pid_to_procid(parent_pid),
248 MSG_WINBIND_FAILED_TO_GO_ONLINE,
249 (uint8 *)domain->name,
250 strlen(domain->name)+1);
251 _exit(0);
254 /* We got a DC. Send a message to our parent to get it to
255 try and do the same. */
257 messaging_send_buf(winbind_messaging_context(),
258 pid_to_procid(parent_pid),
259 MSG_WINBIND_TRY_TO_GO_ONLINE,
260 (uint8 *)domain->name,
261 strlen(domain->name)+1);
262 _exit(0);
265 /****************************************************************
266 Handler triggered if we're offline to try and detect a DC.
267 ****************************************************************/
269 static void check_domain_online_handler(struct event_context *ctx,
270 struct timed_event *te,
271 struct timeval now,
272 void *private_data)
274 struct winbindd_domain *domain =
275 (struct winbindd_domain *)private_data;
277 DEBUG(10,("check_domain_online_handler: called for domain "
278 "%s (online = %s)\n", domain->name,
279 domain->online ? "True" : "False" ));
281 TALLOC_FREE(domain->check_online_event);
283 /* Are we still in "startup" mode ? */
285 if (domain->startup && (now.tv_sec > domain->startup_time + 30)) {
286 /* No longer in "startup" mode. */
287 DEBUG(10,("check_domain_online_handler: domain %s no longer in 'startup' mode.\n",
288 domain->name ));
289 domain->startup = False;
292 /* We've been told to stay offline, so stay
293 that way. */
295 if (get_global_winbindd_state_offline()) {
296 DEBUG(10,("check_domain_online_handler: domain %s remaining globally offline\n",
297 domain->name ));
298 return;
301 /* Fork a child to test if it can contact a DC.
302 If it can then send ourselves a message to
303 cause a reconnect. */
305 fork_child_dc_connect(domain);
308 /****************************************************************
309 If we're still offline setup the timeout check.
310 ****************************************************************/
312 static void calc_new_online_timeout_check(struct winbindd_domain *domain)
314 int wbr = lp_winbind_reconnect_delay();
316 if (domain->startup) {
317 domain->check_online_timeout = 10;
318 } else if (domain->check_online_timeout < wbr) {
319 domain->check_online_timeout = wbr;
323 /****************************************************************
324 Set domain offline and also add handler to put us back online
325 if we detect a DC.
326 ****************************************************************/
328 void set_domain_offline(struct winbindd_domain *domain)
330 DEBUG(10,("set_domain_offline: called for domain %s\n",
331 domain->name ));
333 TALLOC_FREE(domain->check_online_event);
335 if (domain->internal) {
336 DEBUG(3,("set_domain_offline: domain %s is internal - logic error.\n",
337 domain->name ));
338 return;
341 domain->online = False;
343 /* Offline domains are always initialized. They're
344 re-initialized when they go back online. */
346 domain->initialized = True;
348 /* We only add the timeout handler that checks and
349 allows us to go back online when we've not
350 been told to remain offline. */
352 if (get_global_winbindd_state_offline()) {
353 DEBUG(10,("set_domain_offline: domain %s remaining globally offline\n",
354 domain->name ));
355 return;
358 /* If we're in statup mode, check again in 10 seconds, not in
359 lp_winbind_reconnect_delay() seconds (which is 30 seconds by default). */
361 calc_new_online_timeout_check(domain);
363 domain->check_online_event = event_add_timed(winbind_event_context(),
364 NULL,
365 timeval_current_ofs(domain->check_online_timeout,0),
366 check_domain_online_handler,
367 domain);
369 /* The above *has* to succeed for winbindd to work. */
370 if (!domain->check_online_event) {
371 smb_panic("set_domain_offline: failed to add online handler");
374 DEBUG(10,("set_domain_offline: added event handler for domain %s\n",
375 domain->name ));
377 /* Send an offline message to the idmap child when our
378 primary domain goes offline */
380 if ( domain->primary ) {
381 struct winbindd_child *idmap = idmap_child();
383 if ( idmap->pid != 0 ) {
384 messaging_send_buf(winbind_messaging_context(),
385 pid_to_procid(idmap->pid),
386 MSG_WINBIND_OFFLINE,
387 (uint8 *)domain->name,
388 strlen(domain->name)+1);
392 return;
395 /****************************************************************
396 Set domain online - if allowed.
397 ****************************************************************/
399 static void set_domain_online(struct winbindd_domain *domain)
401 DEBUG(10,("set_domain_online: called for domain %s\n",
402 domain->name ));
404 if (domain->internal) {
405 DEBUG(3,("set_domain_online: domain %s is internal - logic error.\n",
406 domain->name ));
407 return;
410 if (get_global_winbindd_state_offline()) {
411 DEBUG(10,("set_domain_online: domain %s remaining globally offline\n",
412 domain->name ));
413 return;
416 winbindd_set_locator_kdc_envs(domain);
418 /* If we are waiting to get a krb5 ticket, trigger immediately. */
419 ccache_regain_all_now();
421 /* Ok, we're out of any startup mode now... */
422 domain->startup = False;
424 if (domain->online == False) {
425 /* We were offline - now we're online. We default to
426 using the MS-RPC backend if we started offline,
427 and if we're going online for the first time we
428 should really re-initialize the backends and the
429 checks to see if we're talking to an AD or NT domain.
432 domain->initialized = False;
434 /* 'reconnect_methods' is the MS-RPC backend. */
435 if (domain->backend == &reconnect_methods) {
436 domain->backend = NULL;
440 /* Ensure we have no online timeout checks. */
441 domain->check_online_timeout = 0;
442 TALLOC_FREE(domain->check_online_event);
444 /* Ensure we ignore any pending child messages. */
445 messaging_deregister(winbind_messaging_context(),
446 MSG_WINBIND_TRY_TO_GO_ONLINE, NULL);
447 messaging_deregister(winbind_messaging_context(),
448 MSG_WINBIND_FAILED_TO_GO_ONLINE, NULL);
450 domain->online = True;
452 /* Send an online message to the idmap child when our
453 primary domain comes online */
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_ONLINE,
462 (uint8 *)domain->name,
463 strlen(domain->name)+1);
467 return;
470 /****************************************************************
471 Requested to set a domain online.
472 ****************************************************************/
474 void set_domain_online_request(struct winbindd_domain *domain)
476 struct timeval tev;
478 DEBUG(10,("set_domain_online_request: called for domain %s\n",
479 domain->name ));
481 if (get_global_winbindd_state_offline()) {
482 DEBUG(10,("set_domain_online_request: domain %s remaining globally offline\n",
483 domain->name ));
484 return;
487 /* We've been told it's safe to go online and
488 try and connect to a DC. But I don't believe it
489 because network manager seems to lie.
490 Wait at least 5 seconds. Heuristics suck... */
493 GetTimeOfDay(&tev);
495 /* Go into "startup" mode again. */
496 domain->startup_time = tev.tv_sec;
497 domain->startup = True;
499 tev.tv_sec += 5;
501 if (!domain->check_online_event) {
502 /* If we've come from being globally offline we
503 don't have a check online event handler set.
504 We need to add one now we're trying to go
505 back online. */
507 DEBUG(10,("set_domain_online_request: domain %s was globally offline.\n",
508 domain->name ));
511 TALLOC_FREE(domain->check_online_event);
513 domain->check_online_event = event_add_timed(winbind_event_context(),
514 NULL,
515 tev,
516 check_domain_online_handler,
517 domain);
519 /* The above *has* to succeed for winbindd to work. */
520 if (!domain->check_online_event) {
521 smb_panic("set_domain_online_request: failed to add online handler");
525 /****************************************************************
526 Add -ve connection cache entries for domain and realm.
527 ****************************************************************/
529 void winbind_add_failed_connection_entry(const struct winbindd_domain *domain,
530 const char *server,
531 NTSTATUS result)
533 add_failed_connection_entry(domain->name, server, result);
534 /* If this was the saf name for the last thing we talked to,
535 remove it. */
536 saf_delete(domain->name);
537 if (*domain->alt_name) {
538 add_failed_connection_entry(domain->alt_name, server, result);
539 saf_delete(domain->alt_name);
541 winbindd_unset_locator_kdc_env(domain);
544 /* Choose between anonymous or authenticated connections. We need to use
545 an authenticated connection if DCs have the RestrictAnonymous registry
546 entry set > 0, or the "Additional restrictions for anonymous
547 connections" set in the win2k Local Security Policy.
549 Caller to free() result in domain, username, password
552 static void cm_get_ipc_userpass(char **username, char **domain, char **password)
554 *username = (char *)secrets_fetch(SECRETS_AUTH_USER, NULL);
555 *domain = (char *)secrets_fetch(SECRETS_AUTH_DOMAIN, NULL);
556 *password = (char *)secrets_fetch(SECRETS_AUTH_PASSWORD, NULL);
558 if (*username && **username) {
560 if (!*domain || !**domain)
561 *domain = smb_xstrdup(lp_workgroup());
563 if (!*password || !**password)
564 *password = smb_xstrdup("");
566 DEBUG(3, ("cm_get_ipc_userpass: Retrieved auth-user from secrets.tdb [%s\\%s]\n",
567 *domain, *username));
569 } else {
570 DEBUG(3, ("cm_get_ipc_userpass: No auth-user defined\n"));
571 *username = smb_xstrdup("");
572 *domain = smb_xstrdup("");
573 *password = smb_xstrdup("");
577 static bool get_dc_name_via_netlogon(struct winbindd_domain *domain,
578 fstring dcname,
579 struct sockaddr_storage *dc_ss)
581 struct winbindd_domain *our_domain = NULL;
582 struct rpc_pipe_client *netlogon_pipe = NULL;
583 NTSTATUS result;
584 WERROR werr;
585 TALLOC_CTX *mem_ctx;
586 unsigned int orig_timeout;
587 const char *tmp = NULL;
588 const char *p;
590 /* Hmmmm. We can only open one connection to the NETLOGON pipe at the
591 * moment.... */
593 if (IS_DC) {
594 return False;
597 if (domain->primary) {
598 return False;
601 our_domain = find_our_domain();
603 if ((mem_ctx = talloc_init("get_dc_name_via_netlogon")) == NULL) {
604 return False;
607 result = cm_connect_netlogon(our_domain, &netlogon_pipe);
608 if (!NT_STATUS_IS_OK(result)) {
609 talloc_destroy(mem_ctx);
610 return False;
613 /* This call can take a long time - allow the server to time out.
614 35 seconds should do it. */
616 orig_timeout = rpccli_set_timeout(netlogon_pipe, 35000);
618 if (our_domain->active_directory) {
619 struct netr_DsRGetDCNameInfo *domain_info = NULL;
621 result = rpccli_netr_DsRGetDCName(netlogon_pipe,
622 mem_ctx,
623 our_domain->dcname,
624 domain->name,
625 NULL,
626 NULL,
627 DS_RETURN_DNS_NAME,
628 &domain_info,
629 &werr);
630 if (NT_STATUS_IS_OK(result) && W_ERROR_IS_OK(werr)) {
631 tmp = talloc_strdup(
632 mem_ctx, domain_info->dc_unc);
633 if (tmp == NULL) {
634 DEBUG(0, ("talloc_strdup failed\n"));
635 talloc_destroy(mem_ctx);
636 return false;
638 if (strlen(domain->alt_name) == 0) {
639 fstrcpy(domain->alt_name,
640 domain_info->domain_name);
642 if (strlen(domain->forest_name) == 0) {
643 fstrcpy(domain->forest_name,
644 domain_info->forest_name);
647 } else {
648 result = rpccli_netr_GetAnyDCName(netlogon_pipe, mem_ctx,
649 our_domain->dcname,
650 domain->name,
651 &tmp,
652 &werr);
655 /* And restore our original timeout. */
656 rpccli_set_timeout(netlogon_pipe, orig_timeout);
658 if (!NT_STATUS_IS_OK(result)) {
659 DEBUG(10,("rpccli_netr_GetAnyDCName failed: %s\n",
660 nt_errstr(result)));
661 talloc_destroy(mem_ctx);
662 return false;
665 if (!W_ERROR_IS_OK(werr)) {
666 DEBUG(10,("rpccli_netr_GetAnyDCName failed: %s\n",
667 win_errstr(werr)));
668 talloc_destroy(mem_ctx);
669 return false;
672 /* rpccli_netr_GetAnyDCName gives us a name with \\ */
673 p = strip_hostname(tmp);
675 fstrcpy(dcname, p);
677 talloc_destroy(mem_ctx);
679 DEBUG(10,("rpccli_netr_GetAnyDCName returned %s\n", dcname));
681 if (!resolve_name(dcname, dc_ss, 0x20)) {
682 return False;
685 return True;
689 * Helper function to assemble trust password and account name
691 static NTSTATUS get_trust_creds(const struct winbindd_domain *domain,
692 char **machine_password,
693 char **machine_account,
694 char **machine_krb5_principal)
696 const char *account_name;
697 const char *name = NULL;
699 /* If we are a DC and this is not our own domain */
701 if (IS_DC) {
702 name = domain->name;
703 } else {
704 struct winbindd_domain *our_domain = find_our_domain();
706 if (!our_domain)
707 return NT_STATUS_INVALID_SERVER_STATE;
709 name = our_domain->name;
712 if (!get_trust_pw_clear(name, machine_password,
713 &account_name, NULL))
715 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
718 if ((machine_account != NULL) &&
719 (asprintf(machine_account, "%s$", account_name) == -1))
721 return NT_STATUS_NO_MEMORY;
724 /* For now assume our machine account only exists in our domain */
726 if (machine_krb5_principal != NULL)
728 struct winbindd_domain *our_domain = find_our_domain();
730 if (!our_domain) {
731 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
734 if (asprintf(machine_krb5_principal, "%s$@%s",
735 account_name, our_domain->alt_name) == -1)
737 return NT_STATUS_NO_MEMORY;
740 strupper_m(*machine_krb5_principal);
743 return NT_STATUS_OK;
746 /************************************************************************
747 Given a fd with a just-connected TCP connection to a DC, open a connection
748 to the pipe.
749 ************************************************************************/
751 static NTSTATUS cm_prepare_connection(const struct winbindd_domain *domain,
752 const int sockfd,
753 const char *controller,
754 struct cli_state **cli,
755 bool *retry)
757 char *machine_password = NULL;
758 char *machine_krb5_principal = NULL;
759 char *machine_account = NULL;
760 char *ipc_username = NULL;
761 char *ipc_domain = NULL;
762 char *ipc_password = NULL;
764 struct named_mutex *mutex;
766 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
768 struct sockaddr peeraddr;
769 socklen_t peeraddr_len;
771 struct sockaddr_in *peeraddr_in = (struct sockaddr_in *)&peeraddr;
773 DEBUG(10,("cm_prepare_connection: connecting to DC %s for domain %s\n",
774 controller, domain->name ));
776 *retry = True;
778 mutex = grab_named_mutex(talloc_tos(), controller,
779 WINBIND_SERVER_MUTEX_WAIT_TIME);
780 if (mutex == NULL) {
781 DEBUG(0,("cm_prepare_connection: mutex grab failed for %s\n",
782 controller));
783 result = NT_STATUS_POSSIBLE_DEADLOCK;
784 goto done;
787 if ((*cli = cli_initialise()) == NULL) {
788 DEBUG(1, ("Could not cli_initialize\n"));
789 result = NT_STATUS_NO_MEMORY;
790 goto done;
793 (*cli)->timeout = 10000; /* 10 seconds */
794 (*cli)->fd = sockfd;
795 fstrcpy((*cli)->desthost, controller);
796 (*cli)->use_kerberos = True;
798 peeraddr_len = sizeof(peeraddr);
800 if ((getpeername((*cli)->fd, &peeraddr, &peeraddr_len) != 0) ||
801 (peeraddr_len != sizeof(struct sockaddr_in)) ||
802 (peeraddr_in->sin_family != PF_INET))
804 DEBUG(0,("cm_prepare_connection: %s\n", strerror(errno)));
805 result = NT_STATUS_UNSUCCESSFUL;
806 goto done;
809 if (ntohs(peeraddr_in->sin_port) == 139) {
810 struct nmb_name calling;
811 struct nmb_name called;
813 make_nmb_name(&calling, global_myname(), 0x0);
814 make_nmb_name(&called, "*SMBSERVER", 0x20);
816 if (!cli_session_request(*cli, &calling, &called)) {
817 DEBUG(8, ("cli_session_request failed for %s\n",
818 controller));
819 result = NT_STATUS_UNSUCCESSFUL;
820 goto done;
824 result = cli_negprot(*cli);
826 if (!NT_STATUS_IS_OK(result)) {
827 DEBUG(1, ("cli_negprot failed: %s\n", nt_errstr(result)));
828 goto done;
831 if (!is_dc_trusted_domain_situation(domain->name) &&
832 (*cli)->protocol >= PROTOCOL_NT1 &&
833 (*cli)->capabilities & CAP_EXTENDED_SECURITY)
835 ADS_STATUS ads_status;
837 result = get_trust_creds(domain, &machine_password,
838 &machine_account,
839 &machine_krb5_principal);
840 if (!NT_STATUS_IS_OK(result)) {
841 goto anon_fallback;
844 if (lp_security() == SEC_ADS) {
846 /* Try a krb5 session */
848 (*cli)->use_kerberos = True;
849 DEBUG(5, ("connecting to %s from %s with kerberos principal "
850 "[%s] and realm [%s]\n", controller, global_myname(),
851 machine_krb5_principal, domain->alt_name));
853 winbindd_set_locator_kdc_envs(domain);
855 ads_status = cli_session_setup_spnego(*cli,
856 machine_krb5_principal,
857 machine_password,
858 lp_workgroup(),
859 domain->alt_name);
861 if (!ADS_ERR_OK(ads_status)) {
862 DEBUG(4,("failed kerberos session setup with %s\n",
863 ads_errstr(ads_status)));
866 result = ads_ntstatus(ads_status);
867 if (NT_STATUS_IS_OK(result)) {
868 /* Ensure creds are stored for NTLMSSP authenticated pipe access. */
869 result = cli_init_creds(*cli, machine_account, lp_workgroup(), machine_password);
870 if (!NT_STATUS_IS_OK(result)) {
871 goto done;
873 goto session_setup_done;
877 /* Fall back to non-kerberos session setup using NTLMSSP SPNEGO with the machine account. */
878 (*cli)->use_kerberos = False;
880 DEBUG(5, ("connecting to %s from %s with username "
881 "[%s]\\[%s]\n", controller, global_myname(),
882 lp_workgroup(), machine_account));
884 ads_status = cli_session_setup_spnego(*cli,
885 machine_account,
886 machine_password,
887 lp_workgroup(),
888 NULL);
889 if (!ADS_ERR_OK(ads_status)) {
890 DEBUG(4, ("authenticated session setup failed with %s\n",
891 ads_errstr(ads_status)));
894 result = ads_ntstatus(ads_status);
895 if (NT_STATUS_IS_OK(result)) {
896 /* Ensure creds are stored for NTLMSSP authenticated pipe access. */
897 result = cli_init_creds(*cli, machine_account, lp_workgroup(), machine_password);
898 if (!NT_STATUS_IS_OK(result)) {
899 goto done;
901 goto session_setup_done;
905 /* Fall back to non-kerberos session setup with auth_user */
907 (*cli)->use_kerberos = False;
909 cm_get_ipc_userpass(&ipc_username, &ipc_domain, &ipc_password);
911 if ((((*cli)->sec_mode & NEGOTIATE_SECURITY_CHALLENGE_RESPONSE) != 0) &&
912 (strlen(ipc_username) > 0)) {
914 /* Only try authenticated if we have a username */
916 DEBUG(5, ("connecting to %s from %s with username "
917 "[%s]\\[%s]\n", controller, global_myname(),
918 ipc_domain, ipc_username));
920 if (NT_STATUS_IS_OK(cli_session_setup(
921 *cli, ipc_username,
922 ipc_password, strlen(ipc_password)+1,
923 ipc_password, strlen(ipc_password)+1,
924 ipc_domain))) {
925 /* Successful logon with given username. */
926 result = cli_init_creds(*cli, ipc_username, ipc_domain, ipc_password);
927 if (!NT_STATUS_IS_OK(result)) {
928 goto done;
930 goto session_setup_done;
931 } else {
932 DEBUG(4, ("authenticated session setup with user %s\\%s failed.\n",
933 ipc_domain, ipc_username ));
937 anon_fallback:
939 /* Fall back to anonymous connection, this might fail later */
940 DEBUG(10,("cm_prepare_connection: falling back to anonymous "
941 "connection for DC %s\n",
942 controller ));
944 if (NT_STATUS_IS_OK(cli_session_setup(*cli, "", NULL, 0,
945 NULL, 0, ""))) {
946 DEBUG(5, ("Connected anonymously\n"));
947 result = cli_init_creds(*cli, "", "", "");
948 if (!NT_STATUS_IS_OK(result)) {
949 goto done;
951 goto session_setup_done;
954 result = cli_nt_error(*cli);
956 if (NT_STATUS_IS_OK(result))
957 result = NT_STATUS_UNSUCCESSFUL;
959 /* We can't session setup */
961 goto done;
963 session_setup_done:
965 /* cache the server name for later connections */
967 saf_store( domain->name, (*cli)->desthost );
968 if (domain->alt_name && (*cli)->use_kerberos) {
969 saf_store( domain->alt_name, (*cli)->desthost );
972 winbindd_set_locator_kdc_envs(domain);
974 result = cli_tcon_andx(*cli, "IPC$", "IPC", "", 0);
976 if (!NT_STATUS_IS_OK(result)) {
977 DEBUG(1,("failed tcon_X with %s\n", nt_errstr(result)));
978 goto done;
981 TALLOC_FREE(mutex);
982 *retry = False;
984 /* set the domain if empty; needed for schannel connections */
985 if ( !(*cli)->domain[0] ) {
986 result = cli_set_domain((*cli), domain->name);
987 if (!NT_STATUS_IS_OK(result)) {
988 return result;
992 result = NT_STATUS_OK;
994 done:
995 TALLOC_FREE(mutex);
996 SAFE_FREE(machine_account);
997 SAFE_FREE(machine_password);
998 SAFE_FREE(machine_krb5_principal);
999 SAFE_FREE(ipc_username);
1000 SAFE_FREE(ipc_domain);
1001 SAFE_FREE(ipc_password);
1003 if (!NT_STATUS_IS_OK(result)) {
1004 winbind_add_failed_connection_entry(domain, controller, result);
1005 if ((*cli) != NULL) {
1006 cli_shutdown(*cli);
1007 *cli = NULL;
1011 return result;
1014 /*******************************************************************
1015 Add a dcname and sockaddr_storage pair to the end of a dc_name_ip
1016 array.
1018 Keeps the list unique by not adding duplicate entries.
1020 @param[in] mem_ctx talloc memory context to allocate from
1021 @param[in] domain_name domain of the DC
1022 @param[in] dcname name of the DC to add to the list
1023 @param[in] pss Internet address and port pair to add to the list
1024 @param[in,out] dcs array of dc_name_ip structures to add to
1025 @param[in,out] num_dcs number of dcs returned in the dcs array
1026 @return true if the list was added to, false otherwise
1027 *******************************************************************/
1029 static bool add_one_dc_unique(TALLOC_CTX *mem_ctx, const char *domain_name,
1030 const char *dcname, struct sockaddr_storage *pss,
1031 struct dc_name_ip **dcs, int *num)
1033 int i = 0;
1035 if (!NT_STATUS_IS_OK(check_negative_conn_cache(domain_name, dcname))) {
1036 DEBUG(10, ("DC %s was in the negative conn cache\n", dcname));
1037 return False;
1040 /* Make sure there's no duplicates in the list */
1041 for (i=0; i<*num; i++)
1042 if (sockaddr_equal((struct sockaddr *)&(*dcs)[i].ss, (struct sockaddr *)pss))
1043 return False;
1045 *dcs = TALLOC_REALLOC_ARRAY(mem_ctx, *dcs, struct dc_name_ip, (*num)+1);
1047 if (*dcs == NULL)
1048 return False;
1050 fstrcpy((*dcs)[*num].name, dcname);
1051 (*dcs)[*num].ss = *pss;
1052 *num += 1;
1053 return True;
1056 static bool add_sockaddr_to_array(TALLOC_CTX *mem_ctx,
1057 struct sockaddr_storage *pss, uint16 port,
1058 struct sockaddr_storage **addrs, int *num)
1060 *addrs = TALLOC_REALLOC_ARRAY(mem_ctx, *addrs, struct sockaddr_storage, (*num)+1);
1062 if (*addrs == NULL) {
1063 *num = 0;
1064 return False;
1067 (*addrs)[*num] = *pss;
1068 set_sockaddr_port((struct sockaddr *)&(*addrs)[*num], port);
1070 *num += 1;
1071 return True;
1074 /*******************************************************************
1075 convert an ip to a name
1076 *******************************************************************/
1078 static bool dcip_to_name(TALLOC_CTX *mem_ctx,
1079 const struct winbindd_domain *domain,
1080 struct sockaddr_storage *pss,
1081 fstring name )
1083 struct ip_service ip_list;
1084 uint32_t nt_version = NETLOGON_NT_VERSION_1;
1086 ip_list.ss = *pss;
1087 ip_list.port = 0;
1089 #ifdef WITH_ADS
1090 /* For active directory servers, try to get the ldap server name.
1091 None of these failures should be considered critical for now */
1093 if (lp_security() == SEC_ADS) {
1094 ADS_STRUCT *ads;
1095 ADS_STATUS ads_status;
1096 char addr[INET6_ADDRSTRLEN];
1098 print_sockaddr(addr, sizeof(addr), pss);
1100 ads = ads_init(domain->alt_name, domain->name, addr);
1101 ads->auth.flags |= ADS_AUTH_NO_BIND;
1103 ads_status = ads_connect(ads);
1104 if (ADS_ERR_OK(ads_status)) {
1105 /* We got a cldap packet. */
1106 fstrcpy(name, ads->config.ldap_server_name);
1107 namecache_store(name, 0x20, 1, &ip_list);
1109 DEBUG(10,("dcip_to_name: flags = 0x%x\n", (unsigned int)ads->config.flags));
1111 if (domain->primary && (ads->config.flags & NBT_SERVER_KDC)) {
1112 if (ads_closest_dc(ads)) {
1113 char *sitename = sitename_fetch(ads->config.realm);
1115 /* We're going to use this KDC for this realm/domain.
1116 If we are using sites, then force the krb5 libs
1117 to use this KDC. */
1119 create_local_private_krb5_conf_for_domain(domain->alt_name,
1120 domain->name,
1121 sitename,
1122 pss);
1124 SAFE_FREE(sitename);
1125 } else {
1126 /* use an off site KDC */
1127 create_local_private_krb5_conf_for_domain(domain->alt_name,
1128 domain->name,
1129 NULL,
1130 pss);
1132 winbindd_set_locator_kdc_envs(domain);
1134 /* Ensure we contact this DC also. */
1135 saf_store( domain->name, name);
1136 saf_store( domain->alt_name, name);
1139 ads_destroy( &ads );
1140 return True;
1143 ads_destroy( &ads );
1145 #endif
1147 /* try GETDC requests next */
1149 if (send_getdc_request(mem_ctx, winbind_messaging_context(),
1150 pss, domain->name, &domain->sid,
1151 nt_version)) {
1152 const char *dc_name = NULL;
1153 int i;
1154 smb_msleep(100);
1155 for (i=0; i<5; i++) {
1156 if (receive_getdc_response(mem_ctx, pss, domain->name,
1157 &nt_version,
1158 &dc_name, NULL)) {
1159 fstrcpy(name, dc_name);
1160 namecache_store(name, 0x20, 1, &ip_list);
1161 return True;
1163 smb_msleep(500);
1167 /* try node status request */
1169 if ( name_status_find(domain->name, 0x1c, 0x20, pss, name) ) {
1170 namecache_store(name, 0x20, 1, &ip_list);
1171 return True;
1173 return False;
1176 /*******************************************************************
1177 Retrieve a list of IP addresses for domain controllers.
1179 The array is sorted in the preferred connection order.
1181 @param[in] mem_ctx talloc memory context to allocate from
1182 @param[in] domain domain to retrieve DCs for
1183 @param[out] dcs array of dcs that will be returned
1184 @param[out] num_dcs number of dcs returned in the dcs array
1185 @return always true
1186 *******************************************************************/
1188 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
1189 struct dc_name_ip **dcs, int *num_dcs)
1191 fstring dcname;
1192 struct sockaddr_storage ss;
1193 struct ip_service *ip_list = NULL;
1194 int iplist_size = 0;
1195 int i;
1196 bool is_our_domain;
1197 enum security_types sec = (enum security_types)lp_security();
1199 is_our_domain = strequal(domain->name, lp_workgroup());
1201 /* If not our domain, get the preferred DC, by asking our primary DC */
1202 if ( !is_our_domain
1203 && get_dc_name_via_netlogon(domain, dcname, &ss)
1204 && add_one_dc_unique(mem_ctx, domain->name, dcname, &ss, dcs,
1205 num_dcs) )
1207 char addr[INET6_ADDRSTRLEN];
1208 print_sockaddr(addr, sizeof(addr), &ss);
1209 DEBUG(10, ("Retrieved DC %s at %s via netlogon\n",
1210 dcname, addr));
1211 return True;
1214 if (sec == SEC_ADS) {
1215 char *sitename = NULL;
1217 /* We need to make sure we know the local site before
1218 doing any DNS queries, as this will restrict the
1219 get_sorted_dc_list() call below to only fetching
1220 DNS records for the correct site. */
1222 /* Find any DC to get the site record.
1223 We deliberately don't care about the
1224 return here. */
1226 get_dc_name(domain->name, domain->alt_name, dcname, &ss);
1228 sitename = sitename_fetch(domain->alt_name);
1229 if (sitename) {
1231 /* Do the site-specific AD dns lookup first. */
1232 get_sorted_dc_list(domain->alt_name, sitename, &ip_list,
1233 &iplist_size, True);
1235 /* Add ips to the DC array. We don't look up the name
1236 of the DC in this function, but we fill in the char*
1237 of the ip now to make the failed connection cache
1238 work */
1239 for ( i=0; i<iplist_size; i++ ) {
1240 char addr[INET6_ADDRSTRLEN];
1241 print_sockaddr(addr, sizeof(addr),
1242 &ip_list[i].ss);
1243 add_one_dc_unique(mem_ctx,
1244 domain->name,
1245 addr,
1246 &ip_list[i].ss,
1247 dcs,
1248 num_dcs);
1251 SAFE_FREE(ip_list);
1252 SAFE_FREE(sitename);
1253 iplist_size = 0;
1256 /* Now we add DCs from the main AD DNS lookup. */
1257 get_sorted_dc_list(domain->alt_name, NULL, &ip_list,
1258 &iplist_size, True);
1260 for ( i=0; i<iplist_size; i++ ) {
1261 char addr[INET6_ADDRSTRLEN];
1262 print_sockaddr(addr, sizeof(addr),
1263 &ip_list[i].ss);
1264 add_one_dc_unique(mem_ctx,
1265 domain->name,
1266 addr,
1267 &ip_list[i].ss,
1268 dcs,
1269 num_dcs);
1272 SAFE_FREE(ip_list);
1273 iplist_size = 0;
1276 /* Try standard netbios queries if no ADS */
1277 if (*num_dcs == 0) {
1278 get_sorted_dc_list(domain->name, NULL, &ip_list, &iplist_size,
1279 False);
1281 for ( i=0; i<iplist_size; i++ ) {
1282 char addr[INET6_ADDRSTRLEN];
1283 print_sockaddr(addr, sizeof(addr),
1284 &ip_list[i].ss);
1285 add_one_dc_unique(mem_ctx,
1286 domain->name,
1287 addr,
1288 &ip_list[i].ss,
1289 dcs,
1290 num_dcs);
1293 SAFE_FREE(ip_list);
1294 iplist_size = 0;
1297 return True;
1300 /*******************************************************************
1301 Find and make a connection to a DC in the given domain.
1303 @param[in] mem_ctx talloc memory context to allocate from
1304 @param[in] domain domain to find a dc in
1305 @param[out] dcname NetBIOS or FQDN of DC that's connected to
1306 @param[out] pss DC Internet address and port
1307 @param[out] fd fd of the open socket connected to the newly found dc
1308 @return true when a DC connection is made, false otherwise
1309 *******************************************************************/
1311 static bool find_new_dc(TALLOC_CTX *mem_ctx,
1312 struct winbindd_domain *domain,
1313 fstring dcname, struct sockaddr_storage *pss, int *fd)
1315 struct dc_name_ip *dcs = NULL;
1316 int num_dcs = 0;
1318 const char **dcnames = NULL;
1319 int num_dcnames = 0;
1321 struct sockaddr_storage *addrs = NULL;
1322 int num_addrs = 0;
1324 int i, fd_index;
1326 *fd = -1;
1328 again:
1329 if (!get_dcs(mem_ctx, domain, &dcs, &num_dcs) || (num_dcs == 0))
1330 return False;
1332 for (i=0; i<num_dcs; i++) {
1334 if (!add_string_to_array(mem_ctx, dcs[i].name,
1335 &dcnames, &num_dcnames)) {
1336 return False;
1338 if (!add_sockaddr_to_array(mem_ctx, &dcs[i].ss, 445,
1339 &addrs, &num_addrs)) {
1340 return False;
1343 if (!add_string_to_array(mem_ctx, dcs[i].name,
1344 &dcnames, &num_dcnames)) {
1345 return False;
1347 if (!add_sockaddr_to_array(mem_ctx, &dcs[i].ss, 139,
1348 &addrs, &num_addrs)) {
1349 return False;
1353 if ((num_dcnames == 0) || (num_dcnames != num_addrs))
1354 return False;
1356 if ((addrs == NULL) || (dcnames == NULL))
1357 return False;
1359 /* 5 second timeout. */
1360 if (!open_any_socket_out(addrs, num_addrs, 5000, &fd_index, fd) ) {
1361 for (i=0; i<num_dcs; i++) {
1362 char ab[INET6_ADDRSTRLEN];
1363 print_sockaddr(ab, sizeof(ab), &dcs[i].ss);
1364 DEBUG(10, ("find_new_dc: open_any_socket_out failed for "
1365 "domain %s address %s. Error was %s\n",
1366 domain->name, ab, strerror(errno) ));
1367 winbind_add_failed_connection_entry(domain,
1368 dcs[i].name, NT_STATUS_UNSUCCESSFUL);
1370 return False;
1373 *pss = addrs[fd_index];
1375 if (*dcnames[fd_index] != '\0' && !is_ipaddress(dcnames[fd_index])) {
1376 /* Ok, we've got a name for the DC */
1377 fstrcpy(dcname, dcnames[fd_index]);
1378 return True;
1381 /* Try to figure out the name */
1382 if (dcip_to_name(mem_ctx, domain, pss, dcname)) {
1383 return True;
1386 /* We can not continue without the DC's name */
1387 winbind_add_failed_connection_entry(domain, dcs[fd_index].name,
1388 NT_STATUS_UNSUCCESSFUL);
1390 /* Throw away all arrays as we're doing this again. */
1391 TALLOC_FREE(dcs);
1392 num_dcs = 0;
1394 TALLOC_FREE(dcnames);
1395 num_dcnames = 0;
1397 TALLOC_FREE(addrs);
1398 num_addrs = 0;
1400 close(*fd);
1401 *fd = -1;
1403 goto again;
1406 static NTSTATUS cm_open_connection(struct winbindd_domain *domain,
1407 struct winbindd_cm_conn *new_conn)
1409 TALLOC_CTX *mem_ctx;
1410 NTSTATUS result;
1411 char *saf_servername = saf_fetch( domain->name );
1412 int retries;
1414 if ((mem_ctx = talloc_init("cm_open_connection")) == NULL) {
1415 SAFE_FREE(saf_servername);
1416 set_domain_offline(domain);
1417 return NT_STATUS_NO_MEMORY;
1420 /* we have to check the server affinity cache here since
1421 later we selecte a DC based on response time and not preference */
1423 /* Check the negative connection cache
1424 before talking to it. It going down may have
1425 triggered the reconnection. */
1427 if ( saf_servername && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, saf_servername))) {
1429 DEBUG(10,("cm_open_connection: saf_servername is '%s' for domain %s\n",
1430 saf_servername, domain->name ));
1432 /* convert an ip address to a name */
1433 if (is_ipaddress( saf_servername ) ) {
1434 fstring saf_name;
1435 struct sockaddr_storage ss;
1437 if (!interpret_string_addr(&ss, saf_servername,
1438 AI_NUMERICHOST)) {
1439 return NT_STATUS_UNSUCCESSFUL;
1441 if (dcip_to_name(mem_ctx, domain, &ss, saf_name )) {
1442 fstrcpy( domain->dcname, saf_name );
1443 } else {
1444 winbind_add_failed_connection_entry(
1445 domain, saf_servername,
1446 NT_STATUS_UNSUCCESSFUL);
1448 } else {
1449 fstrcpy( domain->dcname, saf_servername );
1452 SAFE_FREE( saf_servername );
1455 for (retries = 0; retries < 3; retries++) {
1456 int fd = -1;
1457 bool retry = False;
1459 result = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1461 DEBUG(10,("cm_open_connection: dcname is '%s' for domain %s\n",
1462 domain->dcname, domain->name ));
1464 if (*domain->dcname
1465 && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, domain->dcname))
1466 && (resolve_name(domain->dcname, &domain->dcaddr, 0x20)))
1468 struct sockaddr_storage *addrs = NULL;
1469 int num_addrs = 0;
1470 int dummy = 0;
1472 if (!add_sockaddr_to_array(mem_ctx, &domain->dcaddr, 445, &addrs, &num_addrs)) {
1473 set_domain_offline(domain);
1474 talloc_destroy(mem_ctx);
1475 return NT_STATUS_NO_MEMORY;
1477 if (!add_sockaddr_to_array(mem_ctx, &domain->dcaddr, 139, &addrs, &num_addrs)) {
1478 set_domain_offline(domain);
1479 talloc_destroy(mem_ctx);
1480 return NT_STATUS_NO_MEMORY;
1483 /* 5 second timeout. */
1484 if (!open_any_socket_out(addrs, num_addrs, 5000, &dummy, &fd)) {
1485 fd = -1;
1489 if ((fd == -1)
1490 && !find_new_dc(mem_ctx, domain, domain->dcname, &domain->dcaddr, &fd))
1492 /* This is the one place where we will
1493 set the global winbindd offline state
1494 to true, if a "WINBINDD_OFFLINE" entry
1495 is found in the winbindd cache. */
1496 set_global_winbindd_state_offline();
1497 break;
1500 new_conn->cli = NULL;
1502 result = cm_prepare_connection(domain, fd, domain->dcname,
1503 &new_conn->cli, &retry);
1505 if (!retry)
1506 break;
1509 if (NT_STATUS_IS_OK(result)) {
1511 winbindd_set_locator_kdc_envs(domain);
1513 if (domain->online == False) {
1514 /* We're changing state from offline to online. */
1515 set_global_winbindd_state_online();
1517 set_domain_online(domain);
1518 } else {
1519 /* Ensure we setup the retry handler. */
1520 set_domain_offline(domain);
1523 talloc_destroy(mem_ctx);
1524 return result;
1527 /* Close down all open pipes on a connection. */
1529 void invalidate_cm_connection(struct winbindd_cm_conn *conn)
1531 /* We're closing down a possibly dead
1532 connection. Don't have impossibly long (10s) timeouts. */
1534 if (conn->cli) {
1535 cli_set_timeout(conn->cli, 1000); /* 1 second. */
1538 if (conn->samr_pipe != NULL) {
1539 TALLOC_FREE(conn->samr_pipe);
1540 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1541 if (conn->cli) {
1542 cli_set_timeout(conn->cli, 500);
1546 if (conn->lsa_pipe != NULL) {
1547 TALLOC_FREE(conn->lsa_pipe);
1548 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1549 if (conn->cli) {
1550 cli_set_timeout(conn->cli, 500);
1554 if (conn->lsa_pipe_tcp != NULL) {
1555 TALLOC_FREE(conn->lsa_pipe_tcp);
1556 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1557 if (conn->cli) {
1558 cli_set_timeout(conn->cli, 500);
1562 if (conn->netlogon_pipe != NULL) {
1563 TALLOC_FREE(conn->netlogon_pipe);
1564 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1565 if (conn->cli) {
1566 cli_set_timeout(conn->cli, 500);
1570 if (conn->cli) {
1571 cli_shutdown(conn->cli);
1574 conn->cli = NULL;
1577 void close_conns_after_fork(void)
1579 struct winbindd_domain *domain;
1581 for (domain = domain_list(); domain; domain = domain->next) {
1582 if (domain->conn.cli == NULL)
1583 continue;
1585 if (domain->conn.cli->fd == -1)
1586 continue;
1588 close(domain->conn.cli->fd);
1589 domain->conn.cli->fd = -1;
1593 static bool connection_ok(struct winbindd_domain *domain)
1595 bool ok;
1597 ok = cli_state_is_connected(domain->conn.cli);
1598 if (!ok) {
1599 DEBUG(3, ("connection_ok: Connection to %s for domain %s is not connected\n",
1600 domain->dcname, domain->name));
1601 return False;
1604 if (domain->online == False) {
1605 DEBUG(3, ("connection_ok: Domain %s is offline\n", domain->name));
1606 return False;
1609 return True;
1612 /* Initialize a new connection up to the RPC BIND.
1613 Bypass online status check so always does network calls. */
1615 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain)
1617 NTSTATUS result;
1619 /* Internal connections never use the network. */
1620 if (domain->internal || !winbindd_can_contact_domain(domain)) {
1621 domain->initialized = True;
1622 return NT_STATUS_OK;
1625 if (connection_ok(domain)) {
1626 if (!domain->initialized) {
1627 set_dc_type_and_flags(domain);
1629 return NT_STATUS_OK;
1632 invalidate_cm_connection(&domain->conn);
1634 result = cm_open_connection(domain, &domain->conn);
1636 if (NT_STATUS_IS_OK(result) && !domain->initialized) {
1637 set_dc_type_and_flags(domain);
1640 return result;
1643 NTSTATUS init_dc_connection(struct winbindd_domain *domain)
1645 if (domain->initialized && !domain->online) {
1646 /* We check for online status elsewhere. */
1647 return NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1650 return init_dc_connection_network(domain);
1653 /******************************************************************************
1654 Set the trust flags (direction and forest location) for a domain
1655 ******************************************************************************/
1657 static bool set_dc_type_and_flags_trustinfo( struct winbindd_domain *domain )
1659 struct winbindd_domain *our_domain;
1660 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
1661 struct netr_DomainTrustList trusts;
1662 int i;
1663 uint32 flags = (NETR_TRUST_FLAG_IN_FOREST |
1664 NETR_TRUST_FLAG_OUTBOUND |
1665 NETR_TRUST_FLAG_INBOUND);
1666 struct rpc_pipe_client *cli;
1667 TALLOC_CTX *mem_ctx = NULL;
1669 DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s\n", domain->name ));
1671 /* Our primary domain doesn't need to worry about trust flags.
1672 Force it to go through the network setup */
1673 if ( domain->primary ) {
1674 return False;
1677 our_domain = find_our_domain();
1679 if ( !connection_ok(our_domain) ) {
1680 DEBUG(3,("set_dc_type_and_flags_trustinfo: No connection to our domain!\n"));
1681 return False;
1684 /* This won't work unless our domain is AD */
1686 if ( !our_domain->active_directory ) {
1687 return False;
1690 /* Use DsEnumerateDomainTrusts to get us the trust direction
1691 and type */
1693 result = cm_connect_netlogon(our_domain, &cli);
1695 if (!NT_STATUS_IS_OK(result)) {
1696 DEBUG(5, ("set_dc_type_and_flags_trustinfo: Could not open "
1697 "a connection to %s for PIPE_NETLOGON (%s)\n",
1698 domain->name, nt_errstr(result)));
1699 return False;
1702 if ( (mem_ctx = talloc_init("set_dc_type_and_flags_trustinfo")) == NULL ) {
1703 DEBUG(0,("set_dc_type_and_flags_trustinfo: talloc_init() failed!\n"));
1704 return False;
1707 result = rpccli_netr_DsrEnumerateDomainTrusts(cli, mem_ctx,
1708 cli->desthost,
1709 flags,
1710 &trusts,
1711 NULL);
1712 if (!NT_STATUS_IS_OK(result)) {
1713 DEBUG(0,("set_dc_type_and_flags_trustinfo: "
1714 "failed to query trusted domain list: %s\n",
1715 nt_errstr(result)));
1716 talloc_destroy(mem_ctx);
1717 return false;
1720 /* Now find the domain name and get the flags */
1722 for ( i=0; i<trusts.count; i++ ) {
1723 if ( strequal( domain->name, trusts.array[i].netbios_name) ) {
1724 domain->domain_flags = trusts.array[i].trust_flags;
1725 domain->domain_type = trusts.array[i].trust_type;
1726 domain->domain_trust_attribs = trusts.array[i].trust_attributes;
1728 if ( domain->domain_type == NETR_TRUST_TYPE_UPLEVEL )
1729 domain->active_directory = True;
1731 /* This flag is only set if the domain is *our*
1732 primary domain and the primary domain is in
1733 native mode */
1735 domain->native_mode = (domain->domain_flags & NETR_TRUST_FLAG_NATIVE);
1737 DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s is %sin "
1738 "native mode.\n", domain->name,
1739 domain->native_mode ? "" : "NOT "));
1741 DEBUG(5,("set_dc_type_and_flags_trustinfo: domain %s is %s"
1742 "running active directory.\n", domain->name,
1743 domain->active_directory ? "" : "NOT "));
1746 domain->initialized = True;
1748 break;
1752 talloc_destroy( mem_ctx );
1754 return domain->initialized;
1757 /******************************************************************************
1758 We can 'sense' certain things about the DC by it's replies to certain
1759 questions.
1761 This tells us if this particular remote server is Active Directory, and if it
1762 is native mode.
1763 ******************************************************************************/
1765 static void set_dc_type_and_flags_connect( struct winbindd_domain *domain )
1767 NTSTATUS result;
1768 WERROR werr;
1769 TALLOC_CTX *mem_ctx = NULL;
1770 struct rpc_pipe_client *cli = NULL;
1771 struct policy_handle pol;
1772 union dssetup_DsRoleInfo info;
1773 union lsa_PolicyInformation *lsa_info = NULL;
1775 if (!connection_ok(domain)) {
1776 return;
1779 mem_ctx = talloc_init("set_dc_type_and_flags on domain %s\n",
1780 domain->name);
1781 if (!mem_ctx) {
1782 DEBUG(1, ("set_dc_type_and_flags_connect: talloc_init() failed\n"));
1783 return;
1786 DEBUG(5, ("set_dc_type_and_flags_connect: domain %s\n", domain->name ));
1788 result = cli_rpc_pipe_open_noauth(domain->conn.cli,
1789 &ndr_table_dssetup.syntax_id,
1790 &cli);
1792 if (!NT_STATUS_IS_OK(result)) {
1793 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
1794 "PI_DSSETUP on domain %s: (%s)\n",
1795 domain->name, nt_errstr(result)));
1797 /* if this is just a non-AD domain we need to continue
1798 * identifying so that we can in the end return with
1799 * domain->initialized = True - gd */
1801 goto no_dssetup;
1804 result = rpccli_dssetup_DsRoleGetPrimaryDomainInformation(cli, mem_ctx,
1805 DS_ROLE_BASIC_INFORMATION,
1806 &info,
1807 &werr);
1808 TALLOC_FREE(cli);
1810 if (!NT_STATUS_IS_OK(result)) {
1811 DEBUG(5, ("set_dc_type_and_flags_connect: rpccli_ds_getprimarydominfo "
1812 "on domain %s failed: (%s)\n",
1813 domain->name, nt_errstr(result)));
1815 /* older samba3 DCs will return DCERPC_FAULT_OP_RNG_ERROR for
1816 * every opcode on the DSSETUP pipe, continue with
1817 * no_dssetup mode here as well to get domain->initialized
1818 * set - gd */
1820 if (NT_STATUS_V(result) == DCERPC_FAULT_OP_RNG_ERROR) {
1821 goto no_dssetup;
1824 TALLOC_FREE(mem_ctx);
1825 return;
1828 if ((info.basic.flags & DS_ROLE_PRIMARY_DS_RUNNING) &&
1829 !(info.basic.flags & DS_ROLE_PRIMARY_DS_MIXED_MODE)) {
1830 domain->native_mode = True;
1831 } else {
1832 domain->native_mode = False;
1835 no_dssetup:
1836 result = cli_rpc_pipe_open_noauth(domain->conn.cli,
1837 &ndr_table_lsarpc.syntax_id, &cli);
1839 if (!NT_STATUS_IS_OK(result)) {
1840 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
1841 "PI_LSARPC on domain %s: (%s)\n",
1842 domain->name, nt_errstr(result)));
1843 TALLOC_FREE(cli);
1844 TALLOC_FREE(mem_ctx);
1845 return;
1848 result = rpccli_lsa_open_policy2(cli, mem_ctx, True,
1849 SEC_FLAG_MAXIMUM_ALLOWED, &pol);
1851 if (NT_STATUS_IS_OK(result)) {
1852 /* This particular query is exactly what Win2k clients use
1853 to determine that the DC is active directory */
1854 result = rpccli_lsa_QueryInfoPolicy2(cli, mem_ctx,
1855 &pol,
1856 LSA_POLICY_INFO_DNS,
1857 &lsa_info);
1860 if (NT_STATUS_IS_OK(result)) {
1861 domain->active_directory = True;
1863 if (lsa_info->dns.name.string) {
1864 fstrcpy(domain->name, lsa_info->dns.name.string);
1867 if (lsa_info->dns.dns_domain.string) {
1868 fstrcpy(domain->alt_name,
1869 lsa_info->dns.dns_domain.string);
1872 /* See if we can set some domain trust flags about
1873 ourself */
1875 if (lsa_info->dns.dns_forest.string) {
1876 fstrcpy(domain->forest_name,
1877 lsa_info->dns.dns_forest.string);
1879 if (strequal(domain->forest_name, domain->alt_name)) {
1880 domain->domain_flags |= NETR_TRUST_FLAG_TREEROOT;
1884 if (lsa_info->dns.sid) {
1885 sid_copy(&domain->sid, lsa_info->dns.sid);
1887 } else {
1888 domain->active_directory = False;
1890 result = rpccli_lsa_open_policy(cli, mem_ctx, True,
1891 SEC_FLAG_MAXIMUM_ALLOWED,
1892 &pol);
1894 if (!NT_STATUS_IS_OK(result)) {
1895 goto done;
1898 result = rpccli_lsa_QueryInfoPolicy(cli, mem_ctx,
1899 &pol,
1900 LSA_POLICY_INFO_ACCOUNT_DOMAIN,
1901 &lsa_info);
1903 if (NT_STATUS_IS_OK(result)) {
1905 if (lsa_info->account_domain.name.string) {
1906 fstrcpy(domain->name,
1907 lsa_info->account_domain.name.string);
1910 if (lsa_info->account_domain.sid) {
1911 sid_copy(&domain->sid, lsa_info->account_domain.sid);
1915 done:
1917 DEBUG(5, ("set_dc_type_and_flags_connect: domain %s is %sin native mode.\n",
1918 domain->name, domain->native_mode ? "" : "NOT "));
1920 DEBUG(5,("set_dc_type_and_flags_connect: domain %s is %srunning active directory.\n",
1921 domain->name, domain->active_directory ? "" : "NOT "));
1923 domain->can_do_ncacn_ip_tcp = domain->active_directory;
1925 TALLOC_FREE(cli);
1927 TALLOC_FREE(mem_ctx);
1929 domain->initialized = True;
1932 /**********************************************************************
1933 Set the domain_flags (trust attributes, domain operating modes, etc...
1934 ***********************************************************************/
1936 static void set_dc_type_and_flags( struct winbindd_domain *domain )
1938 /* we always have to contact our primary domain */
1940 if ( domain->primary ) {
1941 DEBUG(10,("set_dc_type_and_flags: setting up flags for "
1942 "primary domain\n"));
1943 set_dc_type_and_flags_connect( domain );
1944 return;
1947 /* Use our DC to get the information if possible */
1949 if ( !set_dc_type_and_flags_trustinfo( domain ) ) {
1950 /* Otherwise, fallback to contacting the
1951 domain directly */
1952 set_dc_type_and_flags_connect( domain );
1955 return;
1960 /**********************************************************************
1961 ***********************************************************************/
1963 static bool cm_get_schannel_dcinfo(struct winbindd_domain *domain,
1964 struct dcinfo **ppdc)
1966 NTSTATUS result;
1967 struct rpc_pipe_client *netlogon_pipe;
1969 if (lp_client_schannel() == False) {
1970 return False;
1973 result = cm_connect_netlogon(domain, &netlogon_pipe);
1974 if (!NT_STATUS_IS_OK(result)) {
1975 return False;
1978 /* Return a pointer to the struct dcinfo from the
1979 netlogon pipe. */
1981 if (!domain->conn.netlogon_pipe->dc) {
1982 return false;
1985 *ppdc = domain->conn.netlogon_pipe->dc;
1986 return True;
1989 NTSTATUS cm_connect_sam(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
1990 struct rpc_pipe_client **cli, struct policy_handle *sam_handle)
1992 struct winbindd_cm_conn *conn;
1993 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
1994 struct dcinfo *p_dcinfo;
1995 char *machine_password = NULL;
1996 char *machine_account = NULL;
1997 char *domain_name = NULL;
1999 result = init_dc_connection(domain);
2000 if (!NT_STATUS_IS_OK(result)) {
2001 return result;
2004 conn = &domain->conn;
2006 if (rpccli_is_connected(conn->samr_pipe)) {
2007 goto done;
2012 * No SAMR pipe yet. Attempt to get an NTLMSSP SPNEGO authenticated
2013 * sign and sealed pipe using the machine account password by
2014 * preference. If we can't - try schannel, if that fails, try
2015 * anonymous.
2018 if ((conn->cli->user_name[0] == '\0') ||
2019 (conn->cli->domain[0] == '\0') ||
2020 (conn->cli->password == NULL || conn->cli->password[0] == '\0'))
2022 result = get_trust_creds(domain, &machine_password,
2023 &machine_account, NULL);
2024 if (!NT_STATUS_IS_OK(result)) {
2025 DEBUG(10, ("cm_connect_sam: No no user available for "
2026 "domain %s, trying schannel\n", conn->cli->domain));
2027 goto schannel;
2029 domain_name = domain->name;
2030 } else {
2031 machine_password = SMB_STRDUP(conn->cli->password);
2032 machine_account = SMB_STRDUP(conn->cli->user_name);
2033 domain_name = conn->cli->domain;
2036 if (!machine_password || !machine_account) {
2037 result = NT_STATUS_NO_MEMORY;
2038 goto done;
2041 /* We have an authenticated connection. Use a NTLMSSP SPNEGO
2042 authenticated SAMR pipe with sign & seal. */
2043 result = cli_rpc_pipe_open_spnego_ntlmssp(conn->cli,
2044 &ndr_table_samr.syntax_id,
2045 NCACN_NP,
2046 PIPE_AUTH_LEVEL_PRIVACY,
2047 domain_name,
2048 machine_account,
2049 machine_password,
2050 &conn->samr_pipe);
2052 if (!NT_STATUS_IS_OK(result)) {
2053 DEBUG(10,("cm_connect_sam: failed to connect to SAMR "
2054 "pipe for domain %s using NTLMSSP "
2055 "authenticated pipe: user %s\\%s. Error was "
2056 "%s\n", domain->name, domain_name,
2057 machine_account, nt_errstr(result)));
2058 goto schannel;
2061 DEBUG(10,("cm_connect_sam: connected to SAMR pipe for "
2062 "domain %s using NTLMSSP authenticated "
2063 "pipe: user %s\\%s\n", domain->name,
2064 domain_name, machine_account));
2066 result = rpccli_samr_Connect2(conn->samr_pipe, mem_ctx,
2067 conn->samr_pipe->desthost,
2068 SEC_FLAG_MAXIMUM_ALLOWED,
2069 &conn->sam_connect_handle);
2070 if (NT_STATUS_IS_OK(result)) {
2071 goto open_domain;
2073 DEBUG(10,("cm_connect_sam: ntlmssp-sealed rpccli_samr_Connect2 "
2074 "failed for domain %s, error was %s. Trying schannel\n",
2075 domain->name, nt_errstr(result) ));
2076 TALLOC_FREE(conn->samr_pipe);
2078 schannel:
2080 /* Fall back to schannel if it's a W2K pre-SP1 box. */
2082 if (!cm_get_schannel_dcinfo(domain, &p_dcinfo)) {
2083 /* If this call fails - conn->cli can now be NULL ! */
2084 DEBUG(10, ("cm_connect_sam: Could not get schannel auth info "
2085 "for domain %s, trying anon\n", domain->name));
2086 goto anonymous;
2088 result = cli_rpc_pipe_open_schannel_with_key
2089 (conn->cli, &ndr_table_samr.syntax_id, NCACN_NP,
2090 PIPE_AUTH_LEVEL_PRIVACY,
2091 domain->name, p_dcinfo, &conn->samr_pipe);
2093 if (!NT_STATUS_IS_OK(result)) {
2094 DEBUG(10,("cm_connect_sam: failed to connect to SAMR pipe for "
2095 "domain %s using schannel. Error was %s\n",
2096 domain->name, nt_errstr(result) ));
2097 goto anonymous;
2099 DEBUG(10,("cm_connect_sam: connected to SAMR pipe for domain %s using "
2100 "schannel.\n", domain->name ));
2102 result = rpccli_samr_Connect2(conn->samr_pipe, mem_ctx,
2103 conn->samr_pipe->desthost,
2104 SEC_FLAG_MAXIMUM_ALLOWED,
2105 &conn->sam_connect_handle);
2106 if (NT_STATUS_IS_OK(result)) {
2107 goto open_domain;
2109 DEBUG(10,("cm_connect_sam: schannel-sealed rpccli_samr_Connect2 failed "
2110 "for domain %s, error was %s. Trying anonymous\n",
2111 domain->name, nt_errstr(result) ));
2112 TALLOC_FREE(conn->samr_pipe);
2114 anonymous:
2116 /* Finally fall back to anonymous. */
2117 result = cli_rpc_pipe_open_noauth(conn->cli, &ndr_table_samr.syntax_id,
2118 &conn->samr_pipe);
2120 if (!NT_STATUS_IS_OK(result)) {
2121 goto done;
2124 result = rpccli_samr_Connect2(conn->samr_pipe, mem_ctx,
2125 conn->samr_pipe->desthost,
2126 SEC_FLAG_MAXIMUM_ALLOWED,
2127 &conn->sam_connect_handle);
2128 if (!NT_STATUS_IS_OK(result)) {
2129 DEBUG(10,("cm_connect_sam: rpccli_samr_Connect2 failed "
2130 "for domain %s Error was %s\n",
2131 domain->name, nt_errstr(result) ));
2132 goto done;
2135 open_domain:
2136 result = rpccli_samr_OpenDomain(conn->samr_pipe,
2137 mem_ctx,
2138 &conn->sam_connect_handle,
2139 SEC_FLAG_MAXIMUM_ALLOWED,
2140 &domain->sid,
2141 &conn->sam_domain_handle);
2143 done:
2145 if (NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
2147 * if we got access denied, we might just have no access rights
2148 * to talk to the remote samr server server (e.g. when we are a
2149 * PDC and we are connecting a w2k8 pdc via an interdomain
2150 * trust). In that case do not invalidate the whole connection
2151 * stack
2153 TALLOC_FREE(conn->samr_pipe);
2154 ZERO_STRUCT(conn->sam_domain_handle);
2155 return result;
2156 } else if (!NT_STATUS_IS_OK(result)) {
2157 invalidate_cm_connection(conn);
2158 return result;
2161 *cli = conn->samr_pipe;
2162 *sam_handle = conn->sam_domain_handle;
2163 SAFE_FREE(machine_password);
2164 SAFE_FREE(machine_account);
2165 return result;
2168 /**********************************************************************
2169 open an schanneld ncacn_ip_tcp connection to LSA
2170 ***********************************************************************/
2172 NTSTATUS cm_connect_lsa_tcp(struct winbindd_domain *domain,
2173 TALLOC_CTX *mem_ctx,
2174 struct rpc_pipe_client **cli)
2176 struct winbindd_cm_conn *conn;
2177 NTSTATUS status;
2179 DEBUG(10,("cm_connect_lsa_tcp\n"));
2181 status = init_dc_connection(domain);
2182 if (!NT_STATUS_IS_OK(status)) {
2183 return status;
2186 conn = &domain->conn;
2188 if (conn->lsa_pipe_tcp &&
2189 conn->lsa_pipe_tcp->transport->transport == NCACN_IP_TCP &&
2190 conn->lsa_pipe_tcp->auth->auth_level == PIPE_AUTH_LEVEL_PRIVACY &&
2191 rpccli_is_connected(conn->lsa_pipe_tcp)) {
2192 goto done;
2195 TALLOC_FREE(conn->lsa_pipe_tcp);
2197 status = cli_rpc_pipe_open_schannel(conn->cli,
2198 &ndr_table_lsarpc.syntax_id,
2199 NCACN_IP_TCP,
2200 PIPE_AUTH_LEVEL_PRIVACY,
2201 domain->name,
2202 &conn->lsa_pipe_tcp);
2203 if (!NT_STATUS_IS_OK(status)) {
2204 DEBUG(10,("cli_rpc_pipe_open_schannel failed: %s\n",
2205 nt_errstr(status)));
2206 goto done;
2209 done:
2210 if (!NT_STATUS_IS_OK(status)) {
2211 TALLOC_FREE(conn->lsa_pipe_tcp);
2212 return status;
2215 *cli = conn->lsa_pipe_tcp;
2217 return status;
2220 NTSTATUS cm_connect_lsa(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2221 struct rpc_pipe_client **cli, struct policy_handle *lsa_policy)
2223 struct winbindd_cm_conn *conn;
2224 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2225 struct dcinfo *p_dcinfo;
2227 result = init_dc_connection(domain);
2228 if (!NT_STATUS_IS_OK(result))
2229 return result;
2231 conn = &domain->conn;
2233 if (rpccli_is_connected(conn->lsa_pipe)) {
2234 goto done;
2237 if ((conn->cli->user_name[0] == '\0') ||
2238 (conn->cli->domain[0] == '\0') ||
2239 (conn->cli->password == NULL || conn->cli->password[0] == '\0')) {
2240 DEBUG(10, ("cm_connect_lsa: No no user available for "
2241 "domain %s, trying schannel\n", conn->cli->domain));
2242 goto schannel;
2245 /* We have an authenticated connection. Use a NTLMSSP SPNEGO
2246 * authenticated LSA pipe with sign & seal. */
2247 result = cli_rpc_pipe_open_spnego_ntlmssp
2248 (conn->cli, &ndr_table_lsarpc.syntax_id, NCACN_NP,
2249 PIPE_AUTH_LEVEL_PRIVACY,
2250 conn->cli->domain, conn->cli->user_name, conn->cli->password,
2251 &conn->lsa_pipe);
2253 if (!NT_STATUS_IS_OK(result)) {
2254 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
2255 "domain %s using NTLMSSP authenticated pipe: user "
2256 "%s\\%s. Error was %s. Trying schannel.\n",
2257 domain->name, conn->cli->domain,
2258 conn->cli->user_name, nt_errstr(result)));
2259 goto schannel;
2262 DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
2263 "NTLMSSP authenticated pipe: user %s\\%s\n",
2264 domain->name, conn->cli->domain, conn->cli->user_name ));
2266 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2267 SEC_FLAG_MAXIMUM_ALLOWED,
2268 &conn->lsa_policy);
2269 if (NT_STATUS_IS_OK(result)) {
2270 goto done;
2273 DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
2274 "schannel\n"));
2276 TALLOC_FREE(conn->lsa_pipe);
2278 schannel:
2280 /* Fall back to schannel if it's a W2K pre-SP1 box. */
2282 if (!cm_get_schannel_dcinfo(domain, &p_dcinfo)) {
2283 /* If this call fails - conn->cli can now be NULL ! */
2284 DEBUG(10, ("cm_connect_lsa: Could not get schannel auth info "
2285 "for domain %s, trying anon\n", domain->name));
2286 goto anonymous;
2288 result = cli_rpc_pipe_open_schannel_with_key
2289 (conn->cli, &ndr_table_lsarpc.syntax_id, NCACN_NP,
2290 PIPE_AUTH_LEVEL_PRIVACY,
2291 domain->name, p_dcinfo, &conn->lsa_pipe);
2293 if (!NT_STATUS_IS_OK(result)) {
2294 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
2295 "domain %s using schannel. Error was %s\n",
2296 domain->name, nt_errstr(result) ));
2297 goto anonymous;
2299 DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
2300 "schannel.\n", domain->name ));
2302 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2303 SEC_FLAG_MAXIMUM_ALLOWED,
2304 &conn->lsa_policy);
2305 if (NT_STATUS_IS_OK(result)) {
2306 goto done;
2309 DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
2310 "anonymous\n"));
2312 TALLOC_FREE(conn->lsa_pipe);
2314 anonymous:
2316 result = cli_rpc_pipe_open_noauth(conn->cli,
2317 &ndr_table_lsarpc.syntax_id,
2318 &conn->lsa_pipe);
2319 if (!NT_STATUS_IS_OK(result)) {
2320 result = NT_STATUS_PIPE_NOT_AVAILABLE;
2321 goto done;
2324 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2325 SEC_FLAG_MAXIMUM_ALLOWED,
2326 &conn->lsa_policy);
2327 done:
2328 if (!NT_STATUS_IS_OK(result)) {
2329 invalidate_cm_connection(conn);
2330 return result;
2333 *cli = conn->lsa_pipe;
2334 *lsa_policy = conn->lsa_policy;
2335 return result;
2338 /****************************************************************************
2339 Open the netlogon pipe to this DC. Use schannel if specified in client conf.
2340 session key stored in conn->netlogon_pipe->dc->sess_key.
2341 ****************************************************************************/
2343 NTSTATUS cm_connect_netlogon(struct winbindd_domain *domain,
2344 struct rpc_pipe_client **cli)
2346 struct winbindd_cm_conn *conn;
2347 NTSTATUS result;
2349 uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS;
2350 uint8 mach_pwd[16];
2351 uint32 sec_chan_type;
2352 const char *account_name;
2353 struct rpc_pipe_client *netlogon_pipe = NULL;
2355 *cli = NULL;
2357 result = init_dc_connection(domain);
2358 if (!NT_STATUS_IS_OK(result)) {
2359 return result;
2362 conn = &domain->conn;
2364 if (rpccli_is_connected(conn->netlogon_pipe)) {
2365 *cli = conn->netlogon_pipe;
2366 return NT_STATUS_OK;
2369 result = cli_rpc_pipe_open_noauth(conn->cli,
2370 &ndr_table_netlogon.syntax_id,
2371 &netlogon_pipe);
2372 if (!NT_STATUS_IS_OK(result)) {
2373 return result;
2376 if ((!IS_DC) && (!domain->primary)) {
2377 /* Clear the schannel request bit and drop down */
2378 neg_flags &= ~NETLOGON_NEG_SCHANNEL;
2379 goto no_schannel;
2382 if (lp_client_schannel() != False) {
2383 neg_flags |= NETLOGON_NEG_SCHANNEL;
2386 if (!get_trust_pw_hash(domain->name, mach_pwd, &account_name,
2387 &sec_chan_type))
2389 TALLOC_FREE(netlogon_pipe);
2390 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2393 result = rpccli_netlogon_setup_creds(
2394 netlogon_pipe,
2395 domain->dcname, /* server name. */
2396 domain->name, /* domain name */
2397 global_myname(), /* client name */
2398 account_name, /* machine account */
2399 mach_pwd, /* machine password */
2400 sec_chan_type, /* from get_trust_pw */
2401 &neg_flags);
2403 if (!NT_STATUS_IS_OK(result)) {
2404 TALLOC_FREE(netlogon_pipe);
2405 return result;
2408 if ((lp_client_schannel() == True) &&
2409 ((neg_flags & NETLOGON_NEG_SCHANNEL) == 0)) {
2410 DEBUG(3, ("Server did not offer schannel\n"));
2411 TALLOC_FREE(netlogon_pipe);
2412 return NT_STATUS_ACCESS_DENIED;
2415 no_schannel:
2416 if ((lp_client_schannel() == False) ||
2417 ((neg_flags & NETLOGON_NEG_SCHANNEL) == 0)) {
2419 * NetSamLogonEx only works for schannel
2421 domain->can_do_samlogon_ex = False;
2423 /* We're done - just keep the existing connection to NETLOGON
2424 * open */
2425 conn->netlogon_pipe = netlogon_pipe;
2426 *cli = conn->netlogon_pipe;
2427 return NT_STATUS_OK;
2430 /* Using the credentials from the first pipe, open a signed and sealed
2431 second netlogon pipe. The session key is stored in the schannel
2432 part of the new pipe auth struct.
2435 result = cli_rpc_pipe_open_schannel_with_key(
2436 conn->cli, &ndr_table_netlogon.syntax_id, NCACN_NP,
2437 PIPE_AUTH_LEVEL_PRIVACY, domain->name, netlogon_pipe->dc,
2438 &conn->netlogon_pipe);
2440 /* We can now close the initial netlogon pipe. */
2441 TALLOC_FREE(netlogon_pipe);
2443 if (!NT_STATUS_IS_OK(result)) {
2444 DEBUG(3, ("Could not open schannel'ed NETLOGON pipe. Error "
2445 "was %s\n", nt_errstr(result)));
2447 /* make sure we return something besides OK */
2448 return !NT_STATUS_IS_OK(result) ? result : NT_STATUS_PIPE_NOT_AVAILABLE;
2452 * Try NetSamLogonEx for AD domains
2454 domain->can_do_samlogon_ex = domain->active_directory;
2456 *cli = conn->netlogon_pipe;
2457 return NT_STATUS_OK;