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