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