This commit was manufactured by cvs2svn to create branch 'SAMBA_3_0'.
[tprouty/samba.git] / source / auth / auth_util.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Authentication utility functions
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Andrew Bartlett 2001
6    Copyright (C) Jeremy Allison 2000-2001
7    Copyright (C) Rafal Szczesniak 2002
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 #include "includes.h"
25
26 #undef DBGC_CLASS
27 #define DBGC_CLASS DBGC_AUTH
28
29 extern DOM_SID global_sid_World;
30 extern DOM_SID global_sid_Network;
31 extern DOM_SID global_sid_Builtin_Guests;
32 extern DOM_SID global_sid_Authenticated_Users;
33
34
35 /****************************************************************************
36  Create a UNIX user on demand.
37 ****************************************************************************/
38
39 static int smb_create_user(const char *unix_user, const char *homedir)
40 {
41         pstring add_script;
42         int ret;
43
44         pstrcpy(add_script, lp_adduser_script());
45         if (! *add_script)
46                 return -1;
47         all_string_sub(add_script, "%u", unix_user, sizeof(pstring));
48         if (homedir)
49                 all_string_sub(add_script, "%H", homedir, sizeof(pstring));
50         ret = smbrun(add_script,NULL);
51         DEBUG(3,("smb_create_user: Running the command `%s' gave %d\n",add_script,ret));
52         return ret;
53 }
54
55 /****************************************************************************
56  Add and Delete UNIX users on demand, based on NTSTATUS codes.
57 ****************************************************************************/
58
59 void smb_user_control(const auth_usersupplied_info *user_info, auth_serversupplied_info *server_info, NTSTATUS nt_status)
60 {
61         struct passwd *pwd=NULL;
62
63         if (NT_STATUS_IS_OK(nt_status)) {
64
65                 if (!(server_info->sam_fill_level & SAM_FILL_UNIX)) {
66                         
67                         /*
68                          * User validated ok against Domain controller.
69                          * If the admin wants us to try and create a UNIX
70                          * user on the fly, do so.
71                          */
72                         
73                         if(lp_adduser_script() && !(pwd = Get_Pwnam(user_info->internal_username.str))) {
74                                 smb_create_user(user_info->internal_username.str, NULL);
75                         }
76                 }
77         }
78 }
79
80 /****************************************************************************
81  Create a SAM_ACCOUNT - either by looking in the pdb, or by faking it up from
82  unix info.
83 ****************************************************************************/
84
85 NTSTATUS auth_get_sam_account(const char *user, SAM_ACCOUNT **account) 
86 {
87         BOOL pdb_ret;
88         NTSTATUS nt_status;
89         if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam(account))) {
90                 return nt_status;
91         }
92         
93         become_root();
94         pdb_ret = pdb_getsampwnam(*account, user);
95         unbecome_root();
96
97         if (!pdb_ret) {
98                 
99                 struct passwd *pass = Get_Pwnam(user);
100                 if (!pass) 
101                         return NT_STATUS_NO_SUCH_USER;
102
103                 if (!NT_STATUS_IS_OK(nt_status = pdb_fill_sam_pw(*account, pass))) {
104                         return nt_status;
105                 }
106         }
107         return NT_STATUS_OK;
108 }
109
110 /****************************************************************************
111  Create an auth_usersupplied_data structure
112 ****************************************************************************/
113
114 static NTSTATUS make_user_info(auth_usersupplied_info **user_info, 
115                                const char *smb_name, 
116                                const char *internal_username,
117                                const char *client_domain, 
118                                const char *domain,
119                                const char *wksta_name, 
120                                DATA_BLOB lm_pwd, DATA_BLOB nt_pwd,
121                                DATA_BLOB plaintext, 
122                                uint32 auth_flags, BOOL encrypted)
123 {
124
125         DEBUG(5,("attempting to make a user_info for %s (%s)\n", internal_username, smb_name));
126
127         *user_info = malloc(sizeof(**user_info));
128         if (!user_info) {
129                 DEBUG(0,("malloc failed for user_info (size %d)\n", sizeof(*user_info)));
130                 return NT_STATUS_NO_MEMORY;
131         }
132
133         ZERO_STRUCTP(*user_info);
134
135         DEBUG(5,("making strings for %s's user_info struct\n", internal_username));
136
137         (*user_info)->smb_name.str = strdup(smb_name);
138         if ((*user_info)->smb_name.str) { 
139                 (*user_info)->smb_name.len = strlen(smb_name);
140         } else {
141                 free_user_info(user_info);
142                 return NT_STATUS_NO_MEMORY;
143         }
144         
145         (*user_info)->internal_username.str = strdup(internal_username);
146         if ((*user_info)->internal_username.str) { 
147                 (*user_info)->internal_username.len = strlen(internal_username);
148         } else {
149                 free_user_info(user_info);
150                 return NT_STATUS_NO_MEMORY;
151         }
152
153         (*user_info)->domain.str = strdup(domain);
154         if ((*user_info)->domain.str) { 
155                 (*user_info)->domain.len = strlen(domain);
156         } else {
157                 free_user_info(user_info);
158                 return NT_STATUS_NO_MEMORY;
159         }
160
161         (*user_info)->client_domain.str = strdup(client_domain);
162         if ((*user_info)->client_domain.str) { 
163                 (*user_info)->client_domain.len = strlen(client_domain);
164         } else {
165                 free_user_info(user_info);
166                 return NT_STATUS_NO_MEMORY;
167         }
168
169         (*user_info)->wksta_name.str = strdup(wksta_name);
170         if ((*user_info)->wksta_name.str) { 
171                 (*user_info)->wksta_name.len = strlen(wksta_name);
172         } else {
173                 free_user_info(user_info);
174                 return NT_STATUS_NO_MEMORY;
175         }
176
177         DEBUG(5,("making blobs for %s's user_info struct\n", internal_username));
178
179         (*user_info)->lm_resp = data_blob(lm_pwd.data, lm_pwd.length);
180         (*user_info)->nt_resp = data_blob(nt_pwd.data, nt_pwd.length);
181         (*user_info)->plaintext_password = data_blob(plaintext.data, plaintext.length);
182
183         (*user_info)->encrypted = encrypted;
184         (*user_info)->auth_flags = auth_flags;
185
186         DEBUG(10,("made an %sencrypted user_info for %s (%s)\n", encrypted ? "":"un" , internal_username, smb_name));
187
188         return NT_STATUS_OK;
189 }
190
191 /****************************************************************************
192  Create an auth_usersupplied_data structure after appropriate mapping.
193 ****************************************************************************/
194
195 NTSTATUS make_user_info_map(auth_usersupplied_info **user_info, 
196                             const char *smb_name, 
197                             const char *client_domain, 
198                             const char *wksta_name, 
199                             DATA_BLOB lm_pwd, DATA_BLOB nt_pwd,
200                             DATA_BLOB plaintext, 
201                             uint32 ntlmssp_flags, BOOL encrypted)
202 {
203         const char *domain;
204         fstring internal_username;
205         fstrcpy(internal_username, smb_name);
206         map_username(internal_username); 
207         
208         DEBUG(5, ("make_user_info_map: Mapping user [%s]\\[%s] from workstation [%s]\n",
209               client_domain, smb_name, wksta_name));
210         
211         if (lp_allow_trusted_domains() && *client_domain) {
212
213                 /* the client could have given us a workstation name
214                    or other crap for the workgroup - we really need a
215                    way of telling if this domain name is one of our
216                    trusted domain names 
217
218                    Also don't allow "" as a domain, fixes a Win9X bug 
219                    where it doens't supply a domain for logon script
220                    'net use' commands.
221
222                    The way I do it here is by checking if the fully
223                    qualified username exists. This is rather reliant
224                    on winbind, but until we have a better method this
225                    will have to do 
226                 */
227
228                 domain = client_domain;
229
230                 if ((smb_name) && (*smb_name)) { /* Don't do this for guests */
231                         char *user = NULL;
232                         if (asprintf(&user, "%s%s%s", 
233                                  client_domain, lp_winbind_separator(), 
234                                  smb_name) < 0) {
235                                 DEBUG(0, ("make_user_info_map: asprintf() failed!\n"));
236                                 return NT_STATUS_NO_MEMORY;
237                         }
238
239                         DEBUG(5, ("make_user_info_map: testing for user %s\n", user));
240                         
241                         if (Get_Pwnam(user) == NULL) {
242                                 DEBUG(5, ("make_user_info_map: test for user %s failed\n", user));
243                                 domain = lp_workgroup();
244                                 DEBUG(5, ("make_user_info_map: trusted domain %s doesn't appear to exist, using %s\n", 
245                                           client_domain, domain));
246                         } else {
247                                 DEBUG(5, ("make_user_info_map: using trusted domain %s\n", domain));
248                         }
249                         SAFE_FREE(user);
250                 }
251         } else {
252                 domain = lp_workgroup();
253         }
254         
255         return make_user_info(user_info, 
256                               smb_name, internal_username,
257                               client_domain, domain,
258                               wksta_name, 
259                               lm_pwd, nt_pwd,
260                               plaintext, 
261                               ntlmssp_flags, encrypted);
262         
263 }
264
265 /****************************************************************************
266  Create an auth_usersupplied_data, making the DATA_BLOBs here. 
267  Decrypt and encrypt the passwords.
268 ****************************************************************************/
269
270 BOOL make_user_info_netlogon_network(auth_usersupplied_info **user_info, 
271                                      const char *smb_name, 
272                                      const char *client_domain, 
273                                      const char *wksta_name, 
274                                      const uchar *lm_network_pwd, int lm_pwd_len,
275                                      const uchar *nt_network_pwd, int nt_pwd_len)
276 {
277         BOOL ret;
278         NTSTATUS nt_status;
279         DATA_BLOB lm_blob = data_blob(lm_network_pwd, lm_pwd_len);
280         DATA_BLOB nt_blob = data_blob(nt_network_pwd, nt_pwd_len);
281         DATA_BLOB plaintext_blob = data_blob(NULL, 0);
282         uint32 auth_flags = AUTH_FLAG_NONE;
283
284         if (lm_pwd_len)
285                 auth_flags |= AUTH_FLAG_LM_RESP;
286         if (nt_pwd_len == 24) {
287                 auth_flags |= AUTH_FLAG_NTLM_RESP; 
288         } else if (nt_pwd_len != 0) {
289                 auth_flags |= AUTH_FLAG_NTLMv2_RESP; 
290         }
291
292         nt_status = make_user_info_map(user_info,
293                                       smb_name, client_domain, 
294                                   wksta_name, 
295                                       lm_blob, nt_blob,
296                                       plaintext_blob, 
297                                       auth_flags, True);
298         
299         ret = NT_STATUS_IS_OK(nt_status) ? True : False;
300                 
301         data_blob_free(&lm_blob);
302         data_blob_free(&nt_blob);
303         return ret;
304 }
305
306 /****************************************************************************
307  Create an auth_usersupplied_data, making the DATA_BLOBs here. 
308  Decrypt and encrypt the passwords.
309 ****************************************************************************/
310
311 BOOL make_user_info_netlogon_interactive(auth_usersupplied_info **user_info, 
312                                          const char *smb_name, 
313                                          const char *client_domain, 
314                                          const char *wksta_name, 
315                                          const uchar chal[8], 
316                                          const uchar lm_interactive_pwd[16], 
317                                          const uchar nt_interactive_pwd[16], 
318                                          const uchar *dc_sess_key)
319 {
320         char lm_pwd[16];
321         char nt_pwd[16];
322         unsigned char local_lm_response[24];
323         unsigned char local_nt_response[24];
324         unsigned char key[16];
325         uint32 auth_flags = AUTH_FLAG_NONE;
326         
327         ZERO_STRUCT(key);
328         memcpy(key, dc_sess_key, 8);
329         
330         if (lm_interactive_pwd) memcpy(lm_pwd, lm_interactive_pwd, sizeof(lm_pwd));
331         if (nt_interactive_pwd) memcpy(nt_pwd, nt_interactive_pwd, sizeof(nt_pwd));
332         
333 #ifdef DEBUG_PASSWORD
334         DEBUG(100,("key:"));
335         dump_data(100, (char *)key, sizeof(key));
336         
337         DEBUG(100,("lm owf password:"));
338         dump_data(100, lm_pwd, sizeof(lm_pwd));
339         
340         DEBUG(100,("nt owf password:"));
341         dump_data(100, nt_pwd, sizeof(nt_pwd));
342 #endif
343         
344         SamOEMhash((uchar *)lm_pwd, key, sizeof(lm_pwd));
345         SamOEMhash((uchar *)nt_pwd, key, sizeof(nt_pwd));
346         
347 #ifdef DEBUG_PASSWORD
348         DEBUG(100,("decrypt of lm owf password:"));
349         dump_data(100, lm_pwd, sizeof(lm_pwd));
350         
351         DEBUG(100,("decrypt of nt owf password:"));
352         dump_data(100, nt_pwd, sizeof(nt_pwd));
353 #endif
354         
355         SMBOWFencrypt((const unsigned char *)lm_pwd, chal, local_lm_response);
356         SMBOWFencrypt((const unsigned char *)nt_pwd, chal, local_nt_response);
357         
358         /* Password info paranoia */
359         ZERO_STRUCT(lm_pwd);
360         ZERO_STRUCT(nt_pwd);
361         ZERO_STRUCT(key);
362
363         {
364                 BOOL ret;
365                 NTSTATUS nt_status;
366                 DATA_BLOB local_lm_blob = data_blob(local_lm_response, sizeof(local_lm_response));
367                 DATA_BLOB local_nt_blob = data_blob(local_nt_response, sizeof(local_nt_response));
368                 DATA_BLOB plaintext_blob = data_blob(NULL, 0);
369
370                 if (lm_interactive_pwd)
371                         auth_flags |= AUTH_FLAG_LM_RESP;
372                 if (nt_interactive_pwd)
373                         auth_flags |= AUTH_FLAG_NTLM_RESP; 
374
375                 nt_status = make_user_info_map(user_info, 
376                                                smb_name, client_domain, 
377                                                wksta_name, 
378                                                local_lm_blob,
379                                                local_nt_blob,
380                                                plaintext_blob, 
381                                                auth_flags, True);
382                 
383                 ret = NT_STATUS_IS_OK(nt_status) ? True : False;
384                 data_blob_free(&local_lm_blob);
385                 data_blob_free(&local_nt_blob);
386                 return ret;
387         }
388 }
389
390
391 /****************************************************************************
392  Create an auth_usersupplied_data structure
393 ****************************************************************************/
394
395 BOOL make_user_info_for_reply(auth_usersupplied_info **user_info, 
396                               const char *smb_name, 
397                               const char *client_domain,
398                               const uint8 chal[8],
399                               DATA_BLOB plaintext_password)
400 {
401
402         DATA_BLOB local_lm_blob;
403         DATA_BLOB local_nt_blob;
404         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
405         uint32 auth_flags = AUTH_FLAG_NONE;
406                         
407         /*
408          * Not encrypted - do so.
409          */
410         
411         DEBUG(5,("make_user_info_for_reply: User passwords not in encrypted format.\n"));
412         
413         if (plaintext_password.data) {
414                 unsigned char local_lm_response[24];
415                 
416 #ifdef DEBUG_PASSWORD
417                 DEBUG(10,("Unencrypted password (len %d):\n",plaintext_password.length));
418                 dump_data(100, plaintext_password.data, plaintext_password.length);
419 #endif
420
421                 SMBencrypt( (const uchar *)plaintext_password.data, (const uchar*)chal, local_lm_response);
422                 local_lm_blob = data_blob(local_lm_response, 24);
423                 
424                 /* We can't do an NT hash here, as the password needs to be
425                    case insensitive */
426                 local_nt_blob = data_blob(NULL, 0); 
427                 
428                 auth_flags = (AUTH_FLAG_PLAINTEXT | AUTH_FLAG_LM_RESP);
429         } else {
430                 local_lm_blob = data_blob(NULL, 0); 
431                 local_nt_blob = data_blob(NULL, 0); 
432         }
433         
434         ret = make_user_info_map(user_info, smb_name,
435                                  client_domain, 
436                                  get_remote_machine_name(),
437                                  local_lm_blob,
438                                  local_nt_blob,
439                                  plaintext_password, 
440                                  auth_flags, False);
441         
442         data_blob_free(&local_lm_blob);
443         return NT_STATUS_IS_OK(ret) ? True : False;
444 }
445
446 /****************************************************************************
447  Create an auth_usersupplied_data structure
448 ****************************************************************************/
449
450 NTSTATUS make_user_info_for_reply_enc(auth_usersupplied_info **user_info, 
451                                       const char *smb_name,
452                                       const char *client_domain, 
453                                       DATA_BLOB lm_resp, DATA_BLOB nt_resp)
454 {
455         uint32 auth_flags = AUTH_FLAG_NONE;
456
457         DATA_BLOB no_plaintext_blob = data_blob(NULL, 0); 
458         
459         if (lm_resp.length == 24) {
460                 auth_flags |= AUTH_FLAG_LM_RESP;
461         }
462         if (nt_resp.length == 0) {
463         } else if (nt_resp.length == 24) {
464                 auth_flags |= AUTH_FLAG_NTLM_RESP;
465         } else {
466                 auth_flags |= AUTH_FLAG_NTLMv2_RESP;
467         }
468
469         return make_user_info_map(user_info, smb_name, 
470                                  client_domain, 
471                                  get_remote_machine_name(), 
472                                  lm_resp, 
473                                  nt_resp, 
474                                  no_plaintext_blob, 
475                                  auth_flags, True);
476 }
477
478 /****************************************************************************
479  Create a guest user_info blob, for anonymous authenticaion.
480 ****************************************************************************/
481
482 BOOL make_user_info_guest(auth_usersupplied_info **user_info) 
483 {
484         DATA_BLOB lm_blob = data_blob(NULL, 0);
485         DATA_BLOB nt_blob = data_blob(NULL, 0);
486         DATA_BLOB plaintext_blob = data_blob(NULL, 0);
487         uint32 auth_flags = AUTH_FLAG_NONE;
488         NTSTATUS nt_status;
489
490         nt_status = make_user_info(user_info, 
491                               "","", 
492                               "","", 
493                               "", 
494                               nt_blob, lm_blob,
495                               plaintext_blob, 
496                               auth_flags, True);
497                               
498         return NT_STATUS_IS_OK(nt_status) ? True : False;
499 }
500
501 /****************************************************************************
502  prints a NT_USER_TOKEN to debug output.
503 ****************************************************************************/
504
505 void debug_nt_user_token(int dbg_class, int dbg_lev, NT_USER_TOKEN *token)
506 {
507         fstring sid_str;
508         size_t     i;
509         
510         if (!token) {
511                 DEBUGC(dbg_class, dbg_lev, ("NT user token: (NULL)\n"));
512                 return;
513         }
514         
515         DEBUGC(dbg_class, dbg_lev, ("NT user token of user %s\n",
516                                     sid_to_string(sid_str, &token->user_sids[0]) ));
517         DEBUGADDC(dbg_class, dbg_lev, ("contains %i SIDs\n", token->num_sids));
518         for (i = 0; i < token->num_sids; i++)
519                 DEBUGADDC(dbg_class, dbg_lev, ("SID[%3i]: %s\n", i, 
520                                                sid_to_string(sid_str, &token->user_sids[i])));
521 }
522
523 /****************************************************************************
524  prints a UNIX 'token' to debug output.
525 ****************************************************************************/
526
527 void debug_unix_user_token(int dbg_class, int dbg_lev, uid_t uid, gid_t gid, int n_groups, gid_t *groups)
528 {
529         int     i;
530         DEBUGC(dbg_class, dbg_lev, ("UNIX token of user %ld\n", (long int)uid));
531
532         DEBUGADDC(dbg_class, dbg_lev, ("Primary group is %ld and contains %i supplementary groups\n", (long int)gid, n_groups));
533         for (i = 0; i < n_groups; i++)
534                 DEBUGADDC(dbg_class, dbg_lev, ("Group[%3i]: %ld\n", i, 
535                         (long int)groups[i]));
536 }
537
538 /****************************************************************************
539  Create the SID list for this user.
540 ****************************************************************************/
541
542 static NTSTATUS create_nt_user_token(const DOM_SID *user_sid, const DOM_SID *group_sid, 
543                                      int n_groupSIDs, DOM_SID *groupSIDs, 
544                                      BOOL is_guest, NT_USER_TOKEN **token)
545 {
546         NTSTATUS       nt_status = NT_STATUS_OK;
547         NT_USER_TOKEN *ptoken;
548         int i;
549         int sid_ndx;
550         
551         if ((ptoken = malloc( sizeof(NT_USER_TOKEN) ) ) == NULL) {
552                 DEBUG(0, ("create_nt_token: Out of memory allocating token\n"));
553                 nt_status = NT_STATUS_NO_MEMORY;
554                 return nt_status;
555         }
556
557         ZERO_STRUCTP(ptoken);
558
559         ptoken->num_sids = n_groupSIDs + 5;
560
561         if ((ptoken->user_sids = (DOM_SID *)malloc( sizeof(DOM_SID) * ptoken->num_sids )) == NULL) {
562                 DEBUG(0, ("create_nt_token: Out of memory allocating SIDs\n"));
563                 nt_status = NT_STATUS_NO_MEMORY;
564                 return nt_status;
565         }
566         
567         memset((char*)ptoken->user_sids,0,sizeof(DOM_SID) * ptoken->num_sids);
568         
569         /*
570          * Note - user SID *MUST* be first in token !
571          * se_access_check depends on this.
572          *
573          * Primary group SID is second in token. Convention.
574          */
575
576         sid_copy(&ptoken->user_sids[PRIMARY_USER_SID_INDEX], user_sid);
577         if (group_sid)
578                 sid_copy(&ptoken->user_sids[PRIMARY_GROUP_SID_INDEX], group_sid);
579
580         /*
581          * Finally add the "standard" SIDs.
582          * The only difference between guest and "anonymous" (which we
583          * don't really support) is the addition of Authenticated_Users.
584          */
585
586         sid_copy(&ptoken->user_sids[2], &global_sid_World);
587         sid_copy(&ptoken->user_sids[3], &global_sid_Network);
588
589         if (is_guest)
590                 sid_copy(&ptoken->user_sids[4], &global_sid_Builtin_Guests);
591         else
592                 sid_copy(&ptoken->user_sids[4], &global_sid_Authenticated_Users);
593         
594         sid_ndx = 5; /* next available spot */
595
596         for (i = 0; i < n_groupSIDs; i++) {
597                 size_t check_sid_idx;
598                 for (check_sid_idx = 1; check_sid_idx < ptoken->num_sids; check_sid_idx++) {
599                         if (sid_equal(&ptoken->user_sids[check_sid_idx], 
600                                       &groupSIDs[i])) {
601                                 break;
602                         }
603                 }
604                 
605                 if (check_sid_idx >= ptoken->num_sids) /* Not found already */ {
606                         sid_copy(&ptoken->user_sids[sid_ndx++], &groupSIDs[i]);
607                 } else {
608                         ptoken->num_sids--;
609                 }
610         }
611         
612         debug_nt_user_token(DBGC_AUTH, 10, ptoken);
613         
614         *token = ptoken;
615
616         return nt_status;
617 }
618
619 /****************************************************************************
620  Create the SID list for this user.
621 ****************************************************************************/
622
623 NT_USER_TOKEN *create_nt_token(uid_t uid, gid_t gid, int ngroups, gid_t *groups, BOOL is_guest)
624 {
625         DOM_SID user_sid;
626         DOM_SID group_sid;
627         DOM_SID *group_sids;
628         NT_USER_TOKEN *token;
629         int i;
630
631         if (!uid_to_sid(&user_sid, uid)) {
632                 return NULL;
633         }
634         if (!gid_to_sid(&group_sid, gid)) {
635                 return NULL;
636         }
637
638         group_sids   = malloc(sizeof(DOM_SID) * ngroups);
639         if (!group_sids) {
640                 DEBUG(0, ("create_nt_token: malloc() failed for DOM_SID list!\n"));
641                 return NULL;
642         }
643
644         for (i = 0; i < ngroups; i++) {
645                 if (!gid_to_sid(&(group_sids)[i], (groups)[i])) {
646                         DEBUG(1, ("create_nt_token: failed to convert gid %ld to a sid!\n", (long int)groups[i]));
647                         SAFE_FREE(group_sids);
648                         return NULL;
649                 }
650         }
651
652         if (!NT_STATUS_IS_OK(create_nt_user_token(&user_sid, &group_sid, 
653                                                   ngroups, group_sids, is_guest, &token))) {
654                 SAFE_FREE(group_sids);
655                 return NULL;
656         }
657
658         SAFE_FREE(group_sids);
659
660         return token;
661 }
662
663 /******************************************************************************
664  * this function returns the groups (SIDs) of the local SAM the user is in.
665  * If this samba server is a DC of the domain the user belongs to, it returns 
666  * both domain groups and local / builtin groups. If the user is in a trusted
667  * domain, or samba is a member server of a domain, then this function returns
668  * local and builtin groups the user is a member of. 
669  *
670  * currently this is a hack, as there is no sam implementation that is capable
671  * of groups.
672  ******************************************************************************/
673
674 static NTSTATUS get_user_groups_from_local_sam(SAM_ACCOUNT *sampass,
675                                                int *n_groups, DOM_SID **groups, gid_t **unix_groups)
676 {
677         uid_t             uid;
678         gid_t             gid;
679         int               n_unix_groups;
680         int               i;
681         struct passwd    *usr;  
682
683         *n_groups = 0;
684         *groups   = NULL;
685
686         if (!IS_SAM_UNIX_USER(sampass)) {
687                 DEBUG(1, ("user %s does not have a unix identity!\n", pdb_get_username(sampass)));
688                 return NT_STATUS_NO_SUCH_USER;
689         }
690
691         uid = pdb_get_uid(sampass);
692         gid = pdb_get_gid(sampass);
693         
694         n_unix_groups = groups_max();
695         if ((*unix_groups = malloc( sizeof(gid_t) * n_unix_groups ) ) == NULL) {
696                 DEBUG(0, ("get_user_groups_from_local_sam: Out of memory allocating unix group list\n"));
697                 passwd_free(&usr);
698                 return NT_STATUS_NO_MEMORY;
699         }
700         
701         if (sys_getgrouplist(pdb_get_username(sampass), gid, *unix_groups, &n_unix_groups) == -1) {
702                 gid_t *groups_tmp;
703                 groups_tmp = Realloc(*unix_groups, sizeof(gid_t) * n_unix_groups);
704                 if (!groups_tmp) {
705                         SAFE_FREE(*unix_groups);
706                         passwd_free(&usr);
707                         return NT_STATUS_NO_MEMORY;
708                 }
709                 *unix_groups = groups_tmp;
710
711                 if (sys_getgrouplist(pdb_get_username(sampass), gid, *unix_groups, &n_unix_groups) == -1) {
712                         DEBUG(0, ("get_user_groups_from_local_sam: failed to get the unix group list\n"));
713                         SAFE_FREE(*unix_groups);
714                         passwd_free(&usr);
715                         return NT_STATUS_NO_SUCH_USER; /* what should this return value be? */
716                 }
717         }
718
719         debug_unix_user_token(DBGC_CLASS, 5, uid, gid, n_unix_groups, *unix_groups);
720         
721         if (n_unix_groups > 0) {
722                 *groups   = malloc(sizeof(DOM_SID) * n_unix_groups);
723                 if (!*groups) {
724                         DEBUG(0, ("get_user_group_from_local_sam: malloc() failed for DOM_SID list!\n"));
725                         SAFE_FREE(*unix_groups);
726                         return NT_STATUS_NO_MEMORY;
727                 }
728         }
729
730         *n_groups = n_unix_groups;
731
732         for (i = 0; i < *n_groups; i++) {
733                 if (!gid_to_sid(&(*groups)[i], (*unix_groups)[i])) {
734                         DEBUG(1, ("get_user_groups_from_local_sam: failed to convert gid %ld to a sid!\n", (long int)(*unix_groups)[i+1]));
735                         SAFE_FREE(*groups);
736                         SAFE_FREE(*unix_groups);
737                         return NT_STATUS_NO_SUCH_USER;
738                 }
739         }
740                      
741         return NT_STATUS_OK;
742 }
743
744 /***************************************************************************
745  Make a user_info struct
746 ***************************************************************************/
747
748 static NTSTATUS make_server_info(auth_serversupplied_info **server_info, SAM_ACCOUNT *sampass)
749 {
750         *server_info = malloc(sizeof(**server_info));
751         if (!*server_info) {
752                 DEBUG(0,("make_server_info: malloc failed!\n"));
753                 return NT_STATUS_NO_MEMORY;
754         }
755         ZERO_STRUCTP(*server_info);
756
757         (*server_info)->sam_fill_level = SAM_FILL_ALL;
758         (*server_info)->sam_account    = sampass;
759
760         return NT_STATUS_OK;
761 }
762
763 /***************************************************************************
764  Make (and fill) a user_info struct from a SAM_ACCOUNT
765 ***************************************************************************/
766
767 NTSTATUS make_server_info_sam(auth_serversupplied_info **server_info, 
768                               SAM_ACCOUNT *sampass)
769 {
770         NTSTATUS nt_status = NT_STATUS_OK;
771         const DOM_SID *user_sid = pdb_get_user_sid(sampass);
772         const DOM_SID *group_sid = pdb_get_group_sid(sampass);
773         int       n_groupSIDs = 0;
774         DOM_SID  *groupSIDs   = NULL;
775         gid_t    *unix_groups = NULL;
776         NT_USER_TOKEN *token;
777         BOOL is_guest;
778         uint32 rid;
779
780         if (!NT_STATUS_IS_OK(nt_status = make_server_info(server_info, sampass))) {
781                 return nt_status;
782         }
783         
784         if (!NT_STATUS_IS_OK(nt_status 
785                              = get_user_groups_from_local_sam(sampass, 
786                 &n_groupSIDs, &groupSIDs, &unix_groups)))
787         {
788                 DEBUG(4,("get_user_groups_from_local_sam failed\n"));
789                 free_server_info(server_info);
790                 return nt_status;
791         }
792         
793         is_guest = (sid_peek_rid(user_sid, &rid) && rid == DOMAIN_USER_RID_GUEST);
794
795         if (!NT_STATUS_IS_OK(nt_status = create_nt_user_token(user_sid, group_sid,
796                                                               n_groupSIDs, groupSIDs, is_guest, 
797                                                               &token)))
798         {
799                 DEBUG(4,("create_nt_user_token failed\n"));
800                 SAFE_FREE(groupSIDs);
801                 SAFE_FREE(unix_groups);
802                 free_server_info(server_info);
803                 return nt_status;
804         }
805         
806         SAFE_FREE(groupSIDs);
807
808         (*server_info)->n_groups = n_groupSIDs;
809         (*server_info)->groups = unix_groups;
810
811         (*server_info)->ptok = token;
812         
813         DEBUG(5,("make_server_info_sam: made server info for user %s\n",
814                  pdb_get_username((*server_info)->sam_account)));
815
816         return nt_status;
817 }
818
819 /***************************************************************************
820  Make (and fill) a user_info struct from a 'struct passwd' by conversion 
821  to a SAM_ACCOUNT
822 ***************************************************************************/
823
824 NTSTATUS make_server_info_pw(auth_serversupplied_info **server_info, const struct passwd *pwd)
825 {
826         NTSTATUS nt_status;
827         SAM_ACCOUNT *sampass = NULL;
828         if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam_pw(&sampass, pwd))) {             
829                 return nt_status;
830         }
831         return make_server_info_sam(server_info, sampass);
832 }
833
834 /***************************************************************************
835  Make (and fill) a user_info struct for a guest login.
836 ***************************************************************************/
837
838 NTSTATUS make_server_info_guest(auth_serversupplied_info **server_info)
839 {
840         NTSTATUS nt_status;
841         SAM_ACCOUNT *sampass = NULL;
842         DOM_SID guest_sid;
843
844         if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam(&sampass))) {
845                 return nt_status;
846         }
847
848         sid_copy(&guest_sid, get_global_sam_sid());
849         sid_append_rid(&guest_sid, DOMAIN_USER_RID_GUEST);
850
851         become_root();
852         if (!pdb_getsampwsid(sampass, &guest_sid)) {
853                 unbecome_root();
854                 return NT_STATUS_NO_SUCH_USER;
855         }
856         unbecome_root();
857
858         nt_status = make_server_info_sam(server_info, sampass);
859
860         if (NT_STATUS_IS_OK(nt_status)) {
861                 (*server_info)->guest = True;
862         }
863
864         return nt_status;
865 }
866
867 /***************************************************************************
868  Make a server_info struct from the info3 returned by a domain logon 
869 ***************************************************************************/
870
871 NTSTATUS make_server_info_info3(TALLOC_CTX *mem_ctx, 
872                                 const char *internal_username,
873                                 const char *sent_nt_username,
874                                 const char *domain,
875                                 auth_serversupplied_info **server_info, 
876                                 NET_USER_INFO_3 *info3) 
877 {
878         NTSTATUS nt_status = NT_STATUS_OK;
879
880         const char *nt_domain;
881         const char *nt_username;
882
883         SAM_ACCOUNT *sam_account = NULL;
884         DOM_SID user_sid;
885         DOM_SID group_sid;
886
887         struct passwd *passwd;
888
889         uid_t uid;
890         gid_t gid;
891
892         int n_lgroupSIDs;
893         DOM_SID *lgroupSIDs   = NULL;
894
895         gid_t *unix_groups = NULL;
896         NT_USER_TOKEN *token;
897
898         DOM_SID *all_group_SIDs;
899         size_t i;
900
901         /* 
902            Here is where we should check the list of
903            trusted domains, and verify that the SID 
904            matches.
905         */
906
907         sid_copy(&user_sid, &info3->dom_sid.sid);
908         if (!sid_append_rid(&user_sid, info3->user_rid)) {
909                 return NT_STATUS_INVALID_PARAMETER;
910         }
911         
912         sid_copy(&group_sid, &info3->dom_sid.sid);
913         if (!sid_append_rid(&group_sid, info3->group_rid)) {
914                 return NT_STATUS_INVALID_PARAMETER;
915         }
916
917         if (!(nt_username = unistr2_tdup(mem_ctx, &(info3->uni_user_name)))) {
918                 /* If the server didn't give us one, just use the one we sent them */
919                 nt_username = sent_nt_username;
920         }
921
922         if (!(nt_domain = unistr2_tdup(mem_ctx, &(info3->uni_logon_dom)))) {
923                 /* If the server didn't give us one, just use the one we sent them */
924                 domain = domain;
925         }
926
927         if (winbind_sid_to_uid(&uid, &user_sid) 
928             && winbind_sid_to_gid(&gid, &group_sid) 
929             && ((passwd = getpwuid_alloc(uid)))) {
930                 nt_status = pdb_init_sam_pw(&sam_account, passwd);
931                 passwd_free(&passwd);
932         } else {
933                 char *dom_user;
934                 dom_user = talloc_asprintf(mem_ctx, "%s%s%s", 
935                                            nt_domain,
936                                            lp_winbind_separator(),
937                                            internal_username);
938                 
939                 if (!dom_user) {
940                         DEBUG(0, ("talloc_asprintf failed!\n"));
941                         return NT_STATUS_NO_MEMORY;
942                 } else { 
943                 
944                         if (!(passwd = Get_Pwnam(dom_user))
945                                 /* Only lookup local for the local
946                                    domain, we don't want this for
947                                    trusted domains */
948                             && strequal(nt_domain, lp_workgroup())) {
949                                 passwd = Get_Pwnam(internal_username);
950                         }
951                             
952                         if (!passwd) {
953                                 return NT_STATUS_NO_SUCH_USER;
954                         } else {
955                                 nt_status = pdb_init_sam_pw(&sam_account, passwd);
956                         }
957                 }
958         }
959         
960         if (!NT_STATUS_IS_OK(nt_status)) {
961                 DEBUG(0, ("make_server_info_info3: pdb_init_sam failed!\n"));
962                 return nt_status;
963         }
964                 
965         if (!pdb_set_user_sid(sam_account, &user_sid, PDB_CHANGED)) {
966                 pdb_free_sam(&sam_account);
967                 return NT_STATUS_UNSUCCESSFUL;
968         }
969
970         if (!pdb_set_group_sid(sam_account, &group_sid, PDB_CHANGED)) {
971                 pdb_free_sam(&sam_account);
972                 return NT_STATUS_UNSUCCESSFUL;
973         }
974                 
975         if (!pdb_set_nt_username(sam_account, nt_username, PDB_CHANGED)) {
976                 pdb_free_sam(&sam_account);
977                 return NT_STATUS_NO_MEMORY;
978         }
979
980         if (!pdb_set_domain(sam_account, nt_domain, PDB_CHANGED)) {
981                 pdb_free_sam(&sam_account);
982                 return NT_STATUS_NO_MEMORY;
983         }
984
985         if (!pdb_set_fullname(sam_account, unistr2_static(&(info3->uni_full_name)), PDB_CHANGED)) {
986                 pdb_free_sam(&sam_account);
987                 return NT_STATUS_NO_MEMORY;
988         }
989
990         if (!pdb_set_logon_script(sam_account, unistr2_static(&(info3->uni_logon_script)), PDB_CHANGED)) {
991                 pdb_free_sam(&sam_account);
992                 return NT_STATUS_NO_MEMORY;
993         }
994
995         if (!pdb_set_profile_path(sam_account, unistr2_static(&(info3->uni_profile_path)), PDB_CHANGED)) {
996                 pdb_free_sam(&sam_account);
997                 return NT_STATUS_NO_MEMORY;
998         }
999
1000         if (!pdb_set_homedir(sam_account, unistr2_static(&(info3->uni_home_dir)), PDB_CHANGED)) {
1001                 pdb_free_sam(&sam_account);
1002                 return NT_STATUS_NO_MEMORY;
1003         }
1004
1005         if (!pdb_set_dir_drive(sam_account, unistr2_static(&(info3->uni_dir_drive)), PDB_CHANGED)) {
1006                 pdb_free_sam(&sam_account);
1007                 return NT_STATUS_NO_MEMORY;
1008         }
1009
1010         if (!NT_STATUS_IS_OK(nt_status = make_server_info(server_info, sam_account))) {
1011                 DEBUG(4, ("make_server_info failed!\n"));
1012                 pdb_free_sam(&sam_account);
1013                 return nt_status;
1014         }
1015
1016         /* Store the user group information in the server_info 
1017            returned to the caller. */
1018         
1019         if (!NT_STATUS_IS_OK(nt_status 
1020                              = get_user_groups_from_local_sam(sam_account, 
1021                                                               &n_lgroupSIDs, 
1022                                                               &lgroupSIDs, 
1023                                                               &unix_groups)))
1024         {
1025                 DEBUG(4,("get_user_groups_from_local_sam failed\n"));
1026                 return nt_status;
1027         }
1028
1029         (*server_info)->groups = unix_groups;
1030         (*server_info)->n_groups = n_lgroupSIDs;
1031         
1032         /* Create a 'combined' list of all SIDs we might want in the SD */
1033         all_group_SIDs   = malloc(sizeof(DOM_SID) * 
1034                                   (n_lgroupSIDs + info3->num_groups2 +
1035                                    info3->num_other_sids));
1036         if (!all_group_SIDs) {
1037                 DEBUG(0, ("create_nt_token_info3: malloc() failed for DOM_SID list!\n"));
1038                 SAFE_FREE(lgroupSIDs);
1039                 return NT_STATUS_NO_MEMORY;
1040         }
1041
1042         /* Copy the 'local' sids */
1043         memcpy(all_group_SIDs, lgroupSIDs, sizeof(DOM_SID) * n_lgroupSIDs);
1044         SAFE_FREE(lgroupSIDs);
1045
1046         /* and create (by appending rids) the 'domain' sids */
1047         for (i = 0; i < info3->num_groups2; i++) {
1048                 sid_copy(&all_group_SIDs[i+n_lgroupSIDs], &(info3->dom_sid.sid));
1049                 if (!sid_append_rid(&all_group_SIDs[i+n_lgroupSIDs], info3->gids[i].g_rid)) {
1050                         nt_status = NT_STATUS_INVALID_PARAMETER;
1051                         DEBUG(3,("create_nt_token_info3: could not append additional group rid 0x%x\n",
1052                                 info3->gids[i].g_rid));                 
1053                         SAFE_FREE(lgroupSIDs);
1054                         return nt_status;
1055                 }
1056         }
1057
1058         /* Copy 'other' sids.  We need to do sid filtering here to
1059            prevent possible elevation of privileges.  See:
1060
1061            http://www.microsoft.com/windows2000/techinfo/administration/security/sidfilter.asp
1062          */
1063
1064         for (i = 0; i < info3->num_other_sids; i++) 
1065                 sid_copy(&all_group_SIDs[
1066                                  n_lgroupSIDs + info3->num_groups2 + i],
1067                          &info3->other_sids[i].sid);
1068         
1069         /* Where are the 'global' sids... */
1070
1071         /* can the user be guest? if yes, where is it stored? */
1072         if (!NT_STATUS_IS_OK(
1073                     nt_status = create_nt_user_token(
1074                             &user_sid, &group_sid,
1075                             n_lgroupSIDs + info3->num_groups2 + info3->num_other_sids, 
1076                             all_group_SIDs, False, &token))) {
1077                 DEBUG(4,("create_nt_user_token failed\n"));
1078                 SAFE_FREE(all_group_SIDs);
1079                 return nt_status;
1080         }
1081
1082         (*server_info)->ptok = token; 
1083
1084         SAFE_FREE(all_group_SIDs);
1085         
1086         memcpy((*server_info)->session_key, info3->user_sess_key, sizeof((*server_info)->session_key)/* 16 */);
1087         memcpy((*server_info)->first_8_lm_hash, info3->padding, 8);
1088
1089         return NT_STATUS_OK;
1090 }
1091
1092 /***************************************************************************
1093  Free a user_info struct
1094 ***************************************************************************/
1095
1096 void free_user_info(auth_usersupplied_info **user_info)
1097 {
1098         DEBUG(5,("attempting to free (and zero) a user_info structure\n"));
1099         if (*user_info != NULL) {
1100                 if ((*user_info)->smb_name.str) {
1101                         DEBUG(10,("structure was created for %s\n", (*user_info)->smb_name.str));
1102                 }
1103                 SAFE_FREE((*user_info)->smb_name.str);
1104                 SAFE_FREE((*user_info)->internal_username.str);
1105                 SAFE_FREE((*user_info)->client_domain.str);
1106                 SAFE_FREE((*user_info)->domain.str);
1107                 SAFE_FREE((*user_info)->wksta_name.str);
1108                 data_blob_free(&(*user_info)->lm_resp);
1109                 data_blob_free(&(*user_info)->nt_resp);
1110                 SAFE_FREE((*user_info)->interactive_password);
1111                 data_blob_clear_free(&(*user_info)->plaintext_password);
1112                 ZERO_STRUCT(**user_info);
1113         }
1114         SAFE_FREE(*user_info);
1115 }
1116
1117 /***************************************************************************
1118  Clear out a server_info struct that has been allocated
1119 ***************************************************************************/
1120
1121 void free_server_info(auth_serversupplied_info **server_info)
1122 {
1123         DEBUG(5,("attempting to free (and zero) a server_info structure\n"));
1124         if (*server_info != NULL) {
1125                 pdb_free_sam(&(*server_info)->sam_account);
1126
1127                 /* call pam_end here, unless we know we are keeping it */
1128                 delete_nt_token( &(*server_info)->ptok );
1129                 SAFE_FREE((*server_info)->groups);
1130                 ZERO_STRUCT(**server_info);
1131         }
1132         SAFE_FREE(*server_info);
1133 }
1134
1135 /***************************************************************************
1136  Make an auth_methods struct
1137 ***************************************************************************/
1138
1139 BOOL make_auth_methods(struct auth_context *auth_context, auth_methods **auth_method) 
1140 {
1141         if (!auth_context) {
1142                 smb_panic("no auth_context supplied to make_auth_methods()!\n");
1143         }
1144
1145         if (!auth_method) {
1146                 smb_panic("make_auth_methods: pointer to auth_method pointer is NULL!\n");
1147         }
1148
1149         *auth_method = talloc(auth_context->mem_ctx, sizeof(**auth_method));
1150         if (!*auth_method) {
1151                 DEBUG(0,("make_auth_method: malloc failed!\n"));
1152                 return False;
1153         }
1154         ZERO_STRUCTP(*auth_method);
1155         
1156         return True;
1157 }
1158
1159 /****************************************************************************
1160  Delete a SID token.
1161 ****************************************************************************/
1162
1163 void delete_nt_token(NT_USER_TOKEN **pptoken)
1164 {
1165     if (*pptoken) {
1166             NT_USER_TOKEN *ptoken = *pptoken;
1167             SAFE_FREE( ptoken->user_sids );
1168             ZERO_STRUCTP(ptoken);
1169     }
1170     SAFE_FREE(*pptoken);
1171 }
1172
1173 /****************************************************************************
1174  Duplicate a SID token.
1175 ****************************************************************************/
1176
1177 NT_USER_TOKEN *dup_nt_token(NT_USER_TOKEN *ptoken)
1178 {
1179         NT_USER_TOKEN *token;
1180
1181         if (!ptoken)
1182                 return NULL;
1183
1184     if ((token = (NT_USER_TOKEN *)malloc( sizeof(NT_USER_TOKEN) ) ) == NULL)
1185         return NULL;
1186
1187     ZERO_STRUCTP(token);
1188
1189     if ((token->user_sids = (DOM_SID *)memdup( ptoken->user_sids, sizeof(DOM_SID) * ptoken->num_sids )) == NULL) {
1190         SAFE_FREE(token);
1191         return NULL;
1192     }
1193
1194     token->num_sids = ptoken->num_sids;
1195
1196         return token;
1197 }
1198
1199 /**
1200  * Squash an NT_STATUS in line with security requirements.
1201  * In an attempt to avoid giving the whole game away when users
1202  * are authenticating, NT replaces both NT_STATUS_NO_SUCH_USER and 
1203  * NT_STATUS_WRONG_PASSWORD with NT_STATUS_LOGON_FAILURE in certain situations 
1204  * (session setups in particular).
1205  *
1206  * @param nt_status NTSTATUS input for squashing.
1207  * @return the 'squashed' nt_status
1208  **/
1209
1210 NTSTATUS nt_status_squash(NTSTATUS nt_status)
1211 {
1212         if NT_STATUS_IS_OK(nt_status) {
1213                 return nt_status;               
1214         } else if NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER) {
1215                 /* Match WinXP and don't give the game away */
1216                 return NT_STATUS_LOGON_FAILURE;
1217                 
1218         } else if NT_STATUS_EQUAL(nt_status, NT_STATUS_WRONG_PASSWORD) {
1219                 /* Match WinXP and don't give the game away */
1220                 return NT_STATUS_LOGON_FAILURE;
1221         } else {
1222                 return nt_status;
1223         }  
1224 }
1225
1226
1227