Add some static. Patch by Stefan Metzmacher <metze@metzemix.de>
[gd/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 extern BOOL global_machine_password_needs_changing;
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
134         *retry = False;
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         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         *retry = True;
168
169         if (!grab_server_mutex(server))
170                 return NT_STATUS_NO_LOGON_SERVERS;
171         
172         /* Attempt connection */
173         result = cli_full_connection(cli, global_myname(), remote_machine,
174                                      &dest_ip, 0, "IPC$", "IPC", "", "", "",0, retry);
175
176         if (!NT_STATUS_IS_OK(result)) {
177                 /* map to something more useful */
178                 if (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)) {
179                         result = NT_STATUS_NO_LOGON_SERVERS;
180                 }
181
182                 release_server_mutex();
183                 return result;
184         }
185
186         /*
187          * We now have an anonymous connection to IPC$ on the domain password server.
188          */
189
190         /*
191          * Even if the connect succeeds we need to setup the netlogon
192          * pipe here. We do this as we may just have changed the domain
193          * account password on the PDC and yet we may be talking to
194          * a BDC that doesn't have this replicated yet. In this case
195          * a successful connect to a DC needs to take the netlogon connect
196          * into account also. This patch from "Bjart Kvarme" <bjart.kvarme@usit.uio.no>.
197          */
198
199         if(cli_nt_session_open(*cli, PI_NETLOGON) == False) {
200                 DEBUG(0,("connect_to_domain_password_server: unable to open the domain client session to \
201 machine %s. Error was : %s.\n", remote_machine, cli_errstr(*cli)));
202                 cli_nt_session_close(*cli);
203                 cli_ulogoff(*cli);
204                 cli_shutdown(*cli);
205                 release_server_mutex();
206                 return NT_STATUS_NO_LOGON_SERVERS;
207         }
208
209         snprintf((*cli)->mach_acct, sizeof((*cli)->mach_acct) - 1, "%s$", setup_creds_as);
210
211         if (!(*cli)->mach_acct) {
212                 release_server_mutex();
213                 return NT_STATUS_NO_MEMORY;
214         }
215
216         result = cli_nt_establish_netlogon(*cli, sec_chan, trust_passwd);
217
218         if (!NT_STATUS_IS_OK(result)) {
219                 DEBUG(0,("connect_to_domain_password_server: unable to setup the NETLOGON credentials to machine \
220 %s. Error was : %s.\n", remote_machine, nt_errstr(result)));
221                 cli_nt_session_close(*cli);
222                 cli_ulogoff(*cli);
223                 cli_shutdown(*cli);
224                 release_server_mutex();
225                 return result;
226         }
227
228         /* We exit here with the mutex *locked*. JRA */
229
230         return NT_STATUS_OK;
231 }
232
233 /***********************************************************************
234  Utility function to attempt a connection to an IP address of a DC.
235 ************************************************************************/
236
237 static NTSTATUS attempt_connect_to_dc(struct cli_state **cli, 
238                                       const char *domain, 
239                                       struct in_addr *ip, 
240                                       const char *setup_creds_as, 
241                                       uint16 sec_chan,
242                                       const unsigned char *trust_passwd)
243 {
244         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
245         BOOL retry = True;
246         fstring dc_name;
247         int i;
248
249         /*
250          * Ignore addresses we have already tried.
251          */
252
253         if (is_zero_ip(*ip))
254                 return NT_STATUS_NO_LOGON_SERVERS;
255
256         if (!lookup_dc_name(global_myname(), domain, ip, dc_name))
257                 return NT_STATUS_NO_LOGON_SERVERS;
258
259         for (i = 0; (!NT_STATUS_IS_OK(ret)) && retry && (i < 3); i++)
260                 ret = connect_to_domain_password_server(cli, dc_name, setup_creds_as,
261                                 sec_chan, trust_passwd, &retry);
262         return ret;
263 }
264
265 /***********************************************************************
266  We have been asked to dynamically determine the IP addresses of
267  the PDC and BDC's for DOMAIN, and query them in turn.
268 ************************************************************************/
269 static NTSTATUS find_connect_dc(struct cli_state **cli, 
270                                  const char *domain,
271                                  const char *setup_creds_as,
272                                  uint16 sec_chan,
273                                  unsigned char *trust_passwd, 
274                                  time_t last_change_time)
275 {
276         struct in_addr dc_ip;
277         fstring srv_name;
278
279         if (!rpc_find_dc(domain, srv_name, &dc_ip)) {
280                 DEBUG(0,("find_connect_dc: Failed to find an DCs for %s\n", lp_workgroup()));
281                 return NT_STATUS_NO_LOGON_SERVERS;
282         }
283         
284         return attempt_connect_to_dc( cli, domain, &dc_ip, setup_creds_as, 
285                         sec_chan, trust_passwd );
286 }
287
288 /***********************************************************************
289  Do the same as security=server, but using NT Domain calls and a session
290  key from the machine password.  If the server parameter is specified
291  use it, otherwise figure out a server from the 'password server' param.
292 ************************************************************************/
293
294 static NTSTATUS domain_client_validate(TALLOC_CTX *mem_ctx,
295                                        const auth_usersupplied_info *user_info, 
296                                        const char *domain,
297                                        uchar chal[8],
298                                        auth_serversupplied_info **server_info, 
299                                        const char *server, const char *setup_creds_as,
300                                        uint16 sec_chan,
301                                        unsigned char trust_passwd[16],
302                                        time_t last_change_time)
303 {
304         fstring remote_machine;
305         NET_USER_INFO_3 info3;
306         struct cli_state *cli = NULL;
307         NTSTATUS nt_status = NT_STATUS_NO_LOGON_SERVERS;
308
309         /*
310          * At this point, smb_apasswd points to the lanman response to
311          * the challenge in local_challenge, and smb_ntpasswd points to
312          * the NT response to the challenge in local_challenge. Ship
313          * these over the secure channel to a domain controller and
314          * see if they were valid.
315          */
316
317         while (!NT_STATUS_IS_OK(nt_status) &&
318                next_token(&server,remote_machine,LIST_SEP,sizeof(remote_machine))) {
319                 if(lp_security() != SEC_ADS && strequal(remote_machine, "*")) {
320                         nt_status = find_connect_dc(&cli, domain, setup_creds_as, sec_chan, trust_passwd, last_change_time);
321                 } else {
322                         int i;
323                         BOOL retry = True;
324                         for (i = 0; !NT_STATUS_IS_OK(nt_status) && retry && (i < 3); i++)
325                                 nt_status = connect_to_domain_password_server(&cli, remote_machine, setup_creds_as,
326                                                 sec_chan, trust_passwd, &retry);
327                 }
328         }
329
330         if (!NT_STATUS_IS_OK(nt_status)) {
331                 DEBUG(0,("domain_client_validate: Domain password server not available.\n"));
332                 return nt_status;
333         }
334
335         ZERO_STRUCT(info3);
336
337         /*
338          * If this call succeeds, we now have lots of info about the user
339          * in the info3 structure.  
340          */
341
342         nt_status = cli_netlogon_sam_network_logon(cli, mem_ctx,
343                                                    NULL,
344                                                    user_info->smb_name.str, user_info->domain.str, 
345                                                    user_info->wksta_name.str, chal, 
346                                                    user_info->lm_resp, user_info->nt_resp, 
347                                                    &info3);
348         
349         if (!NT_STATUS_IS_OK(nt_status)) {
350                 DEBUG(0,("domain_client_validate: unable to validate password "
351                          "for user %s in domain %s to Domain controller %s. "
352                          "Error was %s.\n", user_info->smb_name.str,
353                          user_info->domain.str, cli->srv_name_slash, 
354                          nt_errstr(nt_status)));
355
356                 /* map to something more useful */
357                 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_UNSUCCESSFUL)) {
358                         nt_status = NT_STATUS_NO_LOGON_SERVERS;
359                 }
360         } else {
361                 nt_status = make_server_info_info3(mem_ctx, user_info->internal_username.str, 
362                                                    user_info->smb_name.str, domain, server_info, &info3);
363                 uni_group_cache_store_netlogon(mem_ctx, &info3);
364         }
365
366 #if 0
367         /* 
368          * We don't actually need to do this - plus it fails currently with
369          * NT_STATUS_INVALID_INFO_CLASS - we need to know *exactly* what to
370          * send here. JRA.
371          */
372
373         if (NT_STATUS_IS_OK(status)) {
374                 if(cli_nt_logoff(&cli, &ctr) == False) {
375                         DEBUG(0,("domain_client_validate: unable to log off user %s in domain \
376 %s to Domain controller %s. Error was %s.\n", user, domain, remote_machine, cli_errstr(&cli)));        
377                         nt_status = NT_STATUS_LOGON_FAILURE;
378                 }
379         }
380 #endif /* 0 */
381
382         /* Note - once the cli stream is shutdown the mem_ctx used
383            to allocate the other_sids and gids structures has been deleted - so
384            these pointers are no longer valid..... */
385
386         cli_nt_session_close(cli);
387         cli_ulogoff(cli);
388         cli_shutdown(cli);
389         release_server_mutex();
390         return nt_status;
391 }
392
393 /****************************************************************************
394  Check for a valid username and password in security=domain mode.
395 ****************************************************************************/
396
397 static NTSTATUS check_ntdomain_security(const struct auth_context *auth_context,
398                                         void *my_private_data, 
399                                         TALLOC_CTX *mem_ctx,
400                                         const auth_usersupplied_info *user_info, 
401                                         auth_serversupplied_info **server_info)
402 {
403         NTSTATUS nt_status = NT_STATUS_LOGON_FAILURE;
404         char *password_server;
405         unsigned char trust_passwd[16];
406         time_t last_change_time;
407         const char *domain = lp_workgroup();
408         uint32 sec_channel_type = 0;
409
410         if (!user_info || !server_info || !auth_context) {
411                 DEBUG(1,("check_ntdomain_security: Critical variables not present.  Failing.\n"));
412                 return NT_STATUS_INVALID_PARAMETER;
413         }
414
415         /* 
416          * Check that the requested domain is not our own machine name.
417          * If it is, we should never check the PDC here, we use our own local
418          * password file.
419          */
420
421         if(is_myname(user_info->domain.str)) {
422                 DEBUG(3,("check_ntdomain_security: Requested domain was for this machine.\n"));
423                 return NT_STATUS_LOGON_FAILURE;
424         }
425
426         /*
427          * Get the machine account password for our primary domain
428          * No need to become_root() as secrets_init() is done at startup.
429          */
430
431         if (!secrets_fetch_trust_account_password(domain, trust_passwd, &last_change_time, &sec_channel_type))
432         {
433                 DEBUG(0, ("check_ntdomain_security: could not fetch trust account password for domain '%s'\n", domain));
434                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
435         }
436
437         /* Test if machine password has expired and needs to be changed */
438         if (lp_machine_password_timeout()) {
439                 if (last_change_time > 0 && 
440                     time(NULL) > (last_change_time + 
441                                   lp_machine_password_timeout())) {
442                         global_machine_password_needs_changing = True;
443                 }
444         }
445
446         /*
447          * Treat each name in the 'password server =' line as a potential
448          * PDC/BDC. Contact each in turn and try and authenticate.
449          */
450
451         password_server = lp_passwordserver();
452
453         nt_status = domain_client_validate(mem_ctx, user_info, domain,
454                                            (uchar *)auth_context->challenge.data, 
455                                            server_info, 
456                                            password_server, global_myname(), sec_channel_type,trust_passwd, last_change_time);
457         return nt_status;
458 }
459
460 /* module initialisation */
461 static NTSTATUS auth_init_ntdomain(struct auth_context *auth_context, const char* param, auth_methods **auth_method) 
462 {
463         if (!make_auth_methods(auth_context, auth_method)) {
464                 return NT_STATUS_NO_MEMORY;
465         }
466
467         (*auth_method)->name = "ntdomain";
468         (*auth_method)->auth = check_ntdomain_security;
469         return NT_STATUS_OK;
470 }
471
472
473 /****************************************************************************
474  Check for a valid username and password in a trusted domain
475 ****************************************************************************/
476
477 static NTSTATUS check_trustdomain_security(const struct auth_context *auth_context,
478                                            void *my_private_data, 
479                                            TALLOC_CTX *mem_ctx,
480                                            const auth_usersupplied_info *user_info, 
481                                            auth_serversupplied_info **server_info)
482 {
483         NTSTATUS nt_status = NT_STATUS_LOGON_FAILURE;
484         unsigned char trust_md4_password[16];
485         char *trust_password;
486         time_t last_change_time;
487         DOM_SID sid;
488
489         if (!user_info || !server_info || !auth_context) {
490                 DEBUG(1,("check_trustdomain_security: Critical variables not present.  Failing.\n"));
491                 return NT_STATUS_INVALID_PARAMETER;
492         }
493
494         /* 
495          * Check that the requested domain is not our own machine name.
496          * If it is, we should never check the PDC here, we use our own local
497          * password file.
498          */
499
500         if(is_myname(user_info->domain.str)) {
501                 DEBUG(3,("check_trustdomain_security: Requested domain was for this machine.\n"));
502                 return NT_STATUS_LOGON_FAILURE;
503         }
504
505         /* 
506          * Check that the requested domain is not our own domain,
507          * If it is, we should use our own local password file.
508          */
509
510         if(strequal(lp_workgroup(), (user_info->domain.str))) {
511                 DEBUG(3,("check_trustdomain_security: Requested domain was for this domain.\n"));
512                 return NT_STATUS_LOGON_FAILURE;
513         }
514
515         /*
516          * Get the trusted account password for the trusted domain
517          * No need to become_root() as secrets_init() is done at startup.
518          */
519
520         if (!secrets_fetch_trusted_domain_password(user_info->domain.str, &trust_password, &sid, &last_change_time))
521         {
522                 DEBUG(0, ("check_trustdomain_security: could not fetch trust account password for domain %s\n", user_info->domain.str));
523                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
524         }
525
526 #ifdef DEBUG_PASSWORD
527         DEBUG(100, ("Trust password for domain %s is %s\n", user_info->domain.str, trust_password));
528 #endif
529         E_md4hash(trust_password, trust_md4_password);
530         SAFE_FREE(trust_password);
531
532 #if 0
533         /* Test if machine password is expired and need to be changed */
534         if (time(NULL) > last_change_time + lp_machine_password_timeout())
535         {
536                 global_machine_password_needs_changing = True;
537         }
538 #endif
539
540         nt_status = domain_client_validate(mem_ctx, user_info, user_info->domain.str,
541                                            (uchar *)auth_context->challenge.data, 
542                                            server_info, "*" /* Do a lookup */, 
543                                            lp_workgroup(), SEC_CHAN_DOMAIN, trust_md4_password, last_change_time);
544         
545         return nt_status;
546 }
547
548 /* module initialisation */
549 static NTSTATUS auth_init_trustdomain(struct auth_context *auth_context, const char* param, auth_methods **auth_method) 
550 {
551         if (!make_auth_methods(auth_context, auth_method)) {
552                 return NT_STATUS_NO_MEMORY;
553         }
554
555         (*auth_method)->name = "trustdomain";
556         (*auth_method)->auth = check_trustdomain_security;
557         return NT_STATUS_OK;
558 }
559
560 NTSTATUS auth_domain_init(void) 
561 {
562         smb_register_auth(AUTH_INTERFACE_VERSION, "trustdomain", auth_init_trustdomain);
563         smb_register_auth(AUTH_INTERFACE_VERSION, "ntdomain", auth_init_ntdomain);
564         return NT_STATUS_OK;
565 }