Fix bug found by tpot with given password server.
[kai/samba-autobuild/.git] / source3 / auth / auth_domain.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Authenticate against a remote domain
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Andrew Bartlett 2001
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #include "includes.h"
23
24 #undef DBGC_CLASS
25 #define DBGC_CLASS DBGC_AUTH
26
27 BOOL global_machine_password_needs_changing = False;
28
29 extern pstring global_myname;
30 extern userdom_struct current_user_info;
31
32
33 /*
34   resolve the name of a DC in ways appropriate for an ADS domain mode
35   an ADS domain may not have Netbios enabled at all, so this is 
36   quite different from the RPC case
37   Note that we ignore the 'server' parameter here. That has the effect of using
38   the 'ADS server' smb.conf parameter, which is what we really want anyway
39  */
40 static NTSTATUS ads_resolve_dc(fstring remote_machine, 
41                                struct in_addr *dest_ip)
42 {
43         ADS_STRUCT *ads;
44         ads = ads_init_simple();
45         if (!ads) {
46                 return NT_STATUS_NO_LOGON_SERVERS;              
47         }
48
49         DEBUG(4,("ads_resolve_dc: realm=%s\n", ads->config.realm));
50
51         ads->auth.flags |= ADS_AUTH_NO_BIND;
52
53 #ifdef HAVE_ADS
54         /* a full ads_connect() is actually overkill, as we don't srictly need
55            to do the SASL auth in order to get the info we need, but libads
56            doesn't offer a better way right now */
57         ads_connect(ads);
58 #endif
59
60         fstrcpy(remote_machine, ads->config.ldap_server_name);
61         strupper(remote_machine);
62         *dest_ip = ads->ldap_ip;
63         ads_destroy(&ads);
64         
65         if (!*remote_machine || is_zero_ip(*dest_ip)) {
66                 return NT_STATUS_NO_LOGON_SERVERS;              
67         }
68
69         DEBUG(4,("ads_resolve_dc: using server='%s' IP=%s\n",
70                  remote_machine, inet_ntoa(*dest_ip)));
71         
72         return NT_STATUS_OK;
73 }
74
75 /*
76   resolve the name of a DC in ways appropriate for RPC domain mode
77   this relies on the server supporting netbios and port 137 not being
78   firewalled
79  */
80 static NTSTATUS rpc_resolve_dc(const char *server, 
81                                fstring remote_machine, 
82                                struct in_addr *dest_ip)
83 {
84         if (is_ipaddress(server)) {
85                 struct in_addr to_ip = *interpret_addr2(server);
86
87                 /* we need to know the machines netbios name - this is a lousy
88                    way to find it, but until we have a RPC call that does this
89                    it will have to do */
90                 if (!name_status_find("*", 0x20, 0x20, to_ip, remote_machine)) {
91                         DEBUG(2, ("rpc_resolve_dc: Can't resolve name for IP %s\n", server));
92                         return NT_STATUS_NO_LOGON_SERVERS;
93                 }
94
95                 *dest_ip = to_ip;
96                 return NT_STATUS_OK;
97         } 
98
99         fstrcpy(remote_machine, server);
100         strupper(remote_machine);
101         if (!resolve_name(remote_machine, dest_ip, 0x20)) {
102                 DEBUG(1,("rpc_resolve_dc: Can't resolve address for %s\n", 
103                          remote_machine));
104                 return NT_STATUS_NO_LOGON_SERVERS;
105         }
106
107         DEBUG(4,("rpc_resolve_dc: using server='%s' IP=%s\n",
108                  remote_machine, inet_ntoa(*dest_ip)));
109
110         return NT_STATUS_OK;
111 }
112
113 /**
114  * Connect to a remote server for domain security authenticaion.
115  *
116  * @param cli the cli to return containing the active connection
117  * @param server either a machine name or text IP address to
118  *               connect to.
119  * @param trust_password the trust password to establish the
120  *                       credentials with.
121  *
122  **/
123
124 static NTSTATUS connect_to_domain_password_server(struct cli_state **cli, 
125                                                   const char *server, 
126                                                   const char *setup_creds_as,
127                                                   uint16 sec_chan,
128                                                   const unsigned char *trust_passwd,
129                                                   BOOL *retry)
130 {
131         struct in_addr dest_ip;
132         fstring remote_machine;
133         NTSTATUS result;
134         uint32 neg_flags = 0x000001ff;
135
136         *retry = False;
137
138         if (lp_security() == SEC_ADS)
139                 result = ads_resolve_dc(remote_machine, &dest_ip);
140         else
141                 result = rpc_resolve_dc(server, remote_machine, &dest_ip);
142
143         if (!NT_STATUS_IS_OK(result)) {
144                 DEBUG(2,("connect_to_domain_password_server: unable to resolve DC: %s\n", 
145                          nt_errstr(result)));
146                 return result;
147         }
148
149         if (ismyip(dest_ip)) {
150                 DEBUG(1,("connect_to_domain_password_server: Password server loop - not using password server %s\n",
151                          remote_machine));
152                 return NT_STATUS_NO_LOGON_SERVERS;
153         }
154   
155         /* TODO: Send a SAMLOGON request to determine whether this is a valid
156            logonserver.  We can avoid a 30-second timeout if the DC is down
157            if the SAMLOGON request fails as it is only over UDP. */
158
159         /* we use a mutex to prevent two connections at once - when a 
160            Win2k PDC get two connections where one hasn't completed a 
161            session setup yet it will send a TCP reset to the first 
162            connection (tridge) */
163
164         /*
165          * With NT4.x DC's *all* authentication must be serialized to avoid
166          * ACCESS_DENIED errors if 2 auths are done from the same machine. JRA.
167          */
168
169         *retry = True;
170
171         if (!grab_server_mutex(server))
172                 return NT_STATUS_NO_LOGON_SERVERS;
173         
174         /* Attempt connection */
175         result = cli_full_connection(cli, global_myname, remote_machine,
176                                      &dest_ip, 0, "IPC$", "IPC", "", "", "",0, retry);
177
178         if (!NT_STATUS_IS_OK(result)) {
179                 release_server_mutex();
180                 return result;
181         }
182
183         /*
184          * We now have an anonymous connection to IPC$ on the domain password server.
185          */
186
187         /*
188          * Even if the connect succeeds we need to setup the netlogon
189          * pipe here. We do this as we may just have changed the domain
190          * account password on the PDC and yet we may be talking to
191          * a BDC that doesn't have this replicated yet. In this case
192          * a successful connect to a DC needs to take the netlogon connect
193          * into account also. This patch from "Bjart Kvarme" <bjart.kvarme@usit.uio.no>.
194          */
195
196         if(cli_nt_session_open(*cli, PI_NETLOGON) == False) {
197                 DEBUG(0,("connect_to_domain_password_server: unable to open the domain client session to \
198 machine %s. Error was : %s.\n", remote_machine, cli_errstr(*cli)));
199                 cli_nt_session_close(*cli);
200                 cli_ulogoff(*cli);
201                 cli_shutdown(*cli);
202                 release_server_mutex();
203                 return NT_STATUS_NO_LOGON_SERVERS;
204         }
205
206         snprintf((*cli)->mach_acct, sizeof((*cli)->mach_acct) - 1, "%s$", setup_creds_as);
207
208         if (!(*cli)->mach_acct) {
209                 release_server_mutex();
210                 return NT_STATUS_NO_MEMORY;
211         }
212
213         result = cli_nt_setup_creds(*cli, sec_chan, trust_passwd, &neg_flags, 2);
214
215         if (!NT_STATUS_IS_OK(result)) {
216                 DEBUG(0,("connect_to_domain_password_server: unable to setup the PDC credentials to machine \
217 %s. Error was : %s.\n", remote_machine, nt_errstr(result)));
218                 cli_nt_session_close(*cli);
219                 cli_ulogoff(*cli);
220                 cli_shutdown(*cli);
221                 release_server_mutex();
222                 return result;
223         }
224
225         /* We exit here with the mutex *locked*. JRA */
226
227         return NT_STATUS_OK;
228 }
229
230 /***********************************************************************
231  Utility function to attempt a connection to an IP address of a DC.
232 ************************************************************************/
233
234 static NTSTATUS attempt_connect_to_dc(struct cli_state **cli, 
235                                       const char *domain, 
236                                       struct in_addr *ip, 
237                                       const char *setup_creds_as, 
238                                       uint16 sec_chan,
239                                       const unsigned char *trust_passwd)
240 {
241         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
242         BOOL retry = True;
243         fstring dc_name;
244         int i;
245
246         /*
247          * Ignore addresses we have already tried.
248          */
249
250         if (is_zero_ip(*ip))
251                 return NT_STATUS_NO_LOGON_SERVERS;
252
253         if (!lookup_dc_name(global_myname, domain, ip, dc_name))
254                 return NT_STATUS_NO_LOGON_SERVERS;
255
256         for (i = 0; (!NT_STATUS_IS_OK(ret)) && retry && (i < 3); i++)
257                 ret = connect_to_domain_password_server(cli, dc_name, setup_creds_as,
258                                 sec_chan, trust_passwd, &retry);
259         return ret;
260 }
261
262 /***********************************************************************
263  We have been asked to dynamically determine the IP addresses of
264  the PDC and BDC's for DOMAIN, and query them in turn.
265 ************************************************************************/
266 static NTSTATUS find_connect_pdc(struct cli_state **cli, 
267                                  const char *domain,
268                                  const char *setup_creds_as,
269                                  uint16 sec_chan,
270                                  unsigned char *trust_passwd, 
271                                  time_t last_change_time)
272 {
273         struct in_addr *ip_list = NULL;
274         int count = 0;
275         int i;
276         NTSTATUS nt_status = NT_STATUS_NO_LOGON_SERVERS;
277         time_t time_now = time(NULL);
278         BOOL use_pdc_only = False;
279
280         /*
281          * If the time the machine password has changed
282          * was less than an hour ago then we need to contact
283          * the PDC only, as we cannot be sure domain replication
284          * has yet taken place. Bug found by Gerald (way to go
285          * Gerald !). JRA.
286          */
287
288         if (time_now - last_change_time < 3600)
289                 use_pdc_only = True;
290
291         if (use_pdc_only) {
292                 struct in_addr pdc_ip;
293
294                 if (!get_pdc_ip(domain, &pdc_ip))
295                         return NT_STATUS_NO_LOGON_SERVERS;
296
297                 if ((ip_list = (struct in_addr *)
298                      malloc(sizeof(struct in_addr))) == NULL) 
299                         return NT_STATUS_NO_MEMORY;
300
301                 ip_list[0] = pdc_ip;
302                 count = 1;
303
304         } else {
305                 if (!get_dc_list(domain, &ip_list, &count))
306                         return NT_STATUS_NO_LOGON_SERVERS;
307         }
308
309         /*
310          * Firstly try and contact a PDC/BDC who has the same
311          * network address as any of our interfaces.
312          */
313         for(i = 0; i < count; i++) {
314                 if(!is_local_net(ip_list[i]))
315                         continue;
316
317                 if(NT_STATUS_IS_OK(nt_status = 
318                                    attempt_connect_to_dc(cli, domain, 
319                                                          &ip_list[i], setup_creds_as, 
320                                                          sec_chan, trust_passwd))) 
321                         break;
322                 
323                 zero_ip(&ip_list[i]); /* Tried and failed. */
324         }
325
326         /*
327          * Secondly try and contact a random PDC/BDC.
328          */
329         if(!NT_STATUS_IS_OK(nt_status)) {
330                 i = (sys_random() % count);
331
332                 if (!is_zero_ip(ip_list[i])) {
333                         if (!NT_STATUS_IS_OK(nt_status = 
334                                              attempt_connect_to_dc(cli, domain, 
335                                                                    &ip_list[i], setup_creds_as, 
336                                                                    sec_chan, trust_passwd)))
337                                 zero_ip(&ip_list[i]); /* Tried and failed. */
338                 }
339         }
340
341         /*
342          * Finally go through the IP list in turn, ignoring any addresses
343          * we have already tried.
344          */
345         if(!NT_STATUS_IS_OK(nt_status)) {
346                 /*
347                  * Try and connect to any of the other IP addresses in the PDC/BDC list.
348                  * Note that from a WINS server the #1 IP address is the PDC.
349                  */
350                 for(i = 0; i < count; i++) {
351                         if (is_zero_ip(ip_list[i]))
352                                 continue;
353
354                         if (NT_STATUS_IS_OK(nt_status = attempt_connect_to_dc(cli, domain, 
355                                                   &ip_list[i], setup_creds_as, sec_chan, trust_passwd)))
356                                 break;
357                 }
358         }
359
360         SAFE_FREE(ip_list);
361         return nt_status;
362 }
363
364 /***********************************************************************
365  Do the same as security=server, but using NT Domain calls and a session
366  key from the machine password.  If the server parameter is specified
367  use it, otherwise figure out a server from the 'password server' param.
368 ************************************************************************/
369
370 static NTSTATUS domain_client_validate(TALLOC_CTX *mem_ctx,
371                                        const auth_usersupplied_info *user_info, 
372                                        const char *domain,
373                                        uchar chal[8],
374                                        auth_serversupplied_info **server_info, 
375                                        char *server, char *setup_creds_as,
376                                        uint16 sec_chan,
377                                        unsigned char trust_passwd[16],
378                                        time_t last_change_time)
379 {
380         fstring remote_machine;
381         NET_USER_INFO_3 info3;
382         struct cli_state *cli = NULL;
383         NTSTATUS nt_status = NT_STATUS_NO_LOGON_SERVERS;
384
385         /*
386          * At this point, smb_apasswd points to the lanman response to
387          * the challenge in local_challenge, and smb_ntpasswd points to
388          * the NT response to the challenge in local_challenge. Ship
389          * these over the secure channel to a domain controller and
390          * see if they were valid.
391          */
392
393         while (!NT_STATUS_IS_OK(nt_status) &&
394                next_token(&server,remote_machine,LIST_SEP,sizeof(remote_machine))) {
395                 if(lp_security() != SEC_ADS && strequal(remote_machine, "*")) {
396                         nt_status = find_connect_pdc(&cli, domain, setup_creds_as, sec_chan, trust_passwd, last_change_time);
397                 } else {
398                         int i;
399                         BOOL retry = True;
400                         for (i = 0; !NT_STATUS_IS_OK(nt_status) && retry && (i < 3); i++)
401                                 nt_status = connect_to_domain_password_server(&cli, remote_machine, setup_creds_as,
402                                                 sec_chan, trust_passwd, &retry);
403                 }
404         }
405
406         if (!NT_STATUS_IS_OK(nt_status)) {
407                 DEBUG(0,("domain_client_validate: Domain password server not available.\n"));
408                 return nt_status;
409         }
410
411         ZERO_STRUCT(info3);
412
413         /*
414          * If this call succeeds, we now have lots of info about the user
415          * in the info3 structure.  
416          */
417
418         nt_status = cli_netlogon_sam_network_logon(cli, mem_ctx,
419                                                    user_info->smb_name.str, user_info->domain.str, 
420                                                    user_info->wksta_name.str, chal, 
421                                                    user_info->lm_resp, user_info->nt_resp, 
422                                                    &info3);
423         
424         if (!NT_STATUS_IS_OK(nt_status)) {
425                 DEBUG(0,("domain_client_validate: unable to validate password "
426                          "for user %s in domain %s to Domain controller %s. "
427                          "Error was %s.\n", user_info->smb_name.str,
428                          user_info->domain.str, cli->srv_name_slash, 
429                          nt_errstr(nt_status)));
430         } else {
431                 nt_status = make_server_info_info3(mem_ctx, user_info->internal_username.str, 
432                                                    user_info->smb_name.str, domain, server_info, &info3);
433 #if 0 
434                 /* The stuff doesn't work right yet */
435                 SMB_ASSERT(sizeof((*server_info)->session_key) == sizeof(info3.user_sess_key)); 
436                 memcpy((*server_info)->session_key, info3.user_sess_key, sizeof((*server_info)->session_key)/* 16 */);
437                 SamOEMhash((*server_info)->session_key, trust_passwd, sizeof((*server_info)->session_key));
438 #endif          
439
440                 uni_group_cache_store_netlogon(mem_ctx, &info3);
441         }
442
443 #if 0
444         /* 
445          * We don't actually need to do this - plus it fails currently with
446          * NT_STATUS_INVALID_INFO_CLASS - we need to know *exactly* what to
447          * send here. JRA.
448          */
449
450         if (NT_STATUS_IS_OK(status)) {
451                 if(cli_nt_logoff(&cli, &ctr) == False) {
452                         DEBUG(0,("domain_client_validate: unable to log off user %s in domain \
453 %s to Domain controller %s. Error was %s.\n", user, domain, remote_machine, cli_errstr(&cli)));        
454                         nt_status = NT_STATUS_LOGON_FAILURE;
455                 }
456         }
457 #endif /* 0 */
458
459         /* Note - once the cli stream is shutdown the mem_ctx used
460            to allocate the other_sids and gids structures has been deleted - so
461            these pointers are no longer valid..... */
462
463         cli_nt_session_close(cli);
464         cli_ulogoff(cli);
465         cli_shutdown(cli);
466         release_server_mutex();
467         return nt_status;
468 }
469
470 /****************************************************************************
471  Check for a valid username and password in security=domain mode.
472 ****************************************************************************/
473
474 static NTSTATUS check_ntdomain_security(const struct auth_context *auth_context,
475                                         void *my_private_data, 
476                                         TALLOC_CTX *mem_ctx,
477                                         const auth_usersupplied_info *user_info, 
478                                         auth_serversupplied_info **server_info)
479 {
480         NTSTATUS nt_status = NT_STATUS_LOGON_FAILURE;
481         char *password_server;
482         unsigned char trust_passwd[16];
483         time_t last_change_time;
484         char *domain = lp_workgroup();
485
486         if (!user_info || !server_info || !auth_context) {
487                 DEBUG(1,("check_ntdomain_security: Critical variables not present.  Failing.\n"));
488                 return NT_STATUS_INVALID_PARAMETER;
489         }
490
491         /* 
492          * Check that the requested domain is not our own machine name.
493          * If it is, we should never check the PDC here, we use our own local
494          * password file.
495          */
496
497         if(is_netbios_alias_or_name(user_info->domain.str)) {
498                 DEBUG(3,("check_ntdomain_security: Requested domain was for this machine.\n"));
499                 return NT_STATUS_LOGON_FAILURE;
500         }
501
502         /*
503          * Get the machine account password for our primary domain
504          * No need to become_root() as secrets_init() is done at startup.
505          */
506
507         if (!secrets_fetch_trust_account_password(domain, trust_passwd, &last_change_time))
508         {
509                 DEBUG(0, ("check_ntdomain_security: could not fetch trust account password for domain '%s'\n", domain));
510                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
511         }
512
513         /* Test if machine password has expired and needs to be changed */
514         if (lp_machine_password_timeout()) {
515                 if (time(NULL) > (last_change_time + 
516                                   lp_machine_password_timeout())) {
517                         global_machine_password_needs_changing = True;
518                 }
519         }
520
521         /*
522          * Treat each name in the 'password server =' line as a potential
523          * PDC/BDC. Contact each in turn and try and authenticate.
524          */
525
526         password_server = lp_passwordserver();
527
528         nt_status = domain_client_validate(mem_ctx, user_info, domain,
529                                            (uchar *)auth_context->challenge.data, 
530                                            server_info, 
531                                            password_server, global_myname, SEC_CHAN_WKSTA, trust_passwd, last_change_time);
532         return nt_status;
533 }
534
535 /* module initialisation */
536 NTSTATUS auth_init_ntdomain(struct auth_context *auth_context, const char* param, auth_methods **auth_method) 
537 {
538         if (!make_auth_methods(auth_context, auth_method)) {
539                 return NT_STATUS_NO_MEMORY;
540         }
541
542         (*auth_method)->name = "ntdomain";
543         (*auth_method)->auth = check_ntdomain_security;
544         return NT_STATUS_OK;
545 }
546
547
548 /****************************************************************************
549  Check for a valid username and password in a trusted domain
550 ****************************************************************************/
551
552 static NTSTATUS check_trustdomain_security(const struct auth_context *auth_context,
553                                            void *my_private_data, 
554                                            TALLOC_CTX *mem_ctx,
555                                            const auth_usersupplied_info *user_info, 
556                                            auth_serversupplied_info **server_info)
557 {
558         NTSTATUS nt_status = NT_STATUS_LOGON_FAILURE;
559         unsigned char trust_md4_password[16];
560         char *trust_password;
561         time_t last_change_time;
562         DOM_SID sid;
563
564         if (!user_info || !server_info || !auth_context) {
565                 DEBUG(1,("check_trustdomain_security: Critical variables not present.  Failing.\n"));
566                 return NT_STATUS_INVALID_PARAMETER;
567         }
568
569         /* 
570          * Check that the requested domain is not our own machine name.
571          * If it is, we should never check the PDC here, we use our own local
572          * password file.
573          */
574
575         if(is_netbios_alias_or_name(user_info->domain.str)) {
576                 DEBUG(3,("check_trustdomain_security: Requested domain was for this machine.\n"));
577                 return NT_STATUS_LOGON_FAILURE;
578         }
579
580         /* 
581          * Check that the requested domain is not our own domain,
582          * If it is, we should use our own local password file.
583          */
584
585         if(strequal(lp_workgroup(), (user_info->domain.str))) {
586                 DEBUG(3,("check_trustdomain_security: Requested domain was for this domain.\n"));
587                 return NT_STATUS_LOGON_FAILURE;
588         }
589
590         /*
591          * Get the trusted account password for the trusted domain
592          * No need to become_root() as secrets_init() is done at startup.
593          */
594
595         if (!secrets_fetch_trusted_domain_password(user_info->domain.str, &trust_password, &sid, &last_change_time))
596         {
597                 DEBUG(0, ("check_trustdomain_security: could not fetch trust account password for domain %s\n", user_info->domain.str));
598                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
599         }
600
601 #ifdef DEBUG_PASSWORD
602         DEBUG(100, ("Trust password for domain %s is %s\n", user_info->domain.str, trust_password));
603 #endif
604         E_md4hash(trust_password, trust_md4_password);
605         SAFE_FREE(trust_password);
606
607 #if 0
608         /* Test if machine password is expired and need to be changed */
609         if (time(NULL) > last_change_time + lp_machine_password_timeout())
610         {
611                 global_machine_password_needs_changing = True;
612         }
613 #endif
614
615         nt_status = domain_client_validate(mem_ctx, user_info, user_info->domain.str,
616                                            (uchar *)auth_context->challenge.data, 
617                                            server_info, "*" /* Do a lookup */, 
618                                            lp_workgroup(), SEC_CHAN_DOMAIN, trust_md4_password, last_change_time);
619         
620         return nt_status;
621 }
622
623 /* module initialisation */
624 NTSTATUS auth_init_trustdomain(struct auth_context *auth_context, const char* param, auth_methods **auth_method) 
625 {
626         if (!make_auth_methods(auth_context, auth_method)) {
627                 return NT_STATUS_NO_MEMORY;
628         }
629
630         (*auth_method)->name = "trustdomain";
631         (*auth_method)->auth = check_trustdomain_security;
632         return NT_STATUS_OK;
633 }