This commit was manufactured by cvs2svn to create branch 'SAMBA_3_0'.(This used to...
[jra/samba/.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 userdom_struct current_user_info;
30
31
32 /*
33   resolve the name of a DC in ways appropriate for an ADS domain mode
34   an ADS domain may not have Netbios enabled at all, so this is 
35   quite different from the RPC case
36   Note that we ignore the 'server' parameter here. That has the effect of using
37   the 'ADS server' smb.conf parameter, which is what we really want anyway
38  */
39 static NTSTATUS ads_resolve_dc(fstring remote_machine, 
40                                struct in_addr *dest_ip)
41 {
42         ADS_STRUCT *ads;
43         ads = ads_init_simple();
44         if (!ads) {
45                 return NT_STATUS_NO_LOGON_SERVERS;              
46         }
47
48         DEBUG(4,("ads_resolve_dc: realm=%s\n", ads->config.realm));
49
50         ads->auth.flags |= ADS_AUTH_NO_BIND;
51
52 #ifdef HAVE_ADS
53         /* a full ads_connect() is actually overkill, as we don't srictly need
54            to do the SASL auth in order to get the info we need, but libads
55            doesn't offer a better way right now */
56         ads_connect(ads);
57 #endif
58
59         fstrcpy(remote_machine, ads->config.ldap_server_name);
60         strupper(remote_machine);
61         *dest_ip = ads->ldap_ip;
62         ads_destroy(&ads);
63         
64         if (!*remote_machine || is_zero_ip(*dest_ip)) {
65                 return NT_STATUS_NO_LOGON_SERVERS;              
66         }
67
68         DEBUG(4,("ads_resolve_dc: using server='%s' IP=%s\n",
69                  remote_machine, inet_ntoa(*dest_ip)));
70         
71         return NT_STATUS_OK;
72 }
73
74 /*
75   resolve the name of a DC in ways appropriate for RPC domain mode
76   this relies on the server supporting netbios and port 137 not being
77   firewalled
78  */
79 static NTSTATUS rpc_resolve_dc(const char *server, 
80                                fstring remote_machine, 
81                                struct in_addr *dest_ip)
82 {
83         if (is_ipaddress(server)) {
84                 struct in_addr to_ip = *interpret_addr2(server);
85
86                 /* we need to know the machines netbios name - this is a lousy
87                    way to find it, but until we have a RPC call that does this
88                    it will have to do */
89                 if (!name_status_find("*", 0x20, 0x20, to_ip, remote_machine)) {
90                         DEBUG(2, ("rpc_resolve_dc: Can't resolve name for IP %s\n", server));
91                         return NT_STATUS_NO_LOGON_SERVERS;
92                 }
93
94                 *dest_ip = to_ip;
95                 return NT_STATUS_OK;
96         } 
97
98         fstrcpy(remote_machine, server);
99         strupper(remote_machine);
100         if (!resolve_name(remote_machine, dest_ip, 0x20)) {
101                 DEBUG(1,("rpc_resolve_dc: Can't resolve address for %s\n", 
102                          remote_machine));
103                 return NT_STATUS_NO_LOGON_SERVERS;
104         }
105
106         DEBUG(4,("rpc_resolve_dc: using server='%s' IP=%s\n",
107                  remote_machine, inet_ntoa(*dest_ip)));
108
109         return NT_STATUS_OK;
110 }
111
112 /**
113  * Connect to a remote server for domain security authenticaion.
114  *
115  * @param cli the cli to return containing the active connection
116  * @param server either a machine name or text IP address to
117  *               connect to.
118  * @param trust_passwd the trust password to establish the
119  *                       credentials with.
120  *
121  **/
122
123 static NTSTATUS connect_to_domain_password_server(struct cli_state **cli, 
124                                                   const char *server, 
125                                                   const char *setup_creds_as,
126                                                   uint16 sec_chan,
127                                                   const unsigned char *trust_passwd,
128                                                   BOOL *retry)
129 {
130         struct in_addr dest_ip;
131         fstring remote_machine;
132         NTSTATUS result;
133         uint32 neg_flags = 0x000001ff;
134
135         *retry = False;
136
137         if (lp_security() == SEC_ADS)
138                 result = ads_resolve_dc(remote_machine, &dest_ip);
139         else
140                 result = rpc_resolve_dc(server, remote_machine, &dest_ip);
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         *retry = True;
169
170         if (!grab_server_mutex(server))
171                 return NT_STATUS_NO_LOGON_SERVERS;
172         
173         /* Attempt connection */
174         result = cli_full_connection(cli, global_myname(), remote_machine,
175                                      &dest_ip, 0, "IPC$", "IPC", "", "", "",0, retry);
176
177         if (!NT_STATUS_IS_OK(result)) {
178                 release_server_mutex();
179                 return result;
180         }
181
182         /*
183          * We now have an anonymous connection to IPC$ on the domain password server.
184          */
185
186         /*
187          * Even if the connect succeeds we need to setup the netlogon
188          * pipe here. We do this as we may just have changed the domain
189          * account password on the PDC and yet we may be talking to
190          * a BDC that doesn't have this replicated yet. In this case
191          * a successful connect to a DC needs to take the netlogon connect
192          * into account also. This patch from "Bjart Kvarme" <bjart.kvarme@usit.uio.no>.
193          */
194
195         if(cli_nt_session_open(*cli, PI_NETLOGON) == False) {
196                 DEBUG(0,("connect_to_domain_password_server: unable to open the domain client session to \
197 machine %s. Error was : %s.\n", remote_machine, cli_errstr(*cli)));
198                 cli_nt_session_close(*cli);
199                 cli_ulogoff(*cli);
200                 cli_shutdown(*cli);
201                 release_server_mutex();
202                 return NT_STATUS_NO_LOGON_SERVERS;
203         }
204
205         snprintf((*cli)->mach_acct, sizeof((*cli)->mach_acct) - 1, "%s$", setup_creds_as);
206
207         if (!(*cli)->mach_acct) {
208                 release_server_mutex();
209                 return NT_STATUS_NO_MEMORY;
210         }
211
212         result = cli_nt_setup_creds(*cli, sec_chan, trust_passwd, &neg_flags, 2);
213
214         if (!NT_STATUS_IS_OK(result)) {
215                 DEBUG(0,("connect_to_domain_password_server: unable to setup the NETLOGON credentials to machine \
216 %s. Error was : %s.\n", remote_machine, nt_errstr(result)));
217                 cli_nt_session_close(*cli);
218                 cli_ulogoff(*cli);
219                 cli_shutdown(*cli);
220                 release_server_mutex();
221                 return result;
222         }
223
224         /* We exit here with the mutex *locked*. JRA */
225
226         return NT_STATUS_OK;
227 }
228
229 /***********************************************************************
230  Utility function to attempt a connection to an IP address of a DC.
231 ************************************************************************/
232
233 static NTSTATUS attempt_connect_to_dc(struct cli_state **cli, 
234                                       const char *domain, 
235                                       struct in_addr *ip, 
236                                       const char *setup_creds_as, 
237                                       uint16 sec_chan,
238                                       const unsigned char *trust_passwd)
239 {
240         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
241         BOOL retry = True;
242         fstring dc_name;
243         int i;
244
245         /*
246          * Ignore addresses we have already tried.
247          */
248
249         if (is_zero_ip(*ip))
250                 return NT_STATUS_NO_LOGON_SERVERS;
251
252         if (!lookup_dc_name(global_myname(), domain, ip, dc_name))
253                 return NT_STATUS_NO_LOGON_SERVERS;
254
255         for (i = 0; (!NT_STATUS_IS_OK(ret)) && retry && (i < 3); i++)
256                 ret = connect_to_domain_password_server(cli, dc_name, setup_creds_as,
257                                 sec_chan, trust_passwd, &retry);
258         return ret;
259 }
260
261 /***********************************************************************
262  We have been asked to dynamically determine the IP addresses of
263  the PDC and BDC's for DOMAIN, and query them in turn.
264 ************************************************************************/
265 static NTSTATUS find_connect_dc(struct cli_state **cli, 
266                                  const char *domain,
267                                  const char *setup_creds_as,
268                                  uint16 sec_chan,
269                                  unsigned char *trust_passwd, 
270                                  time_t last_change_time)
271 {
272         struct in_addr dc_ip;
273         fstring srv_name;
274
275         if ( !rpc_find_dc(lp_workgroup(), srv_name, &dc_ip) ) {
276                 DEBUG(0,("find_connect_dc: Failed to find an DCs for %s\n", lp_workgroup()));
277                 return NT_STATUS_NO_LOGON_SERVERS;
278         }
279         
280         return attempt_connect_to_dc( cli, domain, &dc_ip, setup_creds_as, 
281                         sec_chan, trust_passwd );
282 }
283
284 /***********************************************************************
285  Do the same as security=server, but using NT Domain calls and a session
286  key from the machine password.  If the server parameter is specified
287  use it, otherwise figure out a server from the 'password server' param.
288 ************************************************************************/
289
290 static NTSTATUS domain_client_validate(TALLOC_CTX *mem_ctx,
291                                        const auth_usersupplied_info *user_info, 
292                                        const char *domain,
293                                        uchar chal[8],
294                                        auth_serversupplied_info **server_info, 
295                                        const char *server, const char *setup_creds_as,
296                                        uint16 sec_chan,
297                                        unsigned char trust_passwd[16],
298                                        time_t last_change_time)
299 {
300         fstring remote_machine;
301         NET_USER_INFO_3 info3;
302         struct cli_state *cli = NULL;
303         NTSTATUS nt_status = NT_STATUS_NO_LOGON_SERVERS;
304
305         /*
306          * At this point, smb_apasswd points to the lanman response to
307          * the challenge in local_challenge, and smb_ntpasswd points to
308          * the NT response to the challenge in local_challenge. Ship
309          * these over the secure channel to a domain controller and
310          * see if they were valid.
311          */
312
313         while (!NT_STATUS_IS_OK(nt_status) &&
314                next_token(&server,remote_machine,LIST_SEP,sizeof(remote_machine))) {
315                 if(lp_security() != SEC_ADS && strequal(remote_machine, "*")) {
316                         nt_status = find_connect_dc(&cli, domain, setup_creds_as, sec_chan, trust_passwd, last_change_time);
317                 } else {
318                         int i;
319                         BOOL retry = True;
320                         for (i = 0; !NT_STATUS_IS_OK(nt_status) && retry && (i < 3); i++)
321                                 nt_status = connect_to_domain_password_server(&cli, remote_machine, setup_creds_as,
322                                                 sec_chan, trust_passwd, &retry);
323                 }
324         }
325
326         if (!NT_STATUS_IS_OK(nt_status)) {
327                 DEBUG(0,("domain_client_validate: Domain password server not available.\n"));
328                 return nt_status;
329         }
330
331         ZERO_STRUCT(info3);
332
333         /*
334          * If this call succeeds, we now have lots of info about the user
335          * in the info3 structure.  
336          */
337
338         nt_status = cli_netlogon_sam_network_logon(cli, mem_ctx,
339                                                    user_info->smb_name.str, user_info->domain.str, 
340                                                    user_info->wksta_name.str, chal, 
341                                                    user_info->lm_resp, user_info->nt_resp, 
342                                                    &info3);
343         
344         if (!NT_STATUS_IS_OK(nt_status)) {
345                 DEBUG(0,("domain_client_validate: unable to validate password "
346                          "for user %s in domain %s to Domain controller %s. "
347                          "Error was %s.\n", user_info->smb_name.str,
348                          user_info->domain.str, cli->srv_name_slash, 
349                          nt_errstr(nt_status)));
350         } else {
351                 nt_status = make_server_info_info3(mem_ctx, user_info->internal_username.str, 
352                                                    user_info->smb_name.str, domain, server_info, &info3);
353 #if 0 
354                 /* The stuff doesn't work right yet */
355                 SMB_ASSERT(sizeof((*server_info)->session_key) == sizeof(info3.user_sess_key)); 
356                 memcpy((*server_info)->session_key, info3.user_sess_key, sizeof((*server_info)->session_key)/* 16 */);
357                 SamOEMhash((*server_info)->session_key, trust_passwd, sizeof((*server_info)->session_key));
358 #endif          
359
360                 uni_group_cache_store_netlogon(mem_ctx, &info3);
361         }
362
363 #if 0
364         /* 
365          * We don't actually need to do this - plus it fails currently with
366          * NT_STATUS_INVALID_INFO_CLASS - we need to know *exactly* what to
367          * send here. JRA.
368          */
369
370         if (NT_STATUS_IS_OK(status)) {
371                 if(cli_nt_logoff(&cli, &ctr) == False) {
372                         DEBUG(0,("domain_client_validate: unable to log off user %s in domain \
373 %s to Domain controller %s. Error was %s.\n", user, domain, remote_machine, cli_errstr(&cli)));        
374                         nt_status = NT_STATUS_LOGON_FAILURE;
375                 }
376         }
377 #endif /* 0 */
378
379         /* Note - once the cli stream is shutdown the mem_ctx used
380            to allocate the other_sids and gids structures has been deleted - so
381            these pointers are no longer valid..... */
382
383         cli_nt_session_close(cli);
384         cli_ulogoff(cli);
385         cli_shutdown(cli);
386         release_server_mutex();
387         return nt_status;
388 }
389
390 /****************************************************************************
391  Check for a valid username and password in security=domain mode.
392 ****************************************************************************/
393
394 static NTSTATUS check_ntdomain_security(const struct auth_context *auth_context,
395                                         void *my_private_data, 
396                                         TALLOC_CTX *mem_ctx,
397                                         const auth_usersupplied_info *user_info, 
398                                         auth_serversupplied_info **server_info)
399 {
400         NTSTATUS nt_status = NT_STATUS_LOGON_FAILURE;
401         char *password_server;
402         unsigned char trust_passwd[16];
403         time_t last_change_time;
404         const char *domain = lp_workgroup();
405
406         if (!user_info || !server_info || !auth_context) {
407                 DEBUG(1,("check_ntdomain_security: Critical variables not present.  Failing.\n"));
408                 return NT_STATUS_INVALID_PARAMETER;
409         }
410
411         /* 
412          * Check that the requested domain is not our own machine name.
413          * If it is, we should never check the PDC here, we use our own local
414          * password file.
415          */
416
417         if(is_myname(user_info->domain.str)) {
418                 DEBUG(3,("check_ntdomain_security: Requested domain was for this machine.\n"));
419                 return NT_STATUS_LOGON_FAILURE;
420         }
421
422         /*
423          * Get the machine account password for our primary domain
424          * No need to become_root() as secrets_init() is done at startup.
425          */
426
427         if (!secrets_fetch_trust_account_password(domain, trust_passwd, &last_change_time))
428         {
429                 DEBUG(0, ("check_ntdomain_security: could not fetch trust account password for domain '%s'\n", domain));
430                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
431         }
432
433         /* Test if machine password has expired and needs to be changed */
434         if (lp_machine_password_timeout()) {
435                 if (last_change_time > 0 && 
436                     time(NULL) > (last_change_time + 
437                                   lp_machine_password_timeout())) {
438                         global_machine_password_needs_changing = True;
439                 }
440         }
441
442         /*
443          * Treat each name in the 'password server =' line as a potential
444          * PDC/BDC. Contact each in turn and try and authenticate.
445          */
446
447         password_server = lp_passwordserver();
448
449         nt_status = domain_client_validate(mem_ctx, user_info, domain,
450                                            (uchar *)auth_context->challenge.data, 
451                                            server_info, 
452                                            password_server, global_myname(), SEC_CHAN_WKSTA, trust_passwd, last_change_time);
453         return nt_status;
454 }
455
456 /* module initialisation */
457 NTSTATUS auth_init_ntdomain(struct auth_context *auth_context, const char* param, auth_methods **auth_method) 
458 {
459         if (!make_auth_methods(auth_context, auth_method)) {
460                 return NT_STATUS_NO_MEMORY;
461         }
462
463         (*auth_method)->name = "ntdomain";
464         (*auth_method)->auth = check_ntdomain_security;
465         return NT_STATUS_OK;
466 }
467
468
469 /****************************************************************************
470  Check for a valid username and password in a trusted domain
471 ****************************************************************************/
472
473 static NTSTATUS check_trustdomain_security(const struct auth_context *auth_context,
474                                            void *my_private_data, 
475                                            TALLOC_CTX *mem_ctx,
476                                            const auth_usersupplied_info *user_info, 
477                                            auth_serversupplied_info **server_info)
478 {
479         NTSTATUS nt_status = NT_STATUS_LOGON_FAILURE;
480         unsigned char trust_md4_password[16];
481         char *trust_password;
482         time_t last_change_time;
483         DOM_SID sid;
484
485         if (!user_info || !server_info || !auth_context) {
486                 DEBUG(1,("check_trustdomain_security: Critical variables not present.  Failing.\n"));
487                 return NT_STATUS_INVALID_PARAMETER;
488         }
489
490         /* 
491          * Check that the requested domain is not our own machine name.
492          * If it is, we should never check the PDC here, we use our own local
493          * password file.
494          */
495
496         if(is_myname(user_info->domain.str)) {
497                 DEBUG(3,("check_trustdomain_security: Requested domain was for this machine.\n"));
498                 return NT_STATUS_LOGON_FAILURE;
499         }
500
501         /* 
502          * Check that the requested domain is not our own domain,
503          * If it is, we should use our own local password file.
504          */
505
506         if(strequal(lp_workgroup(), (user_info->domain.str))) {
507                 DEBUG(3,("check_trustdomain_security: Requested domain was for this domain.\n"));
508                 return NT_STATUS_LOGON_FAILURE;
509         }
510
511         /*
512          * Get the trusted account password for the trusted domain
513          * No need to become_root() as secrets_init() is done at startup.
514          */
515
516         if (!secrets_fetch_trusted_domain_password(user_info->domain.str, &trust_password, &sid, &last_change_time))
517         {
518                 DEBUG(0, ("check_trustdomain_security: could not fetch trust account password for domain %s\n", user_info->domain.str));
519                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
520         }
521
522 #ifdef DEBUG_PASSWORD
523         DEBUG(100, ("Trust password for domain %s is %s\n", user_info->domain.str, trust_password));
524 #endif
525         E_md4hash(trust_password, trust_md4_password);
526         SAFE_FREE(trust_password);
527
528 #if 0
529         /* Test if machine password is expired and need to be changed */
530         if (time(NULL) > last_change_time + lp_machine_password_timeout())
531         {
532                 global_machine_password_needs_changing = True;
533         }
534 #endif
535
536         nt_status = domain_client_validate(mem_ctx, user_info, user_info->domain.str,
537                                            (uchar *)auth_context->challenge.data, 
538                                            server_info, "*" /* Do a lookup */, 
539                                            lp_workgroup(), SEC_CHAN_DOMAIN, trust_md4_password, last_change_time);
540         
541         return nt_status;
542 }
543
544 /* module initialisation */
545 NTSTATUS auth_init_trustdomain(struct auth_context *auth_context, const char* param, auth_methods **auth_method) 
546 {
547         if (!make_auth_methods(auth_context, auth_method)) {
548                 return NT_STATUS_NO_MEMORY;
549         }
550
551         (*auth_method)->name = "trustdomain";
552         (*auth_method)->auth = check_trustdomain_security;
553         return NT_STATUS_OK;
554 }