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