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