Use NTSTATUS as return value for smb_register_*() functions and init_module()
[metze/samba/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 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         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                 /* map to something more useful */
179                 if (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)) {
180                         result = NT_STATUS_NO_LOGON_SERVERS;
181                 }
182
183                 release_server_mutex();
184                 return result;
185         }
186
187         /*
188          * We now have an anonymous connection to IPC$ on the domain password server.
189          */
190
191         /*
192          * Even if the connect succeeds we need to setup the netlogon
193          * pipe here. We do this as we may just have changed the domain
194          * account password on the PDC and yet we may be talking to
195          * a BDC that doesn't have this replicated yet. In this case
196          * a successful connect to a DC needs to take the netlogon connect
197          * into account also. This patch from "Bjart Kvarme" <bjart.kvarme@usit.uio.no>.
198          */
199
200         if(cli_nt_session_open(*cli, PI_NETLOGON) == False) {
201                 DEBUG(0,("connect_to_domain_password_server: unable to open the domain client session to \
202 machine %s. Error was : %s.\n", remote_machine, cli_errstr(*cli)));
203                 cli_nt_session_close(*cli);
204                 cli_ulogoff(*cli);
205                 cli_shutdown(*cli);
206                 release_server_mutex();
207                 return NT_STATUS_NO_LOGON_SERVERS;
208         }
209
210         snprintf((*cli)->mach_acct, sizeof((*cli)->mach_acct) - 1, "%s$", setup_creds_as);
211
212         if (!(*cli)->mach_acct) {
213                 release_server_mutex();
214                 return NT_STATUS_NO_MEMORY;
215         }
216
217         result = cli_nt_setup_creds(*cli, sec_chan, trust_passwd, &neg_flags, 2);
218
219         if (!NT_STATUS_IS_OK(result)) {
220                 DEBUG(0,("connect_to_domain_password_server: unable to setup the NETLOGON credentials to machine \
221 %s. Error was : %s.\n", remote_machine, nt_errstr(result)));
222                 cli_nt_session_close(*cli);
223                 cli_ulogoff(*cli);
224                 cli_shutdown(*cli);
225                 release_server_mutex();
226                 return result;
227         }
228
229         /* We exit here with the mutex *locked*. JRA */
230
231         return NT_STATUS_OK;
232 }
233
234 /***********************************************************************
235  Utility function to attempt a connection to an IP address of a DC.
236 ************************************************************************/
237
238 static NTSTATUS attempt_connect_to_dc(struct cli_state **cli, 
239                                       const char *domain, 
240                                       struct in_addr *ip, 
241                                       const char *setup_creds_as, 
242                                       uint16 sec_chan,
243                                       const unsigned char *trust_passwd)
244 {
245         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
246         BOOL retry = True;
247         fstring dc_name;
248         int i;
249
250         /*
251          * Ignore addresses we have already tried.
252          */
253
254         if (is_zero_ip(*ip))
255                 return NT_STATUS_NO_LOGON_SERVERS;
256
257         if (!lookup_dc_name(global_myname(), domain, ip, dc_name))
258                 return NT_STATUS_NO_LOGON_SERVERS;
259
260         for (i = 0; (!NT_STATUS_IS_OK(ret)) && retry && (i < 3); i++)
261                 ret = connect_to_domain_password_server(cli, dc_name, setup_creds_as,
262                                 sec_chan, trust_passwd, &retry);
263         return ret;
264 }
265
266 /***********************************************************************
267  We have been asked to dynamically determine the IP addresses of
268  the PDC and BDC's for DOMAIN, and query them in turn.
269 ************************************************************************/
270 static NTSTATUS find_connect_dc(struct cli_state **cli, 
271                                  const char *domain,
272                                  const char *setup_creds_as,
273                                  uint16 sec_chan,
274                                  unsigned char *trust_passwd, 
275                                  time_t last_change_time)
276 {
277         struct in_addr dc_ip;
278         fstring srv_name;
279
280         if (!rpc_find_dc(domain, srv_name, &dc_ip)) {
281                 DEBUG(0,("find_connect_dc: Failed to find an DCs for %s\n", lp_workgroup()));
282                 return NT_STATUS_NO_LOGON_SERVERS;
283         }
284         
285         return attempt_connect_to_dc( cli, domain, &dc_ip, setup_creds_as, 
286                         sec_chan, trust_passwd );
287 }
288
289 /***********************************************************************
290  Do the same as security=server, but using NT Domain calls and a session
291  key from the machine password.  If the server parameter is specified
292  use it, otherwise figure out a server from the 'password server' param.
293 ************************************************************************/
294
295 static NTSTATUS domain_client_validate(TALLOC_CTX *mem_ctx,
296                                        const auth_usersupplied_info *user_info, 
297                                        const char *domain,
298                                        uchar chal[8],
299                                        auth_serversupplied_info **server_info, 
300                                        const char *server, const char *setup_creds_as,
301                                        uint16 sec_chan,
302                                        unsigned char trust_passwd[16],
303                                        time_t last_change_time)
304 {
305         fstring remote_machine;
306         NET_USER_INFO_3 info3;
307         struct cli_state *cli = NULL;
308         NTSTATUS nt_status = NT_STATUS_NO_LOGON_SERVERS;
309
310         /*
311          * At this point, smb_apasswd points to the lanman response to
312          * the challenge in local_challenge, and smb_ntpasswd points to
313          * the NT response to the challenge in local_challenge. Ship
314          * these over the secure channel to a domain controller and
315          * see if they were valid.
316          */
317
318         while (!NT_STATUS_IS_OK(nt_status) &&
319                next_token(&server,remote_machine,LIST_SEP,sizeof(remote_machine))) {
320                 if(lp_security() != SEC_ADS && strequal(remote_machine, "*")) {
321                         nt_status = find_connect_dc(&cli, domain, setup_creds_as, sec_chan, trust_passwd, last_change_time);
322                 } else {
323                         int i;
324                         BOOL retry = True;
325                         for (i = 0; !NT_STATUS_IS_OK(nt_status) && retry && (i < 3); i++)
326                                 nt_status = connect_to_domain_password_server(&cli, remote_machine, setup_creds_as,
327                                                 sec_chan, trust_passwd, &retry);
328                 }
329         }
330
331         if (!NT_STATUS_IS_OK(nt_status)) {
332                 DEBUG(0,("domain_client_validate: Domain password server not available.\n"));
333                 return nt_status;
334         }
335
336         ZERO_STRUCT(info3);
337
338         /*
339          * If this call succeeds, we now have lots of info about the user
340          * in the info3 structure.  
341          */
342
343         nt_status = cli_netlogon_sam_network_logon(cli, mem_ctx,
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 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 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 }