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