again an intrusive patch:
[jra/samba/.git] / source3 / auth / auth_domain.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 3.0.
4    Authenticate against a remote domain
5    Copyright (C) Andrew Tridgell 1992-1998
6    Copyright (C) Andrew Bartlett 2001
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 #include "includes.h"
24
25 BOOL global_machine_password_needs_changing = False;
26
27 extern pstring global_myname;
28 extern userdom_struct current_user_info;
29
30 /***********************************************************************
31  Connect to a remote machine for domain security authentication
32  given a name or IP address.
33  ***********************************************************************/
34
35 static BOOL connect_to_domain_password_server(struct cli_state *pcli, 
36                                               char *server, unsigned char *trust_passwd)
37 {
38         struct in_addr dest_ip;
39         fstring remote_machine;
40         NTSTATUS result;
41
42         if (cli_initialise(pcli) == NULL) {
43                 DEBUG(0,("connect_to_domain_password_server: unable to initialize client connection.\n"));
44                 return False;
45         }
46
47         if (is_ipaddress(server)) {
48                 struct in_addr to_ip;
49           
50                 /* we shouldn't have 255.255.255.255 forthe IP address of 
51                    a password server anyways */
52                 if ((to_ip.s_addr=inet_addr(server)) == 0xFFFFFFFF) {
53                         DEBUG (0,("connect_to_domain_password_server: inet_addr(%s) returned 0xFFFFFFFF!\n", server));
54                         return False;
55                 }
56
57                 if (!name_status_find("*", 0x20, 0x20, to_ip, remote_machine)) {
58                         DEBUG(0, ("connect_to_domain_password_server: Can't "
59                                   "resolve name for IP %s\n", server));
60                         return False;
61                 }
62         } else {
63                 fstrcpy(remote_machine, server);
64         }
65
66         standard_sub_basic(current_user_info.smb_name, remote_machine);
67         strupper(remote_machine);
68
69         if(!resolve_name( remote_machine, &dest_ip, 0x20)) {
70                 DEBUG(1,("connect_to_domain_password_server: Can't resolve address for %s\n", remote_machine));
71                 cli_shutdown(pcli);
72                 return False;
73         }
74   
75         if (ismyip(dest_ip)) {
76                 DEBUG(1,("connect_to_domain_password_server: Password server loop - not using password server %s\n",
77                          remote_machine));
78                 cli_shutdown(pcli);
79                 return False;
80         }
81   
82         if (!cli_connect(pcli, remote_machine, &dest_ip)) {
83                 DEBUG(0,("connect_to_domain_password_server: unable to connect to SMB server on \
84 machine %s. Error was : %s.\n", remote_machine, cli_errstr(pcli) ));
85                 cli_shutdown(pcli);
86                 return False;
87         }
88   
89         if (!attempt_netbios_session_request(pcli, global_myname, remote_machine, &dest_ip)) {
90                 DEBUG(0,("connect_to_password_server: machine %s rejected the NetBIOS \
91 session request. Error was : %s.\n", remote_machine, cli_errstr(pcli) ));
92                 return False;
93         }
94   
95         pcli->protocol = PROTOCOL_NT1;
96
97         if (!cli_negprot(pcli)) {
98                 DEBUG(0,("connect_to_domain_password_server: machine %s rejected the negotiate protocol. \
99 Error was : %s.\n", remote_machine, cli_errstr(pcli) ));
100                 cli_shutdown(pcli);
101                 return False;
102         }
103
104         if (pcli->protocol != PROTOCOL_NT1) {
105                 DEBUG(0,("connect_to_domain_password_server: machine %s didn't negotiate NT protocol.\n",
106                          remote_machine));
107                 cli_shutdown(pcli);
108                 return False;
109         }
110
111         /*
112          * Do an anonymous session setup.
113          */
114
115         if (!cli_session_setup(pcli, "", "", 0, "", 0, "")) {
116                 DEBUG(0,("connect_to_domain_password_server: machine %s rejected the session setup. \
117 Error was : %s.\n", remote_machine, cli_errstr(pcli) ));
118                 cli_shutdown(pcli);
119                 return False;
120         }
121
122         if (!(pcli->sec_mode & 1)) {
123                 DEBUG(1,("connect_to_domain_password_server: machine %s isn't in user level security mode\n",
124                          remote_machine));
125                 cli_shutdown(pcli);
126                 return False;
127         }
128
129         if (!cli_send_tconX(pcli, "IPC$", "IPC", "", 1)) {
130                 DEBUG(0,("connect_to_domain_password_server: machine %s rejected the tconX on the IPC$ share. \
131 Error was : %s.\n", remote_machine, cli_errstr(pcli) ));
132                 cli_shutdown(pcli);
133                 return False;
134         }
135
136         /*
137          * We now have an anonymous connection to IPC$ on the domain password server.
138          */
139
140         /*
141          * Even if the connect succeeds we need to setup the netlogon
142          * pipe here. We do this as we may just have changed the domain
143          * account password on the PDC and yet we may be talking to
144          * a BDC that doesn't have this replicated yet. In this case
145          * a successful connect to a DC needs to take the netlogon connect
146          * into account also. This patch from "Bjart Kvarme" <bjart.kvarme@usit.uio.no>.
147          */
148
149         if(cli_nt_session_open(pcli, PIPE_NETLOGON) == False) {
150                 DEBUG(0,("connect_to_domain_password_server: unable to open the domain client session to \
151 machine %s. Error was : %s.\n", remote_machine, cli_errstr(pcli)));
152                 cli_nt_session_close(pcli);
153                 cli_ulogoff(pcli);
154                 cli_shutdown(pcli);
155                 return False;
156         }
157
158         result = cli_nt_setup_creds(pcli, trust_passwd);
159
160         if (!NT_STATUS_IS_OK(result)) {
161                 DEBUG(0,("connect_to_domain_password_server: unable to setup the PDC credentials to machine \
162 %s. Error was : %s.\n", remote_machine, get_nt_error_msg(result)));
163                 cli_nt_session_close(pcli);
164                 cli_ulogoff(pcli);
165                 cli_shutdown(pcli);
166                 return(False);
167         }
168
169         return True;
170 }
171
172 /***********************************************************************
173  Utility function to attempt a connection to an IP address of a DC.
174 ************************************************************************/
175
176 static BOOL attempt_connect_to_dc(struct cli_state *pcli, struct in_addr *ip, 
177                                   unsigned char *trust_passwd)
178 {
179         fstring dc_name;
180
181         /*
182          * Ignore addresses we have already tried.
183          */
184
185         if (is_zero_ip(*ip))
186                 return False;
187
188         if (!lookup_dc_name(global_myname, lp_workgroup(), ip, dc_name))
189                 return False;
190
191         return connect_to_domain_password_server(pcli, dc_name, trust_passwd);
192 }
193
194 /***********************************************************************
195  We have been asked to dynamcially determine the IP addresses of
196  the PDC and BDC's for this DOMAIN, and query them in turn.
197 ************************************************************************/
198 static BOOL find_connect_pdc(struct cli_state *pcli, 
199                              unsigned char *trust_passwd, 
200                              time_t last_change_time)
201 {
202         struct in_addr *ip_list = NULL;
203         int count = 0;
204         int i;
205         BOOL connected_ok = False;
206         time_t time_now = time(NULL);
207         BOOL use_pdc_only = False;
208
209         /*
210          * If the time the machine password has changed
211          * was less than an hour ago then we need to contact
212          * the PDC only, as we cannot be sure domain replication
213          * has yet taken place. Bug found by Gerald (way to go
214          * Gerald !). JRA.
215          */
216
217         if (time_now - last_change_time < 3600)
218                 use_pdc_only = True;
219
220         if (!get_dc_list(use_pdc_only, lp_workgroup(), &ip_list, &count))
221                 return False;
222
223         /*
224          * Firstly try and contact a PDC/BDC who has the same
225          * network address as any of our interfaces.
226          */
227         for(i = 0; i < count; i++) {
228                 if(!is_local_net(ip_list[i]))
229                         continue;
230
231                 if((connected_ok = attempt_connect_to_dc(pcli, &ip_list[i], trust_passwd))) 
232                         break;
233                 
234                 zero_ip(&ip_list[i]); /* Tried and failed. */
235         }
236
237         /*
238          * Secondly try and contact a random PDC/BDC.
239          */
240         if(!connected_ok) {
241                 i = (sys_random() % count);
242
243                 if (!(connected_ok = attempt_connect_to_dc(pcli, &ip_list[i], trust_passwd)))
244                         zero_ip(&ip_list[i]); /* Tried and failed. */
245         }
246
247         /*
248          * Finally go through the IP list in turn, ignoring any addresses
249          * we have already tried.
250          */
251         if(!connected_ok) {
252                 /*
253                  * Try and connect to any of the other IP addresses in the PDC/BDC list.
254                  * Note that from a WINS server the #1 IP address is the PDC.
255                  */
256                 for(i = 0; i < count; i++) {
257                         if((connected_ok = attempt_connect_to_dc(pcli, &ip_list[i], trust_passwd)))
258                                 break;
259                 }
260         }
261
262         SAFE_FREE(ip_list);
263
264
265         return connected_ok;
266 }
267
268 /***********************************************************************
269  Do the same as security=server, but using NT Domain calls and a session
270  key from the machine password.  If the server parameter is specified
271  use it, otherwise figure out a server from the 'password server' param.
272 ************************************************************************/
273
274 static NTSTATUS domain_client_validate(const auth_usersupplied_info *user_info, 
275                                        uchar chal[8],
276                                        auth_serversupplied_info **server_info, 
277                                        char *server, unsigned char *trust_passwd,
278                                        time_t last_change_time)
279 {
280         fstring remote_machine;
281         NET_ID_INFO_CTR ctr;
282         NET_USER_INFO_3 info3;
283         struct cli_state cli;
284         uint32 smb_uid_low;
285         BOOL connected_ok = False;
286         NTSTATUS status;
287         struct passwd *pass;
288
289         /*
290          * At this point, smb_apasswd points to the lanman response to
291          * the challenge in local_challenge, and smb_ntpasswd points to
292          * the NT response to the challenge in local_challenge. Ship
293          * these over the secure channel to a domain controller and
294          * see if they were valid.
295          */
296
297         ZERO_STRUCT(cli);
298
299         while (!connected_ok &&
300                next_token(&server,remote_machine,LIST_SEP,sizeof(remote_machine))) {
301                 if(strequal(remote_machine, "*")) {
302                         connected_ok = find_connect_pdc(&cli, trust_passwd, last_change_time);
303                 } else {
304                         connected_ok = connect_to_domain_password_server(&cli, remote_machine, trust_passwd);
305                 }
306         }
307
308         if (!connected_ok) {
309                 DEBUG(0,("domain_client_validate: Domain password server not available.\n"));
310                 cli_shutdown(&cli);
311                 return NT_STATUS_LOGON_FAILURE;
312         }
313
314         /* We really don't care what LUID we give the user. */
315         generate_random_buffer( (unsigned char *)&smb_uid_low, 4, False);
316
317         ZERO_STRUCT(info3);
318
319         /*
320          * If this call succeeds, we now have lots of info about the user
321          * in the info3 structure.  
322          */
323
324         status = cli_nt_login_network(&cli, user_info, chal, smb_uid_low, 
325                                       &ctr, &info3);
326         
327         if (!NT_STATUS_IS_OK(status)) {
328                 DEBUG(0,("domain_client_validate: unable to validate password "
329                          "for user %s in domain %s to Domain controller %s. "
330                          "Error was %s.\n", user_info->smb_name.str,
331                          user_info->domain.str, cli.srv_name_slash, 
332                          get_nt_error_msg(status)));
333         } else {
334                 char *dom_user;
335
336                 /* Check DOMAIN\username first to catch winbind users, then
337                    just the username for local users. */
338
339                 asprintf(&dom_user, "%s%s%s", user_info->domain.str,
340                          lp_winbind_separator(),
341                          user_info->internal_username.str);
342
343                 if (!(pass = Get_Pwnam(dom_user)))
344                         pass = Get_Pwnam(user_info->internal_username.str);
345
346                 free(dom_user);
347
348                 if (pass) {
349                         make_server_info_pw(server_info, pass);
350                         if (!server_info) {
351                                 status = NT_STATUS_NO_MEMORY;
352                         }
353                 } else {
354                         status = NT_STATUS_NO_SUCH_USER;
355                 }
356         }
357
358         /* Store the user group information in the server_info returned to the caller. */
359         
360         if (NT_STATUS_IS_OK(status) && (info3.num_groups2 != 0)) {
361                 DOM_SID domain_sid;
362                 int i;
363                 NT_USER_TOKEN *ptok;
364                 auth_serversupplied_info *pserver_info = *server_info;
365
366                 if ((pserver_info->ptok = malloc( sizeof(NT_USER_TOKEN) ) ) == NULL) {
367                         DEBUG(0, ("domain_client_validate: out of memory allocating rid group membership\n"));
368                         status = NT_STATUS_NO_MEMORY;
369                         free_server_info(server_info);
370                         goto done;
371                 }
372
373                 ptok = pserver_info->ptok;
374                 ptok->num_sids = (size_t)info3.num_groups2;
375
376                 if ((ptok->user_sids = (DOM_SID *)malloc( sizeof(DOM_SID) * ptok->num_sids )) == NULL) {
377                         DEBUG(0, ("domain_client_validate: Out of memory allocating group SIDS\n"));
378                         status = NT_STATUS_NO_MEMORY;
379                         free_server_info(server_info);
380                         goto done;
381                 }
382  
383                 if (!secrets_fetch_domain_sid(lp_workgroup(), &domain_sid)) {
384                         DEBUG(0, ("domain_client_validate: unable to fetch domain sid.\n"));
385                         status = NT_STATUS_NO_MEMORY;
386                         free_server_info(server_info);
387                         goto done;
388                 }
389  
390                 for (i = 0; i < ptok->num_sids; i++) {
391                         sid_copy(&ptok->user_sids[i], &domain_sid);
392                         sid_append_rid(&ptok->user_sids[i], info3.gids[i].g_rid);
393                 }
394         }
395
396 #if 0
397         /* 
398          * We don't actually need to do this - plus it fails currently with
399          * NT_STATUS_INVALID_INFO_CLASS - we need to know *exactly* what to
400          * send here. JRA.
401          */
402
403         if (NT_STATUS_IS_OK(status)) {
404                 if(cli_nt_logoff(&cli, &ctr) == False) {
405                         DEBUG(0,("domain_client_validate: unable to log off user %s in domain \
406 %s to Domain controller %s. Error was %s.\n", user, domain, remote_machine, cli_errstr(&cli)));        
407                         status = NT_STATUS_LOGON_FAILURE;
408                 }
409         }
410 #endif /* 0 */
411
412   done:
413
414         /* Note - once the cli stream is shutdown the mem_ctx used
415            to allocate the other_sids and gids structures has been deleted - so
416            these pointers are no longer valid..... */
417
418         cli_nt_session_close(&cli);
419         cli_ulogoff(&cli);
420         cli_shutdown(&cli);
421         return status;
422 }
423
424 /****************************************************************************
425  Check for a valid username and password in security=domain mode.
426 ****************************************************************************/
427
428 static NTSTATUS check_ntdomain_security(void *my_private_data,
429                                         const auth_usersupplied_info *user_info, 
430                                         const auth_authsupplied_info *auth_info,
431                                         auth_serversupplied_info **server_info)
432 {
433         NTSTATUS nt_status = NT_STATUS_LOGON_FAILURE;
434         char *p, *pserver;
435         unsigned char trust_passwd[16];
436         time_t last_change_time;
437
438         if (!user_info || !server_info || !auth_info) {
439                 DEBUG(1,("check_ntdomain_security: Critical variables not present.  Failing.\n"));
440                 return NT_STATUS_LOGON_FAILURE;
441         }
442
443         /* 
444          * Check that the requested domain is not our own machine name.
445          * If it is, we should never check the PDC here, we use our own local
446          * password file.
447          */
448
449         if(is_netbios_alias_or_name(user_info->domain.str)) {
450                 DEBUG(3,("check_ntdomain_security: Requested domain was for this machine.\n"));
451                 return NT_STATUS_LOGON_FAILURE;
452         }
453
454         become_root();
455
456         /*
457          * Get the machine account password for our primary domain
458          */
459
460         if (!secrets_fetch_trust_account_password(lp_workgroup(), trust_passwd, &last_change_time))
461         {
462                 DEBUG(0, ("check_domain_security: could not fetch trust account password for domain %s\n", lp_workgroup()));
463                 unbecome_root();
464                 return NT_STATUS_LOGON_FAILURE;
465         }
466
467         unbecome_root();
468
469         /* Test if machine password is expired and need to be changed */
470         if (time(NULL) > last_change_time + lp_machine_password_timeout())
471         {
472                 global_machine_password_needs_changing = True;
473         }
474
475         /*
476          * Treat each name in the 'password server =' line as a potential
477          * PDC/BDC. Contact each in turn and try and authenticate.
478          */
479
480         pserver = lp_passwordserver();
481         if (! *pserver) pserver = "*";
482         p = pserver;
483
484         nt_status = domain_client_validate(user_info, (uchar *)auth_info->challenge.data,server_info, 
485                                            p, trust_passwd, last_change_time);
486
487         return nt_status;
488 }
489
490 BOOL auth_init_ntdomain(auth_methods **auth_method) 
491 {
492         if (!make_auth_methods(auth_method)) {
493                 return False;
494         }
495
496         (*auth_method)->auth = check_ntdomain_security;
497         return True;
498 }