s3/pam: move variable declaration into belonging ifdef section
[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 3 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, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22 #include "../libcli/auth/libcli_auth.h"
23
24 #undef DBGC_CLASS
25 #define DBGC_CLASS DBGC_AUTH
26
27 extern bool global_machine_password_needs_changing;
28 static struct named_mutex *mutex;
29
30 /*
31  * Change machine password (called from main loop
32  * idle timeout. Must be done as root.
33  */
34
35 void attempt_machine_password_change(void)
36 {
37         unsigned char trust_passwd_hash[16];
38         time_t lct;
39         void *lock;
40
41         if (!global_machine_password_needs_changing) {
42                 return;
43         }
44
45         if (lp_security() != SEC_DOMAIN) {
46                 return;
47         }
48
49         /*
50          * We're in domain level security, and the code that
51          * read the machine password flagged that the machine
52          * password needs changing.
53          */
54
55         /*
56          * First, open the machine password file with an exclusive lock.
57          */
58
59         lock = secrets_get_trust_account_lock(NULL, lp_workgroup());
60
61         if (lock == NULL) {
62                 DEBUG(0,("attempt_machine_password_change: unable to lock "
63                         "the machine account password for machine %s in "
64                         "domain %s.\n",
65                         global_myname(), lp_workgroup() ));
66                 return;
67         }
68
69         if(!secrets_fetch_trust_account_password(lp_workgroup(),
70                         trust_passwd_hash, &lct, NULL)) {
71                 DEBUG(0,("attempt_machine_password_change: unable to read the "
72                         "machine account password for %s in domain %s.\n",
73                         global_myname(), lp_workgroup()));
74                 TALLOC_FREE(lock);
75                 return;
76         }
77
78         /*
79          * Make sure someone else hasn't already done this.
80          */
81
82         if(time(NULL) < lct + lp_machine_password_timeout()) {
83                 global_machine_password_needs_changing = false;
84                 TALLOC_FREE(lock);
85                 return;
86         }
87
88         /* always just contact the PDC here */
89
90         change_trust_account_password( lp_workgroup(), NULL);
91         global_machine_password_needs_changing = false;
92         TALLOC_FREE(lock);
93 }
94
95 /**
96  * Connect to a remote server for (inter)domain security authenticaion.
97  *
98  * @param cli the cli to return containing the active connection
99  * @param server either a machine name or text IP address to
100  *               connect to.
101  * @param setup_creds_as domain account to setup credentials as
102  * @param sec_chan a switch value to distinguish between domain
103  *                 member and interdomain authentication
104  * @param trust_passwd the trust password to establish the
105  *                     credentials with.
106  *
107  **/
108
109 static NTSTATUS connect_to_domain_password_server(struct cli_state **cli,
110                                                 const char *domain,
111                                                 const char *dc_name,
112                                                 struct sockaddr_storage *dc_ss, 
113                                                 struct rpc_pipe_client **pipe_ret,
114                                                 bool *retry)
115 {
116         NTSTATUS result;
117         struct rpc_pipe_client *netlogon_pipe = NULL;
118
119         *cli = NULL;
120
121         *pipe_ret = NULL;
122
123         /* TODO: Send a SAMLOGON request to determine whether this is a valid
124            logonserver.  We can avoid a 30-second timeout if the DC is down
125            if the SAMLOGON request fails as it is only over UDP. */
126
127         /* we use a mutex to prevent two connections at once - when a 
128            Win2k PDC get two connections where one hasn't completed a 
129            session setup yet it will send a TCP reset to the first 
130            connection (tridge) */
131
132         /*
133          * With NT4.x DC's *all* authentication must be serialized to avoid
134          * ACCESS_DENIED errors if 2 auths are done from the same machine. JRA.
135          */
136
137         mutex = grab_named_mutex(NULL, dc_name, 10);
138         if (mutex == NULL) {
139                 return NT_STATUS_NO_LOGON_SERVERS;
140         }
141         
142         /* Attempt connection */
143         *retry = True;
144         result = cli_full_connection(cli, global_myname(), dc_name, dc_ss, 0, 
145                 "IPC$", "IPC", "", "", "", 0, Undefined, retry);
146
147         if (!NT_STATUS_IS_OK(result)) {
148                 /* map to something more useful */
149                 if (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)) {
150                         result = NT_STATUS_NO_LOGON_SERVERS;
151                 }
152
153                 if (*cli) {
154                         cli_shutdown(*cli);
155                         *cli = NULL;
156                 }
157
158                 TALLOC_FREE(mutex);
159                 return result;
160         }
161
162         /*
163          * We now have an anonymous connection to IPC$ on the domain password server.
164          */
165
166         /*
167          * Even if the connect succeeds we need to setup the netlogon
168          * pipe here. We do this as we may just have changed the domain
169          * account password on the PDC and yet we may be talking to
170          * a BDC that doesn't have this replicated yet. In this case
171          * a successful connect to a DC needs to take the netlogon connect
172          * into account also. This patch from "Bjart Kvarme" <bjart.kvarme@usit.uio.no>.
173          */
174
175         /* open the netlogon pipe. */
176         if (lp_client_schannel()) {
177                 /* We also setup the creds chain in the open_schannel call. */
178                 result = cli_rpc_pipe_open_schannel(
179                         *cli, &ndr_table_netlogon.syntax_id, NCACN_NP,
180                         DCERPC_AUTH_LEVEL_PRIVACY, domain, &netlogon_pipe);
181         } else {
182                 result = cli_rpc_pipe_open_noauth(
183                         *cli, &ndr_table_netlogon.syntax_id, &netlogon_pipe);
184         }
185
186         if (!NT_STATUS_IS_OK(result)) {
187                 DEBUG(0,("connect_to_domain_password_server: unable to open the domain client session to \
188 machine %s. Error was : %s.\n", dc_name, nt_errstr(result)));
189                 cli_shutdown(*cli);
190                 *cli = NULL;
191                 TALLOC_FREE(mutex);
192                 return result;
193         }
194
195         if (!lp_client_schannel()) {
196                 /* We need to set up a creds chain on an unauthenticated netlogon pipe. */
197                 uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS;
198                 enum netr_SchannelType sec_chan_type = 0;
199                 unsigned char machine_pwd[16];
200                 const char *account_name;
201
202                 if (!get_trust_pw_hash(domain, machine_pwd, &account_name,
203                                        &sec_chan_type))
204                 {
205                         DEBUG(0, ("connect_to_domain_password_server: could not fetch "
206                         "trust account password for domain '%s'\n",
207                                 domain));
208                         cli_shutdown(*cli);
209                         *cli = NULL;
210                         TALLOC_FREE(mutex);
211                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
212                 }
213
214                 result = rpccli_netlogon_setup_creds(netlogon_pipe,
215                                         dc_name, /* server name */
216                                         domain, /* domain */
217                                         global_myname(), /* client name */
218                                         account_name, /* machine account name */
219                                         machine_pwd,
220                                         sec_chan_type,
221                                         &neg_flags);
222
223                 if (!NT_STATUS_IS_OK(result)) {
224                         cli_shutdown(*cli);
225                         *cli = NULL;
226                         TALLOC_FREE(mutex);
227                         return result;
228                 }
229         }
230
231         if(!netlogon_pipe) {
232                 DEBUG(0,("connect_to_domain_password_server: unable to open the domain client session to \
233 machine %s. Error was : %s.\n", dc_name, cli_errstr(*cli)));
234                 cli_shutdown(*cli);
235                 *cli = NULL;
236                 TALLOC_FREE(mutex);
237                 return NT_STATUS_NO_LOGON_SERVERS;
238         }
239
240         /* We exit here with the mutex *locked*. JRA */
241
242         *pipe_ret = netlogon_pipe;
243
244         return NT_STATUS_OK;
245 }
246
247 /***********************************************************************
248  Do the same as security=server, but using NT Domain calls and a session
249  key from the machine password.  If the server parameter is specified
250  use it, otherwise figure out a server from the 'password server' param.
251 ************************************************************************/
252
253 static NTSTATUS domain_client_validate(TALLOC_CTX *mem_ctx,
254                                         const auth_usersupplied_info *user_info, 
255                                         const char *domain,
256                                         uchar chal[8],
257                                         auth_serversupplied_info **server_info, 
258                                         const char *dc_name,
259                                         struct sockaddr_storage *dc_ss)
260
261 {
262         struct netr_SamInfo3 *info3 = NULL;
263         struct cli_state *cli = NULL;
264         struct rpc_pipe_client *netlogon_pipe = NULL;
265         NTSTATUS nt_status = NT_STATUS_NO_LOGON_SERVERS;
266         int i;
267         bool retry = True;
268
269         /*
270          * At this point, smb_apasswd points to the lanman response to
271          * the challenge in local_challenge, and smb_ntpasswd points to
272          * the NT response to the challenge in local_challenge. Ship
273          * these over the secure channel to a domain controller and
274          * see if they were valid.
275          */
276
277         /* rety loop for robustness */
278         
279         for (i = 0; !NT_STATUS_IS_OK(nt_status) && retry && (i < 3); i++) {
280                 nt_status = connect_to_domain_password_server(&cli,
281                                                         domain,
282                                                         dc_name,
283                                                         dc_ss,
284                                                         &netlogon_pipe,
285                                                         &retry);
286         }
287
288         if ( !NT_STATUS_IS_OK(nt_status) ) {
289                 DEBUG(0,("domain_client_validate: Domain password server not available.\n"));
290                 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED)) {
291                         return NT_STATUS_TRUSTED_RELATIONSHIP_FAILURE;
292                 }
293                 return nt_status;
294         }
295
296         /* store a successful connection */
297
298         saf_store( domain, cli->desthost );
299
300         /*
301          * If this call succeeds, we now have lots of info about the user
302          * in the info3 structure.  
303          */
304
305         nt_status = rpccli_netlogon_sam_network_logon(netlogon_pipe,
306                                                       mem_ctx,
307                                                       user_info->logon_parameters,/* flags such as 'allow workstation logon' */ 
308                                                       dc_name,                    /* server name */
309                                                       user_info->smb_name,        /* user name logging on. */
310                                                       user_info->client_domain,   /* domain name */
311                                                       user_info->wksta_name,      /* workstation name */
312                                                       chal,                       /* 8 byte challenge. */
313                                                       user_info->lm_resp,         /* lanman 24 byte response */
314                                                       user_info->nt_resp,         /* nt 24 byte response */
315                                                       &info3);                    /* info3 out */
316
317         /* Let go as soon as possible so we avoid any potential deadlocks
318            with winbind lookup up users or groups. */
319            
320         TALLOC_FREE(mutex);
321
322         if (!NT_STATUS_IS_OK(nt_status)) {
323                 DEBUG(0,("domain_client_validate: unable to validate password "
324                          "for user %s in domain %s to Domain controller %s. "
325                          "Error was %s.\n", user_info->smb_name,
326                          user_info->client_domain, dc_name, 
327                          nt_errstr(nt_status)));
328
329                 /* map to something more useful */
330                 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_UNSUCCESSFUL)) {
331                         nt_status = NT_STATUS_NO_LOGON_SERVERS;
332                 }
333         } else {
334                 nt_status = make_server_info_info3(mem_ctx,
335                                                 user_info->smb_name,
336                                                 domain,
337                                                 server_info,
338                                                 info3);
339
340                 if (NT_STATUS_IS_OK(nt_status)) {
341                         (*server_info)->nss_token |= user_info->was_mapped;
342
343                         if ( ! (*server_info)->guest) {
344                                 /* if a real user check pam account restrictions */
345                                 /* only really perfomed if "obey pam restriction" is true */
346                                 nt_status = smb_pam_accountcheck((*server_info)->unix_name);
347                                 if (  !NT_STATUS_IS_OK(nt_status)) {
348                                         DEBUG(1, ("PAM account restriction prevents user login\n"));
349                                         cli_shutdown(cli);
350                                         TALLOC_FREE(info3);
351                                         return nt_status;
352                                 }
353                         }
354                 }
355
356                 netsamlogon_cache_store(user_info->smb_name, info3);
357                 TALLOC_FREE(info3);
358         }
359
360         /* Note - once the cli stream is shutdown the mem_ctx used
361            to allocate the other_sids and gids structures has been deleted - so
362            these pointers are no longer valid..... */
363
364         cli_shutdown(cli);
365         return nt_status;
366 }
367
368 /****************************************************************************
369  Check for a valid username and password in security=domain mode.
370 ****************************************************************************/
371
372 static NTSTATUS check_ntdomain_security(const struct auth_context *auth_context,
373                                         void *my_private_data, 
374                                         TALLOC_CTX *mem_ctx,
375                                         const auth_usersupplied_info *user_info, 
376                                         auth_serversupplied_info **server_info)
377 {
378         NTSTATUS nt_status = NT_STATUS_LOGON_FAILURE;
379         const char *domain = lp_workgroup();
380         fstring dc_name;
381         struct sockaddr_storage dc_ss;
382
383         if ( lp_server_role() != ROLE_DOMAIN_MEMBER ) {
384                 DEBUG(0,("check_ntdomain_security: Configuration error!  Cannot use "
385                         "ntdomain auth method when not a member of a domain.\n"));
386                 return NT_STATUS_NOT_IMPLEMENTED;
387         }
388
389         if (!user_info || !server_info || !auth_context) {
390                 DEBUG(1,("check_ntdomain_security: Critical variables not present.  Failing.\n"));
391                 return NT_STATUS_INVALID_PARAMETER;
392         }
393
394         /* 
395          * Check that the requested domain is not our own machine name.
396          * If it is, we should never check the PDC here, we use our own local
397          * password file.
398          */
399
400         if(strequal(get_global_sam_name(), user_info->domain)) {
401                 DEBUG(3,("check_ntdomain_security: Requested domain was for this machine.\n"));
402                 return NT_STATUS_NOT_IMPLEMENTED;
403         }
404
405         /* we need our DC to send the net_sam_logon() request to */
406
407         if ( !get_dc_name(domain, NULL, dc_name, &dc_ss) ) {
408                 DEBUG(5,("check_ntdomain_security: unable to locate a DC for domain %s\n",
409                         user_info->domain));
410                 return NT_STATUS_NO_LOGON_SERVERS;
411         }
412         
413         nt_status = domain_client_validate(mem_ctx,
414                                         user_info,
415                                         domain,
416                                         (uchar *)auth_context->challenge.data,
417                                         server_info,
418                                         dc_name,
419                                         &dc_ss);
420                 
421         return nt_status;
422 }
423
424 /* module initialisation */
425 static NTSTATUS auth_init_ntdomain(struct auth_context *auth_context, const char* param, auth_methods **auth_method) 
426 {
427         if (!make_auth_methods(auth_context, auth_method)) {
428                 return NT_STATUS_NO_MEMORY;
429         }
430
431         (*auth_method)->name = "ntdomain";
432         (*auth_method)->auth = check_ntdomain_security;
433         return NT_STATUS_OK;
434 }
435
436
437 /****************************************************************************
438  Check for a valid username and password in a trusted domain
439 ****************************************************************************/
440
441 static NTSTATUS check_trustdomain_security(const struct auth_context *auth_context,
442                                            void *my_private_data, 
443                                            TALLOC_CTX *mem_ctx,
444                                            const auth_usersupplied_info *user_info, 
445                                            auth_serversupplied_info **server_info)
446 {
447         NTSTATUS nt_status = NT_STATUS_LOGON_FAILURE;
448         unsigned char trust_md4_password[16];
449         char *trust_password;
450         fstring dc_name;
451         struct sockaddr_storage dc_ss;
452
453         if (!user_info || !server_info || !auth_context) {
454                 DEBUG(1,("check_trustdomain_security: Critical variables not present.  Failing.\n"));
455                 return NT_STATUS_INVALID_PARAMETER;
456         }
457
458         /* 
459          * Check that the requested domain is not our own machine name or domain name.
460          */
461
462         if( strequal(get_global_sam_name(), user_info->domain)) {
463                 DEBUG(3,("check_trustdomain_security: Requested domain [%s] was for this machine.\n",
464                         user_info->domain));
465                 return NT_STATUS_NOT_IMPLEMENTED;
466         }
467
468         /* No point is bothering if this is not a trusted domain.
469            This return makes "map to guest = bad user" work again.
470            The logic is that if we know nothing about the domain, that
471            user is not known to us and does not exist */
472         
473         if ( !is_trusted_domain( user_info->domain ) )
474                 return NT_STATUS_NOT_IMPLEMENTED;
475
476         /*
477          * Get the trusted account password for the trusted domain
478          * No need to become_root() as secrets_init() is done at startup.
479          */
480
481         if (!pdb_get_trusteddom_pw(user_info->domain, &trust_password,
482                                    NULL, NULL)) {
483                 DEBUG(0, ("check_trustdomain_security: could not fetch trust "
484                           "account password for domain %s\n",
485                           user_info->domain));
486                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
487         }
488
489 #ifdef DEBUG_PASSWORD
490         DEBUG(100, ("Trust password for domain %s is %s\n", user_info->domain,
491                     trust_password));
492 #endif
493         E_md4hash(trust_password, trust_md4_password);
494         SAFE_FREE(trust_password);
495
496 #if 0
497         /* Test if machine password is expired and need to be changed */
498         if (time(NULL) > last_change_time + (time_t)lp_machine_password_timeout())
499         {
500                 global_machine_password_needs_changing = True;
501         }
502 #endif
503
504         /* use get_dc_name() for consistency even through we know that it will be 
505            a netbios name */
506            
507         if ( !get_dc_name(user_info->domain, NULL, dc_name, &dc_ss) ) {
508                 DEBUG(5,("check_trustdomain_security: unable to locate a DC for domain %s\n",
509                         user_info->domain));
510                 return NT_STATUS_NO_LOGON_SERVERS;
511         }
512         
513         nt_status = domain_client_validate(mem_ctx,
514                                         user_info,
515                                         user_info->domain,
516                                         (uchar *)auth_context->challenge.data,
517                                         server_info,
518                                         dc_name,
519                                         &dc_ss);
520
521         return nt_status;
522 }
523
524 /* module initialisation */
525 static NTSTATUS auth_init_trustdomain(struct auth_context *auth_context, const char* param, auth_methods **auth_method) 
526 {
527         if (!make_auth_methods(auth_context, auth_method)) {
528                 return NT_STATUS_NO_MEMORY;
529         }
530
531         (*auth_method)->name = "trustdomain";
532         (*auth_method)->auth = check_trustdomain_security;
533         return NT_STATUS_OK;
534 }
535
536 NTSTATUS auth_domain_init(void) 
537 {
538         smb_register_auth(AUTH_INTERFACE_VERSION, "trustdomain", auth_init_trustdomain);
539         smb_register_auth(AUTH_INTERFACE_VERSION, "ntdomain", auth_init_ntdomain);
540         return NT_STATUS_OK;
541 }