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