1ef64ab8458535f3e853a8d3fabca3b3add53930
[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  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 = malloc(sizeof(**user_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 = 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 = 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 = 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 = 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 = 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
498 /****************************************************************************
499  prints a UNIX 'token' to debug output.
500 ****************************************************************************/
501
502 void debug_unix_user_token(int dbg_class, int dbg_lev, uid_t uid, gid_t gid, int n_groups, gid_t *groups)
503 {
504         int     i;
505         DEBUGC(dbg_class, dbg_lev, ("UNIX token of user %ld\n", (long int)uid));
506
507         DEBUGADDC(dbg_class, dbg_lev, ("Primary group is %ld and contains %i supplementary groups\n", (long int)gid, n_groups));
508         for (i = 0; i < n_groups; i++)
509                 DEBUGADDC(dbg_class, dbg_lev, ("Group[%3i]: %ld\n", i, 
510                         (long int)groups[i]));
511 }
512
513 /****************************************************************************
514  Create the SID list for this user.
515 ****************************************************************************/
516
517 static NTSTATUS create_nt_user_token(const DOM_SID *user_sid, const DOM_SID *group_sid, 
518                                      int n_groupSIDs, DOM_SID *groupSIDs, 
519                                      BOOL is_guest, NT_USER_TOKEN **token)
520 {
521         NTSTATUS       nt_status = NT_STATUS_OK;
522         NT_USER_TOKEN *ptoken;
523         int i;
524         int sid_ndx;
525         
526         if ((ptoken = malloc( sizeof(NT_USER_TOKEN) ) ) == NULL) {
527                 DEBUG(0, ("create_nt_token: Out of memory allocating token\n"));
528                 nt_status = NT_STATUS_NO_MEMORY;
529                 return nt_status;
530         }
531
532         ZERO_STRUCTP(ptoken);
533
534         ptoken->num_sids = n_groupSIDs + 5;
535
536         if ((ptoken->user_sids = (DOM_SID *)malloc( sizeof(DOM_SID) * ptoken->num_sids )) == NULL) {
537                 DEBUG(0, ("create_nt_token: Out of memory allocating SIDs\n"));
538                 nt_status = NT_STATUS_NO_MEMORY;
539                 return nt_status;
540         }
541         
542         memset((char*)ptoken->user_sids,0,sizeof(DOM_SID) * ptoken->num_sids);
543         
544         /*
545          * Note - user SID *MUST* be first in token !
546          * se_access_check depends on this.
547          *
548          * Primary group SID is second in token. Convention.
549          */
550
551         sid_copy(&ptoken->user_sids[PRIMARY_USER_SID_INDEX], user_sid);
552         if (group_sid)
553                 sid_copy(&ptoken->user_sids[PRIMARY_GROUP_SID_INDEX], group_sid);
554
555         /*
556          * Finally add the "standard" SIDs.
557          * The only difference between guest and "anonymous" (which we
558          * don't really support) is the addition of Authenticated_Users.
559          */
560
561         sid_copy(&ptoken->user_sids[2], &global_sid_World);
562         sid_copy(&ptoken->user_sids[3], &global_sid_Network);
563
564         if (is_guest)
565                 sid_copy(&ptoken->user_sids[4], &global_sid_Builtin_Guests);
566         else
567                 sid_copy(&ptoken->user_sids[4], &global_sid_Authenticated_Users);
568         
569         sid_ndx = 5; /* next available spot */
570
571         for (i = 0; i < n_groupSIDs; i++) {
572                 size_t check_sid_idx;
573                 for (check_sid_idx = 1; check_sid_idx < ptoken->num_sids; check_sid_idx++) {
574                         if (sid_equal(&ptoken->user_sids[check_sid_idx], 
575                                       &groupSIDs[i])) {
576                                 break;
577                         }
578                 }
579                 
580                 if (check_sid_idx >= ptoken->num_sids) /* Not found already */ {
581                         sid_copy(&ptoken->user_sids[sid_ndx++], &groupSIDs[i]);
582                 } else {
583                         ptoken->num_sids--;
584                 }
585         }
586         
587         debug_nt_user_token(DBGC_AUTH, 10, ptoken);
588         
589         *token = ptoken;
590
591         return nt_status;
592 }
593
594 /****************************************************************************
595  Create the SID list for this user.
596 ****************************************************************************/
597
598 NT_USER_TOKEN *create_nt_token(uid_t uid, gid_t gid, int ngroups, gid_t *groups, BOOL is_guest)
599 {
600         DOM_SID user_sid;
601         DOM_SID group_sid;
602         DOM_SID *group_sids;
603         NT_USER_TOKEN *token;
604         int i;
605
606         if (!NT_STATUS_IS_OK(uid_to_sid(&user_sid, uid))) {
607                 return NULL;
608         }
609         if (!NT_STATUS_IS_OK(gid_to_sid(&group_sid, gid))) {
610                 return NULL;
611         }
612
613         group_sids = malloc(sizeof(DOM_SID) * ngroups);
614         if (!group_sids) {
615                 DEBUG(0, ("create_nt_token: malloc() failed for DOM_SID list!\n"));
616                 return NULL;
617         }
618
619         for (i = 0; i < ngroups; i++) {
620                 if (!NT_STATUS_IS_OK(gid_to_sid(&(group_sids)[i], (groups)[i]))) {
621                         DEBUG(1, ("create_nt_token: failed to convert gid %ld to a sid!\n", (long int)groups[i]));
622                         SAFE_FREE(group_sids);
623                         return NULL;
624                 }
625         }
626
627         if (!NT_STATUS_IS_OK(create_nt_user_token(&user_sid, &group_sid, 
628                                                   ngroups, group_sids, is_guest, &token))) {
629                 SAFE_FREE(group_sids);
630                 return NULL;
631         }
632
633         SAFE_FREE(group_sids);
634
635         return token;
636 }
637
638 /******************************************************************************
639  * this function returns the groups (SIDs) of the local SAM the user is in.
640  * If this samba server is a DC of the domain the user belongs to, it returns 
641  * both domain groups and local / builtin groups. If the user is in a trusted
642  * domain, or samba is a member server of a domain, then this function returns
643  * local and builtin groups the user is a member of.
644  *
645  * currently this is a hack, as there is no sam implementation that is capable
646  * of groups.
647  *
648  * NOTE!! This function will fail if you pass in a winbind user without 
649  * the domain   --jerry
650  ******************************************************************************/
651
652 static NTSTATUS get_user_groups(const char *username, uid_t uid, gid_t gid,
653                                 int *n_groups, DOM_SID **groups, gid_t **unix_groups)
654 {
655         int             n_unix_groups;
656         int             i;
657
658         *n_groups = 0;
659         *groups   = NULL;
660
661         if (strchr(username, *lp_winbind_separator()) == NULL) {
662                 NTSTATUS result;
663
664                 become_root();
665                 result = pdb_enum_group_memberships(username, gid, groups,
666                                                     unix_groups, n_groups);
667                 unbecome_root();
668                 return result;
669         }
670
671         /* We have the separator, this must be winbind */
672         
673         n_unix_groups = winbind_getgroups( username, unix_groups );
674
675         DEBUG(10,("get_user_groups: winbind_getgroups(%s): result = %s\n",
676                   username,  n_unix_groups == -1 ? "FAIL" : "SUCCESS"));
677                           
678         if ( n_unix_groups == -1 )
679                 return NT_STATUS_NO_SUCH_USER; /* what should this return
680                                                 * value be? */  
681
682         debug_unix_user_token(DBGC_CLASS, 5, uid, gid, n_unix_groups, *unix_groups);
683         
684         /* now setup the space for storing the SIDS */
685         
686         if (n_unix_groups > 0) {
687         
688                 *groups   = malloc(sizeof(DOM_SID) * n_unix_groups);
689                 
690                 if (!*groups) {
691                         DEBUG(0, ("get_user_group: malloc() failed for DOM_SID list!\n"));
692                         SAFE_FREE(*unix_groups);
693                         return NT_STATUS_NO_MEMORY;
694                 }
695         }
696
697         *n_groups = n_unix_groups;
698
699         for (i = 0; i < *n_groups; i++) {
700                 if (!NT_STATUS_IS_OK(gid_to_sid(&(*groups)[i], (*unix_groups)[i]))) {
701                         DEBUG(1, ("get_user_groups: failed to convert gid %ld to a sid!\n", 
702                                 (long int)(*unix_groups)[i+1]));
703                         SAFE_FREE(*groups);
704                         SAFE_FREE(*unix_groups);
705                         return NT_STATUS_NO_SUCH_USER;
706                 }
707         }
708                      
709         return NT_STATUS_OK;
710 }
711
712 /***************************************************************************
713  Make a user_info struct
714 ***************************************************************************/
715
716 static NTSTATUS make_server_info(auth_serversupplied_info **server_info)
717 {
718         *server_info = malloc(sizeof(**server_info));
719         if (!*server_info) {
720                 DEBUG(0,("make_server_info: malloc failed!\n"));
721                 return NT_STATUS_NO_MEMORY;
722         }
723         ZERO_STRUCTP(*server_info);
724
725         /* Initialise the uid and gid values to something non-zero
726            which may save us from giving away root access if there
727            is a bug in allocating these fields. */
728
729         (*server_info)->uid = -1;
730         (*server_info)->gid = -1;
731
732         return NT_STATUS_OK;
733 }
734
735 /***************************************************************************
736 Fill a server_info struct from a SAM_ACCOUNT with their groups
737 ***************************************************************************/
738
739 static NTSTATUS add_user_groups(auth_serversupplied_info **server_info, 
740                                 const char * unix_username,
741                                 SAM_ACCOUNT *sampass,
742                                 uid_t uid, gid_t gid)
743 {
744         NTSTATUS nt_status;
745         const DOM_SID *user_sid = pdb_get_user_sid(sampass);
746         const DOM_SID *group_sid = pdb_get_group_sid(sampass);
747         int       n_groupSIDs = 0;
748         DOM_SID  *groupSIDs   = NULL;
749         gid_t    *unix_groups = NULL;
750         NT_USER_TOKEN *token;
751         BOOL is_guest;
752         uint32 rid;
753
754         nt_status = get_user_groups(unix_username, uid, gid, 
755                 &n_groupSIDs, &groupSIDs, &unix_groups);
756                 
757         if (!NT_STATUS_IS_OK(nt_status)) {
758                 DEBUG(4,("get_user_groups_from_local_sam failed\n"));
759                 free_server_info(server_info);
760                 return nt_status;
761         }
762         
763         is_guest = (sid_peek_rid(user_sid, &rid) && rid == DOMAIN_USER_RID_GUEST);
764
765         if (!NT_STATUS_IS_OK(nt_status = create_nt_user_token(user_sid, group_sid,
766                                                               n_groupSIDs, groupSIDs, is_guest, 
767                                                               &token)))
768         {
769                 DEBUG(4,("create_nt_user_token failed\n"));
770                 SAFE_FREE(groupSIDs);
771                 SAFE_FREE(unix_groups);
772                 free_server_info(server_info);
773                 return nt_status;
774         }
775         
776         SAFE_FREE(groupSIDs);
777
778         (*server_info)->n_groups = n_groupSIDs;
779         (*server_info)->groups = unix_groups;
780         (*server_info)->ptok = token;
781
782         return nt_status;
783 }
784
785 /***************************************************************************
786  Make (and fill) a user_info struct from a SAM_ACCOUNT
787 ***************************************************************************/
788
789 NTSTATUS make_server_info_sam(auth_serversupplied_info **server_info, 
790                               SAM_ACCOUNT *sampass)
791 {
792         NTSTATUS nt_status;
793         struct passwd *pwd;
794
795         if (!NT_STATUS_IS_OK(nt_status = make_server_info(server_info)))
796                 return nt_status;
797
798         (*server_info)->sam_account    = sampass;
799
800         if ( !(pwd = getpwnam_alloc(pdb_get_username(sampass))) )  {
801                 DEBUG(1, ("User %s in passdb, but getpwnam() fails!\n",
802                           pdb_get_username(sampass)));
803                 free_server_info(server_info);
804                 return NT_STATUS_NO_SUCH_USER;
805         }
806         (*server_info)->unix_name = smb_xstrdup(pwd->pw_name);
807         (*server_info)->gid = pwd->pw_gid;
808         (*server_info)->uid = pwd->pw_uid;
809         
810         passwd_free(&pwd);
811
812         if (!NT_STATUS_IS_OK(nt_status = add_user_groups(server_info, pdb_get_username(sampass), 
813                                                          sampass,
814                                                          (*server_info)->uid, 
815                                                          (*server_info)->gid))) 
816         {
817                 free_server_info(server_info);
818                 return nt_status;
819         }
820
821         (*server_info)->sam_fill_level = SAM_FILL_ALL;
822         DEBUG(5,("make_server_info_sam: made server info for user %s -> %s\n",
823                  pdb_get_username(sampass),
824                  (*server_info)->unix_name));
825
826         return nt_status;
827 }
828
829 /***************************************************************************
830  Make (and fill) a user_info struct from a 'struct passwd' by conversion 
831  to a SAM_ACCOUNT
832 ***************************************************************************/
833
834 NTSTATUS make_server_info_pw(auth_serversupplied_info **server_info, 
835                              char *unix_username,
836                              struct passwd *pwd)
837 {
838         NTSTATUS nt_status;
839         SAM_ACCOUNT *sampass = NULL;
840         if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam_pw(&sampass, pwd))) {             
841                 return nt_status;
842         }
843         if (!NT_STATUS_IS_OK(nt_status = make_server_info(server_info))) {
844                 return nt_status;
845         }
846
847         (*server_info)->sam_account    = sampass;
848
849         if (!NT_STATUS_IS_OK(nt_status = add_user_groups(server_info, unix_username,
850                 sampass, pwd->pw_uid, pwd->pw_gid))) 
851         {
852                 return nt_status;
853         }
854
855         (*server_info)->unix_name = smb_xstrdup(unix_username);
856
857         (*server_info)->sam_fill_level = SAM_FILL_ALL;
858         (*server_info)->uid = pwd->pw_uid;
859         (*server_info)->gid = pwd->pw_gid;
860         return nt_status;
861 }
862
863 /***************************************************************************
864  Make (and fill) a user_info struct for a guest login.
865 ***************************************************************************/
866
867 static NTSTATUS make_new_server_info_guest(auth_serversupplied_info **server_info)
868 {
869         NTSTATUS nt_status;
870         SAM_ACCOUNT *sampass = NULL;
871         DOM_SID guest_sid;
872
873         if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam(&sampass))) {
874                 return nt_status;
875         }
876
877         sid_copy(&guest_sid, get_global_sam_sid());
878         sid_append_rid(&guest_sid, DOMAIN_USER_RID_GUEST);
879
880         become_root();
881         if (!pdb_getsampwsid(sampass, &guest_sid)) {
882                 unbecome_root();
883                 return NT_STATUS_NO_SUCH_USER;
884         }
885         unbecome_root();
886
887         nt_status = make_server_info_sam(server_info, sampass);
888
889         if (NT_STATUS_IS_OK(nt_status)) {
890                 static const char zeros[16];
891                 (*server_info)->guest = True;
892                 
893                 /* annoying, but the Guest really does have a session key, 
894                    and it is all zeros! */
895                 (*server_info)->user_session_key = data_blob(zeros, sizeof(zeros));
896                 (*server_info)->lm_session_key = data_blob(zeros, sizeof(zeros));
897         }
898
899         return nt_status;
900 }
901
902 static auth_serversupplied_info *copy_serverinfo(auth_serversupplied_info *src)
903 {
904         auth_serversupplied_info *dst;
905
906         if (!NT_STATUS_IS_OK(make_server_info(&dst)))
907                 return NULL;
908
909         dst->guest = src->guest;
910         dst->uid = src->uid;
911         dst->gid = src->gid;
912         dst->n_groups = src->n_groups;
913         if (src->n_groups != 0)
914                 dst->groups = memdup(src->groups, sizeof(gid_t)*dst->n_groups);
915         else
916                 dst->groups = NULL;
917         dst->ptok = dup_nt_token(src->ptok);
918         dst->user_session_key = data_blob(src->user_session_key.data,
919                                           src->user_session_key.length);
920         dst->lm_session_key = data_blob(src->lm_session_key.data,
921                                           src->lm_session_key.length);
922         pdb_copy_sam_account(src->sam_account, &dst->sam_account);
923         dst->pam_handle = NULL;
924         dst->unix_name = smb_xstrdup(src->unix_name);
925
926         return dst;
927 }
928
929 static auth_serversupplied_info *guest_info = NULL;
930
931 BOOL init_guest_info(void)
932 {
933         if (guest_info != NULL)
934                 return True;
935
936         return NT_STATUS_IS_OK(make_new_server_info_guest(&guest_info));
937 }
938
939 NTSTATUS make_server_info_guest(auth_serversupplied_info **server_info)
940 {
941         *server_info = copy_serverinfo(guest_info);
942         return (*server_info != NULL) ? NT_STATUS_OK : NT_STATUS_NO_MEMORY;
943 }
944
945 /***************************************************************************
946  Purely internal function for make_server_info_info3
947  Fill the sam account from getpwnam
948 ***************************************************************************/
949 static NTSTATUS fill_sam_account(TALLOC_CTX *mem_ctx, 
950                                  const char *domain,
951                                  const char *username,
952                                  char **found_username,
953                                  uid_t *uid, gid_t *gid,
954                                  SAM_ACCOUNT **sam_account)
955 {
956         fstring dom_user, lower_username;
957         fstring real_username;
958         struct passwd *passwd;
959
960         fstrcpy( lower_username, username );
961         strlower_m( lower_username );
962
963         fstr_sprintf(dom_user, "%s%c%s", domain, *lp_winbind_separator(), 
964                 lower_username);
965
966         /* get the passwd struct but don't create the user if he/she 
967            does not exist.  We were explicitly called from a following
968            a winbindd authentication request so we should assume that 
969            nss_winbindd is working */
970
971         map_username( dom_user );
972
973         if ( !(passwd = smb_getpwnam( dom_user, real_username, True )) )
974                 return NT_STATUS_NO_SUCH_USER;
975
976         *uid = passwd->pw_uid;
977         *gid = passwd->pw_gid;
978
979         /* This is pointless -- there is no suport for differing 
980            unix and windows names.  Make sure to always store the 
981            one we actually looked up and succeeded. Have I mentioned
982            why I hate the 'winbind use default domain' parameter?   
983                                          --jerry              */
984            
985         *found_username = talloc_strdup( mem_ctx, real_username );
986         
987         DEBUG(5,("fill_sam_account: located username was [%s]\n",
988                 *found_username));
989
990         return pdb_init_sam_pw(sam_account, passwd);
991 }
992
993 /****************************************************************************
994  Wrapper to allow the getpwnam() call to strip the domain name and 
995  try again in case a local UNIX user is already there.  Also run through 
996  the username if we fallback to the username only.
997  ****************************************************************************/
998  
999 struct passwd *smb_getpwnam( char *domuser, fstring save_username, BOOL create )
1000 {
1001         struct passwd *pw = NULL;
1002         char *p;
1003         fstring username;
1004         
1005         /* we only save a copy of the username it has been mangled 
1006            by winbindd use default domain */
1007            
1008         save_username[0] = '\0';
1009            
1010         /* don't call map_username() here since it has to be done higher 
1011            up the stack so we don't call it mutliple times */
1012
1013         fstrcpy( username, domuser );
1014         
1015         p = strchr_m( username, *lp_winbind_separator() );
1016         
1017         /* code for a DOMAIN\user string */
1018         
1019         if ( p ) {
1020                 fstring strip_username;
1021
1022                 pw = Get_Pwnam( domuser );
1023                 if ( pw ) {     
1024                         /* make sure we get the case of the username correct */
1025                         /* work around 'winbind use default domain = yes' */
1026
1027                         if ( !strchr_m( pw->pw_name, *lp_winbind_separator() ) ) {
1028                                 char *domain;
1029                                 
1030                                 /* split the domain and username into 2 strings */
1031                                 *p = '\0';
1032                                 domain = username;
1033
1034                                 fstr_sprintf(save_username, "%s%c%s", domain, *lp_winbind_separator(), pw->pw_name);
1035                         }
1036                         else
1037                                 fstrcpy( save_username, pw->pw_name );
1038
1039                         /* whew -- done! */             
1040                         return pw;
1041                 }
1042
1043                 /* setup for lookup of just the username */
1044                 /* remember that p and username are overlapping memory */
1045
1046                 p++;
1047                 fstrcpy( strip_username, p );
1048                 fstrcpy( username, strip_username );
1049         }
1050         
1051         /* just lookup a plain username */
1052         
1053         pw = Get_Pwnam(username);
1054                 
1055         /* Create local user if requested. */
1056         
1057         if ( !pw && create ) {
1058                 /* Don't add a machine account. */
1059                 if (username[strlen(username)-1] == '$')
1060                         return NULL;
1061
1062                 auth_add_user_script(NULL, username);
1063                 pw = Get_Pwnam(username);
1064         }
1065         
1066         /* one last check for a valid passwd struct */
1067         
1068         if ( pw )
1069                 fstrcpy( save_username, pw->pw_name );
1070
1071         return pw;
1072 }
1073
1074 /***************************************************************************
1075  Make a server_info struct from the info3 returned by a domain logon 
1076 ***************************************************************************/
1077
1078 NTSTATUS make_server_info_info3(TALLOC_CTX *mem_ctx, 
1079                                 const char *internal_username,
1080                                 const char *sent_nt_username,
1081                                 const char *domain,
1082                                 auth_serversupplied_info **server_info, 
1083                                 NET_USER_INFO_3 *info3) 
1084 {
1085         static const char zeros[16];
1086
1087         NTSTATUS nt_status = NT_STATUS_OK;
1088         char *found_username;
1089         const char *nt_domain;
1090         const char *nt_username;
1091
1092         SAM_ACCOUNT *sam_account = NULL;
1093         DOM_SID user_sid;
1094         DOM_SID group_sid;
1095
1096         uid_t uid;
1097         gid_t gid;
1098
1099         int n_lgroupSIDs;
1100         DOM_SID *lgroupSIDs   = NULL;
1101
1102         gid_t *unix_groups = NULL;
1103         NT_USER_TOKEN *token;
1104
1105         DOM_SID *all_group_SIDs;
1106         size_t i;
1107
1108         /* 
1109            Here is where we should check the list of
1110            trusted domains, and verify that the SID 
1111            matches.
1112         */
1113
1114         sid_copy(&user_sid, &info3->dom_sid.sid);
1115         if (!sid_append_rid(&user_sid, info3->user_rid)) {
1116                 return NT_STATUS_INVALID_PARAMETER;
1117         }
1118         
1119         sid_copy(&group_sid, &info3->dom_sid.sid);
1120         if (!sid_append_rid(&group_sid, info3->group_rid)) {
1121                 return NT_STATUS_INVALID_PARAMETER;
1122         }
1123
1124         if (!(nt_username = unistr2_tdup(mem_ctx, &(info3->uni_user_name)))) {
1125                 /* If the server didn't give us one, just use the one we sent them */
1126                 nt_username = sent_nt_username;
1127         }
1128
1129         if (!(nt_domain = unistr2_tdup(mem_ctx, &(info3->uni_logon_dom)))) {
1130                 /* If the server didn't give us one, just use the one we sent them */
1131                 nt_domain = domain;
1132         }
1133         
1134         /* try to fill the SAM account..  If getpwnam() fails, then try the 
1135            add user script (2.2.x behavior).
1136
1137            We use the _unmapped_ username here in an attempt to provide
1138            consistent username mapping behavior between kerberos and NTLM[SSP]
1139            authentication in domain mode security.  I.E. Username mapping should
1140            be applied to the fully qualified username (e.g. DOMAIN\user) and
1141            no just the login name.  Yes this mean swe called map_username()
1142            unnecessarily in make_user_info_map() but that is how the current
1143            code is designed.  Making the change here is the least disruptive 
1144            place.    -- jerry */
1145            
1146         nt_status = fill_sam_account(mem_ctx, nt_domain, sent_nt_username,
1147                 &found_username, &uid, &gid, &sam_account);
1148
1149         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1150                 DEBUG(3,("User %s does not exist, trying to add it\n", internal_username));
1151                 auth_add_user_script( nt_domain, sent_nt_username );
1152                 nt_status = fill_sam_account( mem_ctx, nt_domain, sent_nt_username, 
1153                         &found_username, &uid, &gid, &sam_account );
1154         }
1155         
1156         if (!NT_STATUS_IS_OK(nt_status)) {
1157                 DEBUG(0, ("make_server_info_info3: pdb_init_sam failed!\n"));
1158                 return nt_status;
1159         }
1160                 
1161         if (!pdb_set_nt_username(sam_account, nt_username, PDB_CHANGED)) {
1162                 pdb_free_sam(&sam_account);
1163                 return NT_STATUS_NO_MEMORY;
1164         }
1165
1166         if (!pdb_set_username(sam_account, nt_username, PDB_CHANGED)) {
1167                 pdb_free_sam(&sam_account);
1168                 return NT_STATUS_NO_MEMORY;
1169         }
1170
1171         if (!pdb_set_domain(sam_account, nt_domain, PDB_CHANGED)) {
1172                 pdb_free_sam(&sam_account);
1173                 return NT_STATUS_NO_MEMORY;
1174         }
1175
1176         if (!pdb_set_user_sid(sam_account, &user_sid, PDB_CHANGED)) {
1177                 pdb_free_sam(&sam_account);
1178                 return NT_STATUS_UNSUCCESSFUL;
1179         }
1180
1181         if (!pdb_set_group_sid(sam_account, &group_sid, PDB_CHANGED)) {
1182                 pdb_free_sam(&sam_account);
1183                 return NT_STATUS_UNSUCCESSFUL;
1184         }
1185                 
1186         if (!pdb_set_fullname(sam_account, unistr2_static(&(info3->uni_full_name)), 
1187                               PDB_CHANGED)) {
1188                 pdb_free_sam(&sam_account);
1189                 return NT_STATUS_NO_MEMORY;
1190         }
1191
1192         if (!pdb_set_logon_script(sam_account, unistr2_static(&(info3->uni_logon_script)), PDB_CHANGED)) {
1193                 pdb_free_sam(&sam_account);
1194                 return NT_STATUS_NO_MEMORY;
1195         }
1196
1197         if (!pdb_set_profile_path(sam_account, unistr2_static(&(info3->uni_profile_path)), PDB_CHANGED)) {
1198                 pdb_free_sam(&sam_account);
1199                 return NT_STATUS_NO_MEMORY;
1200         }
1201
1202         if (!pdb_set_homedir(sam_account, unistr2_static(&(info3->uni_home_dir)), PDB_CHANGED)) {
1203                 pdb_free_sam(&sam_account);
1204                 return NT_STATUS_NO_MEMORY;
1205         }
1206
1207         if (!pdb_set_dir_drive(sam_account, unistr2_static(&(info3->uni_dir_drive)), PDB_CHANGED)) {
1208                 pdb_free_sam(&sam_account);
1209                 return NT_STATUS_NO_MEMORY;
1210         }
1211
1212         if (!NT_STATUS_IS_OK(nt_status = make_server_info(server_info))) {
1213                 DEBUG(4, ("make_server_info failed!\n"));
1214                 pdb_free_sam(&sam_account);
1215                 return nt_status;
1216         }
1217
1218         /* save this here to _net_sam_logon() doesn't fail (it assumes a 
1219            valid SAM_ACCOUNT) */
1220                    
1221         (*server_info)->sam_account = sam_account;
1222
1223         (*server_info)->unix_name = smb_xstrdup(found_username);
1224
1225         /* Fill in the unix info we found on the way */
1226
1227         (*server_info)->sam_fill_level = SAM_FILL_ALL;
1228         (*server_info)->uid = uid;
1229         (*server_info)->gid = gid;
1230
1231         /* Store the user group information in the server_info 
1232            returned to the caller. */
1233         
1234         nt_status = get_user_groups((*server_info)->unix_name,
1235                 uid, gid, &n_lgroupSIDs, &lgroupSIDs, &unix_groups);
1236                 
1237         if ( !NT_STATUS_IS_OK(nt_status) ) {
1238                 DEBUG(4,("get_user_groups failed\n"));
1239                 return nt_status;
1240         }
1241
1242         (*server_info)->groups = unix_groups;
1243         (*server_info)->n_groups = n_lgroupSIDs;
1244         
1245         /* Create a 'combined' list of all SIDs we might want in the SD */
1246         
1247         all_group_SIDs = malloc(sizeof(DOM_SID) * (info3->num_groups2 + info3->num_other_sids + n_lgroupSIDs));
1248         
1249         if (!all_group_SIDs) {
1250                 DEBUG(0, ("malloc() failed for DOM_SID list!\n"));
1251                 SAFE_FREE(lgroupSIDs);
1252                 free_server_info(server_info);
1253                 return NT_STATUS_NO_MEMORY;
1254         }
1255
1256         /* and create (by appending rids) the 'domain' sids */
1257         
1258         for (i = 0; i < info3->num_groups2; i++) {
1259         
1260                 sid_copy(&all_group_SIDs[i], &(info3->dom_sid.sid));
1261                 
1262                 if (!sid_append_rid(&all_group_SIDs[i], info3->gids[i].g_rid)) {
1263                 
1264                         nt_status = NT_STATUS_INVALID_PARAMETER;
1265                         
1266                         DEBUG(3,("could not append additional group rid 0x%x\n",
1267                                 info3->gids[i].g_rid));                 
1268                                 
1269                         SAFE_FREE(lgroupSIDs);
1270                         SAFE_FREE(all_group_SIDs);
1271                         free_server_info(server_info);
1272                         
1273                         return nt_status;
1274                         
1275                 }
1276         }
1277
1278         /* Copy 'other' sids.  We need to do sid filtering here to
1279            prevent possible elevation of privileges.  See:
1280
1281            http://www.microsoft.com/windows2000/techinfo/administration/security/sidfilter.asp
1282          */
1283
1284         for (i = 0; i < info3->num_other_sids; i++) {
1285                 sid_copy(&all_group_SIDs[info3->num_groups2 + i],
1286                          &info3->other_sids[i].sid);
1287         }
1288
1289
1290         /* add local alias sids */ 
1291
1292         for (i = 0; i < n_lgroupSIDs; i++) {
1293                 sid_copy(&all_group_SIDs[info3->num_groups2 +
1294                                          info3->num_other_sids + i],
1295                          &lgroupSIDs[i]);
1296         }
1297         
1298         /* Where are the 'global' sids... */
1299
1300         /* can the user be guest? if yes, where is it stored? */
1301         
1302         nt_status = create_nt_user_token(&user_sid, &group_sid,
1303                 info3->num_groups2 + info3->num_other_sids + n_lgroupSIDs,
1304                 all_group_SIDs, False, &token);
1305                 
1306         if ( !NT_STATUS_IS_OK(nt_status) ) {
1307                 DEBUG(4,("create_nt_user_token failed\n"));
1308                 SAFE_FREE(lgroupSIDs);
1309                 SAFE_FREE(all_group_SIDs);
1310                 free_server_info(server_info);
1311                 return nt_status;
1312         }
1313
1314         (*server_info)->ptok = token; 
1315
1316         SAFE_FREE(lgroupSIDs);
1317         SAFE_FREE(all_group_SIDs);
1318
1319         /* ensure we are never given NULL session keys */
1320         
1321         if (memcmp(info3->user_sess_key, zeros, sizeof(zeros)) == 0) {
1322                 (*server_info)->user_session_key = data_blob(NULL, 0);
1323         } else {
1324                 (*server_info)->user_session_key = data_blob(info3->user_sess_key, sizeof(info3->user_sess_key));
1325         }
1326
1327         if (memcmp(info3->padding, zeros, sizeof(zeros)) == 0) {
1328                 (*server_info)->lm_session_key = data_blob(NULL, 0);
1329         } else {
1330                 (*server_info)->lm_session_key = data_blob(info3->padding, 16);
1331         }
1332         return NT_STATUS_OK;
1333 }
1334
1335 /***************************************************************************
1336  Free a user_info struct
1337 ***************************************************************************/
1338
1339 void free_user_info(auth_usersupplied_info **user_info)
1340 {
1341         DEBUG(5,("attempting to free (and zero) a user_info structure\n"));
1342         if (*user_info != NULL) {
1343                 if ((*user_info)->smb_name.str) {
1344                         DEBUG(10,("structure was created for %s\n", (*user_info)->smb_name.str));
1345                 }
1346                 SAFE_FREE((*user_info)->smb_name.str);
1347                 SAFE_FREE((*user_info)->internal_username.str);
1348                 SAFE_FREE((*user_info)->client_domain.str);
1349                 SAFE_FREE((*user_info)->domain.str);
1350                 SAFE_FREE((*user_info)->wksta_name.str);
1351                 data_blob_free(&(*user_info)->lm_resp);
1352                 data_blob_free(&(*user_info)->nt_resp);
1353                 data_blob_clear_free(&(*user_info)->lm_interactive_pwd);
1354                 data_blob_clear_free(&(*user_info)->nt_interactive_pwd);
1355                 data_blob_clear_free(&(*user_info)->plaintext_password);
1356                 ZERO_STRUCT(**user_info);
1357         }
1358         SAFE_FREE(*user_info);
1359 }
1360
1361 /***************************************************************************
1362  Clear out a server_info struct that has been allocated
1363 ***************************************************************************/
1364
1365 void free_server_info(auth_serversupplied_info **server_info)
1366 {
1367         DEBUG(5,("attempting to free (and zero) a server_info structure\n"));
1368         if (*server_info != NULL) {
1369                 pdb_free_sam(&(*server_info)->sam_account);
1370
1371                 /* call pam_end here, unless we know we are keeping it */
1372                 delete_nt_token( &(*server_info)->ptok );
1373                 SAFE_FREE((*server_info)->groups);
1374                 SAFE_FREE((*server_info)->unix_name);
1375                 data_blob_free(&(*server_info)->lm_session_key);
1376                 data_blob_free(&(*server_info)->user_session_key);
1377                 ZERO_STRUCT(**server_info);
1378         }
1379         SAFE_FREE(*server_info);
1380 }
1381
1382 /***************************************************************************
1383  Make an auth_methods struct
1384 ***************************************************************************/
1385
1386 BOOL make_auth_methods(struct auth_context *auth_context, auth_methods **auth_method) 
1387 {
1388         if (!auth_context) {
1389                 smb_panic("no auth_context supplied to make_auth_methods()!\n");
1390         }
1391
1392         if (!auth_method) {
1393                 smb_panic("make_auth_methods: pointer to auth_method pointer is NULL!\n");
1394         }
1395
1396         *auth_method = talloc(auth_context->mem_ctx, sizeof(**auth_method));
1397         if (!*auth_method) {
1398                 DEBUG(0,("make_auth_method: malloc failed!\n"));
1399                 return False;
1400         }
1401         ZERO_STRUCTP(*auth_method);
1402         
1403         return True;
1404 }
1405
1406 /****************************************************************************
1407  Delete a SID token.
1408 ****************************************************************************/
1409
1410 void delete_nt_token(NT_USER_TOKEN **pptoken)
1411 {
1412     if (*pptoken) {
1413             NT_USER_TOKEN *ptoken = *pptoken;
1414             SAFE_FREE( ptoken->user_sids );
1415             ZERO_STRUCTP(ptoken);
1416     }
1417     SAFE_FREE(*pptoken);
1418 }
1419
1420 /****************************************************************************
1421  Duplicate a SID token.
1422 ****************************************************************************/
1423
1424 NT_USER_TOKEN *dup_nt_token(NT_USER_TOKEN *ptoken)
1425 {
1426         NT_USER_TOKEN *token;
1427
1428         if (!ptoken)
1429                 return NULL;
1430
1431     if ((token = (NT_USER_TOKEN *)malloc( sizeof(NT_USER_TOKEN) ) ) == NULL)
1432         return NULL;
1433
1434     ZERO_STRUCTP(token);
1435
1436     if ((token->user_sids = (DOM_SID *)memdup( ptoken->user_sids, sizeof(DOM_SID) * ptoken->num_sids )) == NULL) {
1437         SAFE_FREE(token);
1438         return NULL;
1439     }
1440
1441     token->num_sids = ptoken->num_sids;
1442
1443         return token;
1444 }
1445
1446 /**
1447  * Verify whether or not given domain is trusted.
1448  *
1449  * @param domain_name name of the domain to be verified
1450  * @return true if domain is one of the trusted once or
1451  *         false if otherwise
1452  **/
1453
1454 BOOL is_trusted_domain(const char* dom_name)
1455 {
1456         DOM_SID trustdom_sid;
1457         char *pass = NULL;
1458         time_t lct;
1459         BOOL ret;
1460
1461         /* no trusted domains for a standalone server */
1462
1463         if ( lp_server_role() == ROLE_STANDALONE )
1464                 return False;
1465
1466         /* if we are a DC, then check for a direct trust relationships */
1467
1468         if ( IS_DC ) {
1469                 become_root();
1470                 DEBUG (5,("is_trusted_domain: Checking for domain trust with [%s]\n",
1471                         dom_name ));
1472                 ret = secrets_fetch_trusted_domain_password(dom_name, &pass, &trustdom_sid, &lct);
1473                 unbecome_root();
1474                 SAFE_FREE(pass);
1475                 if (ret)
1476                         return True;
1477         }
1478         else {
1479                 /* if winbindd is not up and we are a domain member) then we need to update the
1480                    trustdom_cache ourselves */
1481
1482                 if ( !winbind_ping() )
1483                         update_trustdom_cache();
1484         }
1485
1486         /* now the trustdom cache should be available a DC could still
1487          * have a transitive trust so fall back to the cache of trusted
1488          * domains (like a domain member would use  */
1489
1490         if ( trustdom_cache_fetch(dom_name, &trustdom_sid) ) {
1491                 return True;
1492         }
1493
1494         return False;
1495 }
1496