s3:winbindd: make sure cm_prepare_connection() only returns OK with a valid tree...
[kai/samba-autobuild/.git] / source3 / winbindd / winbindd_cm.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Winbind daemon connection manager
5
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
11
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.
16
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.
21
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/>.
24 */
25
26 /*
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:
30
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
37
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.
44
45    The TNG design is quite good but I disagree with some aspects of the
46    implementation. -tpot
47
48  */
49
50 /*
51    TODO:
52
53      - I'm pretty annoyed by all the make_nmb_name() stuff.  It should be
54        moved down into another function.
55
56      - Take care when destroying cli_structs as they can be shared between
57        various sam handles.
58
59  */
60
61 #include "includes.h"
62 #include "winbindd.h"
63 #include "../libcli/auth/libcli_auth.h"
64 #include "../librpc/gen_ndr/ndr_netlogon_c.h"
65 #include "rpc_client/cli_pipe.h"
66 #include "rpc_client/cli_netlogon.h"
67 #include "../librpc/gen_ndr/ndr_samr_c.h"
68 #include "../librpc/gen_ndr/ndr_lsa_c.h"
69 #include "rpc_client/cli_lsarpc.h"
70 #include "../librpc/gen_ndr/ndr_dssetup_c.h"
71 #include "libads/sitename_cache.h"
72 #include "libsmb/libsmb.h"
73 #include "libsmb/clidgram.h"
74 #include "ads.h"
75 #include "secrets.h"
76 #include "../libcli/security/security.h"
77 #include "passdb.h"
78 #include "messages.h"
79 #include "auth/gensec/gensec.h"
80 #include "../libcli/smb/smbXcli_base.h"
81 #include "libcli/auth/netlogon_creds_cli.h"
82 #include "auth.h"
83 #include "rpc_server/rpc_ncacn_np.h"
84 #include "auth/credentials/credentials.h"
85 #include "lib/param/param.h"
86
87 #undef DBGC_CLASS
88 #define DBGC_CLASS DBGC_WINBIND
89
90 struct dc_name_ip {
91         fstring name;
92         struct sockaddr_storage ss;
93 };
94
95 extern struct winbindd_methods reconnect_methods;
96 extern bool override_logfile;
97
98 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain, bool need_rw_dc);
99 static void set_dc_type_and_flags( struct winbindd_domain *domain );
100 static bool set_dc_type_and_flags_trustinfo( struct winbindd_domain *domain );
101 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
102                     struct dc_name_ip **dcs, int *num_dcs);
103
104 /****************************************************************
105  Child failed to find DC's. Reschedule check.
106 ****************************************************************/
107
108 static void msg_failed_to_go_online(struct messaging_context *msg,
109                                     void *private_data,
110                                     uint32_t msg_type,
111                                     struct server_id server_id,
112                                     DATA_BLOB *data)
113 {
114         struct winbindd_domain *domain;
115         const char *domainname = (const char *)data->data;
116
117         if (data->data == NULL || data->length == 0) {
118                 return;
119         }
120
121         DEBUG(5,("msg_fail_to_go_online: received for domain %s.\n", domainname));
122
123         for (domain = domain_list(); domain; domain = domain->next) {
124                 if (domain->internal) {
125                         continue;
126                 }
127
128                 if (strequal(domain->name, domainname)) {
129                         if (domain->online) {
130                                 /* We're already online, ignore. */
131                                 DEBUG(5,("msg_fail_to_go_online: domain %s "
132                                         "already online.\n", domainname));
133                                 continue;
134                         }
135
136                         /* Reschedule the online check. */
137                         set_domain_offline(domain);
138                         break;
139                 }
140         }
141 }
142
143 /****************************************************************
144  Actually cause a reconnect from a message.
145 ****************************************************************/
146
147 static void msg_try_to_go_online(struct messaging_context *msg,
148                                  void *private_data,
149                                  uint32_t msg_type,
150                                  struct server_id server_id,
151                                  DATA_BLOB *data)
152 {
153         struct winbindd_domain *domain;
154         const char *domainname = (const char *)data->data;
155
156         if (data->data == NULL || data->length == 0) {
157                 return;
158         }
159
160         DEBUG(5,("msg_try_to_go_online: received for domain %s.\n", domainname));
161
162         for (domain = domain_list(); domain; domain = domain->next) {
163                 if (domain->internal) {
164                         continue;
165                 }
166
167                 if (strequal(domain->name, domainname)) {
168
169                         if (domain->online) {
170                                 /* We're already online, ignore. */
171                                 DEBUG(5,("msg_try_to_go_online: domain %s "
172                                         "already online.\n", domainname));
173                                 continue;
174                         }
175
176                         /* This call takes care of setting the online
177                            flag to true if we connected, or re-adding
178                            the offline handler if false. Bypasses online
179                            check so always does network calls. */
180
181                         init_dc_connection_network(domain, true);
182                         break;
183                 }
184         }
185 }
186
187 /****************************************************************
188  Fork a child to try and contact a DC. Do this as contacting a
189  DC requires blocking lookups and we don't want to block our
190  parent.
191 ****************************************************************/
192
193 static bool fork_child_dc_connect(struct winbindd_domain *domain)
194 {
195         struct dc_name_ip *dcs = NULL;
196         int num_dcs = 0;
197         TALLOC_CTX *mem_ctx = NULL;
198         pid_t parent_pid = getpid();
199         char *lfile = NULL;
200         NTSTATUS status;
201
202         if (domain->dc_probe_pid != (pid_t)-1) {
203                 /*
204                  * We might already have a DC probe
205                  * child working, check.
206                  */
207                 if (process_exists_by_pid(domain->dc_probe_pid)) {
208                         DEBUG(10,("fork_child_dc_connect: pid %u already "
209                                 "checking for DC's.\n",
210                                 (unsigned int)domain->dc_probe_pid));
211                         return true;
212                 }
213                 domain->dc_probe_pid = (pid_t)-1;
214         }
215
216         domain->dc_probe_pid = fork();
217
218         if (domain->dc_probe_pid == (pid_t)-1) {
219                 DEBUG(0, ("fork_child_dc_connect: Could not fork: %s\n", strerror(errno)));
220                 return False;
221         }
222
223         if (domain->dc_probe_pid != (pid_t)0) {
224                 /* Parent */
225                 messaging_register(winbind_messaging_context(), NULL,
226                                    MSG_WINBIND_TRY_TO_GO_ONLINE,
227                                    msg_try_to_go_online);
228                 messaging_register(winbind_messaging_context(), NULL,
229                                    MSG_WINBIND_FAILED_TO_GO_ONLINE,
230                                    msg_failed_to_go_online);
231                 return True;
232         }
233
234         /* Child. */
235
236         /* Leave messages blocked - we will never process one. */
237
238         if (!override_logfile) {
239                 if (asprintf(&lfile, "%s/log.winbindd-dc-connect", get_dyn_LOGFILEBASE()) == -1) {
240                         DEBUG(0, ("fork_child_dc_connect: out of memory.\n"));
241                         _exit(1);
242                 }
243         }
244
245         status = winbindd_reinit_after_fork(NULL, lfile);
246         if (!NT_STATUS_IS_OK(status)) {
247                 DEBUG(1, ("winbindd_reinit_after_fork failed: %s\n",
248                           nt_errstr(status)));
249                 messaging_send_buf(winbind_messaging_context(),
250                                    pid_to_procid(parent_pid),
251                                    MSG_WINBIND_FAILED_TO_GO_ONLINE,
252                                    (const uint8_t *)domain->name,
253                                    strlen(domain->name)+1);
254                 _exit(1);
255         }
256         SAFE_FREE(lfile);
257
258         mem_ctx = talloc_init("fork_child_dc_connect");
259         if (!mem_ctx) {
260                 DEBUG(0,("talloc_init failed.\n"));
261                 messaging_send_buf(winbind_messaging_context(),
262                                    pid_to_procid(parent_pid),
263                                    MSG_WINBIND_FAILED_TO_GO_ONLINE,
264                                    (const uint8_t *)domain->name,
265                                    strlen(domain->name)+1);
266                 _exit(1);
267         }
268
269         if ((!get_dcs(mem_ctx, domain, &dcs, &num_dcs)) || (num_dcs == 0)) {
270                 /* Still offline ? Can't find DC's. */
271                 messaging_send_buf(winbind_messaging_context(),
272                                    pid_to_procid(parent_pid),
273                                    MSG_WINBIND_FAILED_TO_GO_ONLINE,
274                                    (const uint8_t *)domain->name,
275                                    strlen(domain->name)+1);
276                 _exit(0);
277         }
278
279         /* We got a DC. Send a message to our parent to get it to
280            try and do the same. */
281
282         messaging_send_buf(winbind_messaging_context(),
283                            pid_to_procid(parent_pid),
284                            MSG_WINBIND_TRY_TO_GO_ONLINE,
285                            (const uint8_t *)domain->name,
286                            strlen(domain->name)+1);
287         _exit(0);
288 }
289
290 /****************************************************************
291  Handler triggered if we're offline to try and detect a DC.
292 ****************************************************************/
293
294 static void check_domain_online_handler(struct tevent_context *ctx,
295                                         struct tevent_timer *te,
296                                         struct timeval now,
297                                         void *private_data)
298 {
299         struct winbindd_domain *domain =
300                 (struct winbindd_domain *)private_data;
301
302         DEBUG(10,("check_domain_online_handler: called for domain "
303                   "%s (online = %s)\n", domain->name, 
304                   domain->online ? "True" : "False" ));
305
306         TALLOC_FREE(domain->check_online_event);
307
308         /* Are we still in "startup" mode ? */
309
310         if (domain->startup && (time_mono(NULL) > domain->startup_time + 30)) {
311                 /* No longer in "startup" mode. */
312                 DEBUG(10,("check_domain_online_handler: domain %s no longer in 'startup' mode.\n",
313                         domain->name ));
314                 domain->startup = False;
315         }
316
317         /* We've been told to stay offline, so stay
318            that way. */
319
320         if (get_global_winbindd_state_offline()) {
321                 DEBUG(10,("check_domain_online_handler: domain %s remaining globally offline\n",
322                         domain->name ));
323                 return;
324         }
325
326         /* Fork a child to test if it can contact a DC. 
327            If it can then send ourselves a message to
328            cause a reconnect. */
329
330         fork_child_dc_connect(domain);
331 }
332
333 /****************************************************************
334  If we're still offline setup the timeout check.
335 ****************************************************************/
336
337 static void calc_new_online_timeout_check(struct winbindd_domain *domain)
338 {
339         int wbr = lp_winbind_reconnect_delay();
340
341         if (domain->startup) {
342                 domain->check_online_timeout = 10;
343         } else if (domain->check_online_timeout < wbr) {
344                 domain->check_online_timeout = wbr;
345         }
346 }
347
348 void winbind_msg_domain_offline(struct messaging_context *msg_ctx,
349                                 void *private_data,
350                                 uint32_t msg_type,
351                                 struct server_id server_id,
352                                 DATA_BLOB *data)
353 {
354         const char *domain_name = (const char *)data->data;
355         struct winbindd_domain *domain;
356
357         domain = find_domain_from_name_noinit(domain_name);
358         if (domain == NULL) {
359                 return;
360         }
361
362         domain->online = false;
363
364         DEBUG(10, ("Domain %s is marked as offline now.\n",
365                    domain_name));
366 }
367
368 void winbind_msg_domain_online(struct messaging_context *msg_ctx,
369                                 void *private_data,
370                                 uint32_t msg_type,
371                                 struct server_id server_id,
372                                 DATA_BLOB *data)
373 {
374         const char *domain_name = (const char *)data->data;
375         struct winbindd_domain *domain;
376
377         domain = find_domain_from_name_noinit(domain_name);
378         if (domain == NULL) {
379                 return;
380         }
381
382         domain->online = true;
383
384         DEBUG(10, ("Domain %s is marked as online now.\n",
385                    domain_name));
386 }
387
388 /****************************************************************
389  Set domain offline and also add handler to put us back online
390  if we detect a DC.
391 ****************************************************************/
392
393 void set_domain_offline(struct winbindd_domain *domain)
394 {
395         pid_t parent_pid = getppid();
396
397         DEBUG(10,("set_domain_offline: called for domain %s\n",
398                 domain->name ));
399
400         TALLOC_FREE(domain->check_online_event);
401
402         if (domain->internal) {
403                 DEBUG(3,("set_domain_offline: domain %s is internal - logic error.\n",
404                         domain->name ));
405                 return;
406         }
407
408         domain->online = False;
409
410         /* Offline domains are always initialized. They're
411            re-initialized when they go back online. */
412
413         domain->initialized = True;
414
415         /* We only add the timeout handler that checks and
416            allows us to go back online when we've not
417            been told to remain offline. */
418
419         if (get_global_winbindd_state_offline()) {
420                 DEBUG(10,("set_domain_offline: domain %s remaining globally offline\n",
421                         domain->name ));
422                 return;
423         }
424
425         /* If we're in startup mode, check again in 10 seconds, not in
426            lp_winbind_reconnect_delay() seconds (which is 30 seconds by default). */
427
428         calc_new_online_timeout_check(domain);
429
430         domain->check_online_event = tevent_add_timer(winbind_event_context(),
431                                                 NULL,
432                                                 timeval_current_ofs(domain->check_online_timeout,0),
433                                                 check_domain_online_handler,
434                                                 domain);
435
436         /* The above *has* to succeed for winbindd to work. */
437         if (!domain->check_online_event) {
438                 smb_panic("set_domain_offline: failed to add online handler");
439         }
440
441         DEBUG(10,("set_domain_offline: added event handler for domain %s\n",
442                 domain->name ));
443
444         /* Send a message to the parent that the domain is offline. */
445         if (parent_pid > 1 && !domain->internal) {
446                 messaging_send_buf(winbind_messaging_context(),
447                                    pid_to_procid(parent_pid),
448                                    MSG_WINBIND_DOMAIN_OFFLINE,
449                                    (uint8_t *)domain->name,
450                                    strlen(domain->name) + 1);
451         }
452
453         /* Send an offline message to the idmap child when our
454            primary domain goes offline */
455
456         if ( domain->primary ) {
457                 struct winbindd_child *idmap = idmap_child();
458
459                 if ( idmap->pid != 0 ) {
460                         messaging_send_buf(winbind_messaging_context(),
461                                            pid_to_procid(idmap->pid), 
462                                            MSG_WINBIND_OFFLINE, 
463                                            (const uint8_t *)domain->name,
464                                            strlen(domain->name)+1);
465                 }                       
466         }
467
468         return; 
469 }
470
471 /****************************************************************
472  Set domain online - if allowed.
473 ****************************************************************/
474
475 static void set_domain_online(struct winbindd_domain *domain)
476 {
477         pid_t parent_pid = getppid();
478
479         DEBUG(10,("set_domain_online: called for domain %s\n",
480                 domain->name ));
481
482         if (domain->internal) {
483                 DEBUG(3,("set_domain_online: domain %s is internal - logic error.\n",
484                         domain->name ));
485                 return;
486         }
487
488         if (get_global_winbindd_state_offline()) {
489                 DEBUG(10,("set_domain_online: domain %s remaining globally offline\n",
490                         domain->name ));
491                 return;
492         }
493
494         winbindd_set_locator_kdc_envs(domain);
495
496         /* If we are waiting to get a krb5 ticket, trigger immediately. */
497         ccache_regain_all_now();
498
499         /* Ok, we're out of any startup mode now... */
500         domain->startup = False;
501
502         if (domain->online == False) {
503                 /* We were offline - now we're online. We default to
504                    using the MS-RPC backend if we started offline,
505                    and if we're going online for the first time we
506                    should really re-initialize the backends and the
507                    checks to see if we're talking to an AD or NT domain.
508                 */
509
510                 domain->initialized = False;
511
512                 /* 'reconnect_methods' is the MS-RPC backend. */
513                 if (domain->backend == &reconnect_methods) {
514                         domain->backend = NULL;
515                 }
516         }
517
518         /* Ensure we have no online timeout checks. */
519         domain->check_online_timeout = 0;
520         TALLOC_FREE(domain->check_online_event);
521
522         /* Ensure we ignore any pending child messages. */
523         messaging_deregister(winbind_messaging_context(),
524                              MSG_WINBIND_TRY_TO_GO_ONLINE, NULL);
525         messaging_deregister(winbind_messaging_context(),
526                              MSG_WINBIND_FAILED_TO_GO_ONLINE, NULL);
527
528         domain->online = True;
529
530         /* Send a message to the parent that the domain is online. */
531         if (parent_pid > 1 && !domain->internal) {
532                 messaging_send_buf(winbind_messaging_context(),
533                                    pid_to_procid(parent_pid),
534                                    MSG_WINBIND_DOMAIN_ONLINE,
535                                    (uint8_t *)domain->name,
536                                    strlen(domain->name) + 1);
537         }
538
539         /* Send an online message to the idmap child when our
540            primary domain comes online */
541
542         if ( domain->primary ) {
543                 struct winbindd_child *idmap = idmap_child();
544
545                 if ( idmap->pid != 0 ) {
546                         messaging_send_buf(winbind_messaging_context(),
547                                            pid_to_procid(idmap->pid), 
548                                            MSG_WINBIND_ONLINE, 
549                                            (const uint8_t *)domain->name,
550                                            strlen(domain->name)+1);
551                 }                       
552         }
553
554         return; 
555 }
556
557 /****************************************************************
558  Requested to set a domain online.
559 ****************************************************************/
560
561 void set_domain_online_request(struct winbindd_domain *domain)
562 {
563         struct timeval tev;
564
565         DEBUG(10,("set_domain_online_request: called for domain %s\n",
566                 domain->name ));
567
568         if (get_global_winbindd_state_offline()) {
569                 DEBUG(10,("set_domain_online_request: domain %s remaining globally offline\n",
570                         domain->name ));
571                 return;
572         }
573
574         if (domain->internal) {
575                 DEBUG(10, ("set_domain_online_request: Internal domains are "
576                            "always online\n"));
577                 return;
578         }
579
580         /* We've been told it's safe to go online and
581            try and connect to a DC. But I don't believe it
582            because network manager seems to lie.
583            Wait at least 5 seconds. Heuristics suck... */
584
585
586         GetTimeOfDay(&tev);
587
588         /* Go into "startup" mode again. */
589         domain->startup_time = time_mono(NULL);
590         domain->startup = True;
591
592         tev.tv_sec += 5;
593
594         if (!domain->check_online_event) {
595                 /* If we've come from being globally offline we
596                    don't have a check online event handler set.
597                    We need to add one now we're trying to go
598                    back online. */
599
600                 DEBUG(10,("set_domain_online_request: domain %s was globally offline.\n",
601                         domain->name ));
602         }
603
604         TALLOC_FREE(domain->check_online_event);
605
606         domain->check_online_event = tevent_add_timer(winbind_event_context(),
607                                                      NULL,
608                                                      tev,
609                                                      check_domain_online_handler,
610                                                      domain);
611
612         /* The above *has* to succeed for winbindd to work. */
613         if (!domain->check_online_event) {
614                 smb_panic("set_domain_online_request: failed to add online handler");
615         }
616 }
617
618 /****************************************************************
619  Add -ve connection cache entries for domain and realm.
620 ****************************************************************/
621
622 static void winbind_add_failed_connection_entry(
623         const struct winbindd_domain *domain,
624         const char *server,
625         NTSTATUS result)
626 {
627         add_failed_connection_entry(domain->name, server, result);
628         /* If this was the saf name for the last thing we talked to,
629            remove it. */
630         saf_delete(domain->name);
631         if (domain->alt_name != NULL) {
632                 add_failed_connection_entry(domain->alt_name, server, result);
633                 saf_delete(domain->alt_name);
634         }
635         winbindd_unset_locator_kdc_env(domain);
636 }
637
638 /* Choose between anonymous or authenticated connections.  We need to use
639    an authenticated connection if DCs have the RestrictAnonymous registry
640    entry set > 0, or the "Additional restrictions for anonymous
641    connections" set in the win2k Local Security Policy. 
642
643    Caller to free() result in domain, username, password
644 */
645
646 static void cm_get_ipc_userpass(char **username, char **domain, char **password)
647 {
648         *username = (char *)secrets_fetch(SECRETS_AUTH_USER, NULL);
649         *domain = (char *)secrets_fetch(SECRETS_AUTH_DOMAIN, NULL);
650         *password = (char *)secrets_fetch(SECRETS_AUTH_PASSWORD, NULL);
651
652         if (*username && **username) {
653
654                 if (!*domain || !**domain)
655                         *domain = smb_xstrdup(lp_workgroup());
656
657                 if (!*password || !**password)
658                         *password = smb_xstrdup("");
659
660                 DEBUG(3, ("cm_get_ipc_userpass: Retrieved auth-user from secrets.tdb [%s\\%s]\n", 
661                           *domain, *username));
662
663         } else {
664                 DEBUG(3, ("cm_get_ipc_userpass: No auth-user defined\n"));
665                 *username = smb_xstrdup("");
666                 *domain = smb_xstrdup("");
667                 *password = smb_xstrdup("");
668         }
669 }
670
671 static NTSTATUS cm_get_ipc_credentials(TALLOC_CTX *mem_ctx,
672                                        struct cli_credentials **_creds)
673 {
674
675         TALLOC_CTX *frame = talloc_stackframe();
676         NTSTATUS status = NT_STATUS_INTERNAL_ERROR;
677         struct loadparm_context *lp_ctx;
678         char *username = NULL;
679         char *netbios_domain = NULL;
680         char *password = NULL;
681         struct cli_credentials *creds = NULL;
682         bool ok;
683
684         cm_get_ipc_userpass(&username, &netbios_domain, &password);
685
686         lp_ctx = loadparm_init_s3(frame, loadparm_s3_helpers());
687         if (lp_ctx == NULL) {
688                 DEBUG(1, ("loadparm_init_s3 failed\n"));
689                 status = NT_STATUS_INTERNAL_ERROR;
690                 goto fail;
691         }
692
693         creds = cli_credentials_init(mem_ctx);
694         if (creds == NULL) {
695                 status = NT_STATUS_NO_MEMORY;
696                 goto fail;
697         }
698
699         cli_credentials_set_conf(creds, lp_ctx);
700         cli_credentials_set_kerberos_state(creds, CRED_DONT_USE_KERBEROS);
701
702         ok = cli_credentials_set_domain(creds, netbios_domain, CRED_SPECIFIED);
703         if (!ok) {
704                 status = NT_STATUS_NO_MEMORY;
705                 goto fail;
706         }
707
708         ok = cli_credentials_set_username(creds, username, CRED_SPECIFIED);
709         if (!ok) {
710                 status = NT_STATUS_NO_MEMORY;
711                 goto fail;
712         }
713
714         ok = cli_credentials_set_password(creds, password, CRED_SPECIFIED);
715         if (!ok) {
716                 status = NT_STATUS_NO_MEMORY;
717                 goto fail;
718         }
719
720         *_creds = creds;
721         creds = NULL;
722         status = NT_STATUS_OK;
723  fail:
724         TALLOC_FREE(creds);
725         SAFE_FREE(username);
726         SAFE_FREE(netbios_domain);
727         SAFE_FREE(password);
728         TALLOC_FREE(frame);
729         return status;
730 }
731
732 static bool cm_is_ipc_credentials(struct cli_credentials *creds)
733 {
734         TALLOC_CTX *frame = talloc_stackframe();
735         char *ipc_account = NULL;
736         char *ipc_domain = NULL;
737         char *ipc_password = NULL;
738         const char *creds_account = NULL;
739         const char *creds_domain = NULL;
740         const char *creds_password = NULL;
741         bool ret = false;
742
743         cm_get_ipc_userpass(&ipc_account, &ipc_domain, &ipc_password);
744
745         creds_account = cli_credentials_get_username(creds);
746         creds_domain = cli_credentials_get_domain(creds);
747         creds_password = cli_credentials_get_password(creds);
748
749         if (!strequal(ipc_domain, creds_domain)) {
750                 goto done;
751         }
752
753         if (!strequal(ipc_account, creds_account)) {
754                 goto done;
755         }
756
757         if (!strcsequal(ipc_password, creds_password)) {
758                 goto done;
759         }
760
761         ret = true;
762  done:
763         SAFE_FREE(ipc_account);
764         SAFE_FREE(ipc_domain);
765         SAFE_FREE(ipc_password);
766         TALLOC_FREE(frame);
767         return ret;
768 }
769
770 static bool get_dc_name_via_netlogon(struct winbindd_domain *domain,
771                                      fstring dcname,
772                                      struct sockaddr_storage *dc_ss)
773 {
774         struct winbindd_domain *our_domain = NULL;
775         struct rpc_pipe_client *netlogon_pipe = NULL;
776         NTSTATUS result;
777         WERROR werr;
778         TALLOC_CTX *mem_ctx;
779         unsigned int orig_timeout;
780         const char *tmp = NULL;
781         const char *p;
782         struct dcerpc_binding_handle *b;
783
784         /* Hmmmm. We can only open one connection to the NETLOGON pipe at the
785          * moment.... */
786
787         if (IS_DC) {
788                 return False;
789         }
790
791         if (domain->primary) {
792                 return False;
793         }
794
795         our_domain = find_our_domain();
796
797         if ((mem_ctx = talloc_init("get_dc_name_via_netlogon")) == NULL) {
798                 return False;
799         }
800
801         result = cm_connect_netlogon(our_domain, &netlogon_pipe);
802         if (!NT_STATUS_IS_OK(result)) {
803                 talloc_destroy(mem_ctx);
804                 return False;
805         }
806
807         b = netlogon_pipe->binding_handle;
808
809         /* This call can take a long time - allow the server to time out.
810            35 seconds should do it. */
811
812         orig_timeout = rpccli_set_timeout(netlogon_pipe, 35000);
813
814         if (our_domain->active_directory) {
815                 struct netr_DsRGetDCNameInfo *domain_info = NULL;
816
817                 result = dcerpc_netr_DsRGetDCName(b,
818                                                   mem_ctx,
819                                                   our_domain->dcname,
820                                                   domain->name,
821                                                   NULL,
822                                                   NULL,
823                                                   DS_RETURN_DNS_NAME,
824                                                   &domain_info,
825                                                   &werr);
826                 if (NT_STATUS_IS_OK(result) && W_ERROR_IS_OK(werr)) {
827                         tmp = talloc_strdup(
828                                 mem_ctx, domain_info->dc_unc);
829                         if (tmp == NULL) {
830                                 DEBUG(0, ("talloc_strdup failed\n"));
831                                 talloc_destroy(mem_ctx);
832                                 return false;
833                         }
834                         if (domain->alt_name == NULL) {
835                                 domain->alt_name = talloc_strdup(domain,
836                                                                  domain_info->domain_name);
837                                 if (domain->alt_name == NULL) {
838                                         DEBUG(0, ("talloc_strdup failed\n"));
839                                         talloc_destroy(mem_ctx);
840                                         return false;
841                                 }
842                         }
843                         if (domain->forest_name == NULL) {
844                                 domain->forest_name = talloc_strdup(domain,
845                                                                     domain_info->forest_name);
846                                 if (domain->forest_name == NULL) {
847                                         DEBUG(0, ("talloc_strdup failed\n"));
848                                         talloc_destroy(mem_ctx);
849                                         return false;
850                                 }
851                         }
852                 }
853         } else {
854                 result = dcerpc_netr_GetAnyDCName(b, mem_ctx,
855                                                   our_domain->dcname,
856                                                   domain->name,
857                                                   &tmp,
858                                                   &werr);
859         }
860
861         /* And restore our original timeout. */
862         rpccli_set_timeout(netlogon_pipe, orig_timeout);
863
864         if (!NT_STATUS_IS_OK(result)) {
865                 DEBUG(10,("dcerpc_netr_GetAnyDCName failed: %s\n",
866                         nt_errstr(result)));
867                 talloc_destroy(mem_ctx);
868                 return false;
869         }
870
871         if (!W_ERROR_IS_OK(werr)) {
872                 DEBUG(10,("dcerpc_netr_GetAnyDCName failed: %s\n",
873                            win_errstr(werr)));
874                 talloc_destroy(mem_ctx);
875                 return false;
876         }
877
878         /* dcerpc_netr_GetAnyDCName gives us a name with \\ */
879         p = strip_hostname(tmp);
880
881         fstrcpy(dcname, p);
882
883         talloc_destroy(mem_ctx);
884
885         DEBUG(10,("dcerpc_netr_GetAnyDCName returned %s\n", dcname));
886
887         if (!resolve_name(dcname, dc_ss, 0x20, true)) {
888                 return False;
889         }
890
891         return True;
892 }
893
894 /**
895  * Helper function to assemble trust password and account name
896  */
897 static NTSTATUS get_trust_credentials(struct winbindd_domain *domain,
898                                       TALLOC_CTX *mem_ctx,
899                                       bool netlogon,
900                                       struct cli_credentials **_creds)
901 {
902         const struct winbindd_domain *creds_domain = NULL;
903         struct cli_credentials *creds;
904         NTSTATUS status;
905         bool force_machine_account = false;
906         bool ok;
907
908         /* If we are a DC and this is not our own domain */
909
910         if (!domain->active_directory) {
911                 if (!netlogon) {
912                         /*
913                          * For non active directory domains
914                          * we can only use NTLMSSP for SMB.
915                          *
916                          * But the trust account is not allowed
917                          * to use SMB with NTLMSSP.
918                          */
919                         force_machine_account = true;
920                 }
921         }
922
923         if (IS_DC && !force_machine_account) {
924                 creds_domain = domain;
925         } else {
926                 creds_domain = find_our_domain();
927                 if (creds_domain == NULL) {
928                         return NT_STATUS_INVALID_SERVER_STATE;
929                 }
930         }
931
932         status = pdb_get_trust_credentials(creds_domain->name,
933                                            creds_domain->alt_name,
934                                            mem_ctx,
935                                            &creds);
936         if (!NT_STATUS_IS_OK(status)) {
937                 goto ipc_fallback;
938         }
939
940         if (domain->primary && lp_security() == SEC_ADS) {
941                 cli_credentials_set_kerberos_state(creds,
942                                                    CRED_AUTO_USE_KERBEROS);
943         } else if (domain->active_directory) {
944                 cli_credentials_set_kerberos_state(creds,
945                                                    CRED_MUST_USE_KERBEROS);
946         } else {
947                 cli_credentials_set_kerberos_state(creds,
948                                                    CRED_DONT_USE_KERBEROS);
949         }
950
951         /*
952          * When we contact our own domain and get a list of the trusted domain
953          * we have the information if we are able to contact the DC with
954          * with our machine account password.
955          */
956         ok = winbindd_can_contact_domain(domain);
957         if (!ok) {
958                 /*
959                  * We can only use schannel against a direct trust
960                  */
961                 cli_credentials_set_secure_channel_type(creds,
962                                                         SEC_CHAN_NULL);
963         }
964
965         *_creds = creds;
966         return NT_STATUS_OK;
967
968  ipc_fallback:
969         if (netlogon) {
970                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
971         }
972
973         status = cm_get_ipc_credentials(mem_ctx, &creds);
974         if (!NT_STATUS_IS_OK(status)) {
975                 return status;
976         }
977
978         *_creds = creds;
979         return NT_STATUS_OK;
980 }
981
982 /************************************************************************
983  Given a fd with a just-connected TCP connection to a DC, open a connection
984  to the pipe.
985 ************************************************************************/
986
987 static NTSTATUS cm_prepare_connection(struct winbindd_domain *domain,
988                                       const int sockfd,
989                                       const char *controller,
990                                       struct cli_state **cli,
991                                       bool *retry)
992 {
993         bool try_ipc_auth = false;
994         const char *machine_principal = NULL;
995         const char *machine_realm = NULL;
996         const char *machine_account = NULL;
997         const char *machine_domain = NULL;
998         int flags = 0;
999         struct cli_credentials *creds = NULL;
1000
1001         struct named_mutex *mutex;
1002
1003         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
1004         NTSTATUS tmp_status;
1005         NTSTATUS tcon_status = NT_STATUS_NETWORK_NAME_DELETED;
1006
1007         enum smb_signing_setting smb_sign_client_connections = lp_client_ipc_signing();
1008
1009         if (smb_sign_client_connections == SMB_SIGNING_DEFAULT) {
1010                 /*
1011                  * If we are connecting to our own AD domain, require
1012                  * smb signing to disrupt MITM attacks
1013                  */
1014                 if (domain->primary && lp_security() == SEC_ADS) {
1015                         smb_sign_client_connections = SMB_SIGNING_REQUIRED;
1016                 /*
1017                  * If we are in or are an AD domain and connecting to another
1018                  * AD domain in our forest
1019                  * then require smb signing to disrupt MITM attacks
1020                  */
1021                 } else if ((lp_security() == SEC_ADS ||
1022                             lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC)
1023                            && domain->active_directory
1024                            && (domain->domain_trust_attribs
1025                                & LSA_TRUST_ATTRIBUTE_WITHIN_FOREST)) {
1026                         smb_sign_client_connections = SMB_SIGNING_REQUIRED;
1027                 }
1028         }
1029
1030         DEBUG(10,("cm_prepare_connection: connecting to DC %s for domain %s\n",
1031                 controller, domain->name ));
1032
1033         *retry = True;
1034
1035         mutex = grab_named_mutex(talloc_tos(), controller,
1036                                  WINBIND_SERVER_MUTEX_WAIT_TIME);
1037         if (mutex == NULL) {
1038                 close(sockfd);
1039                 DEBUG(0,("cm_prepare_connection: mutex grab failed for %s\n",
1040                          controller));
1041                 result = NT_STATUS_POSSIBLE_DEADLOCK;
1042                 goto done;
1043         }
1044
1045         *cli = cli_state_create(NULL, sockfd,
1046                                 controller, domain->alt_name,
1047                                 smb_sign_client_connections, flags);
1048         if (*cli == NULL) {
1049                 close(sockfd);
1050                 DEBUG(1, ("Could not cli_initialize\n"));
1051                 result = NT_STATUS_NO_MEMORY;
1052                 goto done;
1053         }
1054
1055         cli_set_timeout(*cli, 10000); /* 10 seconds */
1056
1057         set_socket_options(sockfd, lp_socket_options());
1058
1059         result = smbXcli_negprot((*cli)->conn, (*cli)->timeout,
1060                                  lp_client_ipc_min_protocol(),
1061                                  lp_client_ipc_max_protocol());
1062
1063         if (!NT_STATUS_IS_OK(result)) {
1064                 DEBUG(1, ("cli_negprot failed: %s\n", nt_errstr(result)));
1065                 goto done;
1066         }
1067
1068         if (smbXcli_conn_protocol((*cli)->conn) >= PROTOCOL_NT1 &&
1069             smb1cli_conn_capabilities((*cli)->conn) & CAP_EXTENDED_SECURITY) {
1070                 try_ipc_auth = true;
1071         } else if (smbXcli_conn_protocol((*cli)->conn) >= PROTOCOL_SMB2_02) {
1072                 try_ipc_auth = true;
1073         } else if (smb_sign_client_connections == SMB_SIGNING_REQUIRED) {
1074                 /*
1075                  * If we are forcing on SMB signing, then we must
1076                  * require authentication unless this is a one-way
1077                  * trust, and we have no stored user/password
1078                  */
1079                 try_ipc_auth = true;
1080         }
1081
1082         if (try_ipc_auth) {
1083                 result = get_trust_credentials(domain, talloc_tos(), false, &creds);
1084                 if (!NT_STATUS_IS_OK(result)) {
1085                         DEBUG(1, ("get_trust_credentials(%s) failed: %s\n",
1086                                   domain->name, nt_errstr(result)));
1087                         goto done;
1088                 }
1089         } else {
1090                 /*
1091                  * Without SPNEGO or NTLMSSP (perhaps via SMB2) we
1092                  * would try and authentication with our machine
1093                  * account password and fail.  This is very rare in
1094                  * the modern world however
1095                  */
1096                 creds = cli_credentials_init_anon(talloc_tos());
1097                 if (creds == NULL) {
1098                         result = NT_STATUS_NO_MEMORY;
1099                         DEBUG(1, ("cli_credentials_init_anon(%s) failed: %s\n",
1100                                   domain->name, nt_errstr(result)));
1101                         goto done;
1102                 }
1103         }
1104
1105         machine_principal = cli_credentials_get_principal(creds,
1106                                                         talloc_tos());
1107         machine_realm = cli_credentials_get_realm(creds);
1108         machine_account = cli_credentials_get_username(creds);
1109         machine_domain = cli_credentials_get_domain(creds);
1110
1111         DEBUG(5, ("connecting to %s (%s, %s) with account [%s\\%s] principal "
1112                   "[%s] and realm [%s]\n",
1113                   controller, domain->name, domain->alt_name,
1114                   machine_domain, machine_account,
1115                   machine_principal, machine_realm));
1116
1117         winbindd_set_locator_kdc_envs(domain);
1118
1119         result = cli_session_setup_creds(*cli, creds);
1120         if (NT_STATUS_IS_OK(result)) {
1121                 goto session_setup_done;
1122         }
1123
1124         /*
1125          * If we are not going to validiate the conneciton
1126          * with SMB signing, then allow us to fall back to
1127          * anonymous
1128          */
1129         if (NT_STATUS_EQUAL(result, NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT)
1130             || NT_STATUS_EQUAL(result, NT_STATUS_TRUSTED_DOMAIN_FAILURE)
1131             || NT_STATUS_EQUAL(result, NT_STATUS_INVALID_ACCOUNT_NAME)
1132             || NT_STATUS_EQUAL(result, NT_STATUS_NO_LOGON_SERVERS)
1133             || NT_STATUS_EQUAL(result, NT_STATUS_LOGON_FAILURE))
1134         {
1135                 if (cli_credentials_is_anonymous(creds)) {
1136                         goto done;
1137                 }
1138
1139                 if (!cm_is_ipc_credentials(creds)) {
1140                         goto ipc_fallback;
1141                 }
1142
1143                 if (smb_sign_client_connections == SMB_SIGNING_REQUIRED) {
1144                         goto done;
1145                 }
1146
1147                 goto anon_fallback;
1148         }
1149
1150         DEBUG(4, ("authenticated session setup failed with %s\n",
1151                 nt_errstr(result)));
1152
1153         goto done;
1154
1155  ipc_fallback:
1156         TALLOC_FREE(creds);
1157         tmp_status = cm_get_ipc_credentials(talloc_tos(), &creds);
1158         if (!NT_STATUS_IS_OK(tmp_status)) {
1159                 result = tmp_status;
1160                 goto done;
1161         }
1162
1163         if (cli_credentials_is_anonymous(creds)) {
1164                 goto anon_fallback;
1165         }
1166
1167         machine_account = cli_credentials_get_username(creds);
1168         machine_domain = cli_credentials_get_domain(creds);
1169
1170         DEBUG(5, ("connecting to %s from %s using NTLMSSP with username "
1171                   "[%s]\\[%s]\n",  controller, lp_netbios_name(),
1172                   machine_domain, machine_account));
1173
1174         result = cli_session_setup_creds(*cli, creds);
1175         if (NT_STATUS_IS_OK(result)) {
1176                 goto session_setup_done;
1177         }
1178
1179         /*
1180          * If we are not going to validiate the conneciton
1181          * with SMB signing, then allow us to fall back to
1182          * anonymous
1183          */
1184         if (NT_STATUS_EQUAL(result, NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT)
1185             || NT_STATUS_EQUAL(result, NT_STATUS_TRUSTED_DOMAIN_FAILURE)
1186             || NT_STATUS_EQUAL(result, NT_STATUS_INVALID_ACCOUNT_NAME)
1187             || NT_STATUS_EQUAL(result, NT_STATUS_NO_LOGON_SERVERS)
1188             || NT_STATUS_EQUAL(result, NT_STATUS_LOGON_FAILURE))
1189         {
1190                 goto anon_fallback;
1191         }
1192
1193         DEBUG(4, ("authenticated session setup failed with %s\n",
1194                 nt_errstr(result)));
1195
1196         goto done;
1197
1198  anon_fallback:
1199         TALLOC_FREE(creds);
1200
1201         if (smb_sign_client_connections == SMB_SIGNING_REQUIRED) {
1202                 goto done;
1203         }
1204
1205         /* Fall back to anonymous connection, this might fail later */
1206         DEBUG(10,("cm_prepare_connection: falling back to anonymous "
1207                 "connection for DC %s\n",
1208                 controller ));
1209
1210         result = cli_session_setup_anon(*cli);
1211         if (NT_STATUS_IS_OK(result)) {
1212                 DEBUG(5, ("Connected anonymously\n"));
1213                 goto session_setup_done;
1214         }
1215
1216         /* We can't session setup */
1217         goto done;
1218
1219  session_setup_done:
1220         TALLOC_FREE(creds);
1221
1222         /*
1223          * This should be a short term hack until
1224          * dynamic re-authentication is implemented.
1225          *
1226          * See Bug 9175 - winbindd doesn't recover from
1227          * NT_STATUS_NETWORK_SESSION_EXPIRED
1228          */
1229         if (smbXcli_conn_protocol((*cli)->conn) >= PROTOCOL_SMB2_02) {
1230                 smbXcli_session_set_disconnect_expired((*cli)->smb2.session);
1231         }
1232
1233         result = cli_tree_connect(*cli, "IPC$", "IPC", NULL);
1234         if (!NT_STATUS_IS_OK(result)) {
1235                 DEBUG(1,("failed tcon_X with %s\n", nt_errstr(result)));
1236                 goto done;
1237         }
1238         tcon_status = result;
1239
1240         /* cache the server name for later connections */
1241
1242         saf_store(domain->name, controller);
1243         if (domain->alt_name) {
1244                 saf_store(domain->alt_name, controller);
1245         }
1246
1247         winbindd_set_locator_kdc_envs(domain);
1248
1249         TALLOC_FREE(mutex);
1250         *retry = False;
1251
1252         result = NT_STATUS_OK;
1253
1254  done:
1255         TALLOC_FREE(mutex);
1256         TALLOC_FREE(creds);
1257
1258         if (NT_STATUS_IS_OK(result)) {
1259                 result = tcon_status;
1260         }
1261
1262         if (!NT_STATUS_IS_OK(result)) {
1263                 winbind_add_failed_connection_entry(domain, controller, result);
1264                 if ((*cli) != NULL) {
1265                         cli_shutdown(*cli);
1266                         *cli = NULL;
1267                 }
1268         }
1269
1270         return result;
1271 }
1272
1273 /*******************************************************************
1274  Add a dcname and sockaddr_storage pair to the end of a dc_name_ip
1275  array.
1276
1277  Keeps the list unique by not adding duplicate entries.
1278
1279  @param[in] mem_ctx talloc memory context to allocate from
1280  @param[in] domain_name domain of the DC
1281  @param[in] dcname name of the DC to add to the list
1282  @param[in] pss Internet address and port pair to add to the list
1283  @param[in,out] dcs array of dc_name_ip structures to add to
1284  @param[in,out] num_dcs number of dcs returned in the dcs array
1285  @return true if the list was added to, false otherwise
1286 *******************************************************************/
1287
1288 static bool add_one_dc_unique(TALLOC_CTX *mem_ctx, const char *domain_name,
1289                               const char *dcname, struct sockaddr_storage *pss,
1290                               struct dc_name_ip **dcs, int *num)
1291 {
1292         int i = 0;
1293
1294         if (!NT_STATUS_IS_OK(check_negative_conn_cache(domain_name, dcname))) {
1295                 DEBUG(10, ("DC %s was in the negative conn cache\n", dcname));
1296                 return False;
1297         }
1298
1299         /* Make sure there's no duplicates in the list */
1300         for (i=0; i<*num; i++)
1301                 if (sockaddr_equal(
1302                             (struct sockaddr *)(void *)&(*dcs)[i].ss,
1303                             (struct sockaddr *)(void *)pss))
1304                         return False;
1305
1306         *dcs = talloc_realloc(mem_ctx, *dcs, struct dc_name_ip, (*num)+1);
1307
1308         if (*dcs == NULL)
1309                 return False;
1310
1311         fstrcpy((*dcs)[*num].name, dcname);
1312         (*dcs)[*num].ss = *pss;
1313         *num += 1;
1314         return True;
1315 }
1316
1317 static bool add_sockaddr_to_array(TALLOC_CTX *mem_ctx,
1318                                   struct sockaddr_storage *pss, uint16_t port,
1319                                   struct sockaddr_storage **addrs, int *num)
1320 {
1321         *addrs = talloc_realloc(mem_ctx, *addrs, struct sockaddr_storage, (*num)+1);
1322
1323         if (*addrs == NULL) {
1324                 *num = 0;
1325                 return False;
1326         }
1327
1328         (*addrs)[*num] = *pss;
1329         set_sockaddr_port((struct sockaddr *)&(*addrs)[*num], port);
1330
1331         *num += 1;
1332         return True;
1333 }
1334
1335 /*******************************************************************
1336  convert an ip to a name
1337 *******************************************************************/
1338
1339 static bool dcip_to_name(TALLOC_CTX *mem_ctx,
1340                 const struct winbindd_domain *domain,
1341                 struct sockaddr_storage *pss,
1342                 char **name)
1343 {
1344         struct ip_service ip_list;
1345         uint32_t nt_version = NETLOGON_NT_VERSION_1;
1346         NTSTATUS status;
1347         const char *dc_name;
1348         fstring nbtname;
1349 #ifdef HAVE_ADS
1350         bool is_ad_domain = false;
1351 #endif
1352         ip_list.ss = *pss;
1353         ip_list.port = 0;
1354
1355 #ifdef HAVE_ADS
1356         /* For active directory servers, try to get the ldap server name.
1357            None of these failures should be considered critical for now */
1358
1359         if ((lp_security() == SEC_ADS) && (domain->alt_name != NULL)) {
1360                 is_ad_domain = true;
1361         } else if (lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC) {
1362                 is_ad_domain = domain->active_directory;
1363         }
1364
1365         if (is_ad_domain) {
1366                 ADS_STRUCT *ads;
1367                 ADS_STATUS ads_status;
1368                 char addr[INET6_ADDRSTRLEN];
1369
1370                 print_sockaddr(addr, sizeof(addr), pss);
1371
1372                 ads = ads_init(domain->alt_name, domain->name, addr);
1373                 ads->auth.flags |= ADS_AUTH_NO_BIND;
1374
1375                 ads_status = ads_connect(ads);
1376                 if (ADS_ERR_OK(ads_status)) {
1377                         /* We got a cldap packet. */
1378                         *name = talloc_strdup(mem_ctx,
1379                                              ads->config.ldap_server_name);
1380                         if (*name == NULL) {
1381                                 return false;
1382                         }
1383                         namecache_store(*name, 0x20, 1, &ip_list);
1384
1385                         DEBUG(10,("dcip_to_name: flags = 0x%x\n", (unsigned int)ads->config.flags));
1386
1387                         if (domain->primary && (ads->config.flags & NBT_SERVER_KDC)) {
1388                                 if (ads_closest_dc(ads)) {
1389                                         char *sitename = sitename_fetch(mem_ctx, ads->config.realm);
1390
1391                                         /* We're going to use this KDC for this realm/domain.
1392                                            If we are using sites, then force the krb5 libs
1393                                            to use this KDC. */
1394
1395                                         create_local_private_krb5_conf_for_domain(domain->alt_name,
1396                                                                         domain->name,
1397                                                                         sitename,
1398                                                                         pss);
1399
1400                                         TALLOC_FREE(sitename);
1401                                 } else {
1402                                         /* use an off site KDC */
1403                                         create_local_private_krb5_conf_for_domain(domain->alt_name,
1404                                                                         domain->name,
1405                                                                         NULL,
1406                                                                         pss);
1407                                 }
1408                                 winbindd_set_locator_kdc_envs(domain);
1409
1410                                 /* Ensure we contact this DC also. */
1411                                 saf_store(domain->name, *name);
1412                                 saf_store(domain->alt_name, *name);
1413                         }
1414
1415                         ads_destroy( &ads );
1416                         return True;
1417                 }
1418
1419                 ads_destroy( &ads );
1420                 return false;
1421         }
1422 #endif
1423
1424         status = nbt_getdc(winbind_messaging_context(), 10, pss, domain->name,
1425                            &domain->sid, nt_version, mem_ctx, &nt_version,
1426                            &dc_name, NULL);
1427         if (NT_STATUS_IS_OK(status)) {
1428                 *name = talloc_strdup(mem_ctx, dc_name);
1429                 if (*name == NULL) {
1430                         return false;
1431                 }
1432                 namecache_store(*name, 0x20, 1, &ip_list);
1433                 return True;
1434         }
1435
1436         /* try node status request */
1437
1438         if (name_status_find(domain->name, 0x1c, 0x20, pss, nbtname) ) {
1439                 namecache_store(nbtname, 0x20, 1, &ip_list);
1440
1441                 if (name != NULL) {
1442                         *name = talloc_strdup(mem_ctx, nbtname);
1443                         if (*name == NULL) {
1444                                 return false;
1445                         }
1446                 }
1447
1448                 return true;
1449         }
1450         return False;
1451 }
1452
1453 /*******************************************************************
1454  Retrieve a list of IP addresses for domain controllers.
1455
1456  The array is sorted in the preferred connection order.
1457
1458  @param[in] mem_ctx talloc memory context to allocate from
1459  @param[in] domain domain to retrieve DCs for
1460  @param[out] dcs array of dcs that will be returned
1461  @param[out] num_dcs number of dcs returned in the dcs array
1462  @return always true
1463 *******************************************************************/
1464
1465 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
1466                     struct dc_name_ip **dcs, int *num_dcs)
1467 {
1468         fstring dcname;
1469         struct  sockaddr_storage ss;
1470         struct  ip_service *ip_list = NULL;
1471         int     iplist_size = 0;
1472         int     i;
1473         bool    is_our_domain;
1474         enum security_types sec = (enum security_types)lp_security();
1475
1476         is_our_domain = strequal(domain->name, lp_workgroup());
1477
1478         /* If not our domain, get the preferred DC, by asking our primary DC */
1479         if ( !is_our_domain
1480                 && get_dc_name_via_netlogon(domain, dcname, &ss)
1481                 && add_one_dc_unique(mem_ctx, domain->name, dcname, &ss, dcs,
1482                        num_dcs) )
1483         {
1484                 char addr[INET6_ADDRSTRLEN];
1485                 print_sockaddr(addr, sizeof(addr), &ss);
1486                 DEBUG(10, ("Retrieved DC %s at %s via netlogon\n",
1487                            dcname, addr));
1488                 return True;
1489         }
1490
1491         if ((sec == SEC_ADS) && (domain->alt_name != NULL)) {
1492                 char *sitename = NULL;
1493
1494                 /* We need to make sure we know the local site before
1495                    doing any DNS queries, as this will restrict the
1496                    get_sorted_dc_list() call below to only fetching
1497                    DNS records for the correct site. */
1498
1499                 /* Find any DC to get the site record.
1500                    We deliberately don't care about the
1501                    return here. */
1502
1503                 get_dc_name(domain->name, domain->alt_name, dcname, &ss);
1504
1505                 sitename = sitename_fetch(mem_ctx, domain->alt_name);
1506                 if (sitename) {
1507
1508                         /* Do the site-specific AD dns lookup first. */
1509                         get_sorted_dc_list(domain->alt_name, sitename, &ip_list,
1510                                &iplist_size, True);
1511
1512                         /* Add ips to the DC array.  We don't look up the name
1513                            of the DC in this function, but we fill in the char*
1514                            of the ip now to make the failed connection cache
1515                            work */
1516                         for ( i=0; i<iplist_size; i++ ) {
1517                                 char addr[INET6_ADDRSTRLEN];
1518                                 print_sockaddr(addr, sizeof(addr),
1519                                                 &ip_list[i].ss);
1520                                 add_one_dc_unique(mem_ctx,
1521                                                 domain->name,
1522                                                 addr,
1523                                                 &ip_list[i].ss,
1524                                                 dcs,
1525                                                 num_dcs);
1526                         }
1527
1528                         SAFE_FREE(ip_list);
1529                         TALLOC_FREE(sitename);
1530                         iplist_size = 0;
1531                 }
1532
1533                 /* Now we add DCs from the main AD DNS lookup. */
1534                 get_sorted_dc_list(domain->alt_name, NULL, &ip_list,
1535                         &iplist_size, True);
1536
1537                 for ( i=0; i<iplist_size; i++ ) {
1538                         char addr[INET6_ADDRSTRLEN];
1539                         print_sockaddr(addr, sizeof(addr),
1540                                         &ip_list[i].ss);
1541                         add_one_dc_unique(mem_ctx,
1542                                         domain->name,
1543                                         addr,
1544                                         &ip_list[i].ss,
1545                                         dcs,
1546                                         num_dcs);
1547                 }
1548
1549                 SAFE_FREE(ip_list);
1550                 iplist_size = 0;
1551         }
1552
1553         /* Try standard netbios queries if no ADS and fall back to DNS queries
1554          * if alt_name is available */
1555         if (*num_dcs == 0) {
1556                 get_sorted_dc_list(domain->name, NULL, &ip_list, &iplist_size,
1557                        false);
1558                 if (iplist_size == 0) {
1559                         if (domain->alt_name != NULL) {
1560                                 get_sorted_dc_list(domain->alt_name, NULL, &ip_list,
1561                                        &iplist_size, true);
1562                         }
1563                 }
1564
1565                 for ( i=0; i<iplist_size; i++ ) {
1566                         char addr[INET6_ADDRSTRLEN];
1567                         print_sockaddr(addr, sizeof(addr),
1568                                         &ip_list[i].ss);
1569                         add_one_dc_unique(mem_ctx,
1570                                         domain->name,
1571                                         addr,
1572                                         &ip_list[i].ss,
1573                                         dcs,
1574                                         num_dcs);
1575                 }
1576
1577                 SAFE_FREE(ip_list);
1578                 iplist_size = 0;
1579         }
1580
1581         return True;
1582 }
1583
1584 /*******************************************************************
1585  Find and make a connection to a DC in the given domain.
1586
1587  @param[in] mem_ctx talloc memory context to allocate from
1588  @param[in] domain domain to find a dc in
1589  @param[out] dcname NetBIOS or FQDN of DC that's connected to
1590  @param[out] pss DC Internet address and port
1591  @param[out] fd fd of the open socket connected to the newly found dc
1592  @return true when a DC connection is made, false otherwise
1593 *******************************************************************/
1594
1595 static bool find_new_dc(TALLOC_CTX *mem_ctx,
1596                         struct winbindd_domain *domain,
1597                         char **dcname, struct sockaddr_storage *pss, int *fd)
1598 {
1599         struct dc_name_ip *dcs = NULL;
1600         int num_dcs = 0;
1601
1602         const char **dcnames = NULL;
1603         size_t num_dcnames = 0;
1604
1605         struct sockaddr_storage *addrs = NULL;
1606         int num_addrs = 0;
1607
1608         int i;
1609         size_t fd_index;
1610
1611         NTSTATUS status;
1612
1613         *fd = -1;
1614
1615  again:
1616         if (!get_dcs(mem_ctx, domain, &dcs, &num_dcs) || (num_dcs == 0))
1617                 return False;
1618
1619         for (i=0; i<num_dcs; i++) {
1620
1621                 if (!add_string_to_array(mem_ctx, dcs[i].name,
1622                                     &dcnames, &num_dcnames)) {
1623                         return False;
1624                 }
1625                 if (!add_sockaddr_to_array(mem_ctx, &dcs[i].ss, TCP_SMB_PORT,
1626                                       &addrs, &num_addrs)) {
1627                         return False;
1628                 }
1629         }
1630
1631         if ((num_dcnames == 0) || (num_dcnames != num_addrs))
1632                 return False;
1633
1634         if ((addrs == NULL) || (dcnames == NULL))
1635                 return False;
1636
1637         status = smbsock_any_connect(addrs, dcnames, NULL, NULL, NULL,
1638                                      num_addrs, 0, 10, fd, &fd_index, NULL);
1639         if (!NT_STATUS_IS_OK(status)) {
1640                 for (i=0; i<num_dcs; i++) {
1641                         char ab[INET6_ADDRSTRLEN];
1642                         print_sockaddr(ab, sizeof(ab), &dcs[i].ss);
1643                         DEBUG(10, ("find_new_dc: smbsock_any_connect failed for "
1644                                 "domain %s address %s. Error was %s\n",
1645                                    domain->name, ab, nt_errstr(status) ));
1646                         winbind_add_failed_connection_entry(domain,
1647                                 dcs[i].name, NT_STATUS_UNSUCCESSFUL);
1648                 }
1649                 return False;
1650         }
1651
1652         *pss = addrs[fd_index];
1653
1654         if (*dcnames[fd_index] != '\0' && !is_ipaddress(dcnames[fd_index])) {
1655                 /* Ok, we've got a name for the DC */
1656                 *dcname = talloc_strdup(mem_ctx, dcnames[fd_index]);
1657                 if (*dcname == NULL) {
1658                         return false;
1659                 }
1660                 return true;
1661         }
1662
1663         /* Try to figure out the name */
1664         if (dcip_to_name(mem_ctx, domain, pss, dcname)) {
1665                 return True;
1666         }
1667
1668         /* We can not continue without the DC's name */
1669         winbind_add_failed_connection_entry(domain, dcs[fd_index].name,
1670                                     NT_STATUS_UNSUCCESSFUL);
1671
1672         /* Throw away all arrays as we're doing this again. */
1673         TALLOC_FREE(dcs);
1674         num_dcs = 0;
1675
1676         TALLOC_FREE(dcnames);
1677         num_dcnames = 0;
1678
1679         TALLOC_FREE(addrs);
1680         num_addrs = 0;
1681
1682         close(*fd);
1683         *fd = -1;
1684
1685         goto again;
1686 }
1687
1688 static char *current_dc_key(TALLOC_CTX *mem_ctx, const char *domain_name)
1689 {
1690         return talloc_asprintf_strupper_m(mem_ctx, "CURRENT_DCNAME/%s",
1691                                           domain_name);
1692 }
1693
1694 static void store_current_dc_in_gencache(const char *domain_name,
1695                                          const char *dc_name,
1696                                          struct cli_state *cli)
1697 {
1698         char addr[INET6_ADDRSTRLEN];
1699         char *key = NULL;
1700         char *value = NULL;
1701
1702         if (!cli_state_is_connected(cli)) {
1703                 return;
1704         }
1705
1706         print_sockaddr(addr, sizeof(addr),
1707                        smbXcli_conn_remote_sockaddr(cli->conn));
1708
1709         key = current_dc_key(talloc_tos(), domain_name);
1710         if (key == NULL) {
1711                 goto done;
1712         }
1713
1714         value = talloc_asprintf(talloc_tos(), "%s %s", addr, dc_name);
1715         if (value == NULL) {
1716                 goto done;
1717         }
1718
1719         gencache_set(key, value, 0x7fffffff);
1720 done:
1721         TALLOC_FREE(value);
1722         TALLOC_FREE(key);
1723 }
1724
1725 bool fetch_current_dc_from_gencache(TALLOC_CTX *mem_ctx,
1726                                     const char *domain_name,
1727                                     char **p_dc_name, char **p_dc_ip)
1728 {
1729         char *key, *p;
1730         char *value = NULL;
1731         bool ret = false;
1732         char *dc_name = NULL;
1733         char *dc_ip = NULL;
1734
1735         key = current_dc_key(talloc_tos(), domain_name);
1736         if (key == NULL) {
1737                 goto done;
1738         }
1739         if (!gencache_get(key, mem_ctx, &value, NULL)) {
1740                 goto done;
1741         }
1742         p = strchr(value, ' ');
1743         if (p == NULL) {
1744                 goto done;
1745         }
1746         dc_ip = talloc_strndup(mem_ctx, value, p - value);
1747         if (dc_ip == NULL) {
1748                 goto done;
1749         }
1750         dc_name = talloc_strdup(mem_ctx, p+1);
1751         if (dc_name == NULL) {
1752                 goto done;
1753         }
1754
1755         if (p_dc_ip != NULL) {
1756                 *p_dc_ip = dc_ip;
1757                 dc_ip = NULL;
1758         }
1759         if (p_dc_name != NULL) {
1760                 *p_dc_name = dc_name;
1761                 dc_name = NULL;
1762         }
1763         ret = true;
1764 done:
1765         TALLOC_FREE(dc_name);
1766         TALLOC_FREE(dc_ip);
1767         TALLOC_FREE(key);
1768         TALLOC_FREE(value);
1769         return ret;
1770 }
1771
1772 NTSTATUS wb_open_internal_pipe(TALLOC_CTX *mem_ctx,
1773                                const struct ndr_interface_table *table,
1774                                struct rpc_pipe_client **ret_pipe)
1775 {
1776         struct rpc_pipe_client *cli = NULL;
1777         const struct auth_session_info *session_info;
1778         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1779
1780
1781         session_info = get_session_info_system();
1782         SMB_ASSERT(session_info != NULL);
1783
1784         /* create a connection to the specified pipe */
1785         if (lp_parm_bool(-1, "winbindd", "use external pipes", false)) {
1786                 status = rpc_pipe_open_interface(mem_ctx,
1787                                                  table,
1788                                                  session_info,
1789                                                  NULL,
1790                                                  winbind_messaging_context(),
1791                                                  &cli);
1792         } else {
1793                 status = rpc_pipe_open_internal(mem_ctx,
1794                                                 table,
1795                                                 session_info,
1796                                                 NULL,
1797                                                 winbind_messaging_context(),
1798                                                 &cli);
1799         }
1800         if (!NT_STATUS_IS_OK(status)) {
1801                 DEBUG(0, ("open_internal_pipe: Could not connect to %s pipe: %s\n",
1802                           table->name, nt_errstr(status)));
1803                 return status;
1804         }
1805
1806         if (ret_pipe) {
1807                 *ret_pipe = cli;
1808         }
1809
1810         return NT_STATUS_OK;
1811 }
1812
1813 static NTSTATUS cm_open_connection(struct winbindd_domain *domain,
1814                                    struct winbindd_cm_conn *new_conn)
1815 {
1816         TALLOC_CTX *mem_ctx;
1817         NTSTATUS result;
1818         char *saf_servername;
1819         int retries;
1820
1821         if ((mem_ctx = talloc_init("cm_open_connection")) == NULL) {
1822                 set_domain_offline(domain);
1823                 return NT_STATUS_NO_MEMORY;
1824         }
1825
1826         saf_servername = saf_fetch(mem_ctx, domain->name );
1827
1828         /* we have to check the server affinity cache here since 
1829            later we select a DC based on response time and not preference */
1830
1831         /* Check the negative connection cache
1832            before talking to it. It going down may have
1833            triggered the reconnection. */
1834
1835         if ( saf_servername && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, saf_servername))) {
1836
1837                 DEBUG(10,("cm_open_connection: saf_servername is '%s' for domain %s\n",
1838                         saf_servername, domain->name ));
1839
1840                 /* convert an ip address to a name */
1841                 if (is_ipaddress( saf_servername ) ) {
1842                         char *dcname = NULL;
1843                         struct sockaddr_storage ss;
1844
1845                         if (!interpret_string_addr(&ss, saf_servername,
1846                                                 AI_NUMERICHOST)) {
1847                                 TALLOC_FREE(mem_ctx);
1848                                 return NT_STATUS_UNSUCCESSFUL;
1849                         }
1850                         if (dcip_to_name(mem_ctx, domain, &ss, &dcname)) {
1851                                 domain->dcname = talloc_strdup(domain,
1852                                                                dcname);
1853                                 if (domain->dcname == NULL) {
1854                                         TALLOC_FREE(mem_ctx);
1855                                         return NT_STATUS_NO_MEMORY;
1856                                 }
1857                         } else {
1858                                 winbind_add_failed_connection_entry(
1859                                         domain, saf_servername,
1860                                         NT_STATUS_UNSUCCESSFUL);
1861                         }
1862                 } else {
1863                         domain->dcname = talloc_strdup(domain, saf_servername);
1864                         if (domain->dcname == NULL) {
1865                                 TALLOC_FREE(mem_ctx);
1866                                 return NT_STATUS_NO_MEMORY;
1867                         }
1868                 }
1869         }
1870
1871         for (retries = 0; retries < 3; retries++) {
1872                 int fd = -1;
1873                 bool retry = False;
1874                 char *dcname = NULL;
1875
1876                 result = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1877
1878                 DEBUG(10,("cm_open_connection: dcname is '%s' for domain %s\n",
1879                         domain->dcname ? domain->dcname : "", domain->name ));
1880
1881                 if (domain->dcname != NULL
1882                         && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, domain->dcname))
1883                         && (resolve_name(domain->dcname, &domain->dcaddr, 0x20, true)))
1884                 {
1885                         NTSTATUS status;
1886
1887                         status = smbsock_connect(&domain->dcaddr, 0,
1888                                                  NULL, -1, NULL, -1,
1889                                                  &fd, NULL, 10);
1890                         if (!NT_STATUS_IS_OK(status)) {
1891                                 fd = -1;
1892                         }
1893                 }
1894
1895                 if ((fd == -1) &&
1896                     !find_new_dc(mem_ctx, domain, &dcname, &domain->dcaddr, &fd))
1897                 {
1898                         /* This is the one place where we will
1899                            set the global winbindd offline state
1900                            to true, if a "WINBINDD_OFFLINE" entry
1901                            is found in the winbindd cache. */
1902                         set_global_winbindd_state_offline();
1903                         break;
1904                 }
1905                 if (dcname != NULL) {
1906                         talloc_free(domain->dcname);
1907
1908                         domain->dcname = talloc_move(domain, &dcname);
1909                         if (domain->dcname == NULL) {
1910                                 result = NT_STATUS_NO_MEMORY;
1911                                 break;
1912                         }
1913                 }
1914
1915                 new_conn->cli = NULL;
1916
1917                 result = cm_prepare_connection(domain, fd, domain->dcname,
1918                         &new_conn->cli, &retry);
1919                 if (!NT_STATUS_IS_OK(result)) {
1920                         /* Don't leak the smb connection socket */
1921                         close(fd);
1922                 }
1923
1924                 if (!retry)
1925                         break;
1926         }
1927
1928         if (NT_STATUS_IS_OK(result)) {
1929                 bool seal_pipes = true;
1930
1931                 winbindd_set_locator_kdc_envs(domain);
1932
1933                 if (domain->online == False) {
1934                         /* We're changing state from offline to online. */
1935                         set_global_winbindd_state_online();
1936                 }
1937                 set_domain_online(domain);
1938
1939                 /*
1940                  * Much as I hate global state, this seems to be the point
1941                  * where we can be certain that we have a proper connection to
1942                  * a DC. wbinfo --dc-info needs that information, store it in
1943                  * gencache with a looong timeout. This will need revisiting
1944                  * once we start to connect to multiple DCs, wbcDcInfo is
1945                  * already prepared for that.
1946                  */
1947                 store_current_dc_in_gencache(domain->name, domain->dcname,
1948                                              new_conn->cli);
1949
1950                 seal_pipes = lp_winbind_sealed_pipes();
1951                 seal_pipes = lp_parm_bool(-1, "winbind sealed pipes",
1952                                           domain->name,
1953                                           seal_pipes);
1954
1955                 if (seal_pipes) {
1956                         new_conn->auth_level = DCERPC_AUTH_LEVEL_PRIVACY;
1957                 } else {
1958                         new_conn->auth_level = DCERPC_AUTH_LEVEL_INTEGRITY;
1959                 }
1960         } else {
1961                 /* Ensure we setup the retry handler. */
1962                 set_domain_offline(domain);
1963         }
1964
1965         talloc_destroy(mem_ctx);
1966         return result;
1967 }
1968
1969 /* Close down all open pipes on a connection. */
1970
1971 void invalidate_cm_connection(struct winbindd_domain *domain)
1972 {
1973         NTSTATUS result;
1974         struct winbindd_cm_conn *conn = &domain->conn;
1975
1976         /* We're closing down a possibly dead
1977            connection. Don't have impossibly long (10s) timeouts. */
1978
1979         if (conn->cli) {
1980                 cli_set_timeout(conn->cli, 1000); /* 1 second. */
1981         }
1982
1983         if (conn->samr_pipe != NULL) {
1984                 if (is_valid_policy_hnd(&conn->sam_connect_handle)) {
1985                         dcerpc_samr_Close(conn->samr_pipe->binding_handle,
1986                                           talloc_tos(),
1987                                           &conn->sam_connect_handle,
1988                                           &result);
1989                 }
1990                 TALLOC_FREE(conn->samr_pipe);
1991                 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1992                 if (conn->cli) {
1993                         cli_set_timeout(conn->cli, 500);
1994                 }
1995         }
1996
1997         if (conn->lsa_pipe != NULL) {
1998                 if (is_valid_policy_hnd(&conn->lsa_policy)) {
1999                         dcerpc_lsa_Close(conn->lsa_pipe->binding_handle,
2000                                          talloc_tos(),
2001                                          &conn->lsa_policy,
2002                                          &result);
2003                 }
2004                 TALLOC_FREE(conn->lsa_pipe);
2005                 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
2006                 if (conn->cli) {
2007                         cli_set_timeout(conn->cli, 500);
2008                 }
2009         }
2010
2011         if (conn->lsa_pipe_tcp != NULL) {
2012                 if (is_valid_policy_hnd(&conn->lsa_policy)) {
2013                         dcerpc_lsa_Close(conn->lsa_pipe_tcp->binding_handle,
2014                                          talloc_tos(),
2015                                          &conn->lsa_policy,
2016                                          &result);
2017                 }
2018                 TALLOC_FREE(conn->lsa_pipe_tcp);
2019                 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
2020                 if (conn->cli) {
2021                         cli_set_timeout(conn->cli, 500);
2022                 }
2023         }
2024
2025         if (conn->netlogon_pipe != NULL) {
2026                 TALLOC_FREE(conn->netlogon_pipe);
2027                 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
2028                 if (conn->cli) {
2029                         cli_set_timeout(conn->cli, 500);
2030                 }
2031         }
2032
2033         conn->auth_level = DCERPC_AUTH_LEVEL_PRIVACY;
2034         conn->netlogon_force_reauth = false;
2035         conn->netlogon_flags = 0;
2036         TALLOC_FREE(conn->netlogon_creds);
2037
2038         if (conn->cli) {
2039                 cli_shutdown(conn->cli);
2040         }
2041
2042         conn->cli = NULL;
2043 }
2044
2045 void close_conns_after_fork(void)
2046 {
2047         struct winbindd_domain *domain;
2048         struct winbindd_cli_state *cli_state;
2049
2050         for (domain = domain_list(); domain; domain = domain->next) {
2051                 /*
2052                  * first close the low level SMB TCP connection
2053                  * so that we don't generate any SMBclose
2054                  * requests in invalidate_cm_connection()
2055                  */
2056                 if (cli_state_is_connected(domain->conn.cli)) {
2057                         smbXcli_conn_disconnect(domain->conn.cli->conn, NT_STATUS_OK);
2058                 }
2059
2060                 invalidate_cm_connection(domain);
2061         }
2062
2063         for (cli_state = winbindd_client_list();
2064              cli_state != NULL;
2065              cli_state = cli_state->next) {
2066                 if (cli_state->sock >= 0) {
2067                         close(cli_state->sock);
2068                         cli_state->sock = -1;
2069                 }
2070         }
2071 }
2072
2073 static bool connection_ok(struct winbindd_domain *domain)
2074 {
2075         bool ok;
2076
2077         ok = cli_state_is_connected(domain->conn.cli);
2078         if (!ok) {
2079                 DEBUG(3, ("connection_ok: Connection to %s for domain %s is not connected\n",
2080                           domain->dcname, domain->name));
2081                 return False;
2082         }
2083
2084         if (domain->online == False) {
2085                 DEBUG(3, ("connection_ok: Domain %s is offline\n", domain->name));
2086                 return False;
2087         }
2088
2089         return True;
2090 }
2091
2092 /* Initialize a new connection up to the RPC BIND.
2093    Bypass online status check so always does network calls. */
2094
2095 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain, bool need_rw_dc)
2096 {
2097         NTSTATUS result;
2098         bool skip_connection = domain->internal;
2099         if (need_rw_dc && domain->rodc) {
2100                 skip_connection = false;
2101         }
2102
2103         /* Internal connections never use the network. */
2104         if (dom_sid_equal(&domain->sid, &global_sid_Builtin)) {
2105                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2106         }
2107
2108         /* Still ask the internal LSA and SAMR server about the local domain */
2109         if (skip_connection || connection_ok(domain)) {
2110                 if (!domain->initialized) {
2111                         set_dc_type_and_flags(domain);
2112                 }
2113                 return NT_STATUS_OK;
2114         }
2115
2116         invalidate_cm_connection(domain);
2117
2118         if (!domain->primary && !domain->initialized) {
2119                 /*
2120                  * Before we connect to a trust, work out if it is an
2121                  * AD domain by asking our own domain.
2122                  */
2123                 set_dc_type_and_flags_trustinfo(domain);
2124         }
2125
2126         result = cm_open_connection(domain, &domain->conn);
2127
2128         if (NT_STATUS_IS_OK(result) && !domain->initialized) {
2129                 set_dc_type_and_flags(domain);
2130         }
2131
2132         return result;
2133 }
2134
2135 NTSTATUS init_dc_connection(struct winbindd_domain *domain, bool need_rw_dc)
2136 {
2137         if (dom_sid_equal(&domain->sid, &global_sid_Builtin)) {
2138                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2139         }
2140
2141         if (domain->initialized && !domain->online) {
2142                 /* We check for online status elsewhere. */
2143                 return NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
2144         }
2145
2146         return init_dc_connection_network(domain, need_rw_dc);
2147 }
2148
2149 static NTSTATUS init_dc_connection_rpc(struct winbindd_domain *domain, bool need_rw_dc)
2150 {
2151         NTSTATUS status;
2152
2153         status = init_dc_connection(domain, need_rw_dc);
2154         if (!NT_STATUS_IS_OK(status)) {
2155                 return status;
2156         }
2157
2158         if (!domain->internal && domain->conn.cli == NULL) {
2159                 /* happens for trusted domains without inbound trust */
2160                 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2161         }
2162
2163         return NT_STATUS_OK;
2164 }
2165
2166 /******************************************************************************
2167  Set the trust flags (direction and forest location) for a domain
2168 ******************************************************************************/
2169
2170 static bool set_dc_type_and_flags_trustinfo( struct winbindd_domain *domain )
2171 {
2172         struct winbindd_domain *our_domain;
2173         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2174         WERROR werr;
2175         struct netr_DomainTrustList trusts;
2176         int i;
2177         uint32_t flags = (NETR_TRUST_FLAG_IN_FOREST |
2178                         NETR_TRUST_FLAG_OUTBOUND |
2179                         NETR_TRUST_FLAG_INBOUND);
2180         struct rpc_pipe_client *cli;
2181         TALLOC_CTX *mem_ctx = NULL;
2182         struct dcerpc_binding_handle *b;
2183
2184         DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s\n", domain->name ));
2185
2186         /* Our primary domain doesn't need to worry about trust flags.
2187            Force it to go through the network setup */
2188         if ( domain->primary ) {                
2189                 return False;           
2190         }
2191
2192         mem_ctx = talloc_stackframe();
2193         our_domain = find_our_domain();
2194         if (our_domain->internal) {
2195                 result = init_dc_connection(our_domain, false);
2196                 if (!NT_STATUS_IS_OK(result)) {
2197                         DEBUG(3,("set_dc_type_and_flags_trustinfo: "
2198                                  "Not able to make a connection to our domain: %s\n",
2199                                   nt_errstr(result)));
2200                         TALLOC_FREE(mem_ctx);
2201                         return false;
2202                 }
2203         }
2204
2205         /* This won't work unless our domain is AD */
2206         if ( !our_domain->active_directory ) {
2207                 TALLOC_FREE(mem_ctx);
2208                 return False;
2209         }
2210
2211         if (our_domain->internal) {
2212                 result = wb_open_internal_pipe(mem_ctx, &ndr_table_netlogon, &cli);
2213         } else if (!connection_ok(our_domain)) {
2214                 DEBUG(3,("set_dc_type_and_flags_trustinfo: "
2215                          "No connection to our domain!\n"));
2216                 TALLOC_FREE(mem_ctx);
2217                 return False;
2218         } else {
2219                 result = cm_connect_netlogon(our_domain, &cli);
2220         }
2221
2222         if (!NT_STATUS_IS_OK(result)) {
2223                 DEBUG(5, ("set_dc_type_and_flags_trustinfo: Could not open "
2224                           "a connection to %s for PIPE_NETLOGON (%s)\n", 
2225                           domain->name, nt_errstr(result)));
2226                 TALLOC_FREE(mem_ctx);
2227                 return False;
2228         }
2229         b = cli->binding_handle;
2230
2231         /* Use DsEnumerateDomainTrusts to get us the trust direction and type. */
2232         result = dcerpc_netr_DsrEnumerateDomainTrusts(b, mem_ctx,
2233                                                       cli->desthost,
2234                                                       flags,
2235                                                       &trusts,
2236                                                       &werr);
2237         if (!NT_STATUS_IS_OK(result)) {
2238                 DEBUG(0,("set_dc_type_and_flags_trustinfo: "
2239                         "failed to query trusted domain list: %s\n",
2240                         nt_errstr(result)));
2241                 TALLOC_FREE(mem_ctx);
2242                 return false;
2243         }
2244         if (!W_ERROR_IS_OK(werr)) {
2245                 DEBUG(0,("set_dc_type_and_flags_trustinfo: "
2246                         "failed to query trusted domain list: %s\n",
2247                         win_errstr(werr)));
2248                 TALLOC_FREE(mem_ctx);
2249                 return false;
2250         }
2251
2252         /* Now find the domain name and get the flags */
2253
2254         for ( i=0; i<trusts.count; i++ ) {
2255                 if ( strequal( domain->name, trusts.array[i].netbios_name) ) {
2256                         domain->domain_flags          = trusts.array[i].trust_flags;
2257                         domain->domain_type           = trusts.array[i].trust_type;
2258                         domain->domain_trust_attribs  = trusts.array[i].trust_attributes;
2259
2260                         if ( domain->domain_type == LSA_TRUST_TYPE_UPLEVEL )
2261                                 domain->active_directory = True;
2262
2263                         /* This flag is only set if the domain is *our* 
2264                            primary domain and the primary domain is in
2265                            native mode */
2266
2267                         domain->native_mode = (domain->domain_flags & NETR_TRUST_FLAG_NATIVE);
2268
2269                         DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s is %sin "
2270                                   "native mode.\n", domain->name, 
2271                                   domain->native_mode ? "" : "NOT "));
2272
2273                         DEBUG(5,("set_dc_type_and_flags_trustinfo: domain %s is %s"
2274                                  "running active directory.\n", domain->name, 
2275                                  domain->active_directory ? "" : "NOT "));
2276
2277                         domain->can_do_ncacn_ip_tcp = domain->active_directory;
2278
2279                         domain->initialized = True;
2280
2281                         break;
2282                 }               
2283         }
2284
2285         TALLOC_FREE(mem_ctx);
2286
2287         return domain->initialized;     
2288 }
2289
2290 /******************************************************************************
2291  We can 'sense' certain things about the DC by it's replies to certain
2292  questions.
2293
2294  This tells us if this particular remote server is Active Directory, and if it
2295  is native mode.
2296 ******************************************************************************/
2297
2298 static void set_dc_type_and_flags_connect( struct winbindd_domain *domain )
2299 {
2300         NTSTATUS status, result;
2301         WERROR werr;
2302         TALLOC_CTX              *mem_ctx = NULL;
2303         struct rpc_pipe_client  *cli = NULL;
2304         struct policy_handle pol;
2305         union dssetup_DsRoleInfo info;
2306         union lsa_PolicyInformation *lsa_info = NULL;
2307
2308         if (!domain->internal && !connection_ok(domain)) {
2309                 return;
2310         }
2311
2312         mem_ctx = talloc_init("set_dc_type_and_flags on domain %s\n",
2313                               domain->name);
2314         if (!mem_ctx) {
2315                 DEBUG(1, ("set_dc_type_and_flags_connect: talloc_init() failed\n"));
2316                 return;
2317         }
2318
2319         DEBUG(5, ("set_dc_type_and_flags_connect: domain %s\n", domain->name ));
2320
2321         if (domain->internal) {
2322                 status = wb_open_internal_pipe(mem_ctx,
2323                                                &ndr_table_dssetup,
2324                                                &cli);
2325         } else {
2326                 status = cli_rpc_pipe_open_noauth(domain->conn.cli,
2327                                                   &ndr_table_dssetup,
2328                                                   &cli);
2329         }
2330
2331         if (!NT_STATUS_IS_OK(status)) {
2332                 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
2333                           "PI_DSSETUP on domain %s: (%s)\n",
2334                           domain->name, nt_errstr(status)));
2335
2336                 /* if this is just a non-AD domain we need to continue
2337                  * identifying so that we can in the end return with
2338                  * domain->initialized = True - gd */
2339
2340                 goto no_dssetup;
2341         }
2342
2343         status = dcerpc_dssetup_DsRoleGetPrimaryDomainInformation(cli->binding_handle, mem_ctx,
2344                                                                   DS_ROLE_BASIC_INFORMATION,
2345                                                                   &info,
2346                                                                   &werr);
2347         TALLOC_FREE(cli);
2348
2349         if (NT_STATUS_IS_OK(status)) {
2350                 result = werror_to_ntstatus(werr);
2351         }
2352         if (!NT_STATUS_IS_OK(status)) {
2353                 DEBUG(5, ("set_dc_type_and_flags_connect: rpccli_ds_getprimarydominfo "
2354                           "on domain %s failed: (%s)\n",
2355                           domain->name, nt_errstr(status)));
2356
2357                 /* older samba3 DCs will return DCERPC_FAULT_OP_RNG_ERROR for
2358                  * every opcode on the DSSETUP pipe, continue with
2359                  * no_dssetup mode here as well to get domain->initialized
2360                  * set - gd */
2361
2362                 if (NT_STATUS_EQUAL(status, NT_STATUS_RPC_PROCNUM_OUT_OF_RANGE)) {
2363                         goto no_dssetup;
2364                 }
2365
2366                 TALLOC_FREE(mem_ctx);
2367                 return;
2368         }
2369
2370         if ((info.basic.flags & DS_ROLE_PRIMARY_DS_RUNNING) &&
2371             !(info.basic.flags & DS_ROLE_PRIMARY_DS_MIXED_MODE)) {
2372                 domain->native_mode = True;
2373         } else {
2374                 domain->native_mode = False;
2375         }
2376
2377 no_dssetup:
2378         if (domain->internal) {
2379                 status = wb_open_internal_pipe(mem_ctx,
2380                                                &ndr_table_lsarpc,
2381                                                &cli);
2382         } else {
2383                 status = cli_rpc_pipe_open_noauth(domain->conn.cli,
2384                                                   &ndr_table_lsarpc, &cli);
2385         }
2386         if (!NT_STATUS_IS_OK(status)) {
2387                 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
2388                           "PI_LSARPC on domain %s: (%s)\n",
2389                           domain->name, nt_errstr(status)));
2390                 TALLOC_FREE(cli);
2391                 TALLOC_FREE(mem_ctx);
2392                 return;
2393         }
2394
2395         status = rpccli_lsa_open_policy2(cli, mem_ctx, True,
2396                                          SEC_FLAG_MAXIMUM_ALLOWED, &pol);
2397
2398         if (NT_STATUS_IS_OK(status)) {
2399                 /* This particular query is exactly what Win2k clients use 
2400                    to determine that the DC is active directory */
2401                 status = dcerpc_lsa_QueryInfoPolicy2(cli->binding_handle, mem_ctx,
2402                                                      &pol,
2403                                                      LSA_POLICY_INFO_DNS,
2404                                                      &lsa_info,
2405                                                      &result);
2406         }
2407
2408         if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2409                 domain->active_directory = True;
2410
2411                 if (lsa_info->dns.name.string) {
2412                         if (!strequal(domain->name, lsa_info->dns.name.string))
2413                         {
2414                                 DEBUG(1, ("set_dc_type_and_flags_connect: DC "
2415                                           "for domain %s claimed it was a DC "
2416                                           "for domain %s, refusing to "
2417                                           "initialize\n",
2418                                           domain->name,
2419                                           lsa_info->dns.name.string));
2420                                 TALLOC_FREE(cli);
2421                                 TALLOC_FREE(mem_ctx);
2422                                 return;
2423                         }
2424                         talloc_free(domain->name);
2425                         domain->name = talloc_strdup(domain,
2426                                                      lsa_info->dns.name.string);
2427                         if (domain->name == NULL) {
2428                                 goto done;
2429                         }
2430                 }
2431
2432                 if (lsa_info->dns.dns_domain.string) {
2433                         if (domain->alt_name != NULL &&
2434                             !strequal(domain->alt_name,
2435                                       lsa_info->dns.dns_domain.string))
2436                         {
2437                                 DEBUG(1, ("set_dc_type_and_flags_connect: DC "
2438                                           "for domain %s (%s) claimed it was "
2439                                           "a DC for domain %s, refusing to "
2440                                           "initialize\n",
2441                                           domain->alt_name, domain->name,
2442                                           lsa_info->dns.dns_domain.string));
2443                                 TALLOC_FREE(cli);
2444                                 TALLOC_FREE(mem_ctx);
2445                                 return;
2446                         }
2447                         talloc_free(domain->alt_name);
2448                         domain->alt_name =
2449                                 talloc_strdup(domain,
2450                                               lsa_info->dns.dns_domain.string);
2451                         if (domain->alt_name == NULL) {
2452                                 goto done;
2453                         }
2454                 }
2455
2456                 /* See if we can set some domain trust flags about
2457                    ourself */
2458
2459                 if (lsa_info->dns.dns_forest.string) {
2460                         talloc_free(domain->forest_name);
2461                         domain->forest_name =
2462                                 talloc_strdup(domain,
2463                                               lsa_info->dns.dns_forest.string);
2464                         if (domain->forest_name == NULL) {
2465                                 goto done;
2466                         }
2467
2468                         if (strequal(domain->forest_name, domain->alt_name)) {
2469                                 domain->domain_flags |= NETR_TRUST_FLAG_TREEROOT;
2470                         }
2471                 }
2472
2473                 if (lsa_info->dns.sid) {
2474                         if (!is_null_sid(&domain->sid) &&
2475                             !dom_sid_equal(&domain->sid,
2476                                            lsa_info->dns.sid))
2477                         {
2478                                 DEBUG(1, ("set_dc_type_and_flags_connect: DC "
2479                                           "for domain %s (%s) claimed it was "
2480                                           "a DC for domain %s, refusing to "
2481                                           "initialize\n",
2482                                           dom_sid_string(talloc_tos(),
2483                                                          &domain->sid),
2484                                           domain->name,
2485                                           dom_sid_string(talloc_tos(),
2486                                                          lsa_info->dns.sid)));
2487                                 TALLOC_FREE(cli);
2488                                 TALLOC_FREE(mem_ctx);
2489                                 return;
2490                         }
2491                         sid_copy(&domain->sid, lsa_info->dns.sid);
2492                 }
2493         } else {
2494                 domain->active_directory = False;
2495
2496                 status = rpccli_lsa_open_policy(cli, mem_ctx, True,
2497                                                 SEC_FLAG_MAXIMUM_ALLOWED,
2498                                                 &pol);
2499
2500                 if (!NT_STATUS_IS_OK(status)) {
2501                         goto done;
2502                 }
2503
2504                 status = dcerpc_lsa_QueryInfoPolicy(cli->binding_handle, mem_ctx,
2505                                                     &pol,
2506                                                     LSA_POLICY_INFO_ACCOUNT_DOMAIN,
2507                                                     &lsa_info,
2508                                                     &result);
2509                 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2510
2511                         if (lsa_info->account_domain.name.string) {
2512                                 if (!strequal(domain->name,
2513                                         lsa_info->account_domain.name.string))
2514                                 {
2515                                         DEBUG(1,
2516                                               ("set_dc_type_and_flags_connect: "
2517                                                "DC for domain %s claimed it was"
2518                                                " a DC for domain %s, refusing "
2519                                                "to initialize\n", domain->name,
2520                                                lsa_info->
2521                                                 account_domain.name.string));
2522                                         TALLOC_FREE(cli);
2523                                         TALLOC_FREE(mem_ctx);
2524                                         return;
2525                                 }
2526                                 talloc_free(domain->name);
2527                                 domain->name =
2528                                         talloc_strdup(domain,
2529                                                       lsa_info->account_domain.name.string);
2530                         }
2531
2532                         if (lsa_info->account_domain.sid) {
2533                                 if (!is_null_sid(&domain->sid) &&
2534                                     !dom_sid_equal(&domain->sid,
2535                                                 lsa_info->account_domain.sid))
2536                                 {
2537                                         DEBUG(1,
2538                                               ("set_dc_type_and_flags_connect: "
2539                                                "DC for domain %s (%s) claimed "
2540                                                "it was a DC for domain %s, "
2541                                                "refusing to initialize\n",
2542                                                dom_sid_string(talloc_tos(),
2543                                                               &domain->sid),
2544                                                domain->name,
2545                                                dom_sid_string(talloc_tos(),
2546                                                 lsa_info->account_domain.sid)));
2547                                         TALLOC_FREE(cli);
2548                                         TALLOC_FREE(mem_ctx);
2549                                         return;
2550                                 }
2551                                 sid_copy(&domain->sid, lsa_info->account_domain.sid);
2552                         }
2553                 }
2554         }
2555 done:
2556
2557         DEBUG(5, ("set_dc_type_and_flags_connect: domain %s is %sin native mode.\n",
2558                   domain->name, domain->native_mode ? "" : "NOT "));
2559
2560         DEBUG(5,("set_dc_type_and_flags_connect: domain %s is %srunning active directory.\n",
2561                   domain->name, domain->active_directory ? "" : "NOT "));
2562
2563         domain->can_do_ncacn_ip_tcp = domain->active_directory;
2564
2565         TALLOC_FREE(cli);
2566
2567         TALLOC_FREE(mem_ctx);
2568
2569         domain->initialized = True;
2570 }
2571
2572 /**********************************************************************
2573  Set the domain_flags (trust attributes, domain operating modes, etc... 
2574 ***********************************************************************/
2575
2576 static void set_dc_type_and_flags( struct winbindd_domain *domain )
2577 {
2578         /* we always have to contact our primary domain */
2579
2580         if ( domain->primary || domain->internal) {
2581                 DEBUG(10,("set_dc_type_and_flags: setting up flags for "
2582                           "primary or internal domain\n"));
2583                 set_dc_type_and_flags_connect( domain );
2584                 return;         
2585         }
2586
2587         /* Use our DC to get the information if possible */
2588
2589         if ( !set_dc_type_and_flags_trustinfo( domain ) ) {
2590                 /* Otherwise, fallback to contacting the 
2591                    domain directly */
2592                 set_dc_type_and_flags_connect( domain );
2593         }
2594
2595         return;
2596 }
2597
2598
2599
2600 /**********************************************************************
2601 ***********************************************************************/
2602
2603 static NTSTATUS cm_get_schannel_creds(struct winbindd_domain *domain,
2604                                    struct netlogon_creds_cli_context **ppdc)
2605 {
2606         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2607         struct rpc_pipe_client *netlogon_pipe;
2608
2609         *ppdc = NULL;
2610
2611         if ((!IS_DC) && (!domain->primary)) {
2612                 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2613         }
2614
2615         if (domain->conn.netlogon_creds != NULL) {
2616                 if (!(domain->conn.netlogon_flags & NETLOGON_NEG_AUTHENTICATED_RPC)) {
2617                         return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2618                 }
2619                 *ppdc = domain->conn.netlogon_creds;
2620                 return NT_STATUS_OK;
2621         }
2622
2623         result = cm_connect_netlogon(domain, &netlogon_pipe);
2624         if (!NT_STATUS_IS_OK(result)) {
2625                 return result;
2626         }
2627
2628         if (domain->conn.netlogon_creds == NULL) {
2629                 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2630         }
2631
2632         if (!(domain->conn.netlogon_flags & NETLOGON_NEG_AUTHENTICATED_RPC)) {
2633                 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2634         }
2635
2636         *ppdc = domain->conn.netlogon_creds;
2637         return NT_STATUS_OK;
2638 }
2639
2640 NTSTATUS cm_connect_sam(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2641                         bool need_rw_dc,
2642                         struct rpc_pipe_client **cli, struct policy_handle *sam_handle)
2643 {
2644         struct winbindd_cm_conn *conn;
2645         NTSTATUS status, result;
2646         struct netlogon_creds_cli_context *p_creds;
2647         struct cli_credentials *creds = NULL;
2648         bool retry = false; /* allow one retry attempt for expired session */
2649
2650         if (sid_check_is_our_sam(&domain->sid)) {
2651                 if (domain->rodc == false || need_rw_dc == false) {
2652                         return open_internal_samr_conn(mem_ctx, domain, cli, sam_handle);
2653                 }
2654         }
2655
2656 retry:
2657         status = init_dc_connection_rpc(domain, need_rw_dc);
2658         if (!NT_STATUS_IS_OK(status)) {
2659                 return status;
2660         }
2661
2662         conn = &domain->conn;
2663
2664         if (rpccli_is_connected(conn->samr_pipe)) {
2665                 goto done;
2666         }
2667
2668         TALLOC_FREE(conn->samr_pipe);
2669
2670         /*
2671          * No SAMR pipe yet. Attempt to get an NTLMSSP SPNEGO authenticated
2672          * sign and sealed pipe using the machine account password by
2673          * preference. If we can't - try schannel, if that fails, try
2674          * anonymous.
2675          */
2676
2677         result = get_trust_credentials(domain, talloc_tos(), false, &creds);
2678         if (!NT_STATUS_IS_OK(result)) {
2679                 DEBUG(10, ("cm_connect_sam: No user available for "
2680                            "domain %s, trying schannel\n", domain->name));
2681                 goto schannel;
2682         }
2683
2684         if (cli_credentials_is_anonymous(creds)) {
2685                 goto anonymous;
2686         }
2687
2688         /*
2689          * We have an authenticated connection. Use a SPNEGO
2690          * authenticated SAMR pipe with sign & seal.
2691          */
2692         status = cli_rpc_pipe_open_with_creds(conn->cli,
2693                                               &ndr_table_samr,
2694                                               NCACN_NP,
2695                                               DCERPC_AUTH_TYPE_SPNEGO,
2696                                               conn->auth_level,
2697                                               smbXcli_conn_remote_name(conn->cli->conn),
2698                                               creds,
2699                                               &conn->samr_pipe);
2700
2701         if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_SESSION_EXPIRED)
2702             && !retry) {
2703                 invalidate_cm_connection(domain);
2704                 retry = true;
2705                 goto retry;
2706         }
2707
2708         if (!NT_STATUS_IS_OK(status)) {
2709                 DEBUG(10,("cm_connect_sam: failed to connect to SAMR "
2710                           "pipe for domain %s using NTLMSSP "
2711                           "authenticated pipe: user %s. Error was "
2712                           "%s\n", domain->name,
2713                           cli_credentials_get_unparsed_name(creds, talloc_tos()),
2714                           nt_errstr(status)));
2715                 goto schannel;
2716         }
2717
2718         DEBUG(10,("cm_connect_sam: connected to SAMR pipe for "
2719                   "domain %s using NTLMSSP authenticated "
2720                   "pipe: user %s\n", domain->name,
2721                   cli_credentials_get_unparsed_name(creds, talloc_tos())));
2722
2723         status = dcerpc_samr_Connect2(conn->samr_pipe->binding_handle, mem_ctx,
2724                                       conn->samr_pipe->desthost,
2725                                       SEC_FLAG_MAXIMUM_ALLOWED,
2726                                       &conn->sam_connect_handle,
2727                                       &result);
2728
2729         if (NT_STATUS_EQUAL(status, NT_STATUS_IO_DEVICE_ERROR) && !retry) {
2730                 invalidate_cm_connection(domain);
2731                 TALLOC_FREE(conn->samr_pipe);
2732                 retry = true;
2733                 goto retry;
2734         }
2735
2736         if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2737                 goto open_domain;
2738         }
2739         if (NT_STATUS_IS_OK(status)) {
2740                 status = result;
2741         }
2742
2743         DEBUG(10,("cm_connect_sam: ntlmssp-sealed dcerpc_samr_Connect2 "
2744                   "failed for domain %s, error was %s. Trying schannel\n",
2745                   domain->name, nt_errstr(status) ));
2746         TALLOC_FREE(conn->samr_pipe);
2747
2748  schannel:
2749
2750         /* Fall back to schannel if it's a W2K pre-SP1 box. */
2751
2752         status = cm_get_schannel_creds(domain, &p_creds);
2753         if (!NT_STATUS_IS_OK(status)) {
2754                 /* If this call fails - conn->cli can now be NULL ! */
2755                 DEBUG(10, ("cm_connect_sam: Could not get schannel auth info "
2756                            "for domain %s (error %s), trying anon\n",
2757                         domain->name,
2758                         nt_errstr(status) ));
2759                 goto anonymous;
2760         }
2761         TALLOC_FREE(creds);
2762         result = get_trust_credentials(domain, talloc_tos(), true, &creds);
2763         if (!NT_STATUS_IS_OK(result)) {
2764                 DEBUG(10, ("cm_connect_sam: No user available for "
2765                            "domain %s (error %s), trying anon\n", domain->name,
2766                            nt_errstr(result)));
2767                 goto anonymous;
2768         }
2769         status = cli_rpc_pipe_open_schannel_with_creds
2770                 (conn->cli, &ndr_table_samr, NCACN_NP,
2771                  creds, p_creds, &conn->samr_pipe);
2772
2773         if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_SESSION_EXPIRED)
2774             && !retry) {
2775                 invalidate_cm_connection(domain);
2776                 retry = true;
2777                 goto retry;
2778         }
2779
2780         if (!NT_STATUS_IS_OK(status)) {
2781                 DEBUG(10,("cm_connect_sam: failed to connect to SAMR pipe for "
2782                           "domain %s using schannel. Error was %s\n",
2783                           domain->name, nt_errstr(status) ));
2784                 goto anonymous;
2785         }
2786         DEBUG(10,("cm_connect_sam: connected to SAMR pipe for domain %s using "
2787                   "schannel.\n", domain->name ));
2788
2789         status = dcerpc_samr_Connect2(conn->samr_pipe->binding_handle, mem_ctx,
2790                                       conn->samr_pipe->desthost,
2791                                       SEC_FLAG_MAXIMUM_ALLOWED,
2792                                       &conn->sam_connect_handle,
2793                                       &result);
2794
2795         if (NT_STATUS_EQUAL(status, NT_STATUS_IO_DEVICE_ERROR) && !retry) {
2796                 invalidate_cm_connection(domain);
2797                 TALLOC_FREE(conn->samr_pipe);
2798                 retry = true;
2799                 goto retry;
2800         }
2801
2802         if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2803                 goto open_domain;
2804         }
2805         if (NT_STATUS_IS_OK(status)) {
2806                 status = result;
2807         }
2808         DEBUG(10,("cm_connect_sam: schannel-sealed dcerpc_samr_Connect2 failed "
2809                   "for domain %s, error was %s. Trying anonymous\n",
2810                   domain->name, nt_errstr(status) ));
2811         TALLOC_FREE(conn->samr_pipe);
2812
2813  anonymous:
2814
2815         /* Finally fall back to anonymous. */
2816         if (lp_winbind_sealed_pipes() || lp_require_strong_key()) {
2817                 status = NT_STATUS_DOWNGRADE_DETECTED;
2818                 DEBUG(1, ("Unwilling to make SAMR connection to domain %s "
2819                           "without connection level security, "
2820                           "must set 'winbind sealed pipes = false' and "
2821                           "'require strong key = false' to proceed: %s\n",
2822                           domain->name, nt_errstr(status)));
2823                 goto done;
2824         }
2825         status = cli_rpc_pipe_open_noauth(conn->cli, &ndr_table_samr,
2826                                           &conn->samr_pipe);
2827
2828         if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_SESSION_EXPIRED)
2829             && !retry) {
2830                 invalidate_cm_connection(domain);
2831                 retry = true;
2832                 goto retry;
2833         }
2834
2835         if (!NT_STATUS_IS_OK(status)) {
2836                 goto done;
2837         }
2838
2839         status = dcerpc_samr_Connect2(conn->samr_pipe->binding_handle, mem_ctx,
2840                                       conn->samr_pipe->desthost,
2841                                       SEC_FLAG_MAXIMUM_ALLOWED,
2842                                       &conn->sam_connect_handle,
2843                                       &result);
2844
2845         if (NT_STATUS_EQUAL(status, NT_STATUS_IO_DEVICE_ERROR) && !retry) {
2846                 invalidate_cm_connection(domain);
2847                 TALLOC_FREE(conn->samr_pipe);
2848                 retry = true;
2849                 goto retry;
2850         }
2851
2852         if (!NT_STATUS_IS_OK(status)) {
2853                 DEBUG(10,("cm_connect_sam: rpccli_samr_Connect2 failed "
2854                           "for domain %s Error was %s\n",
2855                           domain->name, nt_errstr(status) ));
2856                 goto done;
2857         }
2858         if (!NT_STATUS_IS_OK(result)) {
2859                 status = result;
2860                 DEBUG(10,("cm_connect_sam: dcerpc_samr_Connect2 failed "
2861                           "for domain %s Error was %s\n",
2862                           domain->name, nt_errstr(result)));
2863                 goto done;
2864         }
2865
2866  open_domain:
2867         status = dcerpc_samr_OpenDomain(conn->samr_pipe->binding_handle,
2868                                         mem_ctx,
2869                                         &conn->sam_connect_handle,
2870                                         SEC_FLAG_MAXIMUM_ALLOWED,
2871                                         &domain->sid,
2872                                         &conn->sam_domain_handle,
2873                                         &result);
2874         if (!NT_STATUS_IS_OK(status)) {
2875                 goto done;
2876         }
2877
2878         status = result;
2879  done:
2880
2881         if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
2882                 /*
2883                  * if we got access denied, we might just have no access rights
2884                  * to talk to the remote samr server server (e.g. when we are a
2885                  * PDC and we are connecting a w2k8 pdc via an interdomain
2886                  * trust). In that case do not invalidate the whole connection
2887                  * stack
2888                  */
2889                 TALLOC_FREE(conn->samr_pipe);
2890                 ZERO_STRUCT(conn->sam_domain_handle);
2891                 return status;
2892         } else if (!NT_STATUS_IS_OK(status)) {
2893                 invalidate_cm_connection(domain);
2894                 return status;
2895         }
2896
2897         *cli = conn->samr_pipe;
2898         *sam_handle = conn->sam_domain_handle;
2899         return status;
2900 }
2901
2902 /**********************************************************************
2903  open an schanneld ncacn_ip_tcp connection to LSA
2904 ***********************************************************************/
2905
2906 static NTSTATUS cm_connect_lsa_tcp(struct winbindd_domain *domain,
2907                                    TALLOC_CTX *mem_ctx,
2908                                    struct rpc_pipe_client **cli)
2909 {
2910         struct winbindd_cm_conn *conn;
2911         struct netlogon_creds_cli_context *p_creds = NULL;
2912         struct cli_credentials *creds = NULL;
2913         NTSTATUS status;
2914
2915         DEBUG(10,("cm_connect_lsa_tcp\n"));
2916
2917         status = init_dc_connection_rpc(domain, false);
2918         if (!NT_STATUS_IS_OK(status)) {
2919                 return status;
2920         }
2921
2922         conn = &domain->conn;
2923
2924         if (conn->lsa_pipe_tcp &&
2925             conn->lsa_pipe_tcp->transport->transport == NCACN_IP_TCP &&
2926             conn->lsa_pipe_tcp->auth->auth_level >= DCERPC_AUTH_LEVEL_INTEGRITY &&
2927             rpccli_is_connected(conn->lsa_pipe_tcp)) {
2928                 goto done;
2929         }
2930
2931         TALLOC_FREE(conn->lsa_pipe_tcp);
2932
2933         status = cm_get_schannel_creds(domain, &p_creds);
2934         if (!NT_STATUS_IS_OK(status)) {
2935                 goto done;
2936         }
2937
2938         status = get_trust_credentials(domain, talloc_tos(), true, &creds);
2939         if (!NT_STATUS_IS_OK(status)) {
2940                 goto done;
2941         }
2942
2943         status = cli_rpc_pipe_open_schannel_with_creds(conn->cli,
2944                                                        &ndr_table_lsarpc,
2945                                                        NCACN_IP_TCP,
2946                                                        creds,
2947                                                        p_creds,
2948                                                        &conn->lsa_pipe_tcp);
2949         if (!NT_STATUS_IS_OK(status)) {
2950                 DEBUG(10,("cli_rpc_pipe_open_schannel_with_key failed: %s\n",
2951                         nt_errstr(status)));
2952                 goto done;
2953         }
2954
2955  done:
2956         if (!NT_STATUS_IS_OK(status)) {
2957                 TALLOC_FREE(conn->lsa_pipe_tcp);
2958                 return status;
2959         }
2960
2961         *cli = conn->lsa_pipe_tcp;
2962
2963         return status;
2964 }
2965
2966 NTSTATUS cm_connect_lsa(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2967                         struct rpc_pipe_client **cli, struct policy_handle *lsa_policy)
2968 {
2969         struct winbindd_cm_conn *conn;
2970         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2971         struct netlogon_creds_cli_context *p_creds;
2972         struct cli_credentials *creds = NULL;
2973         bool retry = false; /* allow one retry attempt for expired session */
2974
2975 retry:
2976         result = init_dc_connection_rpc(domain, false);
2977         if (!NT_STATUS_IS_OK(result))
2978                 return result;
2979
2980         conn = &domain->conn;
2981
2982         if (rpccli_is_connected(conn->lsa_pipe)) {
2983                 goto done;
2984         }
2985
2986         TALLOC_FREE(conn->lsa_pipe);
2987
2988         result = get_trust_credentials(domain, talloc_tos(), false, &creds);
2989         if (!NT_STATUS_IS_OK(result)) {
2990                 DEBUG(10, ("cm_connect_lsa: No user available for "
2991                            "domain %s, trying schannel\n", domain->name));
2992                 goto schannel;
2993         }
2994
2995         if (cli_credentials_is_anonymous(creds)) {
2996                 goto anonymous;
2997         }
2998
2999         /*
3000          * We have an authenticated connection. Use a SPNEGO
3001          * authenticated LSA pipe with sign & seal.
3002          */
3003         result = cli_rpc_pipe_open_with_creds
3004                 (conn->cli, &ndr_table_lsarpc, NCACN_NP,
3005                  DCERPC_AUTH_TYPE_SPNEGO,
3006                  conn->auth_level,
3007                  smbXcli_conn_remote_name(conn->cli->conn),
3008                  creds,
3009                  &conn->lsa_pipe);
3010
3011         if (NT_STATUS_EQUAL(result, NT_STATUS_NETWORK_SESSION_EXPIRED)
3012             && !retry) {
3013                 invalidate_cm_connection(domain);
3014                 retry = true;
3015                 goto retry;
3016         }
3017
3018         if (!NT_STATUS_IS_OK(result)) {
3019                 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
3020                           "domain %s using NTLMSSP authenticated pipe: user "
3021                           "%s. Error was %s. Trying schannel.\n",
3022                           domain->name,
3023                           cli_credentials_get_unparsed_name(creds, talloc_tos()),
3024                           nt_errstr(result)));
3025                 goto schannel;
3026         }
3027
3028         DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
3029                   "NTLMSSP authenticated pipe: user %s\n",
3030                   domain->name, cli_credentials_get_unparsed_name(creds, talloc_tos())));
3031
3032         result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
3033                                         SEC_FLAG_MAXIMUM_ALLOWED,
3034                                         &conn->lsa_policy);
3035         if (NT_STATUS_EQUAL(result, NT_STATUS_IO_DEVICE_ERROR) && !retry) {
3036                 invalidate_cm_connection(domain);
3037                 TALLOC_FREE(conn->lsa_pipe);
3038                 retry = true;
3039                 goto retry;
3040         }
3041
3042         if (NT_STATUS_IS_OK(result)) {
3043                 goto done;
3044         }
3045
3046         DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
3047                   "schannel\n"));
3048
3049         TALLOC_FREE(conn->lsa_pipe);
3050
3051  schannel:
3052
3053         /* Fall back to schannel if it's a W2K pre-SP1 box. */
3054
3055         result = cm_get_schannel_creds(domain, &p_creds);
3056         if (!NT_STATUS_IS_OK(result)) {
3057                 /* If this call fails - conn->cli can now be NULL ! */
3058                 DEBUG(10, ("cm_connect_lsa: Could not get schannel auth info "
3059                            "for domain %s (error %s), trying anon\n",
3060                         domain->name,
3061                         nt_errstr(result) ));
3062                 goto anonymous;
3063         }
3064
3065         TALLOC_FREE(creds);
3066         result = get_trust_credentials(domain, talloc_tos(), true, &creds);
3067         if (!NT_STATUS_IS_OK(result)) {
3068                 DEBUG(10, ("cm_connect_lsa: No user available for "
3069                            "domain %s (error %s), trying anon\n", domain->name,
3070                            nt_errstr(result)));
3071                 goto anonymous;
3072         }
3073         result = cli_rpc_pipe_open_schannel_with_creds
3074                 (conn->cli, &ndr_table_lsarpc, NCACN_NP,
3075                  creds, p_creds, &conn->lsa_pipe);
3076
3077         if (NT_STATUS_EQUAL(result, NT_STATUS_NETWORK_SESSION_EXPIRED)
3078             && !retry) {
3079                 invalidate_cm_connection(domain);
3080                 retry = true;
3081                 goto retry;
3082         }
3083
3084         if (!NT_STATUS_IS_OK(result)) {
3085                 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
3086                           "domain %s using schannel. Error was %s\n",
3087                           domain->name, nt_errstr(result) ));
3088                 goto anonymous;
3089         }
3090         DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
3091                   "schannel.\n", domain->name ));
3092
3093         result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
3094                                         SEC_FLAG_MAXIMUM_ALLOWED,
3095                                         &conn->lsa_policy);
3096
3097         if (NT_STATUS_EQUAL(result, NT_STATUS_IO_DEVICE_ERROR) && !retry) {
3098                 invalidate_cm_connection(domain);
3099                 TALLOC_FREE(conn->lsa_pipe);
3100                 retry = true;
3101                 goto retry;
3102         }
3103
3104         if (NT_STATUS_IS_OK(result)) {
3105                 goto done;
3106         }
3107
3108         DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
3109                   "anonymous\n"));
3110
3111         TALLOC_FREE(conn->lsa_pipe);
3112
3113  anonymous:
3114
3115         if (lp_winbind_sealed_pipes() || lp_require_strong_key()) {
3116                 result = NT_STATUS_DOWNGRADE_DETECTED;
3117                 DEBUG(1, ("Unwilling to make LSA connection to domain %s "
3118                           "without connection level security, "
3119                           "must set 'winbind sealed pipes = false' and "
3120                           "'require strong key = false' to proceed: %s\n",
3121                           domain->name, nt_errstr(result)));
3122                 goto done;
3123         }
3124
3125         result = cli_rpc_pipe_open_noauth(conn->cli,
3126                                           &ndr_table_lsarpc,
3127                                           &conn->lsa_pipe);
3128
3129         if (NT_STATUS_EQUAL(result, NT_STATUS_NETWORK_SESSION_EXPIRED)
3130             && !retry) {
3131                 invalidate_cm_connection(domain);
3132                 retry = true;
3133                 goto retry;
3134         }
3135
3136         if (!NT_STATUS_IS_OK(result)) {
3137                 goto done;
3138         }
3139
3140         result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
3141                                         SEC_FLAG_MAXIMUM_ALLOWED,
3142                                         &conn->lsa_policy);
3143
3144         if (NT_STATUS_EQUAL(result, NT_STATUS_IO_DEVICE_ERROR) && !retry) {
3145                 invalidate_cm_connection(domain);
3146                 TALLOC_FREE(conn->lsa_pipe);
3147                 retry = true;
3148                 goto retry;
3149         }
3150
3151  done:
3152         if (!NT_STATUS_IS_OK(result)) {
3153                 invalidate_cm_connection(domain);
3154                 return result;
3155         }
3156
3157         *cli = conn->lsa_pipe;
3158         *lsa_policy = conn->lsa_policy;
3159         return result;
3160 }
3161
3162 /****************************************************************************
3163 Open a LSA connection to a DC, suiteable for LSA lookup calls.
3164 ****************************************************************************/
3165
3166 NTSTATUS cm_connect_lsat(struct winbindd_domain *domain,
3167                          TALLOC_CTX *mem_ctx,
3168                          struct rpc_pipe_client **cli,
3169                          struct policy_handle *lsa_policy)
3170 {
3171         NTSTATUS status;
3172
3173         if (domain->can_do_ncacn_ip_tcp) {
3174                 status = cm_connect_lsa_tcp(domain, mem_ctx, cli);
3175                 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED) ||
3176                     NT_STATUS_EQUAL(status, NT_STATUS_RPC_SEC_PKG_ERROR) ||
3177                     NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_ACCESS_DENIED)) {
3178                         invalidate_cm_connection(domain);
3179                         status = cm_connect_lsa_tcp(domain, mem_ctx, cli);
3180                 }
3181                 if (NT_STATUS_IS_OK(status)) {
3182                         return status;
3183                 }
3184
3185                 /*
3186                  * we tried twice to connect via ncan_ip_tcp and schannel and
3187                  * failed - maybe it is a trusted domain we can't connect to ?
3188                  * do not try tcp next time - gd
3189                  *
3190                  * This also prevents NETLOGON over TCP
3191                  */
3192                 domain->can_do_ncacn_ip_tcp = false;
3193         }
3194
3195         status = cm_connect_lsa(domain, mem_ctx, cli, lsa_policy);
3196
3197         return status;
3198 }
3199
3200 /****************************************************************************
3201  Open the netlogon pipe to this DC. Use schannel if specified in client conf.
3202  session key stored in conn->netlogon_pipe->dc->sess_key.
3203 ****************************************************************************/
3204
3205 static NTSTATUS cm_connect_netlogon_transport(struct winbindd_domain *domain,
3206                                               enum dcerpc_transport_t transport,
3207                                               struct rpc_pipe_client **cli)
3208 {
3209         struct messaging_context *msg_ctx = winbind_messaging_context();
3210         struct winbindd_cm_conn *conn;
3211         NTSTATUS result;
3212         enum netr_SchannelType sec_chan_type;
3213         struct netlogon_creds_CredentialState *netlogon_creds = NULL;
3214         struct cli_credentials *creds = NULL;
3215
3216         *cli = NULL;
3217
3218         result = init_dc_connection_rpc(domain, domain->rodc);
3219         if (!NT_STATUS_IS_OK(result)) {
3220                 return result;
3221         }
3222
3223         conn = &domain->conn;
3224
3225         if (rpccli_is_connected(conn->netlogon_pipe)) {
3226                 *cli = conn->netlogon_pipe;
3227                 return NT_STATUS_OK;
3228         }
3229
3230         TALLOC_FREE(conn->netlogon_pipe);
3231         conn->netlogon_flags = 0;
3232         TALLOC_FREE(conn->netlogon_creds);
3233
3234         result = get_trust_credentials(domain, talloc_tos(), true, &creds);
3235         if (!NT_STATUS_IS_OK(result)) {
3236                 DEBUG(10, ("cm_connect_sam: No user available for "
3237                            "domain %s when trying schannel\n", domain->name));
3238                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3239         }
3240
3241         if (cli_credentials_is_anonymous(creds)) {
3242                 DEBUG(1, ("get_trust_credential only gave anonymous for %s, unable to make get NETLOGON credentials\n",
3243                           domain->name));
3244                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3245         }
3246
3247         sec_chan_type = cli_credentials_get_secure_channel_type(creds);
3248         if (sec_chan_type == SEC_CHAN_NULL) {
3249                 DBG_WARNING("get_secure_channel_type gave SEC_CHAN_NULL for %s\n",
3250                             domain->name);
3251                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3252         }
3253
3254         result = rpccli_create_netlogon_creds_with_creds(creds,
3255                                                          domain->dcname,
3256                                                          msg_ctx,
3257                                                          domain,
3258                                                          &conn->netlogon_creds);
3259         if (!NT_STATUS_IS_OK(result)) {
3260                 DEBUG(1, ("rpccli_create_netlogon_creds failed for %s, "
3261                           "unable to create NETLOGON credentials: %s\n",
3262                           domain->name, nt_errstr(result)));
3263                 return result;
3264         }
3265
3266         result = rpccli_setup_netlogon_creds_with_creds(conn->cli, transport,
3267                                                 conn->netlogon_creds,
3268                                                 conn->netlogon_force_reauth,
3269                                                 creds);
3270         conn->netlogon_force_reauth = false;
3271         if (!NT_STATUS_IS_OK(result)) {
3272                 DEBUG(1, ("rpccli_setup_netlogon_creds failed for %s, "
3273                           "unable to setup NETLOGON credentials: %s\n",
3274                           domain->name, nt_errstr(result)));
3275                 return result;
3276         }
3277
3278         result = netlogon_creds_cli_get(conn->netlogon_creds,
3279                                         talloc_tos(),
3280                                         &netlogon_creds);
3281         if (!NT_STATUS_IS_OK(result)) {
3282                 DEBUG(1, ("netlogon_creds_cli_get failed for %s, "
3283                           "unable to get NETLOGON credentials: %s\n",
3284                           domain->name, nt_errstr(result)));
3285                 return result;
3286         }
3287         conn->netlogon_flags = netlogon_creds->negotiate_flags;
3288         TALLOC_FREE(netlogon_creds);
3289
3290         /*
3291          * FIXME: Document in which case we are not able to contact
3292          * a DC without schannel. Which information do we try to get
3293          * from this DC?
3294          */
3295         if (!(conn->netlogon_flags & NETLOGON_NEG_AUTHENTICATED_RPC)) {
3296                 if (lp_winbind_sealed_pipes() || lp_require_strong_key()) {
3297                         result = NT_STATUS_DOWNGRADE_DETECTED;
3298                         DEBUG(1, ("Unwilling to make connection to domain %s"
3299                                   "without connection level security, "
3300                                   "must set 'winbind sealed pipes = false' and "
3301                                   "'require strong key = false' to proceed: %s\n",
3302                                   domain->name, nt_errstr(result)));
3303                         invalidate_cm_connection(domain);
3304                         return result;
3305                 }
3306                 result = cli_rpc_pipe_open_noauth_transport(conn->cli,
3307                                                             transport,
3308                                                             &ndr_table_netlogon,
3309                                                             &conn->netlogon_pipe);
3310                 if (!NT_STATUS_IS_OK(result)) {
3311                         invalidate_cm_connection(domain);
3312                         return result;
3313                 }
3314
3315                 *cli = conn->netlogon_pipe;
3316                 return NT_STATUS_OK;
3317         }
3318
3319         /* Using the credentials from the first pipe, open a signed and sealed
3320            second netlogon pipe. The session key is stored in the schannel
3321            part of the new pipe auth struct.
3322         */
3323
3324         result = cli_rpc_pipe_open_schannel_with_creds(
3325                 conn->cli, &ndr_table_netlogon, transport,
3326                 creds,
3327                 conn->netlogon_creds,
3328                 &conn->netlogon_pipe);
3329         if (!NT_STATUS_IS_OK(result)) {
3330                 DEBUG(3, ("Could not open schannel'ed NETLOGON pipe. Error "
3331                           "was %s\n", nt_errstr(result)));
3332
3333                 invalidate_cm_connection(domain);
3334                 return result;
3335         }
3336
3337         *cli = conn->netlogon_pipe;
3338         return NT_STATUS_OK;
3339 }
3340
3341 /****************************************************************************
3342 Open a NETLOGON connection to a DC, suiteable for SamLogon calls.
3343 ****************************************************************************/
3344
3345 NTSTATUS cm_connect_netlogon(struct winbindd_domain *domain,
3346                              struct rpc_pipe_client **cli)
3347 {
3348         NTSTATUS status;
3349
3350         status = init_dc_connection_rpc(domain, domain->rodc);
3351         if (!NT_STATUS_IS_OK(status)) {
3352                 return status;
3353         }
3354
3355         if (domain->active_directory && domain->can_do_ncacn_ip_tcp) {
3356                 status = cm_connect_netlogon_transport(domain, NCACN_IP_TCP, cli);
3357                 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED) ||
3358                     NT_STATUS_EQUAL(status, NT_STATUS_RPC_SEC_PKG_ERROR) ||
3359                     NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_ACCESS_DENIED)) {
3360                         invalidate_cm_connection(domain);
3361                         status = cm_connect_netlogon_transport(domain, NCACN_IP_TCP, cli);
3362                 }
3363                 if (NT_STATUS_IS_OK(status)) {
3364                         return status;
3365                 }
3366
3367                 /*
3368                  * we tried twice to connect via ncan_ip_tcp and schannel and
3369                  * failed - maybe it is a trusted domain we can't connect to ?
3370                  * do not try tcp next time - gd
3371                  *
3372                  * This also prevents LSA over TCP
3373                  */
3374                 domain->can_do_ncacn_ip_tcp = false;
3375         }
3376
3377         status = cm_connect_netlogon_transport(domain, NCACN_NP, cli);
3378         if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_SESSION_EXPIRED)) {
3379                 /*
3380                  * SMB2 session expired, needs reauthentication. Drop
3381                  * connection and retry.
3382                  */
3383                 invalidate_cm_connection(domain);
3384                 status = cm_connect_netlogon_transport(domain, NCACN_NP, cli);
3385         }
3386
3387         return status;
3388 }
3389
3390 void winbind_msg_ip_dropped(struct messaging_context *msg_ctx,
3391                             void *private_data,
3392                             uint32_t msg_type,
3393                             struct server_id server_id,
3394                             DATA_BLOB *data)
3395 {
3396         struct winbindd_domain *domain;
3397         char *freeit = NULL;
3398         char *addr;
3399
3400         if ((data == NULL)
3401             || (data->data == NULL)
3402             || (data->length == 0)
3403             || (data->data[data->length-1] != '\0')) {
3404                 DEBUG(1, ("invalid msg_ip_dropped message: not a valid "
3405                           "string\n"));
3406                 return;
3407         }
3408
3409         addr = (char *)data->data;
3410         DEBUG(10, ("IP %s dropped\n", addr));
3411
3412         if (!is_ipaddress(addr)) {
3413                 char *slash;
3414                 /*
3415                  * Some code sends us ip addresses with the /netmask
3416                  * suffix
3417                  */
3418                 slash = strchr(addr, '/');
3419                 if (slash == NULL) {
3420                         DEBUG(1, ("invalid msg_ip_dropped message: %s",
3421                                   addr));
3422                         return;
3423                 }
3424                 freeit = talloc_strndup(talloc_tos(), addr, slash-addr);
3425                 if (freeit == NULL) {
3426                         DEBUG(1, ("talloc failed\n"));
3427                         return;
3428                 }
3429                 addr = freeit;
3430                 DEBUG(10, ("Stripped /netmask to IP %s\n", addr));
3431         }
3432
3433         for (domain = domain_list(); domain != NULL; domain = domain->next) {
3434                 char sockaddr[INET6_ADDRSTRLEN];
3435
3436                 if (!cli_state_is_connected(domain->conn.cli)) {
3437                         continue;
3438                 }
3439
3440                 print_sockaddr(sockaddr, sizeof(sockaddr),
3441                                smbXcli_conn_local_sockaddr(domain->conn.cli->conn));
3442
3443                 if (strequal(sockaddr, addr)) {
3444                         smbXcli_conn_disconnect(domain->conn.cli->conn, NT_STATUS_OK);
3445                 }
3446         }
3447         TALLOC_FREE(freeit);
3448 }