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