e4793c3df39745dbbbe444a94632ea827df26591
[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 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  We don't care about RID's here so ignore.
60 ****************************************************************************/
61
62 void auth_add_user_script(const char *domain, const char *username)
63 {
64         uint32 rid;
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() )
72                 smb_create_user(domain, username, NULL);
73         else {
74                 DEBUG(10,("auth_add_user_script: no 'add user script'.  Asking winbindd\n"));
75                 
76                 /* should never get here is we a re a domain member running winbindd
77                    However, a host set for 'security = server' might run winbindd for 
78                    account allocation */
79                    
80                 if ( !winbind_create_user(username, NULL) ) {
81                         DEBUG(5,("auth_add_user_script: winbindd_create_user() failed\n"));
82                         rid = 0;
83                 }
84         }
85 }
86
87 /****************************************************************************
88  Create a SAM_ACCOUNT - either by looking in the pdb, or by faking it up from
89  unix info.
90 ****************************************************************************/
91
92 NTSTATUS auth_get_sam_account(const char *user, SAM_ACCOUNT **account) 
93 {
94         BOOL pdb_ret;
95         NTSTATUS nt_status;
96         if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam(account))) {
97                 return nt_status;
98         }
99         
100         become_root();
101         pdb_ret = pdb_getsampwnam(*account, user);
102         unbecome_root();
103
104         if (!pdb_ret) {
105                 
106                 struct passwd *pass = Get_Pwnam(user);
107                 if (!pass) 
108                         return NT_STATUS_NO_SUCH_USER;
109
110                 if (!NT_STATUS_IS_OK(nt_status = pdb_fill_sam_pw(*account, pass))) {
111                         return nt_status;
112                 }
113         }
114         return NT_STATUS_OK;
115 }
116
117 /****************************************************************************
118  Create an auth_usersupplied_data structure
119 ****************************************************************************/
120
121 static NTSTATUS make_user_info(auth_usersupplied_info **user_info, 
122                                const char *smb_name, 
123                                const char *internal_username,
124                                const char *client_domain, 
125                                const char *domain,
126                                const char *wksta_name, 
127                                DATA_BLOB *lm_pwd, DATA_BLOB *nt_pwd,
128                                DATA_BLOB *lm_interactive_pwd, DATA_BLOB *nt_interactive_pwd,
129                                DATA_BLOB *plaintext, 
130                                BOOL encrypted)
131 {
132
133         DEBUG(5,("attempting to make a user_info for %s (%s)\n", internal_username, smb_name));
134
135         *user_info = SMB_MALLOC_P(auth_usersupplied_info);
136         if (!user_info) {
137                 DEBUG(0,("malloc failed for user_info (size %lu)\n", (unsigned long)sizeof(*user_info)));
138                 return NT_STATUS_NO_MEMORY;
139         }
140
141         ZERO_STRUCTP(*user_info);
142
143         DEBUG(5,("making strings for %s's user_info struct\n", internal_username));
144
145         (*user_info)->smb_name.str = SMB_STRDUP(smb_name);
146         if ((*user_info)->smb_name.str) { 
147                 (*user_info)->smb_name.len = strlen(smb_name);
148         } else {
149                 free_user_info(user_info);
150                 return NT_STATUS_NO_MEMORY;
151         }
152         
153         (*user_info)->internal_username.str = SMB_STRDUP(internal_username);
154         if ((*user_info)->internal_username.str) { 
155                 (*user_info)->internal_username.len = strlen(internal_username);
156         } else {
157                 free_user_info(user_info);
158                 return NT_STATUS_NO_MEMORY;
159         }
160
161         (*user_info)->domain.str = SMB_STRDUP(domain);
162         if ((*user_info)->domain.str) { 
163                 (*user_info)->domain.len = strlen(domain);
164         } else {
165                 free_user_info(user_info);
166                 return NT_STATUS_NO_MEMORY;
167         }
168
169         (*user_info)->client_domain.str = SMB_STRDUP(client_domain);
170         if ((*user_info)->client_domain.str) { 
171                 (*user_info)->client_domain.len = strlen(client_domain);
172         } else {
173                 free_user_info(user_info);
174                 return NT_STATUS_NO_MEMORY;
175         }
176
177         (*user_info)->wksta_name.str = SMB_STRDUP(wksta_name);
178         if ((*user_info)->wksta_name.str) { 
179                 (*user_info)->wksta_name.len = strlen(wksta_name);
180         } else {
181                 free_user_info(user_info);
182                 return NT_STATUS_NO_MEMORY;
183         }
184
185         DEBUG(5,("making blobs for %s's user_info struct\n", internal_username));
186
187         if (lm_pwd)
188                 (*user_info)->lm_resp = data_blob(lm_pwd->data, lm_pwd->length);
189         if (nt_pwd)
190                 (*user_info)->nt_resp = data_blob(nt_pwd->data, nt_pwd->length);
191         if (lm_interactive_pwd)
192                 (*user_info)->lm_interactive_pwd = data_blob(lm_interactive_pwd->data, lm_interactive_pwd->length);
193         if (nt_interactive_pwd)
194                 (*user_info)->nt_interactive_pwd = data_blob(nt_interactive_pwd->data, nt_interactive_pwd->length);
195
196         if (plaintext)
197                 (*user_info)->plaintext_password = data_blob(plaintext->data, plaintext->length);
198
199         (*user_info)->encrypted = encrypted;
200
201         DEBUG(10,("made an %sencrypted user_info for %s (%s)\n", encrypted ? "":"un" , internal_username, smb_name));
202
203         return NT_STATUS_OK;
204 }
205
206 /****************************************************************************
207  Create an auth_usersupplied_data structure after appropriate mapping.
208 ****************************************************************************/
209
210 NTSTATUS make_user_info_map(auth_usersupplied_info **user_info, 
211                             const char *smb_name, 
212                             const char *client_domain, 
213                             const char *wksta_name, 
214                             DATA_BLOB *lm_pwd, DATA_BLOB *nt_pwd,
215                             DATA_BLOB *lm_interactive_pwd, DATA_BLOB *nt_interactive_pwd,
216                             DATA_BLOB *plaintext, 
217                             BOOL encrypted)
218 {
219         const char *domain;
220         fstring internal_username;
221         fstrcpy(internal_username, smb_name);
222         map_username(internal_username); 
223         
224         DEBUG(5, ("make_user_info_map: Mapping user [%s]\\[%s] from workstation [%s]\n",
225               client_domain, smb_name, wksta_name));
226         
227         /* don't allow "" as a domain, fixes a Win9X bug 
228            where it doens't supply a domain for logon script
229            'net use' commands.                                 */
230
231         if ( *client_domain )
232                 domain = client_domain;
233         else
234                 domain = lp_workgroup();
235
236         /* do what win2k does.  Always map unknown domains to our own
237            and let the "passdb backend" handle unknown users. */
238
239         if ( !is_trusted_domain(domain) && !strequal(domain, get_global_sam_name()) ) 
240                 domain = get_default_sam_name();
241         
242         /* we know that it is a trusted domain (and we are allowing them) or it is our domain */
243         
244         return make_user_info(user_info, smb_name, internal_username, 
245                               client_domain, domain, wksta_name, 
246                               lm_pwd, nt_pwd,
247                               lm_interactive_pwd, nt_interactive_pwd,
248                               plaintext, encrypted);
249 }
250
251 /****************************************************************************
252  Create an auth_usersupplied_data, making the DATA_BLOBs here. 
253  Decrypt and encrypt the passwords.
254 ****************************************************************************/
255
256 BOOL make_user_info_netlogon_network(auth_usersupplied_info **user_info, 
257                                      const char *smb_name, 
258                                      const char *client_domain, 
259                                      const char *wksta_name, 
260                                      const uchar *lm_network_pwd, int lm_pwd_len,
261                                      const uchar *nt_network_pwd, int nt_pwd_len)
262 {
263         BOOL ret;
264         NTSTATUS nt_status;
265         DATA_BLOB lm_blob = data_blob(lm_network_pwd, lm_pwd_len);
266         DATA_BLOB nt_blob = data_blob(nt_network_pwd, nt_pwd_len);
267
268         nt_status = make_user_info_map(user_info,
269                                        smb_name, client_domain, 
270                                        wksta_name, 
271                                        lm_pwd_len ? &lm_blob : NULL, 
272                                        nt_pwd_len ? &nt_blob : NULL,
273                                        NULL, NULL, NULL,
274                                        True);
275         
276         ret = NT_STATUS_IS_OK(nt_status) ? True : False;
277                 
278         data_blob_free(&lm_blob);
279         data_blob_free(&nt_blob);
280         return ret;
281 }
282
283 /****************************************************************************
284  Create an auth_usersupplied_data, making the DATA_BLOBs here. 
285  Decrypt and encrypt the passwords.
286 ****************************************************************************/
287
288 BOOL make_user_info_netlogon_interactive(auth_usersupplied_info **user_info, 
289                                          const char *smb_name, 
290                                          const char *client_domain, 
291                                          const char *wksta_name, 
292                                          const uchar chal[8], 
293                                          const uchar lm_interactive_pwd[16], 
294                                          const uchar nt_interactive_pwd[16], 
295                                          const uchar *dc_sess_key)
296 {
297         char lm_pwd[16];
298         char nt_pwd[16];
299         unsigned char local_lm_response[24];
300         unsigned char local_nt_response[24];
301         unsigned char key[16];
302         
303         ZERO_STRUCT(key);
304         memcpy(key, dc_sess_key, 8);
305         
306         if (lm_interactive_pwd) memcpy(lm_pwd, lm_interactive_pwd, sizeof(lm_pwd));
307         if (nt_interactive_pwd) memcpy(nt_pwd, nt_interactive_pwd, sizeof(nt_pwd));
308         
309 #ifdef DEBUG_PASSWORD
310         DEBUG(100,("key:"));
311         dump_data(100, (char *)key, sizeof(key));
312         
313         DEBUG(100,("lm owf password:"));
314         dump_data(100, lm_pwd, sizeof(lm_pwd));
315         
316         DEBUG(100,("nt owf password:"));
317         dump_data(100, nt_pwd, sizeof(nt_pwd));
318 #endif
319         
320         if (lm_interactive_pwd)
321                 SamOEMhash((uchar *)lm_pwd, key, sizeof(lm_pwd));
322         
323         if (nt_interactive_pwd)
324                 SamOEMhash((uchar *)nt_pwd, key, sizeof(nt_pwd));
325         
326 #ifdef DEBUG_PASSWORD
327         DEBUG(100,("decrypt of lm owf password:"));
328         dump_data(100, lm_pwd, sizeof(lm_pwd));
329         
330         DEBUG(100,("decrypt of nt owf password:"));
331         dump_data(100, nt_pwd, sizeof(nt_pwd));
332 #endif
333         
334         if (lm_interactive_pwd)
335                 SMBOWFencrypt((const unsigned char *)lm_pwd, chal, local_lm_response);
336
337         if (nt_interactive_pwd)
338                 SMBOWFencrypt((const unsigned char *)nt_pwd, chal, local_nt_response);
339         
340         /* Password info paranoia */
341         ZERO_STRUCT(key);
342
343         {
344                 BOOL ret;
345                 NTSTATUS nt_status;
346                 DATA_BLOB local_lm_blob;
347                 DATA_BLOB local_nt_blob;
348
349                 DATA_BLOB lm_interactive_blob;
350                 DATA_BLOB nt_interactive_blob;
351                 
352                 if (lm_interactive_pwd) {
353                         local_lm_blob = data_blob(local_lm_response, sizeof(local_lm_response));
354                         lm_interactive_blob = data_blob(lm_pwd, sizeof(lm_pwd));
355                         ZERO_STRUCT(lm_pwd);
356                 }
357                 
358                 if (nt_interactive_pwd) {
359                         local_nt_blob = data_blob(local_nt_response, sizeof(local_nt_response));
360                         nt_interactive_blob = data_blob(nt_pwd, sizeof(nt_pwd));
361                         ZERO_STRUCT(nt_pwd);
362                 }
363
364                 nt_status = make_user_info_map(user_info, 
365                                                smb_name, client_domain, 
366                                                wksta_name, 
367                                                lm_interactive_pwd ? &local_lm_blob : NULL,
368                                                nt_interactive_pwd ? &local_nt_blob : NULL,
369                                                lm_interactive_pwd ? &lm_interactive_blob : NULL,
370                                                nt_interactive_pwd ? &nt_interactive_blob : NULL,
371                                                NULL,
372                                                True);
373
374                 ret = NT_STATUS_IS_OK(nt_status) ? True : False;
375                 data_blob_free(&local_lm_blob);
376                 data_blob_free(&local_nt_blob);
377                 data_blob_free(&lm_interactive_blob);
378                 data_blob_free(&nt_interactive_blob);
379                 return ret;
380         }
381 }
382
383
384 /****************************************************************************
385  Create an auth_usersupplied_data structure
386 ****************************************************************************/
387
388 BOOL make_user_info_for_reply(auth_usersupplied_info **user_info, 
389                               const char *smb_name, 
390                               const char *client_domain,
391                               const uint8 chal[8],
392                               DATA_BLOB plaintext_password)
393 {
394
395         DATA_BLOB local_lm_blob;
396         DATA_BLOB local_nt_blob;
397         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
398                         
399         /*
400          * Not encrypted - do so.
401          */
402         
403         DEBUG(5,("make_user_info_for_reply: User passwords not in encrypted format.\n"));
404         
405         if (plaintext_password.data) {
406                 unsigned char local_lm_response[24];
407                 
408 #ifdef DEBUG_PASSWORD
409                 DEBUG(10,("Unencrypted password (len %d):\n",plaintext_password.length));
410                 dump_data(100, plaintext_password.data, plaintext_password.length);
411 #endif
412
413                 SMBencrypt( (const char *)plaintext_password.data, (const uchar*)chal, local_lm_response);
414                 local_lm_blob = data_blob(local_lm_response, 24);
415                 
416                 /* We can't do an NT hash here, as the password needs to be
417                    case insensitive */
418                 local_nt_blob = data_blob(NULL, 0); 
419                 
420         } else {
421                 local_lm_blob = data_blob(NULL, 0); 
422                 local_nt_blob = data_blob(NULL, 0); 
423         }
424         
425         ret = make_user_info_map(user_info, smb_name,
426                                  client_domain, 
427                                  get_remote_machine_name(),
428                                  local_lm_blob.data ? &local_lm_blob : NULL,
429                                  local_nt_blob.data ? &local_nt_blob : NULL,
430                                  NULL, NULL,
431                                  plaintext_password.data ? &plaintext_password : NULL, 
432                                  False);
433         
434         data_blob_free(&local_lm_blob);
435         return NT_STATUS_IS_OK(ret) ? True : False;
436 }
437
438 /****************************************************************************
439  Create an auth_usersupplied_data structure
440 ****************************************************************************/
441
442 NTSTATUS make_user_info_for_reply_enc(auth_usersupplied_info **user_info, 
443                                       const char *smb_name,
444                                       const char *client_domain, 
445                                       DATA_BLOB lm_resp, DATA_BLOB nt_resp)
446 {
447         return make_user_info_map(user_info, smb_name, 
448                                   client_domain, 
449                                   get_remote_machine_name(), 
450                                   lm_resp.data ? &lm_resp : NULL, 
451                                   nt_resp.data ? &nt_resp : NULL, 
452                                   NULL, NULL, NULL,
453                                   True);
454 }
455
456 /****************************************************************************
457  Create a guest user_info blob, for anonymous authenticaion.
458 ****************************************************************************/
459
460 BOOL make_user_info_guest(auth_usersupplied_info **user_info) 
461 {
462         NTSTATUS nt_status;
463
464         nt_status = make_user_info(user_info, 
465                                    "","", 
466                                    "","", 
467                                    "", 
468                                    NULL, NULL, 
469                                    NULL, NULL, 
470                                    NULL,
471                                    True);
472                               
473         return NT_STATUS_IS_OK(nt_status) ? True : False;
474 }
475
476 /****************************************************************************
477  prints a NT_USER_TOKEN to debug output.
478 ****************************************************************************/
479
480 void debug_nt_user_token(int dbg_class, int dbg_lev, NT_USER_TOKEN *token)
481 {
482         fstring sid_str;
483         size_t     i;
484         
485         if (!token) {
486                 DEBUGC(dbg_class, dbg_lev, ("NT user token: (NULL)\n"));
487                 return;
488         }
489         
490         DEBUGC(dbg_class, dbg_lev, ("NT user token of user %s\n",
491                                     sid_to_string(sid_str, &token->user_sids[0]) ));
492         DEBUGADDC(dbg_class, dbg_lev, ("contains %lu SIDs\n", (unsigned long)token->num_sids));
493         for (i = 0; i < token->num_sids; i++)
494                 DEBUGADDC(dbg_class, dbg_lev, ("SID[%3lu]: %s\n", (unsigned long)i, 
495                                                sid_to_string(sid_str, &token->user_sids[i])));
496
497         DEBUGADDC(dbg_class, dbg_lev, ("Privileges: [%d]\n", token->privileges.count));
498         for ( i=0; i<token->privileges.count; i++ ) {
499                 DEBUGADDC(dbg_class, dbg_lev, ("\t%s\n", luid_to_privilege_name(&token->privileges.set[i].luid) ));
500         }
501 }
502
503 /****************************************************************************
504  prints a UNIX 'token' to debug output.
505 ****************************************************************************/
506
507 void debug_unix_user_token(int dbg_class, int dbg_lev, uid_t uid, gid_t gid, int n_groups, gid_t *groups)
508 {
509         int     i;
510         DEBUGC(dbg_class, dbg_lev, ("UNIX token of user %ld\n", (long int)uid));
511
512         DEBUGADDC(dbg_class, dbg_lev, ("Primary group is %ld and contains %i supplementary groups\n", (long int)gid, n_groups));
513         for (i = 0; i < n_groups; i++)
514                 DEBUGADDC(dbg_class, dbg_lev, ("Group[%3i]: %ld\n", i, 
515                         (long int)groups[i]));
516 }
517
518 /****************************************************************************
519  Create the SID list for this user.
520 ****************************************************************************/
521
522 static NTSTATUS create_nt_user_token(const DOM_SID *user_sid, const DOM_SID *group_sid, 
523                                      int n_groupSIDs, DOM_SID *groupSIDs, 
524                                      BOOL is_guest, NT_USER_TOKEN **token)
525 {
526         NTSTATUS       nt_status = NT_STATUS_OK;
527         NT_USER_TOKEN *ptoken;
528         int i;
529         int sid_ndx;
530         
531         if ((ptoken = SMB_MALLOC_P(NT_USER_TOKEN)) == NULL) {
532                 DEBUG(0, ("create_nt_token: Out of memory allocating token\n"));
533                 nt_status = NT_STATUS_NO_MEMORY;
534                 return nt_status;
535         }
536
537         ZERO_STRUCTP(ptoken);
538
539         ptoken->num_sids = n_groupSIDs + 5;
540
541         if ((ptoken->user_sids = SMB_MALLOC_ARRAY( DOM_SID, ptoken->num_sids )) == NULL) {
542                 DEBUG(0, ("create_nt_token: Out of memory allocating SIDs\n"));
543                 nt_status = NT_STATUS_NO_MEMORY;
544                 return nt_status;
545         }
546         
547         memset((char*)ptoken->user_sids,0,sizeof(DOM_SID) * ptoken->num_sids);
548         
549         /*
550          * Note - user SID *MUST* be first in token !
551          * se_access_check depends on this.
552          *
553          * Primary group SID is second in token. Convention.
554          */
555
556         sid_copy(&ptoken->user_sids[PRIMARY_USER_SID_INDEX], user_sid);
557         if (group_sid)
558                 sid_copy(&ptoken->user_sids[PRIMARY_GROUP_SID_INDEX], group_sid);
559
560         /*
561          * Finally add the "standard" SIDs.
562          * The only difference between guest and "anonymous" (which we
563          * don't really support) is the addition of Authenticated_Users.
564          */
565
566         sid_copy(&ptoken->user_sids[2], &global_sid_World);
567         sid_copy(&ptoken->user_sids[3], &global_sid_Network);
568
569         if (is_guest)
570                 sid_copy(&ptoken->user_sids[4], &global_sid_Builtin_Guests);
571         else
572                 sid_copy(&ptoken->user_sids[4], &global_sid_Authenticated_Users);
573         
574         sid_ndx = 5; /* next available spot */
575
576         for (i = 0; i < n_groupSIDs; i++) {
577                 size_t check_sid_idx;
578                 for (check_sid_idx = 1; check_sid_idx < ptoken->num_sids; check_sid_idx++) {
579                         if (sid_equal(&ptoken->user_sids[check_sid_idx], 
580                                       &groupSIDs[i])) {
581                                 break;
582                         }
583                 }
584                 
585                 if (check_sid_idx >= ptoken->num_sids) /* Not found already */ {
586                         sid_copy(&ptoken->user_sids[sid_ndx++], &groupSIDs[i]);
587                 } else {
588                         ptoken->num_sids--;
589                 }
590         }
591
592         /* add privileges assigned to this user */
593
594         privilege_set_init( &ptoken->privileges );
595
596         get_privileges_for_sids( &ptoken->privileges, ptoken->user_sids, ptoken->num_sids );
597
598         
599         debug_nt_user_token(DBGC_AUTH, 10, ptoken);
600         
601         *token = ptoken;
602
603         return nt_status;
604 }
605
606 /****************************************************************************
607  Create the SID list for this user.
608 ****************************************************************************/
609
610 NT_USER_TOKEN *create_nt_token(uid_t uid, gid_t gid, int ngroups, gid_t *groups, BOOL is_guest)
611 {
612         DOM_SID user_sid;
613         DOM_SID group_sid;
614         DOM_SID *group_sids;
615         NT_USER_TOKEN *token;
616         int i;
617
618         if (!NT_STATUS_IS_OK(uid_to_sid(&user_sid, uid))) {
619                 return NULL;
620         }
621         if (!NT_STATUS_IS_OK(gid_to_sid(&group_sid, gid))) {
622                 return NULL;
623         }
624
625         group_sids = SMB_MALLOC_ARRAY(DOM_SID, ngroups);
626         if (!group_sids) {
627                 DEBUG(0, ("create_nt_token: malloc() failed for DOM_SID list!\n"));
628                 return NULL;
629         }
630
631         for (i = 0; i < ngroups; i++) {
632                 if (!NT_STATUS_IS_OK(gid_to_sid(&(group_sids)[i], (groups)[i]))) {
633                         DEBUG(1, ("create_nt_token: failed to convert gid %ld to a sid!\n", (long int)groups[i]));
634                         SAFE_FREE(group_sids);
635                         return NULL;
636                 }
637         }
638
639         if (!NT_STATUS_IS_OK(create_nt_user_token(&user_sid, &group_sid, 
640                                                   ngroups, group_sids, is_guest, &token))) {
641                 SAFE_FREE(group_sids);
642                 return NULL;
643         }
644
645         SAFE_FREE(group_sids);
646
647         return token;
648 }
649
650 /******************************************************************************
651  * this function returns the groups (SIDs) of the local SAM the user is in.
652  * If this samba server is a DC of the domain the user belongs to, it returns 
653  * both domain groups and local / builtin groups. If the user is in a trusted
654  * domain, or samba is a member server of a domain, then this function returns
655  * local and builtin groups the user is a member of.
656  *
657  * currently this is a hack, as there is no sam implementation that is capable
658  * of groups.
659  *
660  * NOTE!! This function will fail if you pass in a winbind user without 
661  * the domain   --jerry
662  ******************************************************************************/
663
664 static NTSTATUS get_user_groups(const char *username, uid_t uid, gid_t gid,
665                                 int *n_groups, DOM_SID **groups, gid_t **unix_groups)
666 {
667         int             n_unix_groups;
668         int             i;
669
670         *n_groups = 0;
671         *groups   = NULL;
672
673         if (strchr(username, *lp_winbind_separator()) == NULL) {
674                 NTSTATUS result;
675
676                 become_root();
677                 result = pdb_enum_group_memberships(username, gid, groups,
678                                                     unix_groups, n_groups);
679                 unbecome_root();
680                 return result;
681         }
682
683         /* We have the separator, this must be winbind */
684         
685         n_unix_groups = winbind_getgroups( username, unix_groups );
686
687         DEBUG(10,("get_user_groups: winbind_getgroups(%s): result = %s\n",
688                   username,  n_unix_groups == -1 ? "FAIL" : "SUCCESS"));
689                           
690         if ( n_unix_groups == -1 )
691                 return NT_STATUS_NO_SUCH_USER; /* what should this return
692                                                 * value be? */  
693
694         debug_unix_user_token(DBGC_CLASS, 5, uid, gid, n_unix_groups, *unix_groups);
695         
696         /* now setup the space for storing the SIDS */
697         
698         if (n_unix_groups > 0) {
699         
700                 *groups   = SMB_MALLOC_ARRAY(DOM_SID, n_unix_groups);
701                 
702                 if (!*groups) {
703                         DEBUG(0, ("get_user_group: malloc() failed for DOM_SID list!\n"));
704                         SAFE_FREE(*unix_groups);
705                         return NT_STATUS_NO_MEMORY;
706                 }
707         }
708
709         *n_groups = n_unix_groups;
710
711         for (i = 0; i < *n_groups; i++) {
712                 if (!NT_STATUS_IS_OK(gid_to_sid(&(*groups)[i], (*unix_groups)[i]))) {
713                         DEBUG(1, ("get_user_groups: failed to convert gid %ld to a sid!\n", 
714                                 (long int)(*unix_groups)[i+1]));
715                         SAFE_FREE(*groups);
716                         SAFE_FREE(*unix_groups);
717                         return NT_STATUS_NO_SUCH_USER;
718                 }
719         }
720                      
721         return NT_STATUS_OK;
722 }
723
724 /***************************************************************************
725  Make a user_info struct
726 ***************************************************************************/
727
728 static NTSTATUS make_server_info(auth_serversupplied_info **server_info)
729 {
730         *server_info = SMB_MALLOC_P(auth_serversupplied_info);
731         if (!*server_info) {
732                 DEBUG(0,("make_server_info: malloc failed!\n"));
733                 return NT_STATUS_NO_MEMORY;
734         }
735         ZERO_STRUCTP(*server_info);
736
737         /* Initialise the uid and gid values to something non-zero
738            which may save us from giving away root access if there
739            is a bug in allocating these fields. */
740
741         (*server_info)->uid = -1;
742         (*server_info)->gid = -1;
743
744         return NT_STATUS_OK;
745 }
746
747 /***************************************************************************
748 Fill a server_info struct from a SAM_ACCOUNT with their groups
749 ***************************************************************************/
750
751 static NTSTATUS add_user_groups(auth_serversupplied_info **server_info, 
752                                 const char * unix_username,
753                                 SAM_ACCOUNT *sampass,
754                                 uid_t uid, gid_t gid)
755 {
756         NTSTATUS nt_status;
757         const DOM_SID *user_sid = pdb_get_user_sid(sampass);
758         const DOM_SID *group_sid = pdb_get_group_sid(sampass);
759         int       n_groupSIDs = 0;
760         DOM_SID  *groupSIDs   = NULL;
761         gid_t    *unix_groups = NULL;
762         NT_USER_TOKEN *token;
763         BOOL is_guest;
764         uint32 rid;
765
766         nt_status = get_user_groups(unix_username, uid, gid, 
767                 &n_groupSIDs, &groupSIDs, &unix_groups);
768                 
769         if (!NT_STATUS_IS_OK(nt_status)) {
770                 DEBUG(4,("get_user_groups_from_local_sam failed\n"));
771                 free_server_info(server_info);
772                 return nt_status;
773         }
774         
775         is_guest = (sid_peek_rid(user_sid, &rid) && rid == DOMAIN_USER_RID_GUEST);
776
777         if (!NT_STATUS_IS_OK(nt_status = create_nt_user_token(user_sid, group_sid,
778                                                               n_groupSIDs, groupSIDs, is_guest, 
779                                                               &token)))
780         {
781                 DEBUG(4,("create_nt_user_token failed\n"));
782                 SAFE_FREE(groupSIDs);
783                 SAFE_FREE(unix_groups);
784                 free_server_info(server_info);
785                 return nt_status;
786         }
787         
788         SAFE_FREE(groupSIDs);
789
790         (*server_info)->n_groups = n_groupSIDs;
791         (*server_info)->groups = unix_groups;
792         (*server_info)->ptok = token;
793
794         return nt_status;
795 }
796
797 /***************************************************************************
798  Make (and fill) a user_info struct from a SAM_ACCOUNT
799 ***************************************************************************/
800
801 NTSTATUS make_server_info_sam(auth_serversupplied_info **server_info, 
802                               SAM_ACCOUNT *sampass)
803 {
804         NTSTATUS nt_status;
805         struct passwd *pwd;
806
807         if (!NT_STATUS_IS_OK(nt_status = make_server_info(server_info)))
808                 return nt_status;
809
810         (*server_info)->sam_account    = sampass;
811
812         if ( !(pwd = getpwnam_alloc(pdb_get_username(sampass))) )  {
813                 DEBUG(1, ("User %s in passdb, but getpwnam() fails!\n",
814                           pdb_get_username(sampass)));
815                 free_server_info(server_info);
816                 return NT_STATUS_NO_SUCH_USER;
817         }
818         (*server_info)->unix_name = smb_xstrdup(pwd->pw_name);
819         (*server_info)->gid = pwd->pw_gid;
820         (*server_info)->uid = pwd->pw_uid;
821         
822         passwd_free(&pwd);
823
824         if (!NT_STATUS_IS_OK(nt_status = add_user_groups(server_info, pdb_get_username(sampass), 
825                                                          sampass,
826                                                          (*server_info)->uid, 
827                                                          (*server_info)->gid))) 
828         {
829                 free_server_info(server_info);
830                 return nt_status;
831         }
832
833         (*server_info)->sam_fill_level = SAM_FILL_ALL;
834         DEBUG(5,("make_server_info_sam: made server info for user %s -> %s\n",
835                  pdb_get_username(sampass),
836                  (*server_info)->unix_name));
837
838         return nt_status;
839 }
840
841 /***************************************************************************
842  Make (and fill) a user_info struct from a 'struct passwd' by conversion 
843  to a SAM_ACCOUNT
844 ***************************************************************************/
845
846 NTSTATUS make_server_info_pw(auth_serversupplied_info **server_info, 
847                              char *unix_username,
848                              struct passwd *pwd)
849 {
850         NTSTATUS nt_status;
851         SAM_ACCOUNT *sampass = NULL;
852         if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam_pw(&sampass, pwd))) {             
853                 return nt_status;
854         }
855         if (!NT_STATUS_IS_OK(nt_status = make_server_info(server_info))) {
856                 return nt_status;
857         }
858
859         (*server_info)->sam_account    = sampass;
860
861         if (!NT_STATUS_IS_OK(nt_status = add_user_groups(server_info, unix_username,
862                 sampass, pwd->pw_uid, pwd->pw_gid))) 
863         {
864                 return nt_status;
865         }
866
867         (*server_info)->unix_name = smb_xstrdup(unix_username);
868
869         (*server_info)->sam_fill_level = SAM_FILL_ALL;
870         (*server_info)->uid = pwd->pw_uid;
871         (*server_info)->gid = pwd->pw_gid;
872         return nt_status;
873 }
874
875 /***************************************************************************
876  Make (and fill) a user_info struct for a guest login.
877 ***************************************************************************/
878
879 static NTSTATUS make_new_server_info_guest(auth_serversupplied_info **server_info)
880 {
881         NTSTATUS nt_status;
882         SAM_ACCOUNT *sampass = NULL;
883         DOM_SID guest_sid;
884
885         if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam(&sampass))) {
886                 return nt_status;
887         }
888
889         sid_copy(&guest_sid, get_global_sam_sid());
890         sid_append_rid(&guest_sid, DOMAIN_USER_RID_GUEST);
891
892         become_root();
893         if (!pdb_getsampwsid(sampass, &guest_sid)) {
894                 unbecome_root();
895                 return NT_STATUS_NO_SUCH_USER;
896         }
897         unbecome_root();
898
899         nt_status = make_server_info_sam(server_info, sampass);
900
901         if (NT_STATUS_IS_OK(nt_status)) {
902                 static const char zeros[16];
903                 (*server_info)->guest = True;
904                 
905                 /* annoying, but the Guest really does have a session key, 
906                    and it is all zeros! */
907                 (*server_info)->user_session_key = data_blob(zeros, sizeof(zeros));
908                 (*server_info)->lm_session_key = data_blob(zeros, sizeof(zeros));
909         }
910
911         return nt_status;
912 }
913
914 static auth_serversupplied_info *copy_serverinfo(auth_serversupplied_info *src)
915 {
916         auth_serversupplied_info *dst;
917
918         if (!NT_STATUS_IS_OK(make_server_info(&dst)))
919                 return NULL;
920
921         dst->guest = src->guest;
922         dst->uid = src->uid;
923         dst->gid = src->gid;
924         dst->n_groups = src->n_groups;
925         if (src->n_groups != 0)
926                 dst->groups = memdup(src->groups, sizeof(gid_t)*dst->n_groups);
927         else
928                 dst->groups = NULL;
929         dst->ptok = dup_nt_token(src->ptok);
930         dst->user_session_key = data_blob(src->user_session_key.data,
931                                           src->user_session_key.length);
932         dst->lm_session_key = data_blob(src->lm_session_key.data,
933                                           src->lm_session_key.length);
934         pdb_copy_sam_account(src->sam_account, &dst->sam_account);
935         dst->pam_handle = NULL;
936         dst->unix_name = smb_xstrdup(src->unix_name);
937
938         return dst;
939 }
940
941 static auth_serversupplied_info *guest_info = NULL;
942
943 BOOL init_guest_info(void)
944 {
945         if (guest_info != NULL)
946                 return True;
947
948         return NT_STATUS_IS_OK(make_new_server_info_guest(&guest_info));
949 }
950
951 NTSTATUS make_server_info_guest(auth_serversupplied_info **server_info)
952 {
953         *server_info = copy_serverinfo(guest_info);
954         return (*server_info != NULL) ? NT_STATUS_OK : NT_STATUS_NO_MEMORY;
955 }
956
957 /***************************************************************************
958  Purely internal function for make_server_info_info3
959  Fill the sam account from getpwnam
960 ***************************************************************************/
961 static NTSTATUS fill_sam_account(TALLOC_CTX *mem_ctx, 
962                                  const char *domain,
963                                  const char *username,
964                                  char **found_username,
965                                  uid_t *uid, gid_t *gid,
966                                  SAM_ACCOUNT **sam_account)
967 {
968         fstring dom_user, lower_username;
969         fstring real_username;
970         struct passwd *passwd;
971
972         fstrcpy( lower_username, username );
973         strlower_m( lower_username );
974
975         fstr_sprintf(dom_user, "%s%c%s", domain, *lp_winbind_separator(), 
976                 lower_username);
977
978         /* get the passwd struct but don't create the user if he/she 
979            does not exist.  We were explicitly called from a following
980            a winbindd authentication request so we should assume that 
981            nss_winbindd is working */
982
983         map_username( dom_user );
984
985         if ( !(passwd = smb_getpwnam( dom_user, real_username, True )) )
986                 return NT_STATUS_NO_SUCH_USER;
987
988         *uid = passwd->pw_uid;
989         *gid = passwd->pw_gid;
990
991         /* This is pointless -- there is no suport for differing 
992            unix and windows names.  Make sure to always store the 
993            one we actually looked up and succeeded. Have I mentioned
994            why I hate the 'winbind use default domain' parameter?   
995                                          --jerry              */
996            
997         *found_username = talloc_strdup( mem_ctx, real_username );
998         
999         DEBUG(5,("fill_sam_account: located username was [%s]\n",
1000                 *found_username));
1001
1002         return pdb_init_sam_pw(sam_account, passwd);
1003 }
1004
1005 /****************************************************************************
1006  Wrapper to allow the getpwnam() call to strip the domain name and 
1007  try again in case a local UNIX user is already there.  Also run through 
1008  the username if we fallback to the username only.
1009  ****************************************************************************/
1010  
1011 struct passwd *smb_getpwnam( char *domuser, fstring save_username, BOOL create )
1012 {
1013         struct passwd *pw = NULL;
1014         char *p;
1015         fstring username;
1016         
1017         /* we only save a copy of the username it has been mangled 
1018            by winbindd use default domain */
1019            
1020         save_username[0] = '\0';
1021            
1022         /* don't call map_username() here since it has to be done higher 
1023            up the stack so we don't call it mutliple times */
1024
1025         fstrcpy( username, domuser );
1026         
1027         p = strchr_m( username, *lp_winbind_separator() );
1028         
1029         /* code for a DOMAIN\user string */
1030         
1031         if ( p ) {
1032                 fstring strip_username;
1033
1034                 pw = Get_Pwnam( domuser );
1035                 if ( pw ) {     
1036                         /* make sure we get the case of the username correct */
1037                         /* work around 'winbind use default domain = yes' */
1038
1039                         if ( !strchr_m( pw->pw_name, *lp_winbind_separator() ) ) {
1040                                 char *domain;
1041                                 
1042                                 /* split the domain and username into 2 strings */
1043                                 *p = '\0';
1044                                 domain = username;
1045
1046                                 fstr_sprintf(save_username, "%s%c%s", domain, *lp_winbind_separator(), pw->pw_name);
1047                         }
1048                         else
1049                                 fstrcpy( save_username, pw->pw_name );
1050
1051                         /* whew -- done! */             
1052                         return pw;
1053                 }
1054
1055                 /* setup for lookup of just the username */
1056                 /* remember that p and username are overlapping memory */
1057
1058                 p++;
1059                 fstrcpy( strip_username, p );
1060                 fstrcpy( username, strip_username );
1061         }
1062         
1063         /* just lookup a plain username */
1064         
1065         pw = Get_Pwnam(username);
1066                 
1067         /* Create local user if requested. */
1068         
1069         if ( !pw && create ) {
1070                 /* Don't add a machine account. */
1071                 if (username[strlen(username)-1] == '$')
1072                         return NULL;
1073
1074                 auth_add_user_script(NULL, username);
1075                 pw = Get_Pwnam(username);
1076         }
1077         
1078         /* one last check for a valid passwd struct */
1079         
1080         if ( pw )
1081                 fstrcpy( save_username, pw->pw_name );
1082
1083         return pw;
1084 }
1085
1086 /***************************************************************************
1087  Make a server_info struct from the info3 returned by a domain logon 
1088 ***************************************************************************/
1089
1090 NTSTATUS make_server_info_info3(TALLOC_CTX *mem_ctx, 
1091                                 const char *internal_username,
1092                                 const char *sent_nt_username,
1093                                 const char *domain,
1094                                 auth_serversupplied_info **server_info, 
1095                                 NET_USER_INFO_3 *info3) 
1096 {
1097         static const char zeros[16];
1098
1099         NTSTATUS nt_status = NT_STATUS_OK;
1100         char *found_username;
1101         const char *nt_domain;
1102         const char *nt_username;
1103
1104         SAM_ACCOUNT *sam_account = NULL;
1105         DOM_SID user_sid;
1106         DOM_SID group_sid;
1107
1108         uid_t uid;
1109         gid_t gid;
1110
1111         int n_lgroupSIDs;
1112         DOM_SID *lgroupSIDs   = NULL;
1113
1114         gid_t *unix_groups = NULL;
1115         NT_USER_TOKEN *token;
1116
1117         DOM_SID *all_group_SIDs;
1118         size_t i;
1119
1120         /* 
1121            Here is where we should check the list of
1122            trusted domains, and verify that the SID 
1123            matches.
1124         */
1125
1126         sid_copy(&user_sid, &info3->dom_sid.sid);
1127         if (!sid_append_rid(&user_sid, info3->user_rid)) {
1128                 return NT_STATUS_INVALID_PARAMETER;
1129         }
1130         
1131         sid_copy(&group_sid, &info3->dom_sid.sid);
1132         if (!sid_append_rid(&group_sid, info3->group_rid)) {
1133                 return NT_STATUS_INVALID_PARAMETER;
1134         }
1135
1136         if (!(nt_username = unistr2_tdup(mem_ctx, &(info3->uni_user_name)))) {
1137                 /* If the server didn't give us one, just use the one we sent them */
1138                 nt_username = sent_nt_username;
1139         }
1140
1141         if (!(nt_domain = unistr2_tdup(mem_ctx, &(info3->uni_logon_dom)))) {
1142                 /* If the server didn't give us one, just use the one we sent them */
1143                 nt_domain = domain;
1144         }
1145         
1146         /* try to fill the SAM account..  If getpwnam() fails, then try the 
1147            add user script (2.2.x behavior).
1148
1149            We use the _unmapped_ username here in an attempt to provide
1150            consistent username mapping behavior between kerberos and NTLM[SSP]
1151            authentication in domain mode security.  I.E. Username mapping should
1152            be applied to the fully qualified username (e.g. DOMAIN\user) and
1153            no just the login name.  Yes this mean swe called map_username()
1154            unnecessarily in make_user_info_map() but that is how the current
1155            code is designed.  Making the change here is the least disruptive 
1156            place.    -- jerry */
1157            
1158         nt_status = fill_sam_account(mem_ctx, nt_domain, sent_nt_username,
1159                 &found_username, &uid, &gid, &sam_account);
1160
1161         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1162                 DEBUG(3,("User %s does not exist, trying to add it\n", internal_username));
1163                 auth_add_user_script( nt_domain, sent_nt_username );
1164                 nt_status = fill_sam_account( mem_ctx, nt_domain, sent_nt_username, 
1165                         &found_username, &uid, &gid, &sam_account );
1166         }
1167         
1168         if (!NT_STATUS_IS_OK(nt_status)) {
1169                 DEBUG(0, ("make_server_info_info3: pdb_init_sam failed!\n"));
1170                 return nt_status;
1171         }
1172                 
1173         if (!pdb_set_nt_username(sam_account, nt_username, PDB_CHANGED)) {
1174                 pdb_free_sam(&sam_account);
1175                 return NT_STATUS_NO_MEMORY;
1176         }
1177
1178         if (!pdb_set_username(sam_account, nt_username, PDB_CHANGED)) {
1179                 pdb_free_sam(&sam_account);
1180                 return NT_STATUS_NO_MEMORY;
1181         }
1182
1183         if (!pdb_set_domain(sam_account, nt_domain, PDB_CHANGED)) {
1184                 pdb_free_sam(&sam_account);
1185                 return NT_STATUS_NO_MEMORY;
1186         }
1187
1188         if (!pdb_set_user_sid(sam_account, &user_sid, PDB_CHANGED)) {
1189                 pdb_free_sam(&sam_account);
1190                 return NT_STATUS_UNSUCCESSFUL;
1191         }
1192
1193         if (!pdb_set_group_sid(sam_account, &group_sid, PDB_CHANGED)) {
1194                 pdb_free_sam(&sam_account);
1195                 return NT_STATUS_UNSUCCESSFUL;
1196         }
1197                 
1198         if (!pdb_set_fullname(sam_account, unistr2_static(&(info3->uni_full_name)), 
1199                               PDB_CHANGED)) {
1200                 pdb_free_sam(&sam_account);
1201                 return NT_STATUS_NO_MEMORY;
1202         }
1203
1204         if (!pdb_set_logon_script(sam_account, unistr2_static(&(info3->uni_logon_script)), PDB_CHANGED)) {
1205                 pdb_free_sam(&sam_account);
1206                 return NT_STATUS_NO_MEMORY;
1207         }
1208
1209         if (!pdb_set_profile_path(sam_account, unistr2_static(&(info3->uni_profile_path)), PDB_CHANGED)) {
1210                 pdb_free_sam(&sam_account);
1211                 return NT_STATUS_NO_MEMORY;
1212         }
1213
1214         if (!pdb_set_homedir(sam_account, unistr2_static(&(info3->uni_home_dir)), PDB_CHANGED)) {
1215                 pdb_free_sam(&sam_account);
1216                 return NT_STATUS_NO_MEMORY;
1217         }
1218
1219         if (!pdb_set_dir_drive(sam_account, unistr2_static(&(info3->uni_dir_drive)), PDB_CHANGED)) {
1220                 pdb_free_sam(&sam_account);
1221                 return NT_STATUS_NO_MEMORY;
1222         }
1223
1224         if (!NT_STATUS_IS_OK(nt_status = make_server_info(server_info))) {
1225                 DEBUG(4, ("make_server_info failed!\n"));
1226                 pdb_free_sam(&sam_account);
1227                 return nt_status;
1228         }
1229
1230         /* save this here to _net_sam_logon() doesn't fail (it assumes a 
1231            valid SAM_ACCOUNT) */
1232                    
1233         (*server_info)->sam_account = sam_account;
1234
1235         (*server_info)->unix_name = smb_xstrdup(found_username);
1236
1237         /* Fill in the unix info we found on the way */
1238
1239         (*server_info)->sam_fill_level = SAM_FILL_ALL;
1240         (*server_info)->uid = uid;
1241         (*server_info)->gid = gid;
1242
1243         /* Store the user group information in the server_info 
1244            returned to the caller. */
1245         
1246         nt_status = get_user_groups((*server_info)->unix_name,
1247                 uid, gid, &n_lgroupSIDs, &lgroupSIDs, &unix_groups);
1248                 
1249         if ( !NT_STATUS_IS_OK(nt_status) ) {
1250                 DEBUG(4,("get_user_groups failed\n"));
1251                 return nt_status;
1252         }
1253
1254         (*server_info)->groups = unix_groups;
1255         (*server_info)->n_groups = n_lgroupSIDs;
1256         
1257         /* Create a 'combined' list of all SIDs we might want in the SD */
1258         
1259         all_group_SIDs = SMB_MALLOC_ARRAY(DOM_SID,info3->num_groups2 + info3->num_other_sids + n_lgroupSIDs);
1260         
1261         if (!all_group_SIDs) {
1262                 DEBUG(0, ("malloc() failed for DOM_SID list!\n"));
1263                 SAFE_FREE(lgroupSIDs);
1264                 free_server_info(server_info);
1265                 return NT_STATUS_NO_MEMORY;
1266         }
1267
1268         /* and create (by appending rids) the 'domain' sids */
1269         
1270         for (i = 0; i < info3->num_groups2; i++) {
1271         
1272                 sid_copy(&all_group_SIDs[i], &(info3->dom_sid.sid));
1273                 
1274                 if (!sid_append_rid(&all_group_SIDs[i], info3->gids[i].g_rid)) {
1275                 
1276                         nt_status = NT_STATUS_INVALID_PARAMETER;
1277                         
1278                         DEBUG(3,("could not append additional group rid 0x%x\n",
1279                                 info3->gids[i].g_rid));                 
1280                                 
1281                         SAFE_FREE(lgroupSIDs);
1282                         SAFE_FREE(all_group_SIDs);
1283                         free_server_info(server_info);
1284                         
1285                         return nt_status;
1286                         
1287                 }
1288         }
1289
1290         /* Copy 'other' sids.  We need to do sid filtering here to
1291            prevent possible elevation of privileges.  See:
1292
1293            http://www.microsoft.com/windows2000/techinfo/administration/security/sidfilter.asp
1294          */
1295
1296         for (i = 0; i < info3->num_other_sids; i++) {
1297                 sid_copy(&all_group_SIDs[info3->num_groups2 + i],
1298                          &info3->other_sids[i].sid);
1299         }
1300
1301
1302         /* add local alias sids */ 
1303
1304         for (i = 0; i < n_lgroupSIDs; i++) {
1305                 sid_copy(&all_group_SIDs[info3->num_groups2 +
1306                                          info3->num_other_sids + i],
1307                          &lgroupSIDs[i]);
1308         }
1309         
1310         /* Where are the 'global' sids... */
1311
1312         /* can the user be guest? if yes, where is it stored? */
1313         
1314         nt_status = create_nt_user_token(&user_sid, &group_sid,
1315                 info3->num_groups2 + info3->num_other_sids + n_lgroupSIDs,
1316                 all_group_SIDs, False, &token);
1317                 
1318         if ( !NT_STATUS_IS_OK(nt_status) ) {
1319                 DEBUG(4,("create_nt_user_token failed\n"));
1320                 SAFE_FREE(lgroupSIDs);
1321                 SAFE_FREE(all_group_SIDs);
1322                 free_server_info(server_info);
1323                 return nt_status;
1324         }
1325
1326         (*server_info)->ptok = token; 
1327
1328         SAFE_FREE(lgroupSIDs);
1329         SAFE_FREE(all_group_SIDs);
1330
1331         /* ensure we are never given NULL session keys */
1332         
1333         if (memcmp(info3->user_sess_key, zeros, sizeof(zeros)) == 0) {
1334                 (*server_info)->user_session_key = data_blob(NULL, 0);
1335         } else {
1336                 (*server_info)->user_session_key = data_blob(info3->user_sess_key, sizeof(info3->user_sess_key));
1337         }
1338
1339         if (memcmp(info3->lm_sess_key, zeros, 8) == 0) {
1340                 (*server_info)->lm_session_key = data_blob(NULL, 0);
1341         } else {
1342                 (*server_info)->lm_session_key = data_blob(info3->lm_sess_key, sizeof(info3->lm_sess_key));
1343         } 
1344
1345         return NT_STATUS_OK;
1346 }
1347
1348 /***************************************************************************
1349  Free a user_info struct
1350 ***************************************************************************/
1351
1352 void free_user_info(auth_usersupplied_info **user_info)
1353 {
1354         DEBUG(5,("attempting to free (and zero) a user_info structure\n"));
1355         if (*user_info != NULL) {
1356                 if ((*user_info)->smb_name.str) {
1357                         DEBUG(10,("structure was created for %s\n", (*user_info)->smb_name.str));
1358                 }
1359                 SAFE_FREE((*user_info)->smb_name.str);
1360                 SAFE_FREE((*user_info)->internal_username.str);
1361                 SAFE_FREE((*user_info)->client_domain.str);
1362                 SAFE_FREE((*user_info)->domain.str);
1363                 SAFE_FREE((*user_info)->wksta_name.str);
1364                 data_blob_free(&(*user_info)->lm_resp);
1365                 data_blob_free(&(*user_info)->nt_resp);
1366                 data_blob_clear_free(&(*user_info)->lm_interactive_pwd);
1367                 data_blob_clear_free(&(*user_info)->nt_interactive_pwd);
1368                 data_blob_clear_free(&(*user_info)->plaintext_password);
1369                 ZERO_STRUCT(**user_info);
1370         }
1371         SAFE_FREE(*user_info);
1372 }
1373
1374 /***************************************************************************
1375  Clear out a server_info struct that has been allocated
1376 ***************************************************************************/
1377
1378 void free_server_info(auth_serversupplied_info **server_info)
1379 {
1380         DEBUG(5,("attempting to free (and zero) a server_info structure\n"));
1381         if (*server_info != NULL) {
1382                 pdb_free_sam(&(*server_info)->sam_account);
1383
1384                 /* call pam_end here, unless we know we are keeping it */
1385                 delete_nt_token( &(*server_info)->ptok );
1386                 SAFE_FREE((*server_info)->groups);
1387                 SAFE_FREE((*server_info)->unix_name);
1388                 data_blob_free(&(*server_info)->lm_session_key);
1389                 data_blob_free(&(*server_info)->user_session_key);
1390                 ZERO_STRUCT(**server_info);
1391         }
1392         SAFE_FREE(*server_info);
1393 }
1394
1395 /***************************************************************************
1396  Make an auth_methods struct
1397 ***************************************************************************/
1398
1399 BOOL make_auth_methods(struct auth_context *auth_context, auth_methods **auth_method) 
1400 {
1401         if (!auth_context) {
1402                 smb_panic("no auth_context supplied to make_auth_methods()!\n");
1403         }
1404
1405         if (!auth_method) {
1406                 smb_panic("make_auth_methods: pointer to auth_method pointer is NULL!\n");
1407         }
1408
1409         *auth_method = TALLOC_P(auth_context->mem_ctx, auth_methods);
1410         if (!*auth_method) {
1411                 DEBUG(0,("make_auth_method: malloc failed!\n"));
1412                 return False;
1413         }
1414         ZERO_STRUCTP(*auth_method);
1415         
1416         return True;
1417 }
1418
1419 /****************************************************************************
1420  Delete a SID token.
1421 ****************************************************************************/
1422
1423 void delete_nt_token(NT_USER_TOKEN **pptoken)
1424 {
1425         if (*pptoken) {
1426                 NT_USER_TOKEN *ptoken = *pptoken;
1427
1428                 SAFE_FREE( ptoken->user_sids );
1429                 privilege_set_free( &ptoken->privileges );
1430
1431                 ZERO_STRUCTP(ptoken);
1432         }
1433         SAFE_FREE(*pptoken);
1434 }
1435
1436 /****************************************************************************
1437  Duplicate a SID token.
1438 ****************************************************************************/
1439
1440 NT_USER_TOKEN *dup_nt_token(NT_USER_TOKEN *ptoken)
1441 {
1442         NT_USER_TOKEN *token;
1443
1444         if (!ptoken)
1445                 return NULL;
1446
1447         if ((token = SMB_MALLOC_P(NT_USER_TOKEN)) == NULL)
1448                 return NULL;
1449
1450         ZERO_STRUCTP(token);
1451         
1452         token->user_sids = (DOM_SID *)memdup( ptoken->user_sids, sizeof(DOM_SID) * ptoken->num_sids );
1453         
1454         if ( !token ) {
1455                 SAFE_FREE(token);
1456                 return NULL;
1457         }
1458
1459         token->num_sids = ptoken->num_sids;
1460         
1461         /* copy the privileges; don't consider failure to be critical here */
1462         
1463         privilege_set_init( &token->privileges);
1464         if ( !dup_privilege_set( &token->privileges, &ptoken->privileges ) ) {
1465                 DEBUG(0,("dup_nt_token: Failure to copy PRIVILEGE_SET!.  Continuing with 0 privileges assigned.\n"));
1466         }
1467
1468         return token;
1469 }
1470
1471 /****************************************************************************
1472  Check for a SID in an NT_USER_TOKEN
1473 ****************************************************************************/
1474
1475 BOOL nt_token_check_sid ( DOM_SID *sid, NT_USER_TOKEN *token )
1476 {
1477         int i;
1478         
1479         if ( !sid || !token )
1480                 return False;
1481         
1482         for ( i=0; i<token->num_sids; i++ ) {
1483                 if ( sid_equal( sid, &token->user_sids[i] ) )
1484                         return True;
1485         }
1486
1487         return False;
1488 }
1489
1490 BOOL nt_token_check_domain_rid( NT_USER_TOKEN *token, uint32 rid ) 
1491 {
1492         DOM_SID domain_sid;
1493
1494         sid_copy( &domain_sid, get_global_sam_sid() );
1495         sid_append_rid( &domain_sid, rid );
1496         
1497         return nt_token_check_sid( &domain_sid, token );\
1498 }
1499
1500 /**
1501  * Verify whether or not given domain is trusted.
1502  *
1503  * @param domain_name name of the domain to be verified
1504  * @return true if domain is one of the trusted once or
1505  *         false if otherwise
1506  **/
1507
1508 BOOL is_trusted_domain(const char* dom_name)
1509 {
1510         DOM_SID trustdom_sid;
1511         char *pass = NULL;
1512         time_t lct;
1513         BOOL ret;
1514
1515         /* no trusted domains for a standalone server */
1516
1517         if ( lp_server_role() == ROLE_STANDALONE )
1518                 return False;
1519
1520         /* if we are a DC, then check for a direct trust relationships */
1521
1522         if ( IS_DC ) {
1523                 become_root();
1524                 DEBUG (5,("is_trusted_domain: Checking for domain trust with [%s]\n",
1525                         dom_name ));
1526                 ret = secrets_fetch_trusted_domain_password(dom_name, &pass, &trustdom_sid, &lct);
1527                 unbecome_root();
1528                 SAFE_FREE(pass);
1529                 if (ret)
1530                         return True;
1531         }
1532         else {
1533                 /* if winbindd is not up and we are a domain member) then we need to update the
1534                    trustdom_cache ourselves */
1535
1536                 if ( !winbind_ping() )
1537                         update_trustdom_cache();
1538         }
1539
1540         /* now the trustdom cache should be available a DC could still
1541          * have a transitive trust so fall back to the cache of trusted
1542          * domains (like a domain member would use  */
1543
1544         if ( trustdom_cache_fetch(dom_name, &trustdom_sid) ) {
1545                 return True;
1546         }
1547
1548         return False;
1549 }
1550