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