winbind: Use libnbt for NTLOGON SAMLOGON mailslot request and reply.
[Samba/gebeck_regimport.git] / source3 / winbindd / winbindd_cm.c
blob97b22599850d51419e01355c896232fee744e830
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 child_pid;
175 pid_t parent_pid = sys_getpid();
177 /* Stop zombies */
178 CatchChild();
180 child_pid = sys_fork();
182 if (child_pid == -1) {
183 DEBUG(0, ("fork_child_dc_connect: Could not fork: %s\n", strerror(errno)));
184 return False;
187 if (child_pid != 0) {
188 /* Parent */
189 messaging_register(winbind_messaging_context(), NULL,
190 MSG_WINBIND_TRY_TO_GO_ONLINE,
191 msg_try_to_go_online);
192 messaging_register(winbind_messaging_context(), NULL,
193 MSG_WINBIND_FAILED_TO_GO_ONLINE,
194 msg_failed_to_go_online);
195 return True;
198 /* Child. */
200 /* Leave messages blocked - we will never process one. */
202 if (!reinit_after_fork(winbind_messaging_context())) {
203 DEBUG(0,("reinit_after_fork() failed\n"));
204 _exit(0);
207 close_conns_after_fork();
209 if (!override_logfile) {
210 char *logfile;
211 if (asprintf(&logfile, "%s/log.winbindd-dc-connect", get_dyn_LOGFILEBASE()) > 0) {
212 lp_set_logfile(logfile);
213 SAFE_FREE(logfile);
214 reopen_logs();
218 mem_ctx = talloc_init("fork_child_dc_connect");
219 if (!mem_ctx) {
220 DEBUG(0,("talloc_init failed.\n"));
221 _exit(0);
224 if ((!get_dcs(mem_ctx, domain, &dcs, &num_dcs)) || (num_dcs == 0)) {
225 /* Still offline ? Can't find DC's. */
226 messaging_send_buf(winbind_messaging_context(),
227 pid_to_procid(parent_pid),
228 MSG_WINBIND_FAILED_TO_GO_ONLINE,
229 (uint8 *)domain->name,
230 strlen(domain->name)+1);
231 _exit(0);
234 /* We got a DC. Send a message to our parent to get it to
235 try and do the same. */
237 messaging_send_buf(winbind_messaging_context(),
238 pid_to_procid(parent_pid),
239 MSG_WINBIND_TRY_TO_GO_ONLINE,
240 (uint8 *)domain->name,
241 strlen(domain->name)+1);
242 _exit(0);
245 /****************************************************************
246 Handler triggered if we're offline to try and detect a DC.
247 ****************************************************************/
249 static void check_domain_online_handler(struct event_context *ctx,
250 struct timed_event *te,
251 const struct timeval *now,
252 void *private_data)
254 struct winbindd_domain *domain =
255 (struct winbindd_domain *)private_data;
257 DEBUG(10,("check_domain_online_handler: called for domain "
258 "%s (online = %s)\n", domain->name,
259 domain->online ? "True" : "False" ));
261 TALLOC_FREE(domain->check_online_event);
263 /* Are we still in "startup" mode ? */
265 if (domain->startup && (now->tv_sec > domain->startup_time + 30)) {
266 /* No longer in "startup" mode. */
267 DEBUG(10,("check_domain_online_handler: domain %s no longer in 'startup' mode.\n",
268 domain->name ));
269 domain->startup = False;
272 /* We've been told to stay offline, so stay
273 that way. */
275 if (get_global_winbindd_state_offline()) {
276 DEBUG(10,("check_domain_online_handler: domain %s remaining globally offline\n",
277 domain->name ));
278 return;
281 /* Fork a child to test if it can contact a DC.
282 If it can then send ourselves a message to
283 cause a reconnect. */
285 fork_child_dc_connect(domain);
288 /****************************************************************
289 If we're still offline setup the timeout check.
290 ****************************************************************/
292 static void calc_new_online_timeout_check(struct winbindd_domain *domain)
294 int wbc = lp_winbind_cache_time();
296 if (domain->startup) {
297 domain->check_online_timeout = 10;
298 } else if (domain->check_online_timeout < wbc) {
299 domain->check_online_timeout = wbc;
303 /****************************************************************
304 Set domain offline and also add handler to put us back online
305 if we detect a DC.
306 ****************************************************************/
308 void set_domain_offline(struct winbindd_domain *domain)
310 DEBUG(10,("set_domain_offline: called for domain %s\n",
311 domain->name ));
313 TALLOC_FREE(domain->check_online_event);
315 if (domain->internal) {
316 DEBUG(3,("set_domain_offline: domain %s is internal - logic error.\n",
317 domain->name ));
318 return;
321 domain->online = False;
323 /* Offline domains are always initialized. They're
324 re-initialized when they go back online. */
326 domain->initialized = True;
328 /* We only add the timeout handler that checks and
329 allows us to go back online when we've not
330 been told to remain offline. */
332 if (get_global_winbindd_state_offline()) {
333 DEBUG(10,("set_domain_offline: domain %s remaining globally offline\n",
334 domain->name ));
335 return;
338 /* If we're in statup mode, check again in 10 seconds, not in
339 lp_winbind_cache_time() seconds (which is 5 mins by default). */
341 calc_new_online_timeout_check(domain);
343 domain->check_online_event = event_add_timed(winbind_event_context(),
344 NULL,
345 timeval_current_ofs(domain->check_online_timeout,0),
346 "check_domain_online_handler",
347 check_domain_online_handler,
348 domain);
350 /* The above *has* to succeed for winbindd to work. */
351 if (!domain->check_online_event) {
352 smb_panic("set_domain_offline: failed to add online handler");
355 DEBUG(10,("set_domain_offline: added event handler for domain %s\n",
356 domain->name ));
358 /* Send an offline message to the idmap child when our
359 primary domain goes offline */
361 if ( domain->primary ) {
362 struct winbindd_child *idmap = idmap_child();
364 if ( idmap->pid != 0 ) {
365 messaging_send_buf(winbind_messaging_context(),
366 pid_to_procid(idmap->pid),
367 MSG_WINBIND_OFFLINE,
368 (uint8 *)domain->name,
369 strlen(domain->name)+1);
373 return;
376 /****************************************************************
377 Set domain online - if allowed.
378 ****************************************************************/
380 static void set_domain_online(struct winbindd_domain *domain)
382 struct timeval now;
384 DEBUG(10,("set_domain_online: called for domain %s\n",
385 domain->name ));
387 if (domain->internal) {
388 DEBUG(3,("set_domain_online: domain %s is internal - logic error.\n",
389 domain->name ));
390 return;
393 if (get_global_winbindd_state_offline()) {
394 DEBUG(10,("set_domain_online: domain %s remaining globally offline\n",
395 domain->name ));
396 return;
399 winbindd_set_locator_kdc_envs(domain);
401 /* If we are waiting to get a krb5 ticket, trigger immediately. */
402 GetTimeOfDay(&now);
403 set_event_dispatch_time(winbind_event_context(),
404 "krb5_ticket_gain_handler", now);
406 /* Ok, we're out of any startup mode now... */
407 domain->startup = False;
409 if (domain->online == False) {
410 /* We were offline - now we're online. We default to
411 using the MS-RPC backend if we started offline,
412 and if we're going online for the first time we
413 should really re-initialize the backends and the
414 checks to see if we're talking to an AD or NT domain.
417 domain->initialized = False;
419 /* 'reconnect_methods' is the MS-RPC backend. */
420 if (domain->backend == &reconnect_methods) {
421 domain->backend = NULL;
425 /* Ensure we have no online timeout checks. */
426 domain->check_online_timeout = 0;
427 TALLOC_FREE(domain->check_online_event);
429 /* Ensure we ignore any pending child messages. */
430 messaging_deregister(winbind_messaging_context(),
431 MSG_WINBIND_TRY_TO_GO_ONLINE, NULL);
432 messaging_deregister(winbind_messaging_context(),
433 MSG_WINBIND_FAILED_TO_GO_ONLINE, NULL);
435 domain->online = True;
437 /* Send an online message to the idmap child when our
438 primary domain comes online */
440 if ( domain->primary ) {
441 struct winbindd_child *idmap = idmap_child();
443 if ( idmap->pid != 0 ) {
444 messaging_send_buf(winbind_messaging_context(),
445 pid_to_procid(idmap->pid),
446 MSG_WINBIND_ONLINE,
447 (uint8 *)domain->name,
448 strlen(domain->name)+1);
452 return;
455 /****************************************************************
456 Requested to set a domain online.
457 ****************************************************************/
459 void set_domain_online_request(struct winbindd_domain *domain)
461 struct timeval tev;
463 DEBUG(10,("set_domain_online_request: called for domain %s\n",
464 domain->name ));
466 if (get_global_winbindd_state_offline()) {
467 DEBUG(10,("set_domain_online_request: domain %s remaining globally offline\n",
468 domain->name ));
469 return;
472 /* We've been told it's safe to go online and
473 try and connect to a DC. But I don't believe it
474 because network manager seems to lie.
475 Wait at least 5 seconds. Heuristics suck... */
477 if (!domain->check_online_event) {
478 /* If we've come from being globally offline we
479 don't have a check online event handler set.
480 We need to add one now we're trying to go
481 back online. */
483 DEBUG(10,("set_domain_online_request: domain %s was globally offline.\n",
484 domain->name ));
486 domain->check_online_event = event_add_timed(winbind_event_context(),
487 NULL,
488 timeval_current_ofs(5, 0),
489 "check_domain_online_handler",
490 check_domain_online_handler,
491 domain);
493 /* The above *has* to succeed for winbindd to work. */
494 if (!domain->check_online_event) {
495 smb_panic("set_domain_online_request: failed to add online handler");
499 GetTimeOfDay(&tev);
501 /* Go into "startup" mode again. */
502 domain->startup_time = tev.tv_sec;
503 domain->startup = True;
505 tev.tv_sec += 5;
507 set_event_dispatch_time(winbind_event_context(), "check_domain_online_handler", tev);
510 /****************************************************************
511 Add -ve connection cache entries for domain and realm.
512 ****************************************************************/
514 void winbind_add_failed_connection_entry(const struct winbindd_domain *domain,
515 const char *server,
516 NTSTATUS result)
518 add_failed_connection_entry(domain->name, server, result);
519 /* If this was the saf name for the last thing we talked to,
520 remove it. */
521 saf_delete(domain->name);
522 if (*domain->alt_name) {
523 add_failed_connection_entry(domain->alt_name, server, result);
524 saf_delete(domain->alt_name);
526 winbindd_unset_locator_kdc_env(domain);
529 /* Choose between anonymous or authenticated connections. We need to use
530 an authenticated connection if DCs have the RestrictAnonymous registry
531 entry set > 0, or the "Additional restrictions for anonymous
532 connections" set in the win2k Local Security Policy.
534 Caller to free() result in domain, username, password
537 static void cm_get_ipc_userpass(char **username, char **domain, char **password)
539 *username = (char *)secrets_fetch(SECRETS_AUTH_USER, NULL);
540 *domain = (char *)secrets_fetch(SECRETS_AUTH_DOMAIN, NULL);
541 *password = (char *)secrets_fetch(SECRETS_AUTH_PASSWORD, NULL);
543 if (*username && **username) {
545 if (!*domain || !**domain)
546 *domain = smb_xstrdup(lp_workgroup());
548 if (!*password || !**password)
549 *password = smb_xstrdup("");
551 DEBUG(3, ("cm_get_ipc_userpass: Retrieved auth-user from secrets.tdb [%s\\%s]\n",
552 *domain, *username));
554 } else {
555 DEBUG(3, ("cm_get_ipc_userpass: No auth-user defined\n"));
556 *username = smb_xstrdup("");
557 *domain = smb_xstrdup("");
558 *password = smb_xstrdup("");
562 static bool get_dc_name_via_netlogon(struct winbindd_domain *domain,
563 fstring dcname,
564 struct sockaddr_storage *dc_ss)
566 struct winbindd_domain *our_domain = NULL;
567 struct rpc_pipe_client *netlogon_pipe = NULL;
568 NTSTATUS result;
569 WERROR werr;
570 TALLOC_CTX *mem_ctx;
571 unsigned int orig_timeout;
572 const char *tmp = NULL;
573 const char *p;
575 /* Hmmmm. We can only open one connection to the NETLOGON pipe at the
576 * moment.... */
578 if (IS_DC) {
579 return False;
582 if (domain->primary) {
583 return False;
586 our_domain = find_our_domain();
588 if ((mem_ctx = talloc_init("get_dc_name_via_netlogon")) == NULL) {
589 return False;
592 result = cm_connect_netlogon(our_domain, &netlogon_pipe);
593 if (!NT_STATUS_IS_OK(result)) {
594 talloc_destroy(mem_ctx);
595 return False;
598 /* This call can take a long time - allow the server to time out.
599 35 seconds should do it. */
601 orig_timeout = rpccli_set_timeout(netlogon_pipe, 35000);
603 if (our_domain->active_directory) {
604 struct netr_DsRGetDCNameInfo *domain_info = NULL;
606 result = rpccli_netr_DsRGetDCName(netlogon_pipe,
607 mem_ctx,
608 our_domain->dcname,
609 domain->name,
610 NULL,
611 NULL,
612 DS_RETURN_DNS_NAME,
613 &domain_info,
614 &werr);
615 if (W_ERROR_IS_OK(werr)) {
616 tmp = talloc_strdup(
617 mem_ctx, domain_info->dc_unc);
618 if (tmp == NULL) {
619 DEBUG(0, ("talloc_strdup failed\n"));
620 talloc_destroy(mem_ctx);
621 return false;
623 if (strlen(domain->alt_name) == 0) {
624 fstrcpy(domain->alt_name,
625 domain_info->domain_name);
627 if (strlen(domain->forest_name) == 0) {
628 fstrcpy(domain->forest_name,
629 domain_info->forest_name);
632 } else {
633 result = rpccli_netr_GetAnyDCName(netlogon_pipe, mem_ctx,
634 our_domain->dcname,
635 domain->name,
636 &tmp,
637 &werr);
640 /* And restore our original timeout. */
641 rpccli_set_timeout(netlogon_pipe, orig_timeout);
643 if (!NT_STATUS_IS_OK(result)) {
644 DEBUG(10,("rpccli_netr_GetAnyDCName failed: %s\n",
645 nt_errstr(result)));
646 talloc_destroy(mem_ctx);
647 return false;
650 if (!W_ERROR_IS_OK(werr)) {
651 DEBUG(10,("rpccli_netr_GetAnyDCName failed: %s\n",
652 dos_errstr(werr)));
653 talloc_destroy(mem_ctx);
654 return false;
657 /* rpccli_netr_GetAnyDCName gives us a name with \\ */
658 p = tmp;
659 if (*p == '\\') {
660 p+=1;
662 if (*p == '\\') {
663 p+=1;
666 fstrcpy(dcname, p);
668 talloc_destroy(mem_ctx);
670 DEBUG(10,("rpccli_netr_GetAnyDCName returned %s\n", dcname));
672 if (!resolve_name(dcname, dc_ss, 0x20)) {
673 return False;
676 return True;
680 * Helper function to assemble trust password and account name
682 static NTSTATUS get_trust_creds(const struct winbindd_domain *domain,
683 char **machine_password,
684 char **machine_account,
685 char **machine_krb5_principal)
687 const char *account_name;
688 const char *name = NULL;
690 /* If we are a DC and this is not our own domain */
692 if (IS_DC) {
693 name = domain->name;
694 } else {
695 struct winbindd_domain *our_domain = find_our_domain();
697 if (!our_domain)
698 return NT_STATUS_INVALID_SERVER_STATE;
700 name = our_domain->name;
703 if (!get_trust_pw_clear(name, machine_password,
704 &account_name, NULL))
706 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
709 if ((machine_account != NULL) &&
710 (asprintf(machine_account, "%s$", account_name) == -1))
712 return NT_STATUS_NO_MEMORY;
715 /* this is at least correct when domain is our domain,
716 * which is the only case, when this is currently used: */
717 if (machine_krb5_principal != NULL)
719 if (asprintf(machine_krb5_principal, "%s$@%s",
720 account_name, domain->alt_name) == -1)
722 return NT_STATUS_NO_MEMORY;
725 strupper_m(*machine_krb5_principal);
728 return NT_STATUS_OK;
731 /************************************************************************
732 Given a fd with a just-connected TCP connection to a DC, open a connection
733 to the pipe.
734 ************************************************************************/
736 static NTSTATUS cm_prepare_connection(const struct winbindd_domain *domain,
737 const int sockfd,
738 const char *controller,
739 struct cli_state **cli,
740 bool *retry)
742 char *machine_password = NULL;
743 char *machine_krb5_principal = NULL;
744 char *machine_account = NULL;
745 char *ipc_username = NULL;
746 char *ipc_domain = NULL;
747 char *ipc_password = NULL;
749 struct named_mutex *mutex;
751 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
753 struct sockaddr peeraddr;
754 socklen_t peeraddr_len;
756 struct sockaddr_in *peeraddr_in = (struct sockaddr_in *)&peeraddr;
758 DEBUG(10,("cm_prepare_connection: connecting to DC %s for domain %s\n",
759 controller, domain->name ));
761 *retry = True;
763 mutex = grab_named_mutex(talloc_tos(), controller,
764 WINBIND_SERVER_MUTEX_WAIT_TIME);
765 if (mutex == NULL) {
766 DEBUG(0,("cm_prepare_connection: mutex grab failed for %s\n",
767 controller));
768 result = NT_STATUS_POSSIBLE_DEADLOCK;
769 goto done;
772 if ((*cli = cli_initialise()) == NULL) {
773 DEBUG(1, ("Could not cli_initialize\n"));
774 result = NT_STATUS_NO_MEMORY;
775 goto done;
778 (*cli)->timeout = 10000; /* 10 seconds */
779 (*cli)->fd = sockfd;
780 fstrcpy((*cli)->desthost, controller);
781 (*cli)->use_kerberos = True;
783 peeraddr_len = sizeof(peeraddr);
785 if ((getpeername((*cli)->fd, &peeraddr, &peeraddr_len) != 0) ||
786 (peeraddr_len != sizeof(struct sockaddr_in)) ||
787 (peeraddr_in->sin_family != PF_INET))
789 DEBUG(0,("cm_prepare_connection: %s\n", strerror(errno)));
790 result = NT_STATUS_UNSUCCESSFUL;
791 goto done;
794 if (ntohs(peeraddr_in->sin_port) == 139) {
795 struct nmb_name calling;
796 struct nmb_name called;
798 make_nmb_name(&calling, global_myname(), 0x0);
799 make_nmb_name(&called, "*SMBSERVER", 0x20);
801 if (!cli_session_request(*cli, &calling, &called)) {
802 DEBUG(8, ("cli_session_request failed for %s\n",
803 controller));
804 result = NT_STATUS_UNSUCCESSFUL;
805 goto done;
809 cli_setup_signing_state(*cli, Undefined);
811 if (!cli_negprot(*cli)) {
812 DEBUG(1, ("cli_negprot failed\n"));
813 result = NT_STATUS_UNSUCCESSFUL;
814 goto done;
817 if (!is_trusted_domain_situation(domain->name) &&
818 (*cli)->protocol >= PROTOCOL_NT1 &&
819 (*cli)->capabilities & CAP_EXTENDED_SECURITY)
821 ADS_STATUS ads_status;
823 result = get_trust_creds(domain, &machine_password,
824 &machine_account,
825 &machine_krb5_principal);
826 if (!NT_STATUS_IS_OK(result)) {
827 goto anon_fallback;
830 if (lp_security() == SEC_ADS) {
832 /* Try a krb5 session */
834 (*cli)->use_kerberos = True;
835 DEBUG(5, ("connecting to %s from %s with kerberos principal "
836 "[%s]\n", controller, global_myname(),
837 machine_krb5_principal));
839 winbindd_set_locator_kdc_envs(domain);
841 ads_status = cli_session_setup_spnego(*cli,
842 machine_krb5_principal,
843 machine_password,
844 domain->name);
846 if (!ADS_ERR_OK(ads_status)) {
847 DEBUG(4,("failed kerberos session setup with %s\n",
848 ads_errstr(ads_status)));
851 result = ads_ntstatus(ads_status);
852 if (NT_STATUS_IS_OK(result)) {
853 /* Ensure creds are stored for NTLMSSP authenticated pipe access. */
854 cli_init_creds(*cli, machine_account, domain->name, machine_password);
855 goto session_setup_done;
859 /* Fall back to non-kerberos session setup using NTLMSSP SPNEGO with the machine account. */
860 (*cli)->use_kerberos = False;
862 DEBUG(5, ("connecting to %s from %s with username "
863 "[%s]\\[%s]\n", controller, global_myname(),
864 domain->name, machine_account));
866 ads_status = cli_session_setup_spnego(*cli,
867 machine_account,
868 machine_password,
869 domain->name);
870 if (!ADS_ERR_OK(ads_status)) {
871 DEBUG(4, ("authenticated session setup failed with %s\n",
872 ads_errstr(ads_status)));
875 result = ads_ntstatus(ads_status);
876 if (NT_STATUS_IS_OK(result)) {
877 /* Ensure creds are stored for NTLMSSP authenticated pipe access. */
878 cli_init_creds(*cli, machine_account, domain->name, machine_password);
879 goto session_setup_done;
883 /* Fall back to non-kerberos session setup with auth_user */
885 (*cli)->use_kerberos = False;
887 cm_get_ipc_userpass(&ipc_username, &ipc_domain, &ipc_password);
889 if ((((*cli)->sec_mode & NEGOTIATE_SECURITY_CHALLENGE_RESPONSE) != 0) &&
890 (strlen(ipc_username) > 0)) {
892 /* Only try authenticated if we have a username */
894 DEBUG(5, ("connecting to %s from %s with username "
895 "[%s]\\[%s]\n", controller, global_myname(),
896 ipc_domain, ipc_username));
898 if (NT_STATUS_IS_OK(cli_session_setup(
899 *cli, ipc_username,
900 ipc_password, strlen(ipc_password)+1,
901 ipc_password, strlen(ipc_password)+1,
902 ipc_domain))) {
903 /* Successful logon with given username. */
904 cli_init_creds(*cli, ipc_username, ipc_domain, ipc_password);
905 goto session_setup_done;
906 } else {
907 DEBUG(4, ("authenticated session setup with user %s\\%s failed.\n",
908 ipc_domain, ipc_username ));
912 anon_fallback:
914 /* Fall back to anonymous connection, this might fail later */
916 if (NT_STATUS_IS_OK(cli_session_setup(*cli, "", NULL, 0,
917 NULL, 0, ""))) {
918 DEBUG(5, ("Connected anonymously\n"));
919 cli_init_creds(*cli, "", "", "");
920 goto session_setup_done;
923 result = cli_nt_error(*cli);
925 if (NT_STATUS_IS_OK(result))
926 result = NT_STATUS_UNSUCCESSFUL;
928 /* We can't session setup */
930 goto done;
932 session_setup_done:
934 /* cache the server name for later connections */
936 saf_store( domain->name, (*cli)->desthost );
937 if (domain->alt_name && (*cli)->use_kerberos) {
938 saf_store( domain->alt_name, (*cli)->desthost );
941 winbindd_set_locator_kdc_envs(domain);
943 if (!cli_send_tconX(*cli, "IPC$", "IPC", "", 0)) {
945 result = cli_nt_error(*cli);
947 DEBUG(1,("failed tcon_X with %s\n", nt_errstr(result)));
949 if (NT_STATUS_IS_OK(result))
950 result = NT_STATUS_UNSUCCESSFUL;
952 goto done;
955 TALLOC_FREE(mutex);
956 *retry = False;
958 /* set the domain if empty; needed for schannel connections */
959 if ( !*(*cli)->domain ) {
960 fstrcpy( (*cli)->domain, domain->name );
963 result = NT_STATUS_OK;
965 done:
966 TALLOC_FREE(mutex);
967 SAFE_FREE(machine_account);
968 SAFE_FREE(machine_password);
969 SAFE_FREE(machine_krb5_principal);
970 SAFE_FREE(ipc_username);
971 SAFE_FREE(ipc_domain);
972 SAFE_FREE(ipc_password);
974 if (!NT_STATUS_IS_OK(result)) {
975 winbind_add_failed_connection_entry(domain, controller, result);
976 if ((*cli) != NULL) {
977 cli_shutdown(*cli);
978 *cli = NULL;
982 return result;
985 static bool add_one_dc_unique(TALLOC_CTX *mem_ctx, const char *domain_name,
986 const char *dcname, struct sockaddr_storage *pss,
987 struct dc_name_ip **dcs, int *num)
989 if (!NT_STATUS_IS_OK(check_negative_conn_cache(domain_name, dcname))) {
990 DEBUG(10, ("DC %s was in the negative conn cache\n", dcname));
991 return False;
994 *dcs = TALLOC_REALLOC_ARRAY(mem_ctx, *dcs, struct dc_name_ip, (*num)+1);
996 if (*dcs == NULL)
997 return False;
999 fstrcpy((*dcs)[*num].name, dcname);
1000 (*dcs)[*num].ss = *pss;
1001 *num += 1;
1002 return True;
1005 static bool add_sockaddr_to_array(TALLOC_CTX *mem_ctx,
1006 struct sockaddr_storage *pss, uint16 port,
1007 struct sockaddr_storage **addrs, int *num)
1009 *addrs = TALLOC_REALLOC_ARRAY(mem_ctx, *addrs, struct sockaddr_storage, (*num)+1);
1011 if (*addrs == NULL) {
1012 *num = 0;
1013 return False;
1016 (*addrs)[*num] = *pss;
1017 set_sockaddr_port(&(*addrs)[*num], port);
1019 *num += 1;
1020 return True;
1023 /*******************************************************************
1024 convert an ip to a name
1025 *******************************************************************/
1027 static bool dcip_to_name(const struct winbindd_domain *domain,
1028 struct sockaddr_storage *pss,
1029 fstring name )
1031 struct ip_service ip_list;
1033 ip_list.ss = *pss;
1034 ip_list.port = 0;
1036 #ifdef WITH_ADS
1037 /* For active directory servers, try to get the ldap server name.
1038 None of these failures should be considered critical for now */
1040 if (lp_security() == SEC_ADS) {
1041 ADS_STRUCT *ads;
1042 char addr[INET6_ADDRSTRLEN];
1044 print_sockaddr(addr, sizeof(addr), pss);
1046 ads = ads_init(domain->alt_name, domain->name, NULL);
1047 ads->auth.flags |= ADS_AUTH_NO_BIND;
1049 if (ads_try_connect(ads, addr)) {
1050 /* We got a cldap packet. */
1051 fstrcpy(name, ads->config.ldap_server_name);
1052 namecache_store(name, 0x20, 1, &ip_list);
1054 DEBUG(10,("dcip_to_name: flags = 0x%x\n", (unsigned int)ads->config.flags));
1056 if (domain->primary && (ads->config.flags & ADS_KDC)) {
1057 if (ads_closest_dc(ads)) {
1058 char *sitename = sitename_fetch(ads->config.realm);
1060 /* We're going to use this KDC for this realm/domain.
1061 If we are using sites, then force the krb5 libs
1062 to use this KDC. */
1064 create_local_private_krb5_conf_for_domain(domain->alt_name,
1065 domain->name,
1066 sitename,
1067 pss);
1069 SAFE_FREE(sitename);
1070 } else {
1071 /* use an off site KDC */
1072 create_local_private_krb5_conf_for_domain(domain->alt_name,
1073 domain->name,
1074 NULL,
1075 pss);
1077 winbindd_set_locator_kdc_envs(domain);
1079 /* Ensure we contact this DC also. */
1080 saf_store( domain->name, name);
1081 saf_store( domain->alt_name, name);
1084 ads_destroy( &ads );
1085 return True;
1088 ads_destroy( &ads );
1090 #endif
1092 /* try GETDC requests next */
1094 if (send_getdc_request(winbind_messaging_context(),
1095 pss, domain->name, &domain->sid)) {
1096 const char *dc_name = NULL;
1097 int i;
1098 smb_msleep(100);
1099 for (i=0; i<5; i++) {
1100 if (receive_getdc_response(pss, domain->name, &dc_name)) {
1101 fstrcpy(name, dc_name);
1102 namecache_store(name, 0x20, 1, &ip_list);
1103 return True;
1105 smb_msleep(500);
1109 /* try node status request */
1111 if ( name_status_find(domain->name, 0x1c, 0x20, pss, name) ) {
1112 namecache_store(name, 0x20, 1, &ip_list);
1113 return True;
1115 return False;
1118 /*******************************************************************
1119 Retreive a list of IP address for domain controllers. Fill in
1120 the dcs[] with results.
1121 *******************************************************************/
1123 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
1124 struct dc_name_ip **dcs, int *num_dcs)
1126 fstring dcname;
1127 struct sockaddr_storage ss;
1128 struct ip_service *ip_list = NULL;
1129 int iplist_size = 0;
1130 int i;
1131 bool is_our_domain;
1132 enum security_types sec = (enum security_types)lp_security();
1134 is_our_domain = strequal(domain->name, lp_workgroup());
1136 if ( !is_our_domain
1137 && get_dc_name_via_netlogon(domain, dcname, &ss)
1138 && add_one_dc_unique(mem_ctx, domain->name, dcname, &ss, dcs, num_dcs) )
1140 char addr[INET6_ADDRSTRLEN];
1141 print_sockaddr(addr, sizeof(addr), &ss);
1142 DEBUG(10, ("Retrieved DC %s at %s via netlogon\n",
1143 dcname, addr));
1144 return True;
1147 if (sec == SEC_ADS) {
1148 char *sitename = NULL;
1150 /* We need to make sure we know the local site before
1151 doing any DNS queries, as this will restrict the
1152 get_sorted_dc_list() call below to only fetching
1153 DNS records for the correct site. */
1155 /* Find any DC to get the site record.
1156 We deliberately don't care about the
1157 return here. */
1159 get_dc_name(domain->name, domain->alt_name, dcname, &ss);
1161 sitename = sitename_fetch(domain->alt_name);
1162 if (sitename) {
1164 /* Do the site-specific AD dns lookup first. */
1165 get_sorted_dc_list(domain->alt_name, sitename, &ip_list, &iplist_size, True);
1167 for ( i=0; i<iplist_size; i++ ) {
1168 char addr[INET6_ADDRSTRLEN];
1169 print_sockaddr(addr, sizeof(addr),
1170 &ip_list[i].ss);
1171 add_one_dc_unique(mem_ctx,
1172 domain->name,
1173 addr,
1174 &ip_list[i].ss,
1175 dcs,
1176 num_dcs);
1179 SAFE_FREE(ip_list);
1180 SAFE_FREE(sitename);
1181 iplist_size = 0;
1184 /* Now we add DCs from the main AD dns lookup. */
1185 get_sorted_dc_list(domain->alt_name, NULL, &ip_list, &iplist_size, True);
1187 for ( i=0; i<iplist_size; i++ ) {
1188 char addr[INET6_ADDRSTRLEN];
1189 print_sockaddr(addr, sizeof(addr),
1190 &ip_list[i].ss);
1191 add_one_dc_unique(mem_ctx,
1192 domain->name,
1193 addr,
1194 &ip_list[i].ss,
1195 dcs,
1196 num_dcs);
1200 /* try standard netbios queries if no ADS */
1202 if (iplist_size==0) {
1203 get_sorted_dc_list(domain->name, NULL, &ip_list, &iplist_size, False);
1206 /* FIXME!! this is where we should re-insert the GETDC requests --jerry */
1208 /* now add to the dc array. We'll wait until the last minute
1209 to look up the name of the DC. But we fill in the char* for
1210 the ip now in to make the failed connection cache work */
1212 for ( i=0; i<iplist_size; i++ ) {
1213 char addr[INET6_ADDRSTRLEN];
1214 print_sockaddr(addr, sizeof(addr),
1215 &ip_list[i].ss);
1216 add_one_dc_unique(mem_ctx, domain->name, addr,
1217 &ip_list[i].ss, dcs, num_dcs);
1220 SAFE_FREE( ip_list );
1222 return True;
1225 static bool find_new_dc(TALLOC_CTX *mem_ctx,
1226 struct winbindd_domain *domain,
1227 fstring dcname, struct sockaddr_storage *pss, int *fd)
1229 struct dc_name_ip *dcs = NULL;
1230 int num_dcs = 0;
1232 const char **dcnames = NULL;
1233 int num_dcnames = 0;
1235 struct sockaddr_storage *addrs = NULL;
1236 int num_addrs = 0;
1238 int i, fd_index;
1240 again:
1241 if (!get_dcs(mem_ctx, domain, &dcs, &num_dcs) || (num_dcs == 0))
1242 return False;
1244 for (i=0; i<num_dcs; i++) {
1246 if (!add_string_to_array(mem_ctx, dcs[i].name,
1247 &dcnames, &num_dcnames)) {
1248 return False;
1250 if (!add_sockaddr_to_array(mem_ctx, &dcs[i].ss, 445,
1251 &addrs, &num_addrs)) {
1252 return False;
1255 if (!add_string_to_array(mem_ctx, dcs[i].name,
1256 &dcnames, &num_dcnames)) {
1257 return False;
1259 if (!add_sockaddr_to_array(mem_ctx, &dcs[i].ss, 139,
1260 &addrs, &num_addrs)) {
1261 return False;
1265 if ((num_dcnames == 0) || (num_dcnames != num_addrs))
1266 return False;
1268 if ((addrs == NULL) || (dcnames == NULL))
1269 return False;
1271 /* 5 second timeout. */
1272 if (!open_any_socket_out(addrs, num_addrs, 5000, &fd_index, fd) ) {
1273 for (i=0; i<num_dcs; i++) {
1274 char ab[INET6_ADDRSTRLEN];
1275 print_sockaddr(ab, sizeof(ab), &dcs[i].ss);
1276 DEBUG(10, ("find_new_dc: open_any_socket_out failed for "
1277 "domain %s address %s. Error was %s\n",
1278 domain->name, ab, strerror(errno) ));
1279 winbind_add_failed_connection_entry(domain,
1280 dcs[i].name, NT_STATUS_UNSUCCESSFUL);
1282 return False;
1285 *pss = addrs[fd_index];
1287 if (*dcnames[fd_index] != '\0' && !is_ipaddress(dcnames[fd_index])) {
1288 /* Ok, we've got a name for the DC */
1289 fstrcpy(dcname, dcnames[fd_index]);
1290 return True;
1293 /* Try to figure out the name */
1294 if (dcip_to_name(domain, pss, dcname)) {
1295 return True;
1298 /* We can not continue without the DC's name */
1299 winbind_add_failed_connection_entry(domain, dcs[fd_index].name,
1300 NT_STATUS_UNSUCCESSFUL);
1301 goto again;
1304 static NTSTATUS cm_open_connection(struct winbindd_domain *domain,
1305 struct winbindd_cm_conn *new_conn)
1307 TALLOC_CTX *mem_ctx;
1308 NTSTATUS result;
1309 char *saf_servername = saf_fetch( domain->name );
1310 int retries;
1312 if ((mem_ctx = talloc_init("cm_open_connection")) == NULL) {
1313 SAFE_FREE(saf_servername);
1314 set_domain_offline(domain);
1315 return NT_STATUS_NO_MEMORY;
1318 /* we have to check the server affinity cache here since
1319 later we selecte a DC based on response time and not preference */
1321 /* Check the negative connection cache
1322 before talking to it. It going down may have
1323 triggered the reconnection. */
1325 if ( saf_servername && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, saf_servername))) {
1327 DEBUG(10,("cm_open_connection: saf_servername is '%s' for domain %s\n",
1328 saf_servername, domain->name ));
1330 /* convert an ip address to a name */
1331 if (is_ipaddress( saf_servername ) ) {
1332 fstring saf_name;
1333 struct sockaddr_storage ss;
1335 if (!interpret_string_addr(&ss, saf_servername,
1336 AI_NUMERICHOST)) {
1337 return NT_STATUS_UNSUCCESSFUL;
1339 if (dcip_to_name( domain, &ss, saf_name )) {
1340 fstrcpy( domain->dcname, saf_name );
1341 } else {
1342 winbind_add_failed_connection_entry(
1343 domain, saf_servername,
1344 NT_STATUS_UNSUCCESSFUL);
1346 } else {
1347 fstrcpy( domain->dcname, saf_servername );
1350 SAFE_FREE( saf_servername );
1353 for (retries = 0; retries < 3; retries++) {
1354 int fd = -1;
1355 bool retry = False;
1357 result = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1359 DEBUG(10,("cm_open_connection: dcname is '%s' for domain %s\n",
1360 domain->dcname, domain->name ));
1362 if (*domain->dcname
1363 && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, domain->dcname))
1364 && (resolve_name(domain->dcname, &domain->dcaddr, 0x20)))
1366 struct sockaddr_storage *addrs = NULL;
1367 int num_addrs = 0;
1368 int dummy = 0;
1370 if (!add_sockaddr_to_array(mem_ctx, &domain->dcaddr, 445, &addrs, &num_addrs)) {
1371 set_domain_offline(domain);
1372 talloc_destroy(mem_ctx);
1373 return NT_STATUS_NO_MEMORY;
1375 if (!add_sockaddr_to_array(mem_ctx, &domain->dcaddr, 139, &addrs, &num_addrs)) {
1376 set_domain_offline(domain);
1377 talloc_destroy(mem_ctx);
1378 return NT_STATUS_NO_MEMORY;
1381 /* 5 second timeout. */
1382 if (!open_any_socket_out(addrs, num_addrs, 5000, &dummy, &fd)) {
1383 fd = -1;
1387 if ((fd == -1)
1388 && !find_new_dc(mem_ctx, domain, domain->dcname, &domain->dcaddr, &fd))
1390 /* This is the one place where we will
1391 set the global winbindd offline state
1392 to true, if a "WINBINDD_OFFLINE" entry
1393 is found in the winbindd cache. */
1394 set_global_winbindd_state_offline();
1395 break;
1398 new_conn->cli = NULL;
1400 result = cm_prepare_connection(domain, fd, domain->dcname,
1401 &new_conn->cli, &retry);
1403 if (!retry)
1404 break;
1407 if (NT_STATUS_IS_OK(result)) {
1409 winbindd_set_locator_kdc_envs(domain);
1411 if (domain->online == False) {
1412 /* We're changing state from offline to online. */
1413 set_global_winbindd_state_online();
1415 set_domain_online(domain);
1416 } else {
1417 /* Ensure we setup the retry handler. */
1418 set_domain_offline(domain);
1421 talloc_destroy(mem_ctx);
1422 return result;
1425 /* Close down all open pipes on a connection. */
1427 void invalidate_cm_connection(struct winbindd_cm_conn *conn)
1429 /* We're closing down a possibly dead
1430 connection. Don't have impossibly long (10s) timeouts. */
1432 if (conn->cli) {
1433 cli_set_timeout(conn->cli, 1000); /* 1 second. */
1436 if (conn->samr_pipe != NULL) {
1437 TALLOC_FREE(conn->samr_pipe);
1438 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1439 if (conn->cli) {
1440 cli_set_timeout(conn->cli, 500);
1444 if (conn->lsa_pipe != NULL) {
1445 TALLOC_FREE(conn->lsa_pipe);
1446 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1447 if (conn->cli) {
1448 cli_set_timeout(conn->cli, 500);
1452 if (conn->netlogon_pipe != NULL) {
1453 TALLOC_FREE(conn->netlogon_pipe);
1454 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1455 if (conn->cli) {
1456 cli_set_timeout(conn->cli, 500);
1460 if (conn->cli) {
1461 cli_shutdown(conn->cli);
1464 conn->cli = NULL;
1467 void close_conns_after_fork(void)
1469 struct winbindd_domain *domain;
1471 for (domain = domain_list(); domain; domain = domain->next) {
1472 if (domain->conn.cli == NULL)
1473 continue;
1475 if (domain->conn.cli->fd == -1)
1476 continue;
1478 close(domain->conn.cli->fd);
1479 domain->conn.cli->fd = -1;
1483 static bool connection_ok(struct winbindd_domain *domain)
1485 if (domain->conn.cli == NULL) {
1486 DEBUG(8, ("connection_ok: Connection to %s for domain %s has NULL "
1487 "cli!\n", domain->dcname, domain->name));
1488 return False;
1491 if (!domain->conn.cli->initialised) {
1492 DEBUG(3, ("connection_ok: Connection to %s for domain %s was never "
1493 "initialised!\n", domain->dcname, domain->name));
1494 return False;
1497 if (domain->conn.cli->fd == -1) {
1498 DEBUG(3, ("connection_ok: Connection to %s for domain %s has died or was "
1499 "never started (fd == -1)\n",
1500 domain->dcname, domain->name));
1501 return False;
1504 if (domain->online == False) {
1505 DEBUG(3, ("connection_ok: Domain %s is offline\n", domain->name));
1506 return False;
1509 return True;
1512 /* Initialize a new connection up to the RPC BIND.
1513 Bypass online status check so always does network calls. */
1515 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain)
1517 NTSTATUS result;
1519 /* Internal connections never use the network. */
1520 if (domain->internal) {
1521 domain->initialized = True;
1522 return NT_STATUS_OK;
1525 if (connection_ok(domain)) {
1526 if (!domain->initialized) {
1527 set_dc_type_and_flags(domain);
1529 return NT_STATUS_OK;
1532 invalidate_cm_connection(&domain->conn);
1534 result = cm_open_connection(domain, &domain->conn);
1536 if (NT_STATUS_IS_OK(result) && !domain->initialized) {
1537 set_dc_type_and_flags(domain);
1540 return result;
1543 NTSTATUS init_dc_connection(struct winbindd_domain *domain)
1545 if (domain->initialized && !domain->online) {
1546 /* We check for online status elsewhere. */
1547 return NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1550 return init_dc_connection_network(domain);
1553 /******************************************************************************
1554 Set the trust flags (direction and forest location) for a domain
1555 ******************************************************************************/
1557 static bool set_dc_type_and_flags_trustinfo( struct winbindd_domain *domain )
1559 struct winbindd_domain *our_domain;
1560 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
1561 struct netr_DomainTrustList trusts;
1562 int i;
1563 uint32 flags = (NETR_TRUST_FLAG_IN_FOREST |
1564 NETR_TRUST_FLAG_OUTBOUND |
1565 NETR_TRUST_FLAG_INBOUND);
1566 struct rpc_pipe_client *cli;
1567 TALLOC_CTX *mem_ctx = NULL;
1569 DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s\n", domain->name ));
1571 /* Our primary domain doesn't need to worry about trust flags.
1572 Force it to go through the network setup */
1573 if ( domain->primary ) {
1574 return False;
1577 our_domain = find_our_domain();
1579 if ( !connection_ok(our_domain) ) {
1580 DEBUG(3,("set_dc_type_and_flags_trustinfo: No connection to our domain!\n"));
1581 return False;
1584 /* This won't work unless our domain is AD */
1586 if ( !our_domain->active_directory ) {
1587 return False;
1590 /* Use DsEnumerateDomainTrusts to get us the trust direction
1591 and type */
1593 result = cm_connect_netlogon(our_domain, &cli);
1595 if (!NT_STATUS_IS_OK(result)) {
1596 DEBUG(5, ("set_dc_type_and_flags_trustinfo: Could not open "
1597 "a connection to %s for PIPE_NETLOGON (%s)\n",
1598 domain->name, nt_errstr(result)));
1599 return False;
1602 if ( (mem_ctx = talloc_init("set_dc_type_and_flags_trustinfo")) == NULL ) {
1603 DEBUG(0,("set_dc_type_and_flags_trustinfo: talloc_init() failed!\n"));
1604 return False;
1607 result = rpccli_netr_DsrEnumerateDomainTrusts(cli, mem_ctx,
1608 cli->desthost,
1609 flags,
1610 &trusts,
1611 NULL);
1612 if (!NT_STATUS_IS_OK(result)) {
1613 DEBUG(0,("set_dc_type_and_flags_trustinfo: "
1614 "failed to query trusted domain list: %s\n",
1615 nt_errstr(result)));
1616 talloc_destroy(mem_ctx);
1617 return false;
1620 /* Now find the domain name and get the flags */
1622 for ( i=0; i<trusts.count; i++ ) {
1623 if ( strequal( domain->name, trusts.array[i].netbios_name) ) {
1624 domain->domain_flags = trusts.array[i].trust_flags;
1625 domain->domain_type = trusts.array[i].trust_type;
1626 domain->domain_trust_attribs = trusts.array[i].trust_attributes;
1628 if ( domain->domain_type == NETR_TRUST_TYPE_UPLEVEL )
1629 domain->active_directory = True;
1631 /* This flag is only set if the domain is *our*
1632 primary domain and the primary domain is in
1633 native mode */
1635 domain->native_mode = (domain->domain_flags & NETR_TRUST_FLAG_NATIVE);
1637 DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s is %sin "
1638 "native mode.\n", domain->name,
1639 domain->native_mode ? "" : "NOT "));
1641 DEBUG(5,("set_dc_type_and_flags_trustinfo: domain %s is %s"
1642 "running active directory.\n", domain->name,
1643 domain->active_directory ? "" : "NOT "));
1646 domain->initialized = True;
1648 if ( !winbindd_can_contact_domain( domain) )
1649 domain->internal = True;
1651 break;
1655 talloc_destroy( mem_ctx );
1657 return domain->initialized;
1660 /******************************************************************************
1661 We can 'sense' certain things about the DC by it's replies to certain
1662 questions.
1664 This tells us if this particular remote server is Active Directory, and if it
1665 is native mode.
1666 ******************************************************************************/
1668 static void set_dc_type_and_flags_connect( struct winbindd_domain *domain )
1670 NTSTATUS result;
1671 WERROR werr;
1672 TALLOC_CTX *mem_ctx = NULL;
1673 struct rpc_pipe_client *cli;
1674 POLICY_HND pol;
1675 union dssetup_DsRoleInfo info;
1676 union lsa_PolicyInformation *lsa_info = NULL;
1678 if (!connection_ok(domain)) {
1679 return;
1682 mem_ctx = talloc_init("set_dc_type_and_flags on domain %s\n",
1683 domain->name);
1684 if (!mem_ctx) {
1685 DEBUG(1, ("set_dc_type_and_flags_connect: talloc_init() failed\n"));
1686 return;
1689 DEBUG(5, ("set_dc_type_and_flags_connect: domain %s\n", domain->name ));
1691 cli = cli_rpc_pipe_open_noauth(domain->conn.cli, PI_DSSETUP,
1692 &result);
1694 if (cli == NULL) {
1695 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
1696 "PI_DSSETUP on domain %s: (%s)\n",
1697 domain->name, nt_errstr(result)));
1699 /* if this is just a non-AD domain we need to continue
1700 * identifying so that we can in the end return with
1701 * domain->initialized = True - gd */
1703 goto no_dssetup;
1706 result = rpccli_dssetup_DsRoleGetPrimaryDomainInformation(cli, mem_ctx,
1707 DS_ROLE_BASIC_INFORMATION,
1708 &info,
1709 &werr);
1710 TALLOC_FREE(cli);
1712 if (!NT_STATUS_IS_OK(result)) {
1713 DEBUG(5, ("set_dc_type_and_flags_connect: rpccli_ds_getprimarydominfo "
1714 "on domain %s failed: (%s)\n",
1715 domain->name, nt_errstr(result)));
1717 /* older samba3 DCs will return DCERPC_FAULT_OP_RNG_ERROR for
1718 * every opcode on the DSSETUP pipe, continue with
1719 * no_dssetup mode here as well to get domain->initialized
1720 * set - gd */
1722 if (NT_STATUS_V(result) == DCERPC_FAULT_OP_RNG_ERROR) {
1723 goto no_dssetup;
1726 TALLOC_FREE(mem_ctx);
1727 return;
1730 if ((info.basic.flags & DS_ROLE_PRIMARY_DS_RUNNING) &&
1731 !(info.basic.flags & DS_ROLE_PRIMARY_DS_MIXED_MODE)) {
1732 domain->native_mode = True;
1733 } else {
1734 domain->native_mode = False;
1737 no_dssetup:
1738 cli = cli_rpc_pipe_open_noauth(domain->conn.cli, PI_LSARPC, &result);
1740 if (cli == NULL) {
1741 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
1742 "PI_LSARPC on domain %s: (%s)\n",
1743 domain->name, nt_errstr(result)));
1744 TALLOC_FREE(cli);
1745 TALLOC_FREE(mem_ctx);
1746 return;
1749 result = rpccli_lsa_open_policy2(cli, mem_ctx, True,
1750 SEC_RIGHTS_MAXIMUM_ALLOWED, &pol);
1752 if (NT_STATUS_IS_OK(result)) {
1753 /* This particular query is exactly what Win2k clients use
1754 to determine that the DC is active directory */
1755 result = rpccli_lsa_QueryInfoPolicy2(cli, mem_ctx,
1756 &pol,
1757 LSA_POLICY_INFO_DNS,
1758 &lsa_info);
1761 if (NT_STATUS_IS_OK(result)) {
1762 domain->active_directory = True;
1764 if (lsa_info->dns.name.string) {
1765 fstrcpy(domain->name, lsa_info->dns.name.string);
1768 if (lsa_info->dns.dns_domain.string) {
1769 fstrcpy(domain->alt_name,
1770 lsa_info->dns.dns_domain.string);
1773 /* See if we can set some domain trust flags about
1774 ourself */
1776 if (lsa_info->dns.dns_forest.string) {
1777 fstrcpy(domain->forest_name,
1778 lsa_info->dns.dns_forest.string);
1780 if (strequal(domain->forest_name, domain->alt_name)) {
1781 domain->domain_flags |= NETR_TRUST_FLAG_TREEROOT;
1785 if (lsa_info->dns.sid) {
1786 sid_copy(&domain->sid, lsa_info->dns.sid);
1788 } else {
1789 domain->active_directory = False;
1791 result = rpccli_lsa_open_policy(cli, mem_ctx, True,
1792 SEC_RIGHTS_MAXIMUM_ALLOWED,
1793 &pol);
1795 if (!NT_STATUS_IS_OK(result)) {
1796 goto done;
1799 result = rpccli_lsa_QueryInfoPolicy(cli, mem_ctx,
1800 &pol,
1801 LSA_POLICY_INFO_ACCOUNT_DOMAIN,
1802 &lsa_info);
1804 if (NT_STATUS_IS_OK(result)) {
1806 if (lsa_info->account_domain.name.string) {
1807 fstrcpy(domain->name,
1808 lsa_info->account_domain.name.string);
1811 if (lsa_info->account_domain.sid) {
1812 sid_copy(&domain->sid, lsa_info->account_domain.sid);
1816 done:
1818 DEBUG(5, ("set_dc_type_and_flags_connect: domain %s is %sin native mode.\n",
1819 domain->name, domain->native_mode ? "" : "NOT "));
1821 DEBUG(5,("set_dc_type_and_flags_connect: domain %s is %srunning active directory.\n",
1822 domain->name, domain->active_directory ? "" : "NOT "));
1824 TALLOC_FREE(cli);
1826 TALLOC_FREE(mem_ctx);
1828 domain->initialized = True;
1831 /**********************************************************************
1832 Set the domain_flags (trust attributes, domain operating modes, etc...
1833 ***********************************************************************/
1835 static void set_dc_type_and_flags( struct winbindd_domain *domain )
1837 /* we always have to contact our primary domain */
1839 if ( domain->primary ) {
1840 DEBUG(10,("set_dc_type_and_flags: setting up flags for "
1841 "primary domain\n"));
1842 set_dc_type_and_flags_connect( domain );
1843 return;
1846 /* Use our DC to get the information if possible */
1848 if ( !set_dc_type_and_flags_trustinfo( domain ) ) {
1849 /* Otherwise, fallback to contacting the
1850 domain directly */
1851 set_dc_type_and_flags_connect( domain );
1854 return;
1859 /**********************************************************************
1860 ***********************************************************************/
1862 static bool cm_get_schannel_dcinfo(struct winbindd_domain *domain,
1863 struct dcinfo **ppdc)
1865 NTSTATUS result;
1866 struct rpc_pipe_client *netlogon_pipe;
1868 if (lp_client_schannel() == False) {
1869 return False;
1872 result = cm_connect_netlogon(domain, &netlogon_pipe);
1873 if (!NT_STATUS_IS_OK(result)) {
1874 return False;
1877 /* Return a pointer to the struct dcinfo from the
1878 netlogon pipe. */
1880 *ppdc = domain->conn.netlogon_pipe->dc;
1881 return True;
1884 NTSTATUS cm_connect_sam(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
1885 struct rpc_pipe_client **cli, POLICY_HND *sam_handle)
1887 struct winbindd_cm_conn *conn;
1888 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
1889 fstring conn_pwd;
1890 struct dcinfo *p_dcinfo;
1891 char *machine_password = NULL;
1892 char *machine_account = NULL;
1893 char *domain_name = NULL;
1895 result = init_dc_connection(domain);
1896 if (!NT_STATUS_IS_OK(result)) {
1897 return result;
1900 conn = &domain->conn;
1902 if (conn->samr_pipe != NULL) {
1903 goto done;
1907 * No SAMR pipe yet. Attempt to get an NTLMSSP SPNEGO authenticated
1908 * sign and sealed pipe using the machine account password by
1909 * preference. If we can't - try schannel, if that fails, try
1910 * anonymous.
1913 pwd_get_cleartext(&conn->cli->pwd, conn_pwd);
1914 if ((conn->cli->user_name[0] == '\0') ||
1915 (conn->cli->domain[0] == '\0') ||
1916 (conn_pwd[0] == '\0'))
1918 result = get_trust_creds(domain, &machine_password,
1919 &machine_account, NULL);
1920 if (!NT_STATUS_IS_OK(result)) {
1921 DEBUG(10, ("cm_connect_sam: No no user available for "
1922 "domain %s, trying schannel\n", conn->cli->domain));
1923 goto schannel;
1925 domain_name = domain->name;
1926 } else {
1927 machine_password = SMB_STRDUP(conn_pwd);
1928 machine_account = SMB_STRDUP(conn->cli->user_name);
1929 domain_name = conn->cli->domain;
1932 if (!machine_password || !machine_account) {
1933 result = NT_STATUS_NO_MEMORY;
1934 goto done;
1937 /* We have an authenticated connection. Use a NTLMSSP SPNEGO
1938 authenticated SAMR pipe with sign & seal. */
1939 conn->samr_pipe =
1940 cli_rpc_pipe_open_spnego_ntlmssp(conn->cli, PI_SAMR,
1941 PIPE_AUTH_LEVEL_PRIVACY,
1942 domain_name,
1943 machine_account,
1944 machine_password, &result);
1946 if (conn->samr_pipe == NULL) {
1947 DEBUG(10,("cm_connect_sam: failed to connect to SAMR "
1948 "pipe for domain %s using NTLMSSP "
1949 "authenticated pipe: user %s\\%s. Error was "
1950 "%s\n", domain->name, domain_name,
1951 machine_account, nt_errstr(result)));
1952 goto schannel;
1955 DEBUG(10,("cm_connect_sam: connected to SAMR pipe for "
1956 "domain %s using NTLMSSP authenticated "
1957 "pipe: user %s\\%s\n", domain->name,
1958 domain_name, machine_account));
1960 result = rpccli_samr_Connect2(conn->samr_pipe, mem_ctx,
1961 conn->samr_pipe->desthost,
1962 SEC_RIGHTS_MAXIMUM_ALLOWED,
1963 &conn->sam_connect_handle);
1964 if (NT_STATUS_IS_OK(result)) {
1965 goto open_domain;
1967 DEBUG(10,("cm_connect_sam: ntlmssp-sealed rpccli_samr_Connect2 "
1968 "failed for domain %s, error was %s. Trying schannel\n",
1969 domain->name, nt_errstr(result) ));
1970 TALLOC_FREE(conn->samr_pipe);
1972 schannel:
1974 /* Fall back to schannel if it's a W2K pre-SP1 box. */
1976 if (!cm_get_schannel_dcinfo(domain, &p_dcinfo)) {
1977 /* If this call fails - conn->cli can now be NULL ! */
1978 DEBUG(10, ("cm_connect_sam: Could not get schannel auth info "
1979 "for domain %s, trying anon\n", domain->name));
1980 goto anonymous;
1982 conn->samr_pipe = cli_rpc_pipe_open_schannel_with_key
1983 (conn->cli, PI_SAMR, PIPE_AUTH_LEVEL_PRIVACY,
1984 domain->name, p_dcinfo, &result);
1986 if (conn->samr_pipe == NULL) {
1987 DEBUG(10,("cm_connect_sam: failed to connect to SAMR pipe for "
1988 "domain %s using schannel. Error was %s\n",
1989 domain->name, nt_errstr(result) ));
1990 goto anonymous;
1992 DEBUG(10,("cm_connect_sam: connected to SAMR pipe for domain %s using "
1993 "schannel.\n", domain->name ));
1995 result = rpccli_samr_Connect2(conn->samr_pipe, mem_ctx,
1996 conn->samr_pipe->desthost,
1997 SEC_RIGHTS_MAXIMUM_ALLOWED,
1998 &conn->sam_connect_handle);
1999 if (NT_STATUS_IS_OK(result)) {
2000 goto open_domain;
2002 DEBUG(10,("cm_connect_sam: schannel-sealed rpccli_samr_Connect2 failed "
2003 "for domain %s, error was %s. Trying anonymous\n",
2004 domain->name, nt_errstr(result) ));
2005 TALLOC_FREE(conn->samr_pipe);
2007 anonymous:
2009 /* Finally fall back to anonymous. */
2010 conn->samr_pipe = cli_rpc_pipe_open_noauth(conn->cli, PI_SAMR,
2011 &result);
2013 if (conn->samr_pipe == NULL) {
2014 result = NT_STATUS_PIPE_NOT_AVAILABLE;
2015 goto done;
2018 result = rpccli_samr_Connect2(conn->samr_pipe, mem_ctx,
2019 conn->samr_pipe->desthost,
2020 SEC_RIGHTS_MAXIMUM_ALLOWED,
2021 &conn->sam_connect_handle);
2022 if (!NT_STATUS_IS_OK(result)) {
2023 DEBUG(10,("cm_connect_sam: rpccli_samr_Connect2 failed "
2024 "for domain %s Error was %s\n",
2025 domain->name, nt_errstr(result) ));
2026 goto done;
2029 open_domain:
2030 result = rpccli_samr_OpenDomain(conn->samr_pipe,
2031 mem_ctx,
2032 &conn->sam_connect_handle,
2033 SEC_RIGHTS_MAXIMUM_ALLOWED,
2034 &domain->sid,
2035 &conn->sam_domain_handle);
2037 done:
2039 if (!NT_STATUS_IS_OK(result)) {
2040 invalidate_cm_connection(conn);
2041 return result;
2044 *cli = conn->samr_pipe;
2045 *sam_handle = conn->sam_domain_handle;
2046 SAFE_FREE(machine_password);
2047 SAFE_FREE(machine_account);
2048 return result;
2051 NTSTATUS cm_connect_lsa(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2052 struct rpc_pipe_client **cli, POLICY_HND *lsa_policy)
2054 struct winbindd_cm_conn *conn;
2055 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2056 fstring conn_pwd;
2057 struct dcinfo *p_dcinfo;
2059 result = init_dc_connection(domain);
2060 if (!NT_STATUS_IS_OK(result))
2061 return result;
2063 conn = &domain->conn;
2065 if (conn->lsa_pipe != NULL) {
2066 goto done;
2069 pwd_get_cleartext(&conn->cli->pwd, conn_pwd);
2070 if ((conn->cli->user_name[0] == '\0') ||
2071 (conn->cli->domain[0] == '\0') ||
2072 (conn_pwd[0] == '\0')) {
2073 DEBUG(10, ("cm_connect_lsa: No no user available for "
2074 "domain %s, trying schannel\n", conn->cli->domain));
2075 goto schannel;
2078 /* We have an authenticated connection. Use a NTLMSSP SPNEGO
2079 * authenticated LSA pipe with sign & seal. */
2080 conn->lsa_pipe = cli_rpc_pipe_open_spnego_ntlmssp
2081 (conn->cli, PI_LSARPC, PIPE_AUTH_LEVEL_PRIVACY,
2082 conn->cli->domain, conn->cli->user_name, conn_pwd, &result);
2084 if (conn->lsa_pipe == NULL) {
2085 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
2086 "domain %s using NTLMSSP authenticated pipe: user "
2087 "%s\\%s. Error was %s. Trying schannel.\n",
2088 domain->name, conn->cli->domain,
2089 conn->cli->user_name, nt_errstr(result)));
2090 goto schannel;
2093 DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
2094 "NTLMSSP authenticated pipe: user %s\\%s\n",
2095 domain->name, conn->cli->domain, conn->cli->user_name ));
2097 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2098 SEC_RIGHTS_MAXIMUM_ALLOWED,
2099 &conn->lsa_policy);
2100 if (NT_STATUS_IS_OK(result)) {
2101 goto done;
2104 DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
2105 "schannel\n"));
2107 TALLOC_FREE(conn->lsa_pipe);
2109 schannel:
2111 /* Fall back to schannel if it's a W2K pre-SP1 box. */
2113 if (!cm_get_schannel_dcinfo(domain, &p_dcinfo)) {
2114 /* If this call fails - conn->cli can now be NULL ! */
2115 DEBUG(10, ("cm_connect_lsa: Could not get schannel auth info "
2116 "for domain %s, trying anon\n", domain->name));
2117 goto anonymous;
2119 conn->lsa_pipe = cli_rpc_pipe_open_schannel_with_key
2120 (conn->cli, PI_LSARPC, PIPE_AUTH_LEVEL_PRIVACY,
2121 domain->name, p_dcinfo, &result);
2123 if (conn->lsa_pipe == NULL) {
2124 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
2125 "domain %s using schannel. Error was %s\n",
2126 domain->name, nt_errstr(result) ));
2127 goto anonymous;
2129 DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
2130 "schannel.\n", domain->name ));
2132 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2133 SEC_RIGHTS_MAXIMUM_ALLOWED,
2134 &conn->lsa_policy);
2135 if (NT_STATUS_IS_OK(result)) {
2136 goto done;
2139 DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
2140 "anonymous\n"));
2142 TALLOC_FREE(conn->lsa_pipe);
2144 anonymous:
2146 conn->lsa_pipe = cli_rpc_pipe_open_noauth(conn->cli, PI_LSARPC,
2147 &result);
2148 if (conn->lsa_pipe == NULL) {
2149 result = NT_STATUS_PIPE_NOT_AVAILABLE;
2150 goto done;
2153 result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2154 SEC_RIGHTS_MAXIMUM_ALLOWED,
2155 &conn->lsa_policy);
2156 done:
2157 if (!NT_STATUS_IS_OK(result)) {
2158 invalidate_cm_connection(conn);
2159 return result;
2162 *cli = conn->lsa_pipe;
2163 *lsa_policy = conn->lsa_policy;
2164 return result;
2167 /****************************************************************************
2168 Open the netlogon pipe to this DC. Use schannel if specified in client conf.
2169 session key stored in conn->netlogon_pipe->dc->sess_key.
2170 ****************************************************************************/
2172 NTSTATUS cm_connect_netlogon(struct winbindd_domain *domain,
2173 struct rpc_pipe_client **cli)
2175 struct winbindd_cm_conn *conn;
2176 NTSTATUS result;
2178 uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS;
2179 uint8 mach_pwd[16];
2180 uint32 sec_chan_type;
2181 const char *account_name;
2182 struct rpc_pipe_client *netlogon_pipe = NULL;
2184 *cli = NULL;
2186 result = init_dc_connection(domain);
2187 if (!NT_STATUS_IS_OK(result)) {
2188 return result;
2191 conn = &domain->conn;
2193 if (conn->netlogon_pipe != NULL) {
2194 *cli = conn->netlogon_pipe;
2195 return NT_STATUS_OK;
2198 netlogon_pipe = cli_rpc_pipe_open_noauth(conn->cli, PI_NETLOGON,
2199 &result);
2200 if (netlogon_pipe == NULL) {
2201 return result;
2204 if ((!IS_DC) && (!domain->primary)) {
2205 /* Clear the schannel request bit and drop down */
2206 neg_flags &= ~NETLOGON_NEG_SCHANNEL;
2207 goto no_schannel;
2210 if (lp_client_schannel() != False) {
2211 neg_flags |= NETLOGON_NEG_SCHANNEL;
2214 if (!get_trust_pw_hash(domain->name, mach_pwd, &account_name,
2215 &sec_chan_type))
2217 TALLOC_FREE(netlogon_pipe);
2218 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2221 result = rpccli_netlogon_setup_creds(
2222 netlogon_pipe,
2223 domain->dcname, /* server name. */
2224 domain->name, /* domain name */
2225 global_myname(), /* client name */
2226 account_name, /* machine account */
2227 mach_pwd, /* machine password */
2228 sec_chan_type, /* from get_trust_pw */
2229 &neg_flags);
2231 if (!NT_STATUS_IS_OK(result)) {
2232 TALLOC_FREE(netlogon_pipe);
2233 return result;
2236 if ((lp_client_schannel() == True) &&
2237 ((neg_flags & NETLOGON_NEG_SCHANNEL) == 0)) {
2238 DEBUG(3, ("Server did not offer schannel\n"));
2239 TALLOC_FREE(netlogon_pipe);
2240 return NT_STATUS_ACCESS_DENIED;
2243 no_schannel:
2244 if ((lp_client_schannel() == False) ||
2245 ((neg_flags & NETLOGON_NEG_SCHANNEL) == 0)) {
2247 * NetSamLogonEx only works for schannel
2249 domain->can_do_samlogon_ex = False;
2251 /* We're done - just keep the existing connection to NETLOGON
2252 * open */
2253 conn->netlogon_pipe = netlogon_pipe;
2254 *cli = conn->netlogon_pipe;
2255 return NT_STATUS_OK;
2258 /* Using the credentials from the first pipe, open a signed and sealed
2259 second netlogon pipe. The session key is stored in the schannel
2260 part of the new pipe auth struct.
2263 conn->netlogon_pipe =
2264 cli_rpc_pipe_open_schannel_with_key(conn->cli,
2265 PI_NETLOGON,
2266 PIPE_AUTH_LEVEL_PRIVACY,
2267 domain->name,
2268 netlogon_pipe->dc,
2269 &result);
2271 /* We can now close the initial netlogon pipe. */
2272 TALLOC_FREE(netlogon_pipe);
2274 if (conn->netlogon_pipe == NULL) {
2275 DEBUG(3, ("Could not open schannel'ed NETLOGON pipe. Error "
2276 "was %s\n", nt_errstr(result)));
2278 /* make sure we return something besides OK */
2279 return !NT_STATUS_IS_OK(result) ? result : NT_STATUS_PIPE_NOT_AVAILABLE;
2283 * Try NetSamLogonEx for AD domains
2285 domain->can_do_samlogon_ex = domain->active_directory;
2287 *cli = conn->netlogon_pipe;
2288 return NT_STATUS_OK;