off by one in writing to malloced array. this fixes smbd crash I saw at
[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
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", 
631                           sid_to_string(str, user_sid)));
632                 /* This might be a non-unix account */
633                 return NT_STATUS_OK;
634         }
635
636         usr = getpwuid_alloc(uid);
637         
638         n_unix_groups = groups_max();
639         if ((*unix_groups = malloc( sizeof(gid_t) * groups_max() ) ) == NULL) {
640                 DEBUG(0, ("get_user_groups_from_local_sam: Out of memory allocating unix group list\n"));
641                 passwd_free(&usr);
642                 return NT_STATUS_NO_MEMORY;
643         }
644         
645         if (sys_getgrouplist(usr->pw_name, usr->pw_gid, *unix_groups, &n_unix_groups) == -1) {
646                 *unix_groups = Realloc(unix_groups, sizeof(gid_t) * n_unix_groups);
647                 if (sys_getgrouplist(usr->pw_name, usr->pw_gid, *unix_groups, &n_unix_groups) == -1) {
648                         DEBUG(0, ("get_user_groups_from_local_sam: failed to get the unix group list\n"));
649                         SAFE_FREE(unix_groups);
650                         passwd_free(&usr);
651                         return NT_STATUS_NO_SUCH_USER; /* what should this return value be? */
652                 }
653         }
654
655         passwd_free(&usr);
656         
657         DEBUG(5,("get_user_groups_from_local_sam: user is in the unix following groups\n"));
658         for (i = 0; i < n_unix_groups; i++)
659                 DEBUGADD(5,("supplementary group gid:%ld\n",(long int)(*unix_groups)[i]));
660
661         if (n_unix_groups > 0) {
662                 *groups   = malloc(sizeof(DOM_SID) * n_unix_groups);
663                 if (!*groups) {
664                         DEBUG(0, ("get_user_group_from_local_sam: malloc() failed for DOM_SID list!\n"));
665                         SAFE_FREE(unix_groups);
666                         return NT_STATUS_NO_MEMORY;
667                 }
668         }
669
670         *n_groups = n_unix_groups;
671
672         for (i = 0; i < *n_groups; i++) {
673                 if (!gid_to_sid(&(*groups)[i], (*unix_groups)[i])) {
674                         DEBUG(1, ("get_user_groups_from_local_sam: failed to convert gid %ld to a sid!\n", (long int)unix_groups[i+1]));
675                         SAFE_FREE(groups);
676                         SAFE_FREE(unix_groups);
677                         return NT_STATUS_NO_SUCH_USER;
678                 }
679         }
680                      
681         return NT_STATUS_OK;
682 }
683
684 /***************************************************************************
685  Make a user_info struct
686 ***************************************************************************/
687
688 static NTSTATUS make_server_info(auth_serversupplied_info **server_info, SAM_ACCOUNT *sampass)
689 {
690         *server_info = malloc(sizeof(**server_info));
691         if (!*server_info) {
692                 DEBUG(0,("make_server_info: malloc failed!\n"));
693                 return NT_STATUS_NO_MEMORY;
694         }
695         ZERO_STRUCTP(*server_info);
696
697         (*server_info)->sam_fill_level = SAM_FILL_ALL;
698         (*server_info)->sam_account    = sampass;
699
700         return NT_STATUS_OK;
701 }
702
703 /***************************************************************************
704  Make (and fill) a user_info struct from a SAM_ACCOUNT
705 ***************************************************************************/
706
707 NTSTATUS make_server_info_sam(auth_serversupplied_info **server_info, 
708                               SAM_ACCOUNT *sampass)
709 {
710         NTSTATUS nt_status = NT_STATUS_OK;
711         const DOM_SID *user_sid = pdb_get_user_sid(sampass);
712         const DOM_SID *group_sid = pdb_get_group_sid(sampass);
713         int       n_groupSIDs = 0;
714         DOM_SID  *groupSIDs   = NULL;
715         gid_t    *unix_groups = NULL;
716         NT_USER_TOKEN *token;
717         BOOL is_guest;
718         uint32 rid;
719
720         if (!NT_STATUS_IS_OK(nt_status = make_server_info(server_info, sampass))) {
721                 return nt_status;
722         }
723         
724         if (!NT_STATUS_IS_OK(nt_status 
725                              = get_user_groups_from_local_sam(pdb_get_user_sid(sampass), 
726                 &n_groupSIDs, &groupSIDs, &unix_groups)))
727         {
728                 DEBUG(4,("get_user_groups_from_local_sam failed\n"));
729                 free_server_info(server_info);
730                 return nt_status;
731         }
732         
733         is_guest = (sid_peek_rid(user_sid, &rid) && rid == DOMAIN_USER_RID_GUEST);
734
735         if (!NT_STATUS_IS_OK(nt_status = create_nt_user_token(user_sid, group_sid,
736                                                               n_groupSIDs, groupSIDs, is_guest, 
737                                                               &token)))
738         {
739                 DEBUG(4,("create_nt_user_token failed\n"));
740                 SAFE_FREE(groupSIDs);
741                 SAFE_FREE(unix_groups);
742                 free_server_info(server_info);
743                 return nt_status;
744         }
745         
746         SAFE_FREE(groupSIDs);
747
748         (*server_info)->n_groups = n_groupSIDs;
749         (*server_info)->groups = unix_groups;
750
751         (*server_info)->ptok = token;
752         
753         debug_nt_user_token(DBGC_AUTH, 5, token);
754
755         DEBUG(5,("make_server_info_sam: made server info for user %s\n",
756                  pdb_get_username((*server_info)->sam_account)));
757
758         return nt_status;
759 }
760
761 /***************************************************************************
762  Make (and fill) a user_info struct from a 'struct passwd' by conversion 
763  to a SAM_ACCOUNT
764 ***************************************************************************/
765
766 NTSTATUS make_server_info_pw(auth_serversupplied_info **server_info, const struct passwd *pwd)
767 {
768         NTSTATUS nt_status;
769         SAM_ACCOUNT *sampass = NULL;
770         if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam_pw(&sampass, pwd))) {             
771                 return nt_status;
772         }
773         return make_server_info_sam(server_info, sampass);
774 }
775
776 /***************************************************************************
777  Make (and fill) a user_info struct for a guest login.
778 ***************************************************************************/
779
780 NTSTATUS make_server_info_guest(auth_serversupplied_info **server_info)
781 {
782         NTSTATUS nt_status;
783         SAM_ACCOUNT *sampass = NULL;
784         DOM_SID guest_sid;
785
786         if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam(&sampass))) {
787                 return nt_status;
788         }
789
790         sid_copy(&guest_sid, get_global_sam_sid());
791         sid_append_rid(&guest_sid, DOMAIN_USER_RID_GUEST);
792
793         if (!pdb_getsampwsid(sampass, &guest_sid)) {
794                 return NT_STATUS_NO_SUCH_USER;
795         }
796
797         nt_status = make_server_info_sam(server_info, sampass);
798
799         (*server_info)->guest = True;
800
801         return nt_status;
802 }
803
804 /***************************************************************************
805  Make a server_info struct from the info3 returned by a domain logon 
806 ***************************************************************************/
807
808 NTSTATUS make_server_info_info3(TALLOC_CTX *mem_ctx, 
809                                 const char *internal_username,
810                                 const char *sent_nt_username,
811                                 const char *domain,
812                                 auth_serversupplied_info **server_info, 
813                                 NET_USER_INFO_3 *info3) 
814 {
815         NTSTATUS nt_status = NT_STATUS_OK;
816
817         const char *nt_domain;
818         const char *nt_username;
819
820         SAM_ACCOUNT *sam_account = NULL;
821         DOM_SID user_sid;
822         DOM_SID group_sid;
823
824         struct passwd *passwd;
825
826         uid_t uid;
827         gid_t gid;
828
829         int n_lgroupSIDs;
830         DOM_SID *lgroupSIDs   = NULL;
831
832         gid_t *unix_groups = NULL;
833         NT_USER_TOKEN *token;
834
835         DOM_SID *all_group_SIDs;
836         int i;
837
838         /* 
839            Here is where we should check the list of
840            trusted domains, and verify that the SID 
841            matches.
842         */
843
844         sid_copy(&user_sid, &info3->dom_sid.sid);
845         if (!sid_append_rid(&user_sid, info3->user_rid)) {
846                 return NT_STATUS_INVALID_PARAMETER;
847         }
848         
849         sid_copy(&group_sid, &info3->dom_sid.sid);
850         if (!sid_append_rid(&group_sid, info3->group_rid)) {
851                 return NT_STATUS_INVALID_PARAMETER;
852         }
853
854         if (!(nt_username = unistr2_tdup(mem_ctx, &(info3->uni_user_name)))) {
855                 /* If the server didn't give us one, just use the one we sent them */
856                 nt_username = sent_nt_username;
857         }
858
859         if (!(nt_domain = unistr2_tdup(mem_ctx, &(info3->uni_logon_dom)))) {
860                 /* If the server didn't give us one, just use the one we sent them */
861                 domain = domain;
862         }
863
864         if (winbind_sid_to_uid(&uid, &user_sid) 
865             && winbind_sid_to_gid(&gid, &group_sid) 
866             && ((passwd = getpwuid_alloc(uid)))) {
867                 nt_status = pdb_init_sam_pw(&sam_account, passwd);
868                 passwd_free(&passwd);
869         } else {
870                 char *dom_user;
871                 dom_user = talloc_asprintf(mem_ctx, "%s%s%s", 
872                                            nt_domain,
873                                            lp_winbind_separator(),
874                                            internal_username);
875                 
876                 if (!dom_user) {
877                         DEBUG(0, ("talloc_asprintf failed!\n"));
878                         return NT_STATUS_NO_MEMORY;
879                 } else { 
880                 
881                         if (!(passwd = Get_Pwnam(dom_user))
882                                 /* Only lookup local for the local
883                                    domain, we don't want this for
884                                    trusted domains */
885                             && strequal(nt_domain, lp_workgroup())) {
886                                 passwd = Get_Pwnam(internal_username);
887                         }
888                             
889                         if (!passwd) {
890                                 return NT_STATUS_NO_SUCH_USER;
891                         } else {
892                                 nt_status = pdb_init_sam_pw(&sam_account, passwd);
893                         }
894                 }
895         }
896         
897         if (!NT_STATUS_IS_OK(nt_status)) {
898                 DEBUG(0, ("make_server_info_info3: pdb_init_sam failed!\n"));
899                 return nt_status;
900         }
901                 
902         if (!pdb_set_user_sid(sam_account, &user_sid)) {
903                 pdb_free_sam(&sam_account);
904                 return NT_STATUS_UNSUCCESSFUL;
905         }
906
907         if (!pdb_set_group_sid(sam_account, &group_sid)) {
908                 pdb_free_sam(&sam_account);
909                 return NT_STATUS_UNSUCCESSFUL;
910         }
911                 
912         if (!pdb_set_nt_username(sam_account, nt_username)) {
913                 pdb_free_sam(&sam_account);
914                 return NT_STATUS_NO_MEMORY;
915         }
916
917         if (!pdb_set_domain(sam_account, nt_domain)) {
918                 pdb_free_sam(&sam_account);
919                 return NT_STATUS_NO_MEMORY;
920         }
921
922         if (!pdb_set_fullname(sam_account, pdb_unistr2_convert(&(info3->uni_full_name)))) {
923                 pdb_free_sam(&sam_account);
924                 return NT_STATUS_NO_MEMORY;
925         }
926
927         if (!pdb_set_logon_script(sam_account, pdb_unistr2_convert(&(info3->uni_logon_script)), True)) {
928                 pdb_free_sam(&sam_account);
929                 return NT_STATUS_NO_MEMORY;
930         }
931
932         if (!pdb_set_profile_path(sam_account, pdb_unistr2_convert(&(info3->uni_profile_path)), True)) {
933                 pdb_free_sam(&sam_account);
934                 return NT_STATUS_NO_MEMORY;
935         }
936
937         if (!pdb_set_homedir(sam_account, pdb_unistr2_convert(&(info3->uni_home_dir)), True)) {
938                 pdb_free_sam(&sam_account);
939                 return NT_STATUS_NO_MEMORY;
940         }
941
942         if (!pdb_set_dir_drive(sam_account, pdb_unistr2_convert(&(info3->uni_dir_drive)), True)) {
943                 pdb_free_sam(&sam_account);
944                 return NT_STATUS_NO_MEMORY;
945         }
946
947         if (!NT_STATUS_IS_OK(nt_status = make_server_info(server_info, sam_account))) {
948                 DEBUG(4, ("make_server_info failed!\n"));
949                 pdb_free_sam(&sam_account);
950                 return nt_status;
951         }
952
953         /* Store the user group information in the server_info 
954            returned to the caller. */
955         
956         if (!NT_STATUS_IS_OK(nt_status 
957                              = get_user_groups_from_local_sam(&user_sid, 
958                                                               &n_lgroupSIDs, 
959                                                               &lgroupSIDs, 
960                                                               &unix_groups)))
961         {
962                 DEBUG(4,("get_user_groups_from_local_sam failed\n"));
963                 return nt_status;
964         }
965
966         (*server_info)->groups = unix_groups;
967         (*server_info)->n_groups = n_lgroupSIDs;
968         
969         /* Create a 'combined' list of all SIDs we might want in the SD */
970         all_group_SIDs   = malloc(sizeof(DOM_SID) * (n_lgroupSIDs+info3->num_groups2));
971         if (!all_group_SIDs) {
972                 DEBUG(0, ("create_nt_token_info3: malloc() failed for DOM_SID list!\n"));
973                 SAFE_FREE(lgroupSIDs);
974                 return NT_STATUS_NO_MEMORY;
975         }
976
977         /* Copy the 'local' sids */
978         memcpy(all_group_SIDs, lgroupSIDs, sizeof(DOM_SID) * n_lgroupSIDs);
979         SAFE_FREE(lgroupSIDs);
980
981         /* and create (by appending rids) the 'domain' sids */
982         for (i = 0; i < info3->num_groups2; i++) {
983                 sid_copy(&all_group_SIDs[i+n_lgroupSIDs], &(info3->dom_sid.sid));
984                 if (!sid_append_rid(&all_group_SIDs[i+n_lgroupSIDs], info3->gids[i].g_rid)) {
985                         nt_status = NT_STATUS_INVALID_PARAMETER;
986                         DEBUG(3,("create_nt_token_info3: could not append additional group rid 0x%x\n",
987                                 info3->gids[i].g_rid));                 
988                         SAFE_FREE(lgroupSIDs);
989                         return nt_status;
990                 }
991         }
992
993         /* Where are the 'global' sids... */
994
995         /* can the user be guest? if yes, where is it stored? */
996         if (!NT_STATUS_IS_OK(nt_status = create_nt_user_token(&user_sid, &group_sid,
997                                                              n_lgroupSIDs+info3->num_groups2, all_group_SIDs, 
998                                                               False, &token))) {
999                 DEBUG(4,("create_nt_user_token failed\n"));
1000                 SAFE_FREE(all_group_SIDs);
1001                 return nt_status;
1002         }
1003
1004         (*server_info)->ptok = token; 
1005
1006         SAFE_FREE(all_group_SIDs);
1007         
1008         debug_nt_user_token(DBGC_AUTH, 5, token);
1009         
1010         return NT_STATUS_OK;
1011 }
1012
1013 /***************************************************************************
1014  Free a user_info struct
1015 ***************************************************************************/
1016
1017 void free_user_info(auth_usersupplied_info **user_info)
1018 {
1019         DEBUG(5,("attempting to free (and zero) a user_info structure\n"));
1020         if (*user_info != NULL) {
1021                 if ((*user_info)->smb_name.str) {
1022                         DEBUG(10,("structure was created for %s\n", (*user_info)->smb_name.str));
1023                 }
1024                 SAFE_FREE((*user_info)->smb_name.str);
1025                 SAFE_FREE((*user_info)->internal_username.str);
1026                 SAFE_FREE((*user_info)->client_domain.str);
1027                 SAFE_FREE((*user_info)->domain.str);
1028                 SAFE_FREE((*user_info)->wksta_name.str);
1029                 data_blob_free(&(*user_info)->lm_resp);
1030                 data_blob_free(&(*user_info)->nt_resp);
1031                 SAFE_FREE((*user_info)->interactive_password);
1032                 data_blob_clear_free(&(*user_info)->plaintext_password);
1033                 ZERO_STRUCT(**user_info);
1034         }
1035         SAFE_FREE(*user_info);
1036 }
1037
1038 /***************************************************************************
1039  Clear out a server_info struct that has been allocated
1040 ***************************************************************************/
1041
1042 void free_server_info(auth_serversupplied_info **server_info)
1043 {
1044         DEBUG(5,("attempting to free (and zero) a server_info structure\n"));
1045         if (*server_info != NULL) {
1046                 pdb_free_sam(&(*server_info)->sam_account);
1047
1048                 /* call pam_end here, unless we know we are keeping it */
1049                 delete_nt_token( &(*server_info)->ptok );
1050                 SAFE_FREE((*server_info)->groups);
1051                 ZERO_STRUCT(**server_info);
1052         }
1053         SAFE_FREE(*server_info);
1054 }
1055
1056 /***************************************************************************
1057  Make an auth_methods struct
1058 ***************************************************************************/
1059
1060 BOOL make_auth_methods(struct auth_context *auth_context, auth_methods **auth_method) 
1061 {
1062         if (!auth_context) {
1063                 smb_panic("no auth_context supplied to make_auth_methods()!\n");
1064         }
1065
1066         if (!auth_method) {
1067                 smb_panic("make_auth_methods: pointer to auth_method pointer is NULL!\n");
1068         }
1069
1070         *auth_method = talloc(auth_context->mem_ctx, sizeof(**auth_method));
1071         if (!*auth_method) {
1072                 DEBUG(0,("make_auth_method: malloc failed!\n"));
1073                 return False;
1074         }
1075         ZERO_STRUCTP(*auth_method);
1076         
1077         return True;
1078 }
1079
1080 /****************************************************************************
1081  Delete a SID token.
1082 ****************************************************************************/
1083
1084 void delete_nt_token(NT_USER_TOKEN **pptoken)
1085 {
1086     if (*pptoken) {
1087             NT_USER_TOKEN *ptoken = *pptoken;
1088             SAFE_FREE( ptoken->user_sids );
1089             ZERO_STRUCTP(ptoken);
1090     }
1091     SAFE_FREE(*pptoken);
1092 }
1093
1094 /****************************************************************************
1095  Duplicate a SID token.
1096 ****************************************************************************/
1097
1098 NT_USER_TOKEN *dup_nt_token(NT_USER_TOKEN *ptoken)
1099 {
1100         NT_USER_TOKEN *token;
1101
1102         if (!ptoken)
1103                 return NULL;
1104
1105     if ((token = (NT_USER_TOKEN *)malloc( sizeof(NT_USER_TOKEN) ) ) == NULL)
1106         return NULL;
1107
1108     ZERO_STRUCTP(token);
1109
1110     if ((token->user_sids = (DOM_SID *)memdup( ptoken->user_sids, sizeof(DOM_SID) * ptoken->num_sids )) == NULL) {
1111         SAFE_FREE(token);
1112         return NULL;
1113     }
1114
1115     token->num_sids = ptoken->num_sids;
1116
1117         return token;
1118 }
1119
1120 /**
1121  * Squash an NT_STATUS in line with security requirements.
1122  * In an attempt to avoid giving the whole game away when users
1123  * are authenticating, NT replaces both NT_STATUS_NO_SUCH_USER and 
1124  * NT_STATUS_WRONG_PASSWORD with NT_STATUS_LOGON_FAILURE in certain situations 
1125  * (session setups in particular).
1126  *
1127  * @param nt_status NTSTATUS input for squashing.
1128  * @return the 'squashed' nt_status
1129  **/
1130
1131 NTSTATUS nt_status_squash(NTSTATUS nt_status)
1132 {
1133         if NT_STATUS_IS_OK(nt_status) {
1134                 return nt_status;               
1135         } else if NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER) {
1136                 /* Match WinXP and don't give the game away */
1137                 return NT_STATUS_LOGON_FAILURE;
1138                 
1139         } else if NT_STATUS_EQUAL(nt_status, NT_STATUS_WRONG_PASSWORD) {
1140                 /* Match WinXP and don't give the game away */
1141                 return NT_STATUS_LOGON_FAILURE;
1142         } else {
1143                 return nt_status;
1144         }  
1145 }
1146
1147
1148