d48cec5b2932444b7e102f90410bf7c7c6614501
[tprouty/samba.git] / source / 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.no_bind = 1;
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, ("connect_to_domain_password_server: Can't "
92                                   "resolve name for IP %s\n", server));
93                         return NT_STATUS_NO_LOGON_SERVERS;
94                 }
95
96                 *dest_ip = to_ip;
97                 return NT_STATUS_OK;
98         } 
99
100         fstrcpy(remote_machine, server);
101         strupper(remote_machine);
102         if (!resolve_name(remote_machine, dest_ip, 0x20)) {
103                 DEBUG(1,("connect_to_domain_password_server: Can't resolve address for %s\n", 
104                          remote_machine));
105                 return NT_STATUS_NO_LOGON_SERVERS;
106         }
107
108         DEBUG(4,("rpc_resolve_dc: using server='%s' IP=%s\n",
109                  remote_machine, inet_ntoa(*dest_ip)));
110
111         return NT_STATUS_OK;
112 }
113
114 /**
115  * Connect to a remote server for domain security authenticaion.
116  *
117  * @param cli the cli to return containing the active connection
118  * @param server either a machine name or text IP address to
119  *               connect to.
120  * @param trust_password the trust password to establish the
121  *                       credentials with.
122  *
123  **/
124
125 static NTSTATUS connect_to_domain_password_server(struct cli_state **cli, 
126                                                   const char *server, 
127                                                   const char *setup_creds_as,
128                                                   uint16 sec_chan,
129                                                   const unsigned char *trust_passwd)
130 {
131         struct in_addr dest_ip;
132         fstring remote_machine;
133         NTSTATUS result;
134
135         if (lp_security() == SEC_ADS) {
136                 result = ads_resolve_dc(remote_machine, &dest_ip);
137         } else {
138                 result = rpc_resolve_dc(server, remote_machine, &dest_ip);
139         }
140
141         if (!NT_STATUS_IS_OK(result)) {
142                 DEBUG(2,("connect_to_domain_password_server: unable to resolve DC: %s\n", 
143                          nt_errstr(result)));
144                 return result;
145         }
146
147         if (ismyip(dest_ip)) {
148                 DEBUG(1,("connect_to_domain_password_server: Password server loop - not using password server %s\n",
149                          remote_machine));
150                 return NT_STATUS_NO_LOGON_SERVERS;
151         }
152   
153         /* TODO: Send a SAMLOGON request to determine whether this is a valid
154            logonserver.  We can avoid a 30-second timeout if the DC is down
155            if the SAMLOGON request fails as it is only over UDP. */
156
157         /* we use a mutex to prevent two connections at once - when a 
158            Win2k PDC get two connections where one hasn't completed a 
159            session setup yet it will send a TCP reset to the first 
160            connection (tridge) */
161
162         /*
163          * With NT4.x DC's *all* authentication must be serialized to avoid
164          * ACCESS_DENIED errors if 2 auths are done from the same machine. JRA.
165          */
166
167         if (!grab_server_mutex(server))
168                 return NT_STATUS_NO_LOGON_SERVERS;
169         
170         /* Attempt connection */
171         result = cli_full_connection(cli, global_myname, remote_machine,
172                                      &dest_ip, 0, "IPC$", "IPC", "", "", "",0);
173
174         if (!NT_STATUS_IS_OK(result)) {
175                 release_server_mutex();
176                 return result;
177         }
178
179         /*
180          * We now have an anonymous connection to IPC$ on the domain password server.
181          */
182
183         /*
184          * Even if the connect succeeds we need to setup the netlogon
185          * pipe here. We do this as we may just have changed the domain
186          * account password on the PDC and yet we may be talking to
187          * a BDC that doesn't have this replicated yet. In this case
188          * a successful connect to a DC needs to take the netlogon connect
189          * into account also. This patch from "Bjart Kvarme" <bjart.kvarme@usit.uio.no>.
190          */
191
192         if(cli_nt_session_open(*cli, PIPE_NETLOGON) == False) {
193                 DEBUG(0,("connect_to_domain_password_server: unable to open the domain client session to \
194 machine %s. Error was : %s.\n", remote_machine, cli_errstr(*cli)));
195                 cli_nt_session_close(*cli);
196                 cli_ulogoff(*cli);
197                 cli_shutdown(*cli);
198                 release_server_mutex();
199                 return NT_STATUS_NO_LOGON_SERVERS;
200         }
201
202         snprintf((*cli)->mach_acct, sizeof((*cli)->mach_acct) - 1, "%s$", setup_creds_as);
203
204         if (!(*cli)->mach_acct) {
205                 release_server_mutex();
206                 return NT_STATUS_NO_MEMORY;
207         }
208
209         result = cli_nt_setup_creds(*cli, sec_chan, trust_passwd);
210
211         if (!NT_STATUS_IS_OK(result)) {
212                 DEBUG(0,("connect_to_domain_password_server: unable to setup the PDC credentials to machine \
213 %s. Error was : %s.\n", remote_machine, nt_errstr(result)));
214                 cli_nt_session_close(*cli);
215                 cli_ulogoff(*cli);
216                 cli_shutdown(*cli);
217                 release_server_mutex();
218                 return result;
219         }
220
221         /* We exit here with the mutex *locked*. JRA */
222
223         return NT_STATUS_OK;
224 }
225
226 /***********************************************************************
227  Utility function to attempt a connection to an IP address of a DC.
228 ************************************************************************/
229
230 static NTSTATUS attempt_connect_to_dc(struct cli_state **cli, 
231                                       const char *domain, 
232                                       struct in_addr *ip, 
233                                       const char *setup_creds_as, 
234                                       uint16 sec_chan,
235                                       const unsigned char *trust_passwd)
236 {
237         fstring dc_name;
238
239         /*
240          * Ignore addresses we have already tried.
241          */
242
243         if (is_zero_ip(*ip))
244                 return NT_STATUS_NO_LOGON_SERVERS;
245
246         if (!lookup_dc_name(global_myname, domain, ip, dc_name))
247                 return NT_STATUS_NO_LOGON_SERVERS;
248
249         return connect_to_domain_password_server(cli, dc_name, setup_creds_as, sec_chan, trust_passwd);
250 }
251
252 /***********************************************************************
253  We have been asked to dynamcially determine the IP addresses of
254  the PDC and BDC's for DOMAIN, and query them in turn.
255 ************************************************************************/
256 static NTSTATUS find_connect_pdc(struct cli_state **cli, 
257                                  const char *domain,
258                                  const char *setup_creds_as,
259                                  uint16 sec_chan,
260                                  unsigned char *trust_passwd, 
261                                  time_t last_change_time)
262 {
263         struct in_addr *ip_list = NULL;
264         int count = 0;
265         int i;
266         NTSTATUS nt_status = NT_STATUS_NO_LOGON_SERVERS;
267         time_t time_now = time(NULL);
268         BOOL use_pdc_only = False;
269
270         /*
271          * If the time the machine password has changed
272          * was less than an hour ago then we need to contact
273          * the PDC only, as we cannot be sure domain replication
274          * has yet taken place. Bug found by Gerald (way to go
275          * Gerald !). JRA.
276          */
277
278         if (time_now - last_change_time < 3600)
279                 use_pdc_only = True;
280
281         if (!get_dc_list(use_pdc_only, domain, &ip_list, &count))
282                 return NT_STATUS_NO_LOGON_SERVERS;
283
284         /*
285          * Firstly try and contact a PDC/BDC who has the same
286          * network address as any of our interfaces.
287          */
288         for(i = 0; i < count; i++) {
289                 if(!is_local_net(ip_list[i]))
290                         continue;
291
292                 if(NT_STATUS_IS_OK(nt_status = 
293                                    attempt_connect_to_dc(cli, domain, 
294                                                          &ip_list[i], setup_creds_as, 
295                                                          sec_chan, trust_passwd))) 
296                         break;
297                 
298                 zero_ip(&ip_list[i]); /* Tried and failed. */
299         }
300
301         /*
302          * Secondly try and contact a random PDC/BDC.
303          */
304         if(!NT_STATUS_IS_OK(nt_status)) {
305                 i = (sys_random() % count);
306
307                 if (!is_zero_ip(ip_list[i])) {
308                         if (!NT_STATUS_IS_OK(nt_status = 
309                                              attempt_connect_to_dc(cli, domain, 
310                                                                    &ip_list[i], setup_creds_as, 
311                                                                    sec_chan, trust_passwd)))
312                                 zero_ip(&ip_list[i]); /* Tried and failed. */
313                 }
314         }
315
316         /*
317          * Finally go through the IP list in turn, ignoring any addresses
318          * we have already tried.
319          */
320         if(!NT_STATUS_IS_OK(nt_status)) {
321                 /*
322                  * Try and connect to any of the other IP addresses in the PDC/BDC list.
323                  * Note that from a WINS server the #1 IP address is the PDC.
324                  */
325                 for(i = 0; i < count; i++) {
326                         if (is_zero_ip(ip_list[i]))
327                                 continue;
328
329                         if (NT_STATUS_IS_OK(nt_status = attempt_connect_to_dc(cli, domain, 
330                                                   &ip_list[i], setup_creds_as, sec_chan, trust_passwd)))
331                                 break;
332                 }
333         }
334
335         SAFE_FREE(ip_list);
336         return nt_status;
337 }
338
339 /***********************************************************************
340  Do the same as security=server, but using NT Domain calls and a session
341  key from the machine password.  If the server parameter is specified
342  use it, otherwise figure out a server from the 'password server' param.
343 ************************************************************************/
344
345 static NTSTATUS domain_client_validate(TALLOC_CTX *mem_ctx,
346                                        const auth_usersupplied_info *user_info, 
347                                        const char *domain,
348                                        uchar chal[8],
349                                        auth_serversupplied_info **server_info, 
350                                        char *server, char *setup_creds_as,
351                                        uint16 sec_chan,
352                                        unsigned char trust_passwd[16],
353                                        time_t last_change_time)
354 {
355         fstring remote_machine;
356         NET_USER_INFO_3 info3;
357         struct cli_state *cli = NULL;
358         NTSTATUS nt_status = NT_STATUS_NO_LOGON_SERVERS;
359
360         /*
361          * At this point, smb_apasswd points to the lanman response to
362          * the challenge in local_challenge, and smb_ntpasswd points to
363          * the NT response to the challenge in local_challenge. Ship
364          * these over the secure channel to a domain controller and
365          * see if they were valid.
366          */
367
368         while (!NT_STATUS_IS_OK(nt_status) &&
369                next_token(&server,remote_machine,LIST_SEP,sizeof(remote_machine))) {
370                 if(lp_security() != SEC_ADS && strequal(remote_machine, "*")) {
371                         nt_status = find_connect_pdc(&cli, domain, setup_creds_as, sec_chan, trust_passwd, last_change_time);
372                 } else {
373                         nt_status = connect_to_domain_password_server(&cli, remote_machine, setup_creds_as, sec_chan, trust_passwd);
374                 }
375         }
376
377         if (!NT_STATUS_IS_OK(nt_status)) {
378                 DEBUG(0,("domain_client_validate: Domain password server not available.\n"));
379                 return nt_status;
380         }
381
382         ZERO_STRUCT(info3);
383
384         /*
385          * If this call succeeds, we now have lots of info about the user
386          * in the info3 structure.  
387          */
388
389         nt_status = cli_netlogon_sam_network_logon(cli, mem_ctx,
390                                                    user_info->smb_name.str, user_info->domain.str, 
391                                                    user_info->wksta_name.str, chal, 
392                                                    user_info->lm_resp, user_info->nt_resp, 
393                                                    &info3);
394         
395         if (!NT_STATUS_IS_OK(nt_status)) {
396                 DEBUG(0,("domain_client_validate: unable to validate password "
397                          "for user %s in domain %s to Domain controller %s. "
398                          "Error was %s.\n", user_info->smb_name.str,
399                          user_info->domain.str, cli->srv_name_slash, 
400                          nt_errstr(nt_status)));
401         } else {
402                 nt_status = make_server_info_info3(mem_ctx, user_info->internal_username.str, 
403                                                    user_info->smb_name.str, domain, server_info, &info3);
404 #if 0 
405                 /* The stuff doesn't work right yet */
406                 SMB_ASSERT(sizeof((*server_info)->session_key) == sizeof(info3.user_sess_key)); 
407                 memcpy((*server_info)->session_key, info3.user_sess_key, sizeof((*server_info)->session_key)/* 16 */);
408                 SamOEMhash((*server_info)->session_key, trust_passwd, sizeof((*server_info)->session_key));
409 #endif          
410
411                 uni_group_cache_store_netlogon(mem_ctx, &info3);
412         }
413
414 #if 0
415         /* 
416          * We don't actually need to do this - plus it fails currently with
417          * NT_STATUS_INVALID_INFO_CLASS - we need to know *exactly* what to
418          * send here. JRA.
419          */
420
421         if (NT_STATUS_IS_OK(status)) {
422                 if(cli_nt_logoff(&cli, &ctr) == False) {
423                         DEBUG(0,("domain_client_validate: unable to log off user %s in domain \
424 %s to Domain controller %s. Error was %s.\n", user, domain, remote_machine, cli_errstr(&cli)));        
425                         nt_status = NT_STATUS_LOGON_FAILURE;
426                 }
427         }
428 #endif /* 0 */
429
430         /* Note - once the cli stream is shutdown the mem_ctx used
431            to allocate the other_sids and gids structures has been deleted - so
432            these pointers are no longer valid..... */
433
434         cli_nt_session_close(cli);
435         cli_ulogoff(cli);
436         cli_shutdown(cli);
437         release_server_mutex();
438         return nt_status;
439 }
440
441 /****************************************************************************
442  Check for a valid username and password in security=domain mode.
443 ****************************************************************************/
444
445 static NTSTATUS check_ntdomain_security(const struct auth_context *auth_context,
446                                         void *my_private_data, 
447                                         TALLOC_CTX *mem_ctx,
448                                         const auth_usersupplied_info *user_info, 
449                                         auth_serversupplied_info **server_info)
450 {
451         NTSTATUS nt_status = NT_STATUS_LOGON_FAILURE;
452         char *password_server;
453         unsigned char trust_passwd[16];
454         time_t last_change_time;
455         char *domain = lp_workgroup();
456
457         if (!user_info || !server_info || !auth_context) {
458                 DEBUG(1,("check_ntdomain_security: Critical variables not present.  Failing.\n"));
459                 return NT_STATUS_INVALID_PARAMETER;
460         }
461
462         /* 
463          * Check that the requested domain is not our own machine name.
464          * If it is, we should never check the PDC here, we use our own local
465          * password file.
466          */
467
468         if(is_netbios_alias_or_name(user_info->domain.str)) {
469                 DEBUG(3,("check_ntdomain_security: Requested domain was for this machine.\n"));
470                 return NT_STATUS_LOGON_FAILURE;
471         }
472
473         /*
474          * Get the machine account password for our primary domain
475          * No need to become_root() as secrets_init() is done at startup.
476          */
477
478         if (!secrets_fetch_trust_account_password(domain, trust_passwd, &last_change_time))
479         {
480                 DEBUG(0, ("check_ntdomain_security: could not fetch trust account password for domain '%s'\n", domain));
481                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
482         }
483
484         /* Test if machine password is expired and need to be changed */
485         if (time(NULL) > last_change_time + lp_machine_password_timeout())
486         {
487                 global_machine_password_needs_changing = True;
488         }
489
490         /*
491          * Treat each name in the 'password server =' line as a potential
492          * PDC/BDC. Contact each in turn and try and authenticate.
493          */
494
495         password_server = lp_passwordserver();
496
497         nt_status = domain_client_validate(mem_ctx, user_info, domain,
498                                            (uchar *)auth_context->challenge.data, 
499                                            server_info, 
500                                            password_server, global_myname, SEC_CHAN_WKSTA, trust_passwd, last_change_time);
501         return nt_status;
502 }
503
504 /* module initialisation */
505 NTSTATUS auth_init_ntdomain(struct auth_context *auth_context, const char* param, auth_methods **auth_method) 
506 {
507         if (!make_auth_methods(auth_context, auth_method)) {
508                 return NT_STATUS_NO_MEMORY;
509         }
510
511         (*auth_method)->name = "ntdomain";
512         (*auth_method)->auth = check_ntdomain_security;
513         return NT_STATUS_OK;
514 }
515
516
517 /****************************************************************************
518  Check for a valid username and password in a trusted domain
519 ****************************************************************************/
520
521 static NTSTATUS check_trustdomain_security(const struct auth_context *auth_context,
522                                            void *my_private_data, 
523                                            TALLOC_CTX *mem_ctx,
524                                            const auth_usersupplied_info *user_info, 
525                                            auth_serversupplied_info **server_info)
526 {
527         NTSTATUS nt_status = NT_STATUS_LOGON_FAILURE;
528         unsigned char trust_md4_password[16];
529         char *trust_password;
530         time_t last_change_time;
531         DOM_SID sid;
532
533         if (!user_info || !server_info || !auth_context) {
534                 DEBUG(1,("check_trustdomain_security: Critical variables not present.  Failing.\n"));
535                 return NT_STATUS_INVALID_PARAMETER;
536         }
537
538         /* 
539          * Check that the requested domain is not our own machine name.
540          * If it is, we should never check the PDC here, we use our own local
541          * password file.
542          */
543
544         if(is_netbios_alias_or_name(user_info->domain.str)) {
545                 DEBUG(3,("check_trustdomain_security: Requested domain was for this machine.\n"));
546                 return NT_STATUS_LOGON_FAILURE;
547         }
548
549         /* 
550          * Check that the requested domain is not our own domain,
551          * If it is, we should use our own local password file.
552          */
553
554         if(strequal(lp_workgroup(), (user_info->domain.str))) {
555                 DEBUG(3,("check_trustdomain_security: Requested domain was for this domain.\n"));
556                 return NT_STATUS_LOGON_FAILURE;
557         }
558
559         /*
560          * Get the trusted account password for the trusted domain
561          * No need to become_root() as secrets_init() is done at startup.
562          */
563
564         if (!secrets_fetch_trusted_domain_password(user_info->domain.str, &trust_password, &sid, &last_change_time))
565         {
566                 DEBUG(0, ("check_trustdomain_security: could not fetch trust account password for domain %s\n", user_info->domain.str));
567                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
568         }
569
570 #ifdef DEBUG_PASSWORD
571         DEBUG(100, ("Trust password for domain %s is %s\n", user_info->domain.str, trust_password));
572 #endif
573         E_md4hash(trust_password, trust_md4_password);
574         SAFE_FREE(trust_password);
575
576 #if 0
577         /* Test if machine password is expired and need to be changed */
578         if (time(NULL) > last_change_time + lp_machine_password_timeout())
579         {
580                 global_machine_password_needs_changing = True;
581         }
582 #endif
583
584         nt_status = domain_client_validate(mem_ctx, user_info, user_info->domain.str,
585                                            (uchar *)auth_context->challenge.data, 
586                                            server_info, "*" /* Do a lookup */, 
587                                            lp_workgroup(), SEC_CHAN_DOMAIN, trust_md4_password, last_change_time);
588         
589         return nt_status;
590 }
591
592 /* module initialisation */
593 NTSTATUS auth_init_trustdomain(struct auth_context *auth_context, const char* param, auth_methods **auth_method) 
594 {
595         if (!make_auth_methods(auth_context, auth_method)) {
596                 return NT_STATUS_NO_MEMORY;
597         }
598
599         (*auth_method)->name = "trustdomain";
600         (*auth_method)->auth = check_trustdomain_security;
601         return NT_STATUS_OK;
602 }