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