9d29987c0dcd8125f3a025b133edc6d2ad2a826f
[samba.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    Copyright (C) Volker Lendecke 2006
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "../libcli/auth/libcli_auth.h"
26
27 #undef DBGC_CLASS
28 #define DBGC_CLASS DBGC_AUTH
29
30 /****************************************************************************
31  Ensure primary group SID is always at position 0 in a 
32  auth_serversupplied_info struct.
33 ****************************************************************************/
34
35 static void sort_sid_array_for_smbd(auth_serversupplied_info *result,
36                                 const DOM_SID *pgroup_sid)
37 {
38         unsigned int i;
39
40         if (!result->sids) {
41                 return;
42         }
43
44         if (sid_compare(&result->sids[0], pgroup_sid)==0) {
45                 return;
46         }
47
48         for (i = 1; i < result->num_sids; i++) {
49                 if (sid_compare(pgroup_sid,
50                                 &result->sids[i]) == 0) {
51                         sid_copy(&result->sids[i], &result->sids[0]);
52                         sid_copy(&result->sids[0], pgroup_sid);
53                         return;
54                 }
55         }
56 }
57
58 /****************************************************************************
59  Create a UNIX user on demand.
60 ****************************************************************************/
61
62 static int _smb_create_user(const char *domain, const char *unix_username, const char *homedir)
63 {
64         TALLOC_CTX *ctx = talloc_tos();
65         char *add_script;
66         int ret;
67
68         add_script = talloc_strdup(ctx, lp_adduser_script());
69         if (!add_script || !*add_script) {
70                 return -1;
71         }
72         add_script = talloc_all_string_sub(ctx,
73                                 add_script,
74                                 "%u",
75                                 unix_username);
76         if (!add_script) {
77                 return -1;
78         }
79         if (domain) {
80                 add_script = talloc_all_string_sub(ctx,
81                                         add_script,
82                                         "%D",
83                                         domain);
84                 if (!add_script) {
85                         return -1;
86                 }
87         }
88         if (homedir) {
89                 add_script = talloc_all_string_sub(ctx,
90                                 add_script,
91                                 "%H",
92                                 homedir);
93                 if (!add_script) {
94                         return -1;
95                 }
96         }
97         ret = smbrun(add_script,NULL);
98         flush_pwnam_cache();
99         DEBUG(ret ? 0 : 3,
100                 ("smb_create_user: Running the command `%s' gave %d\n",
101                  add_script,ret));
102         return ret;
103 }
104
105 /****************************************************************************
106  Create an auth_usersupplied_data structure
107 ****************************************************************************/
108
109 static NTSTATUS make_user_info(auth_usersupplied_info **user_info,
110                                const char *smb_name,
111                                const char *internal_username,
112                                const char *client_domain,
113                                const char *domain,
114                                const char *wksta_name,
115                                DATA_BLOB *lm_pwd, DATA_BLOB *nt_pwd,
116                                DATA_BLOB *lm_interactive_pwd, DATA_BLOB *nt_interactive_pwd,
117                                DATA_BLOB *plaintext,
118                                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 = SMB_MALLOC_P(auth_usersupplied_info);
124         if (*user_info == NULL) {
125                 DEBUG(0,("malloc failed for user_info (size %lu)\n", (unsigned long)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 = SMB_STRDUP(smb_name);
134         if ((*user_info)->smb_name == NULL) { 
135                 free_user_info(user_info);
136                 return NT_STATUS_NO_MEMORY;
137         }
138         
139         (*user_info)->internal_username = SMB_STRDUP(internal_username);
140         if ((*user_info)->internal_username == NULL) { 
141                 free_user_info(user_info);
142                 return NT_STATUS_NO_MEMORY;
143         }
144
145         (*user_info)->domain = SMB_STRDUP(domain);
146         if ((*user_info)->domain == NULL) { 
147                 free_user_info(user_info);
148                 return NT_STATUS_NO_MEMORY;
149         }
150
151         (*user_info)->client_domain = SMB_STRDUP(client_domain);
152         if ((*user_info)->client_domain == NULL) { 
153                 free_user_info(user_info);
154                 return NT_STATUS_NO_MEMORY;
155         }
156
157         (*user_info)->wksta_name = SMB_STRDUP(wksta_name);
158         if ((*user_info)->wksta_name == NULL) { 
159                 free_user_info(user_info);
160                 return NT_STATUS_NO_MEMORY;
161         }
162
163         DEBUG(5,("making blobs for %s's user_info struct\n", internal_username));
164
165         if (lm_pwd)
166                 (*user_info)->lm_resp = data_blob(lm_pwd->data, lm_pwd->length);
167         if (nt_pwd)
168                 (*user_info)->nt_resp = data_blob(nt_pwd->data, nt_pwd->length);
169         if (lm_interactive_pwd)
170                 (*user_info)->lm_interactive_pwd = data_blob(lm_interactive_pwd->data, lm_interactive_pwd->length);
171         if (nt_interactive_pwd)
172                 (*user_info)->nt_interactive_pwd = data_blob(nt_interactive_pwd->data, nt_interactive_pwd->length);
173
174         if (plaintext)
175                 (*user_info)->plaintext_password = data_blob(plaintext->data, plaintext->length);
176
177         (*user_info)->encrypted = encrypted;
178
179         (*user_info)->logon_parameters = 0;
180
181         DEBUG(10,("made an %sencrypted user_info for %s (%s)\n", encrypted ? "":"un" , internal_username, smb_name));
182
183         return NT_STATUS_OK;
184 }
185
186 /****************************************************************************
187  Create an auth_usersupplied_data structure after appropriate mapping.
188 ****************************************************************************/
189
190 NTSTATUS make_user_info_map(auth_usersupplied_info **user_info,
191                             const char *smb_name,
192                             const char *client_domain,
193                             const char *wksta_name,
194                             DATA_BLOB *lm_pwd,
195                             DATA_BLOB *nt_pwd,
196                             DATA_BLOB *lm_interactive_pwd,
197                             DATA_BLOB *nt_interactive_pwd,
198                             DATA_BLOB *plaintext,
199                             bool encrypted)
200 {
201         const char *domain;
202         NTSTATUS result;
203         bool was_mapped;
204         fstring internal_username;
205         fstrcpy(internal_username, smb_name);
206         was_mapped = map_username(internal_username);
207
208         DEBUG(5, ("Mapping user [%s]\\[%s] from workstation [%s]\n",
209                  client_domain, smb_name, wksta_name));
210
211         domain = client_domain;
212
213         /* If you connect to a Windows domain member using a bogus domain name,
214          * the Windows box will map the BOGUS\user to SAMNAME\user.  Thus, if
215          * the Windows box is a DC the name will become DOMAIN\user and be
216          * authenticated against AD, if the Windows box is a member server but
217          * not a DC the name will become WORKSTATION\user.  A standalone
218          * non-domain member box will also map to WORKSTATION\user.
219          * This also deals with the client passing in a "" domain */
220
221         if (!is_trusted_domain(domain) &&
222             !strequal(domain, get_global_sam_name()) )
223         {
224                 if (lp_map_untrusted_to_domain())
225                         domain = my_sam_name();
226                 else
227                         domain = get_global_sam_name();
228                 DEBUG(5, ("Mapped domain from [%s] to [%s] for user [%s] from "
229                           "workstation [%s]\n",
230                           client_domain, domain, smb_name, wksta_name));
231         }
232
233         /* We know that the given domain is trusted (and we are allowing them),
234          * it is our global SAM name, or for legacy behavior it is our
235          * primary domain name */
236
237         result = make_user_info(user_info, smb_name, internal_username,
238                               client_domain, domain, wksta_name,
239                               lm_pwd, nt_pwd,
240                               lm_interactive_pwd, nt_interactive_pwd,
241                               plaintext, encrypted);
242         if (NT_STATUS_IS_OK(result)) {
243                 (*user_info)->was_mapped = was_mapped;
244         }
245         return result;
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                                      uint32 logon_parameters,
258                                      const uchar *lm_network_pwd,
259                                      int lm_pwd_len,
260                                      const uchar *nt_network_pwd,
261                                      int nt_pwd_len)
262 {
263         bool ret;
264         NTSTATUS status;
265         DATA_BLOB lm_blob = data_blob(lm_network_pwd, lm_pwd_len);
266         DATA_BLOB nt_blob = data_blob(nt_network_pwd, nt_pwd_len);
267
268         status = make_user_info_map(user_info,
269                                     smb_name, client_domain, 
270                                     wksta_name, 
271                                     lm_pwd_len ? &lm_blob : NULL, 
272                                     nt_pwd_len ? &nt_blob : NULL,
273                                     NULL, NULL, NULL,
274                                     True);
275
276         if (NT_STATUS_IS_OK(status)) {
277                 (*user_info)->logon_parameters = logon_parameters;
278         }
279         ret = NT_STATUS_IS_OK(status) ? True : False;
280
281         data_blob_free(&lm_blob);
282         data_blob_free(&nt_blob);
283         return ret;
284 }
285
286 /****************************************************************************
287  Create an auth_usersupplied_data, making the DATA_BLOBs here. 
288  Decrypt and encrypt the passwords.
289 ****************************************************************************/
290
291 bool make_user_info_netlogon_interactive(auth_usersupplied_info **user_info, 
292                                          const char *smb_name, 
293                                          const char *client_domain, 
294                                          const char *wksta_name, 
295                                          uint32 logon_parameters,
296                                          const uchar chal[8], 
297                                          const uchar lm_interactive_pwd[16], 
298                                          const uchar nt_interactive_pwd[16], 
299                                          const uchar *dc_sess_key)
300 {
301         unsigned char lm_pwd[16];
302         unsigned char nt_pwd[16];
303         unsigned char local_lm_response[24];
304         unsigned char local_nt_response[24];
305         unsigned char key[16];
306         
307         memcpy(key, dc_sess_key, 16);
308         
309         if (lm_interactive_pwd)
310                 memcpy(lm_pwd, lm_interactive_pwd, sizeof(lm_pwd));
311
312         if (nt_interactive_pwd)
313                 memcpy(nt_pwd, nt_interactive_pwd, sizeof(nt_pwd));
314         
315 #ifdef DEBUG_PASSWORD
316         DEBUG(100,("key:"));
317         dump_data(100, key, sizeof(key));
318         
319         DEBUG(100,("lm owf password:"));
320         dump_data(100, lm_pwd, sizeof(lm_pwd));
321         
322         DEBUG(100,("nt owf password:"));
323         dump_data(100, nt_pwd, sizeof(nt_pwd));
324 #endif
325         
326         if (lm_interactive_pwd)
327                 arcfour_crypt(lm_pwd, key, sizeof(lm_pwd));
328         
329         if (nt_interactive_pwd)
330                 arcfour_crypt(nt_pwd, key, sizeof(nt_pwd));
331         
332 #ifdef DEBUG_PASSWORD
333         DEBUG(100,("decrypt of lm owf password:"));
334         dump_data(100, lm_pwd, sizeof(lm_pwd));
335         
336         DEBUG(100,("decrypt of nt owf password:"));
337         dump_data(100, nt_pwd, sizeof(nt_pwd));
338 #endif
339         
340         if (lm_interactive_pwd)
341                 SMBOWFencrypt(lm_pwd, chal,
342                               local_lm_response);
343
344         if (nt_interactive_pwd)
345                 SMBOWFencrypt(nt_pwd, chal,
346                               local_nt_response);
347         
348         /* Password info paranoia */
349         ZERO_STRUCT(key);
350
351         {
352                 bool ret;
353                 NTSTATUS nt_status;
354                 DATA_BLOB local_lm_blob;
355                 DATA_BLOB local_nt_blob;
356
357                 DATA_BLOB lm_interactive_blob;
358                 DATA_BLOB nt_interactive_blob;
359                 
360                 if (lm_interactive_pwd) {
361                         local_lm_blob = data_blob(local_lm_response,
362                                                   sizeof(local_lm_response));
363                         lm_interactive_blob = data_blob(lm_pwd,
364                                                         sizeof(lm_pwd));
365                         ZERO_STRUCT(lm_pwd);
366                 }
367                 
368                 if (nt_interactive_pwd) {
369                         local_nt_blob = data_blob(local_nt_response,
370                                                   sizeof(local_nt_response));
371                         nt_interactive_blob = data_blob(nt_pwd,
372                                                         sizeof(nt_pwd));
373                         ZERO_STRUCT(nt_pwd);
374                 }
375
376                 nt_status = make_user_info_map(
377                         user_info, 
378                         smb_name, client_domain, wksta_name, 
379                         lm_interactive_pwd ? &local_lm_blob : NULL,
380                         nt_interactive_pwd ? &local_nt_blob : NULL,
381                         lm_interactive_pwd ? &lm_interactive_blob : NULL,
382                         nt_interactive_pwd ? &nt_interactive_blob : NULL,
383                         NULL, True);
384
385                 if (NT_STATUS_IS_OK(nt_status)) {
386                         (*user_info)->logon_parameters = logon_parameters;
387                 }
388
389                 ret = NT_STATUS_IS_OK(nt_status) ? True : False;
390                 data_blob_free(&local_lm_blob);
391                 data_blob_free(&local_nt_blob);
392                 data_blob_free(&lm_interactive_blob);
393                 data_blob_free(&nt_interactive_blob);
394                 return ret;
395         }
396 }
397
398
399 /****************************************************************************
400  Create an auth_usersupplied_data structure
401 ****************************************************************************/
402
403 bool make_user_info_for_reply(auth_usersupplied_info **user_info, 
404                               const char *smb_name, 
405                               const char *client_domain,
406                               const uint8 chal[8],
407                               DATA_BLOB plaintext_password)
408 {
409
410         DATA_BLOB local_lm_blob;
411         DATA_BLOB local_nt_blob;
412         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
413                         
414         /*
415          * Not encrypted - do so.
416          */
417         
418         DEBUG(5,("make_user_info_for_reply: User passwords not in encrypted "
419                  "format.\n"));
420         
421         if (plaintext_password.data) {
422                 unsigned char local_lm_response[24];
423                 
424 #ifdef DEBUG_PASSWORD
425                 DEBUG(10,("Unencrypted password (len %d):\n",
426                           (int)plaintext_password.length));
427                 dump_data(100, plaintext_password.data,
428                           plaintext_password.length);
429 #endif
430
431                 SMBencrypt( (const char *)plaintext_password.data,
432                             (const uchar*)chal, local_lm_response);
433                 local_lm_blob = data_blob(local_lm_response, 24);
434                 
435                 /* We can't do an NT hash here, as the password needs to be
436                    case insensitive */
437                 local_nt_blob = data_blob_null; 
438                 
439         } else {
440                 local_lm_blob = data_blob_null; 
441                 local_nt_blob = data_blob_null; 
442         }
443         
444         ret = make_user_info_map(
445                 user_info, smb_name, client_domain, 
446                 get_remote_machine_name(),
447                 local_lm_blob.data ? &local_lm_blob : NULL,
448                 local_nt_blob.data ? &local_nt_blob : NULL,
449                 NULL, NULL,
450                 plaintext_password.data ? &plaintext_password : NULL, 
451                 False);
452         
453         data_blob_free(&local_lm_blob);
454         return NT_STATUS_IS_OK(ret) ? True : False;
455 }
456
457 /****************************************************************************
458  Create an auth_usersupplied_data structure
459 ****************************************************************************/
460
461 NTSTATUS make_user_info_for_reply_enc(auth_usersupplied_info **user_info, 
462                                       const char *smb_name,
463                                       const char *client_domain, 
464                                       DATA_BLOB lm_resp, DATA_BLOB nt_resp)
465 {
466         return make_user_info_map(user_info, smb_name, 
467                                   client_domain, 
468                                   get_remote_machine_name(), 
469                                   lm_resp.data ? &lm_resp : NULL, 
470                                   nt_resp.data ? &nt_resp : NULL, 
471                                   NULL, NULL, NULL,
472                                   True);
473 }
474
475 /****************************************************************************
476  Create a guest user_info blob, for anonymous authenticaion.
477 ****************************************************************************/
478
479 bool make_user_info_guest(auth_usersupplied_info **user_info) 
480 {
481         NTSTATUS nt_status;
482
483         nt_status = make_user_info(user_info, 
484                                    "","", 
485                                    "","", 
486                                    "", 
487                                    NULL, NULL, 
488                                    NULL, NULL, 
489                                    NULL,
490                                    True);
491                               
492         return NT_STATUS_IS_OK(nt_status) ? True : False;
493 }
494
495 static int server_info_dtor(auth_serversupplied_info *server_info)
496 {
497         TALLOC_FREE(server_info->sam_account);
498         ZERO_STRUCTP(server_info);
499         return 0;
500 }
501
502 /***************************************************************************
503  Make a server_info struct. Free with TALLOC_FREE().
504 ***************************************************************************/
505
506 static auth_serversupplied_info *make_server_info(TALLOC_CTX *mem_ctx)
507 {
508         struct auth_serversupplied_info *result;
509
510         result = TALLOC_ZERO_P(mem_ctx, auth_serversupplied_info);
511         if (result == NULL) {
512                 DEBUG(0, ("talloc failed\n"));
513                 return NULL;
514         }
515
516         talloc_set_destructor(result, server_info_dtor);
517
518         /* Initialise the uid and gid values to something non-zero
519            which may save us from giving away root access if there
520            is a bug in allocating these fields. */
521
522         result->utok.uid = -1;
523         result->utok.gid = -1;
524         return result;
525 }
526
527 static char *sanitize_username(TALLOC_CTX *mem_ctx, const char *username)
528 {
529         fstring tmp;
530
531         alpha_strcpy(tmp, username, ". _-$", sizeof(tmp));
532         return talloc_strdup(mem_ctx, tmp);
533 }
534
535 /***************************************************************************
536  Is the incoming username our own machine account ?
537  If so, the connection is almost certainly from winbindd.
538 ***************************************************************************/
539
540 static bool is_our_machine_account(const char *username)
541 {
542         bool ret;
543         char *truncname = NULL;
544         size_t ulen = strlen(username);
545
546         if (ulen == 0 || username[ulen-1] != '$') {
547                 return false;
548         }
549         truncname = SMB_STRDUP(username);
550         if (!truncname) {
551                 return false;
552         }
553         truncname[ulen-1] = '\0';
554         ret = strequal(truncname, global_myname());
555         SAFE_FREE(truncname);
556         return ret;
557 }
558
559 /***************************************************************************
560  Make (and fill) a user_info struct from a struct samu
561 ***************************************************************************/
562
563 NTSTATUS make_server_info_sam(auth_serversupplied_info **server_info,
564                               struct samu *sampass)
565 {
566         struct passwd *pwd;
567         gid_t *gids;
568         auth_serversupplied_info *result;
569         const char *username = pdb_get_username(sampass);
570         NTSTATUS status;
571
572         if ( !(result = make_server_info(NULL)) ) {
573                 return NT_STATUS_NO_MEMORY;
574         }
575
576         if ( !(pwd = getpwnam_alloc(result, username)) ) {
577                 DEBUG(1, ("User %s in passdb, but getpwnam() fails!\n",
578                           pdb_get_username(sampass)));
579                 TALLOC_FREE(result);
580                 return NT_STATUS_NO_SUCH_USER;
581         }
582
583         result->sam_account = sampass;
584         result->unix_name = pwd->pw_name;
585         /* Ensure that we keep pwd->pw_name, because we will free pwd below */
586         talloc_steal(result, pwd->pw_name);
587         result->utok.gid = pwd->pw_gid;
588         result->utok.uid = pwd->pw_uid;
589
590         TALLOC_FREE(pwd);
591
592         result->sanitized_username = sanitize_username(result,
593                                                        result->unix_name);
594         if (result->sanitized_username == NULL) {
595                 TALLOC_FREE(result);
596                 return NT_STATUS_NO_MEMORY;
597         }
598
599         if (IS_DC && is_our_machine_account(username)) {
600                 /*
601                  * Ensure for a connection from our own
602                  * machine account (from winbindd on a DC)
603                  * there are no supplementary groups.
604                  * Prevents loops in calling gid_to_sid().
605                  */
606                 result->sids = NULL;
607                 gids = NULL;
608                 result->num_sids = 0;
609
610                 /*
611                  * This is a hack of monstrous proportions.
612                  * If we know it's winbindd talking to us,
613                  * we know we must never recurse into it,
614                  * so turn off contacting winbindd for this
615                  * entire process. This will get fixed when
616                  * winbindd doesn't need to talk to smbd on
617                  * a PDC. JRA.
618                  */
619
620                 (void)winbind_off();
621
622                 DEBUG(10, ("make_server_info_sam: our machine account %s "
623                         "setting supplementary group list empty and "
624                         "turning off winbindd requests.\n",
625                         username));
626         } else {
627                 status = pdb_enum_group_memberships(result, sampass,
628                                             &result->sids, &gids,
629                                             &result->num_sids);
630
631                 if (!NT_STATUS_IS_OK(status)) {
632                         DEBUG(10, ("pdb_enum_group_memberships failed: %s\n",
633                                    nt_errstr(status)));
634                         result->sam_account = NULL; /* Don't free on error exit. */
635                         TALLOC_FREE(result);
636                         return status;
637                 }
638         }
639
640         /* For now we throw away the gids and convert via sid_to_gid
641          * later. This needs fixing, but I'd like to get the code straight and
642          * simple first. */
643          
644         TALLOC_FREE(gids);
645
646         DEBUG(5,("make_server_info_sam: made server info for user %s -> %s\n",
647                  pdb_get_username(sampass), result->unix_name));
648
649         *server_info = result;
650         /* Ensure that the sampass will be freed with the result */
651         talloc_steal(result, sampass);
652
653         return NT_STATUS_OK;
654 }
655
656 static NTSTATUS log_nt_token(NT_USER_TOKEN *token)
657 {
658         TALLOC_CTX *frame = talloc_stackframe();
659         char *command;
660         char *group_sidstr;
661         size_t i;
662
663         if ((lp_log_nt_token_command() == NULL) ||
664             (strlen(lp_log_nt_token_command()) == 0)) {
665                 TALLOC_FREE(frame);
666                 return NT_STATUS_OK;
667         }
668
669         group_sidstr = talloc_strdup(frame, "");
670         for (i=1; i<token->num_sids; i++) {
671                 group_sidstr = talloc_asprintf(
672                         frame, "%s %s", group_sidstr,
673                         sid_string_talloc(frame, &token->user_sids[i]));
674         }
675
676         command = talloc_string_sub(
677                 frame, lp_log_nt_token_command(),
678                 "%s", sid_string_talloc(frame, &token->user_sids[0]));
679         command = talloc_string_sub(frame, command, "%t", group_sidstr);
680
681         if (command == NULL) {
682                 TALLOC_FREE(frame);
683                 return NT_STATUS_NO_MEMORY;
684         }
685
686         DEBUG(8, ("running command: [%s]\n", command));
687         if (smbrun(command, NULL) != 0) {
688                 DEBUG(0, ("Could not log NT token\n"));
689                 TALLOC_FREE(frame);
690                 return NT_STATUS_ACCESS_DENIED;
691         }
692
693         TALLOC_FREE(frame);
694         return NT_STATUS_OK;
695 }
696
697 /*
698  * Create the token to use from server_info->sam_account and
699  * server_info->sids (the info3/sam groups). Find the unix gids.
700  */
701
702 NTSTATUS create_local_token(auth_serversupplied_info *server_info)
703 {
704         NTSTATUS status;
705         size_t i;
706         struct dom_sid tmp_sid;
707
708         /*
709          * If winbind is not around, we can not make much use of the SIDs the
710          * domain controller provided us with. Likewise if the user name was
711          * mapped to some local unix user.
712          */
713
714         if (((lp_server_role() == ROLE_DOMAIN_MEMBER) && !winbind_ping()) ||
715             (server_info->nss_token)) {
716                 status = create_token_from_username(server_info,
717                                                     server_info->unix_name,
718                                                     server_info->guest,
719                                                     &server_info->utok.uid,
720                                                     &server_info->utok.gid,
721                                                     &server_info->unix_name,
722                                                     &server_info->ptok);
723
724         } else {
725                 server_info->ptok = create_local_nt_token(
726                         server_info,
727                         pdb_get_user_sid(server_info->sam_account),
728                         server_info->guest,
729                         server_info->num_sids, server_info->sids);
730                 status = server_info->ptok ?
731                         NT_STATUS_OK : NT_STATUS_NO_SUCH_USER;
732         }
733
734         if (!NT_STATUS_IS_OK(status)) {
735                 return status;
736         }
737
738         /* Convert the SIDs to gids. */
739
740         server_info->utok.ngroups = 0;
741         server_info->utok.groups = NULL;
742
743         /* Start at index 1, where the groups start. */
744
745         for (i=1; i<server_info->ptok->num_sids; i++) {
746                 gid_t gid;
747                 DOM_SID *sid = &server_info->ptok->user_sids[i];
748
749                 if (!sid_to_gid(sid, &gid)) {
750                         DEBUG(10, ("Could not convert SID %s to gid, "
751                                    "ignoring it\n", sid_string_dbg(sid)));
752                         continue;
753                 }
754                 add_gid_to_array_unique(server_info, gid,
755                                         &server_info->utok.groups,
756                                         &server_info->utok.ngroups);
757         }
758
759         /*
760          * Add the "Unix Group" SID for each gid to catch mapped groups
761          * and their Unix equivalent.  This is to solve the backwards
762          * compatibility problem of 'valid users = +ntadmin' where
763          * ntadmin has been paired with "Domain Admins" in the group
764          * mapping table.  Otherwise smb.conf would need to be changed
765          * to 'valid user = "Domain Admins"'.  --jerry
766          *
767          * For consistency we also add the "Unix User" SID,
768          * so that the complete unix token is represented within
769          * the nt token.
770          */
771
772         if (!uid_to_unix_users_sid(server_info->utok.uid, &tmp_sid)) {
773                 DEBUG(1,("create_local_token: Failed to create SID "
774                         "for uid %u!\n", (unsigned int)server_info->utok.uid));
775         }
776         add_sid_to_array_unique(server_info->ptok, &tmp_sid,
777                                 &server_info->ptok->user_sids,
778                                 &server_info->ptok->num_sids);
779
780         for ( i=0; i<server_info->utok.ngroups; i++ ) {
781                 if (!gid_to_unix_groups_sid( server_info->utok.groups[i], &tmp_sid ) ) {
782                         DEBUG(1,("create_local_token: Failed to create SID "
783                                 "for gid %u!\n", (unsigned int)server_info->utok.groups[i]));
784                         continue;
785                 }
786                 add_sid_to_array_unique(server_info->ptok, &tmp_sid,
787                                         &server_info->ptok->user_sids,
788                                         &server_info->ptok->num_sids);
789         }
790
791         debug_nt_user_token(DBGC_AUTH, 10, server_info->ptok);
792         debug_unix_user_token(DBGC_AUTH, 10,
793                               server_info->utok.uid,
794                               server_info->utok.gid,
795                               server_info->utok.ngroups,
796                               server_info->utok.groups);
797
798         status = log_nt_token(server_info->ptok);
799         return status;
800 }
801
802 /*
803  * Create an artificial NT token given just a username. (Initially intended
804  * for force user)
805  *
806  * We go through lookup_name() to avoid problems we had with 'winbind use
807  * default domain'.
808  *
809  * We have 3 cases:
810  *
811  * unmapped unix users: Go directly to nss to find the user's group.
812  *
813  * A passdb user: The list of groups is provided by pdb_enum_group_memberships.
814  *
815  * If the user is provided by winbind, the primary gid is set to "domain
816  * users" of the user's domain. For an explanation why this is necessary, see
817  * the thread starting at
818  * http://lists.samba.org/archive/samba-technical/2006-January/044803.html.
819  */
820
821 NTSTATUS create_token_from_username(TALLOC_CTX *mem_ctx, const char *username,
822                                     bool is_guest,
823                                     uid_t *uid, gid_t *gid,
824                                     char **found_username,
825                                     struct nt_user_token **token)
826 {
827         NTSTATUS result = NT_STATUS_NO_SUCH_USER;
828         TALLOC_CTX *tmp_ctx;
829         DOM_SID user_sid;
830         enum lsa_SidType type;
831         gid_t *gids;
832         DOM_SID *group_sids;
833         DOM_SID unix_group_sid;
834         size_t num_group_sids;
835         size_t num_gids;
836         size_t i;
837
838         tmp_ctx = talloc_new(NULL);
839         if (tmp_ctx == NULL) {
840                 DEBUG(0, ("talloc_new failed\n"));
841                 return NT_STATUS_NO_MEMORY;
842         }
843
844         if (!lookup_name_smbconf(tmp_ctx, username, LOOKUP_NAME_ALL,
845                          NULL, NULL, &user_sid, &type)) {
846                 DEBUG(1, ("lookup_name_smbconf for %s failed\n", username));
847                 goto done;
848         }
849
850         if (type != SID_NAME_USER) {
851                 DEBUG(1, ("%s is a %s, not a user\n", username,
852                           sid_type_lookup(type)));
853                 goto done;
854         }
855
856         if (sid_check_is_in_our_domain(&user_sid)) {
857                 bool ret;
858
859                 /* This is a passdb user, so ask passdb */
860
861                 struct samu *sam_acct = NULL;
862
863                 if ( !(sam_acct = samu_new( tmp_ctx )) ) {
864                         result = NT_STATUS_NO_MEMORY;
865                         goto done;
866                 }
867
868                 become_root();
869                 ret = pdb_getsampwsid(sam_acct, &user_sid);
870                 unbecome_root();
871
872                 if (!ret) {
873                         DEBUG(1, ("pdb_getsampwsid(%s) for user %s failed\n",
874                                   sid_string_dbg(&user_sid), username));
875                         DEBUGADD(1, ("Fall back to unix user %s\n", username));
876                         goto unix_user;
877                 }
878
879                 result = pdb_enum_group_memberships(tmp_ctx, sam_acct,
880                                                     &group_sids, &gids,
881                                                     &num_group_sids);
882                 if (!NT_STATUS_IS_OK(result)) {
883                         DEBUG(1, ("enum_group_memberships failed for %s (%s): "
884                                   "%s\n", username, sid_string_dbg(&user_sid),
885                                   nt_errstr(result)));
886                         DEBUGADD(1, ("Fall back to unix user %s\n", username));
887                         goto unix_user;
888                 }
889
890                 /* see the smb_panic() in pdb_default_enum_group_memberships */
891                 SMB_ASSERT(num_group_sids > 0); 
892
893                 *gid = gids[0];
894
895                 /* Ensure we're returning the found_username on the right context. */
896                 *found_username = talloc_strdup(mem_ctx,
897                                                 pdb_get_username(sam_acct));
898
899                 /*
900                  * If the SID from lookup_name() was the guest sid, passdb knows
901                  * about the mapping of guest sid to lp_guestaccount()
902                  * username and will return the unix_pw info for a guest
903                  * user. Use it if it's there, else lookup the *uid details
904                  * using getpwnam_alloc(). See bug #6291 for details. JRA.
905                  */
906
907                 /* We must always assign the *uid. */
908                 if (sam_acct->unix_pw == NULL) {
909                         struct passwd *pwd = getpwnam_alloc(sam_acct, *found_username );
910                         if (!pwd) {
911                                 DEBUG(10, ("getpwnam_alloc failed for %s\n",
912                                         *found_username));
913                                 result = NT_STATUS_NO_SUCH_USER;
914                                 goto done;
915                         }
916                         result = samu_set_unix(sam_acct, pwd );
917                         if (!NT_STATUS_IS_OK(result)) {
918                                 DEBUG(10, ("samu_set_unix failed for %s\n",
919                                         *found_username));
920                                 result = NT_STATUS_NO_SUCH_USER;
921                                 goto done;
922                         }
923                 }
924                 *uid = sam_acct->unix_pw->pw_uid;
925
926         } else  if (sid_check_is_in_unix_users(&user_sid)) {
927
928                 /* This is a unix user not in passdb. We need to ask nss
929                  * directly, without consulting passdb */
930
931                 struct passwd *pass;
932
933                 /*
934                  * This goto target is used as a fallback for the passdb
935                  * case. The concrete bug report is when passdb gave us an
936                  * unmapped gid.
937                  */
938
939         unix_user:
940
941                 if (!sid_to_uid(&user_sid, uid)) {
942                         DEBUG(1, ("unix_user case, sid_to_uid for %s (%s) failed\n",
943                                   username, sid_string_dbg(&user_sid)));
944                         result = NT_STATUS_NO_SUCH_USER;
945                         goto done;
946                 }
947
948                 uid_to_unix_users_sid(*uid, &user_sid);
949
950                 pass = getpwuid_alloc(tmp_ctx, *uid);
951                 if (pass == NULL) {
952                         DEBUG(1, ("getpwuid(%u) for user %s failed\n",
953                                   (unsigned int)*uid, username));
954                         goto done;
955                 }
956
957                 if (!getgroups_unix_user(tmp_ctx, username, pass->pw_gid,
958                                          &gids, &num_group_sids)) {
959                         DEBUG(1, ("getgroups_unix_user for user %s failed\n",
960                                   username));
961                         goto done;
962                 }
963
964                 if (num_group_sids) {
965                         group_sids = TALLOC_ARRAY(tmp_ctx, DOM_SID, num_group_sids);
966                         if (group_sids == NULL) {
967                                 DEBUG(1, ("TALLOC_ARRAY failed\n"));
968                                 result = NT_STATUS_NO_MEMORY;
969                                 goto done;
970                         }
971                 } else {
972                         group_sids = NULL;
973                 }
974
975                 for (i=0; i<num_group_sids; i++) {
976                         gid_to_sid(&group_sids[i], gids[i]);
977                 }
978
979                 /* In getgroups_unix_user we always set the primary gid */
980                 SMB_ASSERT(num_group_sids > 0); 
981
982                 *gid = gids[0];
983
984                 /* Ensure we're returning the found_username on the right context. */
985                 *found_username = talloc_strdup(mem_ctx, pass->pw_name);
986         } else {
987
988                 /* This user is from winbind, force the primary gid to the
989                  * user's "domain users" group. Under certain circumstances
990                  * (user comes from NT4), this might be a loss of
991                  * information. But we can not rely on winbind getting the
992                  * correct info. AD might prohibit winbind looking up that
993                  * information. */
994
995                 uint32 dummy;
996
997                 /* We must always assign the *uid. */
998                 if (!sid_to_uid(&user_sid, uid)) {
999                         DEBUG(1, ("winbindd case, sid_to_uid for %s (%s) failed\n",
1000                                   username, sid_string_dbg(&user_sid)));
1001                         result = NT_STATUS_NO_SUCH_USER;
1002                         goto done;
1003                 }
1004
1005                 num_group_sids = 1;
1006                 group_sids = TALLOC_ARRAY(tmp_ctx, DOM_SID, num_group_sids);
1007                 if (group_sids == NULL) {
1008                         DEBUG(1, ("TALLOC_ARRAY failed\n"));
1009                         result = NT_STATUS_NO_MEMORY;
1010                         goto done;
1011                 }
1012
1013                 sid_copy(&group_sids[0], &user_sid);
1014                 sid_split_rid(&group_sids[0], &dummy);
1015                 sid_append_rid(&group_sids[0], DOMAIN_GROUP_RID_USERS);
1016
1017                 if (!sid_to_gid(&group_sids[0], gid)) {
1018                         DEBUG(1, ("sid_to_gid(%s) failed\n",
1019                                   sid_string_dbg(&group_sids[0])));
1020                         goto done;
1021                 }
1022
1023                 gids = gid;
1024
1025                 /* Ensure we're returning the found_username on the right context. */
1026                 *found_username = talloc_strdup(mem_ctx, username);
1027         }
1028
1029         /* Add the "Unix Group" SID for each gid to catch mapped groups
1030            and their Unix equivalent.  This is to solve the backwards
1031            compatibility problem of 'valid users = +ntadmin' where
1032            ntadmin has been paired with "Domain Admins" in the group
1033            mapping table.  Otherwise smb.conf would need to be changed
1034            to 'valid user = "Domain Admins"'.  --jerry */
1035
1036         num_gids = num_group_sids;
1037         for ( i=0; i<num_gids; i++ ) {
1038                 gid_t high, low;
1039
1040                 /* don't pickup anything managed by Winbind */
1041
1042                 if ( lp_idmap_gid(&low, &high) && (gids[i] >= low) && (gids[i] <= high) )
1043                         continue;
1044
1045                 if ( !gid_to_unix_groups_sid( gids[i], &unix_group_sid ) ) {
1046                         DEBUG(1,("create_token_from_username: Failed to create SID "
1047                                 "for gid %u!\n", (unsigned int)gids[i]));
1048                         continue;
1049                 }
1050                 result = add_sid_to_array_unique(tmp_ctx, &unix_group_sid,
1051                                                  &group_sids, &num_group_sids);
1052                 if (!NT_STATUS_IS_OK(result)) {
1053                         goto done;
1054                 }
1055         }
1056
1057         /* Ensure we're creating the nt_token on the right context. */
1058         *token = create_local_nt_token(mem_ctx, &user_sid,
1059                                        is_guest, num_group_sids, group_sids);
1060
1061         if ((*token == NULL) || (*found_username == NULL)) {
1062                 result = NT_STATUS_NO_MEMORY;
1063                 goto done;
1064         }
1065
1066         result = NT_STATUS_OK;
1067  done:
1068         TALLOC_FREE(tmp_ctx);
1069         return result;
1070 }
1071
1072 /***************************************************************************
1073  Build upon create_token_from_username:
1074
1075  Expensive helper function to figure out whether a user given its name is
1076  member of a particular group.
1077 ***************************************************************************/
1078
1079 bool user_in_group_sid(const char *username, const DOM_SID *group_sid)
1080 {
1081         NTSTATUS status;
1082         uid_t uid;
1083         gid_t gid;
1084         char *found_username;
1085         struct nt_user_token *token;
1086         bool result;
1087
1088         TALLOC_CTX *mem_ctx;
1089
1090         mem_ctx = talloc_new(NULL);
1091         if (mem_ctx == NULL) {
1092                 DEBUG(0, ("talloc_new failed\n"));
1093                 return False;
1094         }
1095
1096         status = create_token_from_username(mem_ctx, username, False,
1097                                             &uid, &gid, &found_username,
1098                                             &token);
1099
1100         if (!NT_STATUS_IS_OK(status)) {
1101                 DEBUG(10, ("could not create token for %s\n", username));
1102                 return False;
1103         }
1104
1105         result = nt_token_check_sid(group_sid, token);
1106
1107         TALLOC_FREE(mem_ctx);
1108         return result;
1109         
1110 }
1111
1112 bool user_in_group(const char *username, const char *groupname)
1113 {
1114         TALLOC_CTX *mem_ctx;
1115         DOM_SID group_sid;
1116         bool ret;
1117
1118         mem_ctx = talloc_new(NULL);
1119         if (mem_ctx == NULL) {
1120                 DEBUG(0, ("talloc_new failed\n"));
1121                 return False;
1122         }
1123
1124         ret = lookup_name(mem_ctx, groupname, LOOKUP_NAME_ALL,
1125                           NULL, NULL, &group_sid, NULL);
1126         TALLOC_FREE(mem_ctx);
1127
1128         if (!ret) {
1129                 DEBUG(10, ("lookup_name for (%s) failed.\n", groupname));
1130                 return False;
1131         }
1132
1133         return user_in_group_sid(username, &group_sid);
1134 }
1135
1136 /***************************************************************************
1137  Make (and fill) a server_info struct from a 'struct passwd' by conversion
1138  to a struct samu
1139 ***************************************************************************/
1140
1141 NTSTATUS make_server_info_pw(auth_serversupplied_info **server_info, 
1142                              char *unix_username,
1143                              struct passwd *pwd)
1144 {
1145         NTSTATUS status;
1146         struct samu *sampass = NULL;
1147         gid_t *gids;
1148         char *qualified_name = NULL;
1149         TALLOC_CTX *mem_ctx = NULL;
1150         DOM_SID u_sid;
1151         enum lsa_SidType type;
1152         auth_serversupplied_info *result;
1153         
1154         if ( !(sampass = samu_new( NULL )) ) {
1155                 return NT_STATUS_NO_MEMORY;
1156         }
1157         
1158         status = samu_set_unix( sampass, pwd );
1159         if (!NT_STATUS_IS_OK(status)) {
1160                 return status;
1161         }
1162
1163         result = make_server_info(NULL);
1164         if (result == NULL) {
1165                 TALLOC_FREE(sampass);
1166                 return NT_STATUS_NO_MEMORY;
1167         }
1168
1169         result->sam_account = sampass;
1170
1171         result->unix_name = talloc_strdup(result, unix_username);
1172         result->sanitized_username = sanitize_username(result, unix_username);
1173
1174         if ((result->unix_name == NULL)
1175             || (result->sanitized_username == NULL)) {
1176                 TALLOC_FREE(sampass);
1177                 TALLOC_FREE(result);
1178                 return NT_STATUS_NO_MEMORY;
1179         }
1180
1181         result->utok.uid = pwd->pw_uid;
1182         result->utok.gid = pwd->pw_gid;
1183
1184         status = pdb_enum_group_memberships(result, sampass,
1185                                             &result->sids, &gids,
1186                                             &result->num_sids);
1187
1188         if (!NT_STATUS_IS_OK(status)) {
1189                 DEBUG(10, ("pdb_enum_group_memberships failed: %s\n",
1190                            nt_errstr(status)));
1191                 TALLOC_FREE(result);
1192                 return status;
1193         }
1194
1195         /*
1196          * The SID returned in server_info->sam_account is based
1197          * on our SAM sid even though for a pure UNIX account this should
1198          * not be the case as it doesn't really exist in the SAM db.
1199          * This causes lookups on "[in]valid users" to fail as they
1200          * will lookup this name as a "Unix User" SID to check against
1201          * the user token. Fix this by adding the "Unix User"\unix_username
1202          * SID to the sid array. The correct fix should probably be
1203          * changing the server_info->sam_account user SID to be a
1204          * S-1-22 Unix SID, but this might break old configs where
1205          * plaintext passwords were used with no SAM backend.
1206          */
1207
1208         mem_ctx = talloc_init("make_server_info_pw_tmp");
1209         if (!mem_ctx) {
1210                 TALLOC_FREE(result);
1211                 return NT_STATUS_NO_MEMORY;
1212         }
1213
1214         qualified_name = talloc_asprintf(mem_ctx, "%s\\%s",
1215                                         unix_users_domain_name(),
1216                                         unix_username );
1217         if (!qualified_name) {
1218                 TALLOC_FREE(result);
1219                 TALLOC_FREE(mem_ctx);
1220                 return NT_STATUS_NO_MEMORY;
1221         }
1222
1223         if (!lookup_name(mem_ctx, qualified_name, LOOKUP_NAME_ALL,
1224                                                 NULL, NULL,
1225                                                 &u_sid, &type)) {
1226                 TALLOC_FREE(result);
1227                 TALLOC_FREE(mem_ctx);
1228                 return NT_STATUS_NO_SUCH_USER;
1229         }
1230
1231         TALLOC_FREE(mem_ctx);
1232
1233         if (type != SID_NAME_USER) {
1234                 TALLOC_FREE(result);
1235                 return NT_STATUS_NO_SUCH_USER;
1236         }
1237
1238         status = add_sid_to_array_unique(result, &u_sid,
1239                                          &result->sids,
1240                                          &result->num_sids);
1241         if (!NT_STATUS_IS_OK(status)) {
1242                 TALLOC_FREE(result);
1243                 return status;
1244         }
1245
1246         /* For now we throw away the gids and convert via sid_to_gid
1247          * later. This needs fixing, but I'd like to get the code straight and
1248          * simple first. */
1249         TALLOC_FREE(gids);
1250
1251         *server_info = result;
1252
1253         return NT_STATUS_OK;
1254 }
1255
1256 /***************************************************************************
1257  Make (and fill) a user_info struct for a guest login.
1258  This *must* succeed for smbd to start. If there is no mapping entry for
1259  the guest gid, then create one.
1260 ***************************************************************************/
1261
1262 static NTSTATUS make_new_server_info_guest(auth_serversupplied_info **server_info)
1263 {
1264         NTSTATUS status;
1265         struct samu *sampass = NULL;
1266         DOM_SID guest_sid;
1267         bool ret;
1268         char zeros[16];
1269         fstring tmp;
1270
1271         if ( !(sampass = samu_new( NULL )) ) {
1272                 return NT_STATUS_NO_MEMORY;
1273         }
1274
1275         sid_copy(&guest_sid, get_global_sam_sid());
1276         sid_append_rid(&guest_sid, DOMAIN_USER_RID_GUEST);
1277
1278         become_root();
1279         ret = pdb_getsampwsid(sampass, &guest_sid);
1280         unbecome_root();
1281
1282         if (!ret) {
1283                 TALLOC_FREE(sampass);
1284                 return NT_STATUS_NO_SUCH_USER;
1285         }
1286
1287         status = make_server_info_sam(server_info, sampass);
1288         if (!NT_STATUS_IS_OK(status)) {
1289                 TALLOC_FREE(sampass);
1290                 return status;
1291         }
1292         
1293         (*server_info)->guest = True;
1294
1295         status = create_local_token(*server_info);
1296         if (!NT_STATUS_IS_OK(status)) {
1297                 DEBUG(10, ("create_local_token failed: %s\n",
1298                            nt_errstr(status)));
1299                 return status;
1300         }
1301
1302         /* annoying, but the Guest really does have a session key, and it is
1303            all zeros! */
1304         ZERO_STRUCT(zeros);
1305         (*server_info)->user_session_key = data_blob(zeros, sizeof(zeros));
1306         (*server_info)->lm_session_key = data_blob(zeros, sizeof(zeros));
1307
1308         alpha_strcpy(tmp, pdb_get_username(sampass), ". _-$", sizeof(tmp));
1309         (*server_info)->sanitized_username = talloc_strdup(*server_info, tmp);
1310
1311         return NT_STATUS_OK;
1312 }
1313
1314 /****************************************************************************
1315   Fake a auth_serversupplied_info just from a username
1316 ****************************************************************************/
1317
1318 NTSTATUS make_serverinfo_from_username(TALLOC_CTX *mem_ctx,
1319                                        const char *username,
1320                                        bool is_guest,
1321                                        struct auth_serversupplied_info **presult)
1322 {
1323         struct auth_serversupplied_info *result;
1324         struct passwd *pwd;
1325         NTSTATUS status;
1326
1327         pwd = getpwnam_alloc(talloc_tos(), username);
1328         if (pwd == NULL) {
1329                 return NT_STATUS_NO_SUCH_USER;
1330         }
1331
1332         status = make_server_info_pw(&result, pwd->pw_name, pwd);
1333
1334         TALLOC_FREE(pwd);
1335
1336         if (!NT_STATUS_IS_OK(status)) {
1337                 return status;
1338         }
1339
1340         result->nss_token = true;
1341         result->guest = is_guest;
1342
1343         status = create_local_token(result);
1344
1345         if (!NT_STATUS_IS_OK(status)) {
1346                 TALLOC_FREE(result);
1347                 return status;
1348         }
1349
1350         *presult = result;
1351         return NT_STATUS_OK;
1352 }
1353
1354
1355 struct auth_serversupplied_info *copy_serverinfo(TALLOC_CTX *mem_ctx,
1356                                                  const auth_serversupplied_info *src)
1357 {
1358         auth_serversupplied_info *dst;
1359
1360         dst = make_server_info(mem_ctx);
1361         if (dst == NULL) {
1362                 return NULL;
1363         }
1364
1365         dst->guest = src->guest;
1366         dst->utok.uid = src->utok.uid;
1367         dst->utok.gid = src->utok.gid;
1368         dst->utok.ngroups = src->utok.ngroups;
1369         if (src->utok.ngroups != 0) {
1370                 dst->utok.groups = (gid_t *)TALLOC_MEMDUP(
1371                         dst, src->utok.groups,
1372                         sizeof(gid_t)*dst->utok.ngroups);
1373         } else {
1374                 dst->utok.groups = NULL;
1375         }
1376
1377         if (src->ptok) {
1378                 dst->ptok = dup_nt_token(dst, src->ptok);
1379                 if (!dst->ptok) {
1380                         TALLOC_FREE(dst);
1381                         return NULL;
1382                 }
1383         }
1384         
1385         dst->user_session_key = data_blob_talloc( dst, src->user_session_key.data,
1386                                                 src->user_session_key.length);
1387
1388         dst->lm_session_key = data_blob_talloc(dst, src->lm_session_key.data,
1389                                                 src->lm_session_key.length);
1390
1391         dst->sam_account = samu_new(NULL);
1392         if (!dst->sam_account) {
1393                 TALLOC_FREE(dst);
1394                 return NULL;
1395         }
1396
1397         if (!pdb_copy_sam_account(dst->sam_account, src->sam_account)) {
1398                 TALLOC_FREE(dst);
1399                 return NULL;
1400         }
1401         
1402         dst->pam_handle = NULL;
1403         dst->unix_name = talloc_strdup(dst, src->unix_name);
1404         if (!dst->unix_name) {
1405                 TALLOC_FREE(dst);
1406                 return NULL;
1407         }
1408
1409         dst->sanitized_username = talloc_strdup(dst, src->sanitized_username);
1410         if (!dst->sanitized_username) {
1411                 TALLOC_FREE(dst);
1412                 return NULL;
1413         }
1414
1415         return dst;
1416 }
1417
1418 /*
1419  * Set a new session key. Used in the rpc server where we have to override the
1420  * SMB level session key with SystemLibraryDTC
1421  */
1422
1423 bool server_info_set_session_key(struct auth_serversupplied_info *info,
1424                                  DATA_BLOB session_key)
1425 {
1426         TALLOC_FREE(info->user_session_key.data);
1427
1428         info->user_session_key = data_blob_talloc(
1429                 info, session_key.data, session_key.length);
1430
1431         return (info->user_session_key.data != NULL);
1432 }
1433
1434 static auth_serversupplied_info *guest_info = NULL;
1435
1436 bool init_guest_info(void)
1437 {
1438         if (guest_info != NULL)
1439                 return True;
1440
1441         return NT_STATUS_IS_OK(make_new_server_info_guest(&guest_info));
1442 }
1443
1444 NTSTATUS make_server_info_guest(TALLOC_CTX *mem_ctx,
1445                                 auth_serversupplied_info **server_info)
1446 {
1447         *server_info = copy_serverinfo(mem_ctx, guest_info);
1448         return (*server_info != NULL) ? NT_STATUS_OK : NT_STATUS_NO_MEMORY;
1449 }
1450
1451 bool copy_current_user(struct current_user *dst, struct current_user *src)
1452 {
1453         gid_t *groups;
1454         NT_USER_TOKEN *nt_token;
1455
1456         groups = (gid_t *)memdup(src->ut.groups,
1457                                  sizeof(gid_t) * src->ut.ngroups);
1458         if ((src->ut.ngroups != 0) && (groups == NULL)) {
1459                 return False;
1460         }
1461
1462         nt_token = dup_nt_token(NULL, src->nt_user_token);
1463         if (nt_token == NULL) {
1464                 SAFE_FREE(groups);
1465                 return False;
1466         }
1467
1468         dst->conn = src->conn;
1469         dst->vuid = src->vuid;
1470         dst->ut.uid = src->ut.uid;
1471         dst->ut.gid = src->ut.gid;
1472         dst->ut.ngroups = src->ut.ngroups;
1473         dst->ut.groups = groups;
1474         dst->nt_user_token = nt_token;
1475         return True;
1476 }
1477
1478 /***************************************************************************
1479  Purely internal function for make_server_info_info3
1480  Fill the sam account from getpwnam
1481 ***************************************************************************/
1482 static NTSTATUS fill_sam_account(TALLOC_CTX *mem_ctx, 
1483                                  const char *domain,
1484                                  const char *username,
1485                                  char **found_username,
1486                                  uid_t *uid, gid_t *gid,
1487                                  struct samu *account,
1488                                  bool *username_was_mapped)
1489 {
1490         NTSTATUS nt_status;
1491         fstring dom_user, lower_username;
1492         fstring real_username;
1493         struct passwd *passwd;
1494
1495         fstrcpy( lower_username, username );
1496         strlower_m( lower_username );
1497
1498         fstr_sprintf(dom_user, "%s%c%s", domain, *lp_winbind_separator(), 
1499                 lower_username);
1500
1501         /* Get the passwd struct.  Try to create the account is necessary. */
1502
1503         *username_was_mapped = map_username( dom_user );
1504
1505         if ( !(passwd = smb_getpwnam( NULL, dom_user, real_username, True )) )
1506                 return NT_STATUS_NO_SUCH_USER;
1507
1508         *uid = passwd->pw_uid;
1509         *gid = passwd->pw_gid;
1510
1511         /* This is pointless -- there is no suport for differing 
1512            unix and windows names.  Make sure to always store the 
1513            one we actually looked up and succeeded. Have I mentioned
1514            why I hate the 'winbind use default domain' parameter?   
1515                                          --jerry              */
1516            
1517         *found_username = talloc_strdup( mem_ctx, real_username );
1518         
1519         DEBUG(5,("fill_sam_account: located username was [%s]\n", *found_username));
1520
1521         nt_status = samu_set_unix( account, passwd );
1522         
1523         TALLOC_FREE(passwd);
1524         
1525         return nt_status;
1526 }
1527
1528 /****************************************************************************
1529  Wrapper to allow the getpwnam() call to strip the domain name and 
1530  try again in case a local UNIX user is already there.  Also run through 
1531  the username if we fallback to the username only.
1532  ****************************************************************************/
1533  
1534 struct passwd *smb_getpwnam( TALLOC_CTX *mem_ctx, char *domuser,
1535                              fstring save_username, bool create )
1536 {
1537         struct passwd *pw = NULL;
1538         char *p;
1539         fstring username;
1540         
1541         /* we only save a copy of the username it has been mangled 
1542            by winbindd use default domain */
1543            
1544         save_username[0] = '\0';
1545            
1546         /* don't call map_username() here since it has to be done higher 
1547            up the stack so we don't call it mutliple times */
1548
1549         fstrcpy( username, domuser );
1550         
1551         p = strchr_m( username, *lp_winbind_separator() );
1552         
1553         /* code for a DOMAIN\user string */
1554         
1555         if ( p ) {
1556                 fstring strip_username;
1557
1558                 pw = Get_Pwnam_alloc( mem_ctx, domuser );
1559                 if ( pw ) {     
1560                         /* make sure we get the case of the username correct */
1561                         /* work around 'winbind use default domain = yes' */
1562
1563                         if ( !strchr_m( pw->pw_name, *lp_winbind_separator() ) ) {
1564                                 char *domain;
1565                                 
1566                                 /* split the domain and username into 2 strings */
1567                                 *p = '\0';
1568                                 domain = username;
1569
1570                                 fstr_sprintf(save_username, "%s%c%s", domain, *lp_winbind_separator(), pw->pw_name);
1571                         }
1572                         else
1573                                 fstrcpy( save_username, pw->pw_name );
1574
1575                         /* whew -- done! */             
1576                         return pw;
1577                 }
1578
1579                 /* setup for lookup of just the username */
1580                 /* remember that p and username are overlapping memory */
1581
1582                 p++;
1583                 fstrcpy( strip_username, p );
1584                 fstrcpy( username, strip_username );
1585         }
1586         
1587         /* just lookup a plain username */
1588         
1589         pw = Get_Pwnam_alloc(mem_ctx, username);
1590                 
1591         /* Create local user if requested but only if winbindd
1592            is not running.  We need to protect against cases
1593            where winbindd is failing and then prematurely
1594            creating users in /etc/passwd */
1595         
1596         if ( !pw && create && !winbind_ping() ) {
1597                 /* Don't add a machine account. */
1598                 if (username[strlen(username)-1] == '$')
1599                         return NULL;
1600
1601                 _smb_create_user(NULL, username, NULL);
1602                 pw = Get_Pwnam_alloc(mem_ctx, username);
1603         }
1604         
1605         /* one last check for a valid passwd struct */
1606         
1607         if ( pw )
1608                 fstrcpy( save_username, pw->pw_name );
1609
1610         return pw;
1611 }
1612
1613 /***************************************************************************
1614  Make a server_info struct from the info3 returned by a domain logon 
1615 ***************************************************************************/
1616
1617 NTSTATUS make_server_info_info3(TALLOC_CTX *mem_ctx, 
1618                                 const char *sent_nt_username,
1619                                 const char *domain,
1620                                 auth_serversupplied_info **server_info, 
1621                                 struct netr_SamInfo3 *info3)
1622 {
1623         char zeros[16];
1624
1625         NTSTATUS nt_status = NT_STATUS_OK;
1626         char *found_username = NULL;
1627         const char *nt_domain;
1628         const char *nt_username;
1629         struct samu *sam_account = NULL;
1630         DOM_SID user_sid;
1631         DOM_SID group_sid;
1632         bool username_was_mapped;
1633
1634         uid_t uid = (uid_t)-1;
1635         gid_t gid = (gid_t)-1;
1636
1637         auth_serversupplied_info *result;
1638
1639         /* 
1640            Here is where we should check the list of
1641            trusted domains, and verify that the SID 
1642            matches.
1643         */
1644
1645         sid_copy(&user_sid, info3->base.domain_sid);
1646         if (!sid_append_rid(&user_sid, info3->base.rid)) {
1647                 return NT_STATUS_INVALID_PARAMETER;
1648         }
1649         
1650         sid_copy(&group_sid, info3->base.domain_sid);
1651         if (!sid_append_rid(&group_sid, info3->base.primary_gid)) {
1652                 return NT_STATUS_INVALID_PARAMETER;
1653         }
1654
1655         nt_username = talloc_strdup(mem_ctx, info3->base.account_name.string);
1656         if (!nt_username) {
1657                 /* If the server didn't give us one, just use the one we sent
1658                  * them */
1659                 nt_username = sent_nt_username;
1660         }
1661
1662         nt_domain = talloc_strdup(mem_ctx, info3->base.domain.string);
1663         if (!nt_domain) {
1664                 /* If the server didn't give us one, just use the one we sent
1665                  * them */
1666                 nt_domain = domain;
1667         }
1668         
1669         /* try to fill the SAM account..  If getpwnam() fails, then try the 
1670            add user script (2.2.x behavior).
1671
1672            We use the _unmapped_ username here in an attempt to provide
1673            consistent username mapping behavior between kerberos and NTLM[SSP]
1674            authentication in domain mode security.  I.E. Username mapping
1675            should be applied to the fully qualified username
1676            (e.g. DOMAIN\user) and not just the login name.  Yes this means we
1677            called map_username() unnecessarily in make_user_info_map() but
1678            that is how the current code is designed.  Making the change here
1679            is the least disruptive place.  -- jerry */
1680            
1681         if ( !(sam_account = samu_new( NULL )) ) {
1682                 return NT_STATUS_NO_MEMORY;
1683         }
1684
1685         /* this call will try to create the user if necessary */
1686
1687         nt_status = fill_sam_account(mem_ctx, nt_domain, sent_nt_username,
1688                                      &found_username, &uid, &gid, sam_account,
1689                                      &username_was_mapped);
1690
1691         
1692         /* if we still don't have a valid unix account check for 
1693           'map to guest = bad uid' */
1694           
1695         if (!NT_STATUS_IS_OK(nt_status)) {
1696                 TALLOC_FREE( sam_account );
1697                 if ( lp_map_to_guest() == MAP_TO_GUEST_ON_BAD_UID ) {
1698                         make_server_info_guest(NULL, server_info);
1699                         return NT_STATUS_OK;
1700                 }
1701                 return nt_status;
1702         }
1703                 
1704         if (!pdb_set_nt_username(sam_account, nt_username, PDB_CHANGED)) {
1705                 TALLOC_FREE(sam_account);
1706                 return NT_STATUS_NO_MEMORY;
1707         }
1708
1709         if (!pdb_set_username(sam_account, nt_username, PDB_CHANGED)) {
1710                 TALLOC_FREE(sam_account);
1711                 return NT_STATUS_NO_MEMORY;
1712         }
1713
1714         if (!pdb_set_domain(sam_account, nt_domain, PDB_CHANGED)) {
1715                 TALLOC_FREE(sam_account);
1716                 return NT_STATUS_NO_MEMORY;
1717         }
1718
1719         if (!pdb_set_user_sid(sam_account, &user_sid, PDB_CHANGED)) {
1720                 TALLOC_FREE(sam_account);
1721                 return NT_STATUS_UNSUCCESSFUL;
1722         }
1723
1724         if (!pdb_set_group_sid(sam_account, &group_sid, PDB_CHANGED)) {
1725                 TALLOC_FREE(sam_account);
1726                 return NT_STATUS_UNSUCCESSFUL;
1727         }
1728
1729         if (!pdb_set_fullname(sam_account,
1730                               info3->base.full_name.string,
1731                               PDB_CHANGED)) {
1732                 TALLOC_FREE(sam_account);
1733                 return NT_STATUS_NO_MEMORY;
1734         }
1735
1736         if (!pdb_set_logon_script(sam_account,
1737                                   info3->base.logon_script.string,
1738                                   PDB_CHANGED)) {
1739                 TALLOC_FREE(sam_account);
1740                 return NT_STATUS_NO_MEMORY;
1741         }
1742
1743         if (!pdb_set_profile_path(sam_account,
1744                                   info3->base.profile_path.string,
1745                                   PDB_CHANGED)) {
1746                 TALLOC_FREE(sam_account);
1747                 return NT_STATUS_NO_MEMORY;
1748         }
1749
1750         if (!pdb_set_homedir(sam_account,
1751                              info3->base.home_directory.string,
1752                              PDB_CHANGED)) {
1753                 TALLOC_FREE(sam_account);
1754                 return NT_STATUS_NO_MEMORY;
1755         }
1756
1757         if (!pdb_set_dir_drive(sam_account,
1758                                info3->base.home_drive.string,
1759                                PDB_CHANGED)) {
1760                 TALLOC_FREE(sam_account);
1761                 return NT_STATUS_NO_MEMORY;
1762         }
1763
1764         if (!pdb_set_acct_ctrl(sam_account, info3->base.acct_flags, PDB_CHANGED)) {
1765                 TALLOC_FREE(sam_account);
1766                 return NT_STATUS_NO_MEMORY;
1767         }
1768
1769         if (!pdb_set_pass_last_set_time(
1770                     sam_account,
1771                     nt_time_to_unix(info3->base.last_password_change),
1772                     PDB_CHANGED)) {
1773                 TALLOC_FREE(sam_account);
1774                 return NT_STATUS_NO_MEMORY;
1775         }
1776
1777         if (!pdb_set_pass_can_change_time(
1778                     sam_account,
1779                     nt_time_to_unix(info3->base.allow_password_change),
1780                     PDB_CHANGED)) {
1781                 TALLOC_FREE(sam_account);
1782                 return NT_STATUS_NO_MEMORY;
1783         }
1784
1785         if (!pdb_set_pass_must_change_time(
1786                     sam_account,
1787                     nt_time_to_unix(info3->base.force_password_change),
1788                     PDB_CHANGED)) {
1789                 TALLOC_FREE(sam_account);
1790                 return NT_STATUS_NO_MEMORY;
1791         }
1792
1793         result = make_server_info(NULL);
1794         if (result == NULL) {
1795                 DEBUG(4, ("make_server_info failed!\n"));
1796                 TALLOC_FREE(sam_account);
1797                 return NT_STATUS_NO_MEMORY;
1798         }
1799
1800         /* save this here to _net_sam_logon() doesn't fail (it assumes a 
1801            valid struct samu) */
1802                    
1803         result->sam_account = sam_account;
1804         result->unix_name = talloc_strdup(result, found_username);
1805
1806         result->sanitized_username = sanitize_username(result,
1807                                                        result->unix_name);
1808         if (result->sanitized_username == NULL) {
1809                 TALLOC_FREE(result);
1810                 return NT_STATUS_NO_MEMORY;
1811         }
1812
1813         /* Fill in the unix info we found on the way */
1814
1815         result->utok.uid = uid;
1816         result->utok.gid = gid;
1817
1818         /* Create a 'combined' list of all SIDs we might want in the SD */
1819
1820         result->num_sids = 0;
1821         result->sids = NULL;
1822
1823         nt_status = sid_array_from_info3(result, info3,
1824                                          &result->sids,
1825                                          &result->num_sids,
1826                                          false, false);
1827         if (!NT_STATUS_IS_OK(nt_status)) {
1828                 TALLOC_FREE(result);
1829                 return nt_status;
1830         }
1831
1832         /* Ensure the primary group sid is at position 0. */
1833         sort_sid_array_for_smbd(result, &group_sid);
1834
1835         result->login_server = talloc_strdup(result,
1836                                              info3->base.logon_server.string);
1837
1838         /* ensure we are never given NULL session keys */
1839
1840         ZERO_STRUCT(zeros);
1841
1842         if (memcmp(info3->base.key.key, zeros, sizeof(zeros)) == 0) {
1843                 result->user_session_key = data_blob_null;
1844         } else {
1845                 result->user_session_key = data_blob_talloc(
1846                         result, info3->base.key.key,
1847                         sizeof(info3->base.key.key));
1848         }
1849
1850         if (memcmp(info3->base.LMSessKey.key, zeros, 8) == 0) {
1851                 result->lm_session_key = data_blob_null;
1852         } else {
1853                 result->lm_session_key = data_blob_talloc(
1854                         result, info3->base.LMSessKey.key,
1855                         sizeof(info3->base.LMSessKey.key));
1856         }
1857
1858         result->nss_token |= username_was_mapped;
1859
1860         *server_info = result;
1861
1862         return NT_STATUS_OK;
1863 }
1864
1865 /*****************************************************************************
1866  Make a server_info struct from the wbcAuthUserInfo returned by a domain logon
1867 ******************************************************************************/
1868
1869 NTSTATUS make_server_info_wbcAuthUserInfo(TALLOC_CTX *mem_ctx,
1870                                           const char *sent_nt_username,
1871                                           const char *domain,
1872                                           const struct wbcAuthUserInfo *info,
1873                                           auth_serversupplied_info **server_info)
1874 {
1875         char zeros[16];
1876
1877         NTSTATUS nt_status = NT_STATUS_OK;
1878         char *found_username = NULL;
1879         const char *nt_domain;
1880         const char *nt_username;
1881         struct samu *sam_account = NULL;
1882         DOM_SID user_sid;
1883         DOM_SID group_sid;
1884         bool username_was_mapped;
1885         uint32_t i;
1886
1887         uid_t uid = (uid_t)-1;
1888         gid_t gid = (gid_t)-1;
1889
1890         auth_serversupplied_info *result;
1891
1892         result = make_server_info(NULL);
1893         if (result == NULL) {
1894                 DEBUG(4, ("make_server_info failed!\n"));
1895                 return NT_STATUS_NO_MEMORY;
1896         }
1897
1898         /*
1899            Here is where we should check the list of
1900            trusted domains, and verify that the SID
1901            matches.
1902         */
1903
1904         memcpy(&user_sid, &info->sids[0].sid, sizeof(user_sid));
1905         memcpy(&group_sid, &info->sids[1].sid, sizeof(group_sid));
1906
1907         if (info->account_name) {
1908                 nt_username = talloc_strdup(result, info->account_name);
1909         } else {
1910                 /* If the server didn't give us one, just use the one we sent
1911                  * them */
1912                 nt_username = talloc_strdup(result, sent_nt_username);
1913         }
1914         if (!nt_username) {
1915                 TALLOC_FREE(result);
1916                 return NT_STATUS_NO_MEMORY;
1917         }
1918
1919         if (info->domain_name) {
1920                 nt_domain = talloc_strdup(result, info->domain_name);
1921         } else {
1922                 /* If the server didn't give us one, just use the one we sent
1923                  * them */
1924                 nt_domain = talloc_strdup(result, domain);
1925         }
1926         if (!nt_domain) {
1927                 TALLOC_FREE(result);
1928                 return NT_STATUS_NO_MEMORY;
1929         }
1930
1931         /* try to fill the SAM account..  If getpwnam() fails, then try the
1932            add user script (2.2.x behavior).
1933
1934            We use the _unmapped_ username here in an attempt to provide
1935            consistent username mapping behavior between kerberos and NTLM[SSP]
1936            authentication in domain mode security.  I.E. Username mapping
1937            should be applied to the fully qualified username
1938            (e.g. DOMAIN\user) and not just the login name.  Yes this means we
1939            called map_username() unnecessarily in make_user_info_map() but
1940            that is how the current code is designed.  Making the change here
1941            is the least disruptive place.  -- jerry */
1942
1943         if ( !(sam_account = samu_new( result )) ) {
1944                 TALLOC_FREE(result);
1945                 return NT_STATUS_NO_MEMORY;
1946         }
1947
1948         /* this call will try to create the user if necessary */
1949
1950         nt_status = fill_sam_account(result, nt_domain, sent_nt_username,
1951                                      &found_username, &uid, &gid, sam_account,
1952                                      &username_was_mapped);
1953
1954         /* if we still don't have a valid unix account check for
1955           'map to guest = bad uid' */
1956
1957         if (!NT_STATUS_IS_OK(nt_status)) {
1958                 TALLOC_FREE( result );
1959                 if ( lp_map_to_guest() == MAP_TO_GUEST_ON_BAD_UID ) {
1960                         make_server_info_guest(NULL, server_info);
1961                         return NT_STATUS_OK;
1962                 }
1963                 return nt_status;
1964         }
1965
1966         if (!pdb_set_nt_username(sam_account, nt_username, PDB_CHANGED)) {
1967                 TALLOC_FREE(result);
1968                 return NT_STATUS_NO_MEMORY;
1969         }
1970
1971         if (!pdb_set_username(sam_account, nt_username, PDB_CHANGED)) {
1972                 TALLOC_FREE(result);
1973                 return NT_STATUS_NO_MEMORY;
1974         }
1975
1976         if (!pdb_set_domain(sam_account, nt_domain, PDB_CHANGED)) {
1977                 TALLOC_FREE(result);
1978                 return NT_STATUS_NO_MEMORY;
1979         }
1980
1981         if (!pdb_set_user_sid(sam_account, &user_sid, PDB_CHANGED)) {
1982                 TALLOC_FREE(result);
1983                 return NT_STATUS_UNSUCCESSFUL;
1984         }
1985
1986         if (!pdb_set_group_sid(sam_account, &group_sid, PDB_CHANGED)) {
1987                 TALLOC_FREE(result);
1988                 return NT_STATUS_UNSUCCESSFUL;
1989         }
1990
1991         if (!pdb_set_fullname(sam_account, info->full_name, PDB_CHANGED)) {
1992                 TALLOC_FREE(result);
1993                 return NT_STATUS_NO_MEMORY;
1994         }
1995
1996         if (!pdb_set_logon_script(sam_account, info->logon_script, PDB_CHANGED)) {
1997                 TALLOC_FREE(result);
1998                 return NT_STATUS_NO_MEMORY;
1999         }
2000
2001         if (!pdb_set_profile_path(sam_account, info->profile_path, PDB_CHANGED)) {
2002                 TALLOC_FREE(result);
2003                 return NT_STATUS_NO_MEMORY;
2004         }
2005
2006         if (!pdb_set_homedir(sam_account, info->home_directory, PDB_CHANGED)) {
2007                 TALLOC_FREE(result);
2008                 return NT_STATUS_NO_MEMORY;
2009         }
2010
2011         if (!pdb_set_dir_drive(sam_account, info->home_drive, PDB_CHANGED)) {
2012                 TALLOC_FREE(result);
2013                 return NT_STATUS_NO_MEMORY;
2014         }
2015
2016         if (!pdb_set_acct_ctrl(sam_account, info->acct_flags, PDB_CHANGED)) {
2017                 TALLOC_FREE(result);
2018                 return NT_STATUS_NO_MEMORY;
2019         }
2020
2021         if (!pdb_set_pass_last_set_time(
2022                     sam_account,
2023                     nt_time_to_unix(info->pass_last_set_time),
2024                     PDB_CHANGED)) {
2025                 TALLOC_FREE(result);
2026                 return NT_STATUS_NO_MEMORY;
2027         }
2028
2029         if (!pdb_set_pass_can_change_time(
2030                     sam_account,
2031                     nt_time_to_unix(info->pass_can_change_time),
2032                     PDB_CHANGED)) {
2033                 TALLOC_FREE(result);
2034                 return NT_STATUS_NO_MEMORY;
2035         }
2036
2037         if (!pdb_set_pass_must_change_time(
2038                     sam_account,
2039                     nt_time_to_unix(info->pass_must_change_time),
2040                     PDB_CHANGED)) {
2041                 TALLOC_FREE(result);
2042                 return NT_STATUS_NO_MEMORY;
2043         }
2044
2045         /* save this here to _net_sam_logon() doesn't fail (it assumes a
2046            valid struct samu) */
2047
2048         result->sam_account = sam_account;
2049         result->unix_name = talloc_strdup(result, found_username);
2050
2051         result->sanitized_username = sanitize_username(result,
2052                                                        result->unix_name);
2053         result->login_server = talloc_strdup(result, info->logon_server);
2054
2055         if ((result->unix_name == NULL)
2056             || (result->sanitized_username == NULL)
2057             || (result->login_server == NULL)) {
2058                 TALLOC_FREE(result);
2059                 return NT_STATUS_NO_MEMORY;
2060         }
2061
2062         /* Fill in the unix info we found on the way */
2063
2064         result->utok.uid = uid;
2065         result->utok.gid = gid;
2066
2067         /* Create a 'combined' list of all SIDs we might want in the SD */
2068
2069         result->num_sids = info->num_sids - 2;
2070         result->sids = talloc_array(result, DOM_SID, result->num_sids);
2071         if (result->sids == NULL) {
2072                 TALLOC_FREE(result);
2073                 return NT_STATUS_NO_MEMORY;
2074         }
2075
2076         for (i=0; i < result->num_sids; i++) {
2077                 memcpy(&result->sids[i], &info->sids[i+2].sid, sizeof(result->sids[i]));
2078         }
2079
2080         /* Ensure the primary group sid is at position 0. */
2081         sort_sid_array_for_smbd(result, &group_sid);
2082
2083         /* ensure we are never given NULL session keys */
2084
2085         ZERO_STRUCT(zeros);
2086
2087         if (memcmp(info->user_session_key, zeros, sizeof(zeros)) == 0) {
2088                 result->user_session_key = data_blob_null;
2089         } else {
2090                 result->user_session_key = data_blob_talloc(
2091                         result, info->user_session_key,
2092                         sizeof(info->user_session_key));
2093         }
2094
2095         if (memcmp(info->lm_session_key, zeros, 8) == 0) {
2096                 result->lm_session_key = data_blob_null;
2097         } else {
2098                 result->lm_session_key = data_blob_talloc(
2099                         result, info->lm_session_key,
2100                         sizeof(info->lm_session_key));
2101         }
2102
2103         result->nss_token |= username_was_mapped;
2104
2105         *server_info = result;
2106
2107         return NT_STATUS_OK;
2108 }
2109
2110 /***************************************************************************
2111  Free a user_info struct
2112 ***************************************************************************/
2113
2114 void free_user_info(auth_usersupplied_info **user_info)
2115 {
2116         DEBUG(5,("attempting to free (and zero) a user_info structure\n"));
2117         if (*user_info != NULL) {
2118                 if ((*user_info)->smb_name) {
2119                         DEBUG(10,("structure was created for %s\n",
2120                                   (*user_info)->smb_name));
2121                 }
2122                 SAFE_FREE((*user_info)->smb_name);
2123                 SAFE_FREE((*user_info)->internal_username);
2124                 SAFE_FREE((*user_info)->client_domain);
2125                 SAFE_FREE((*user_info)->domain);
2126                 SAFE_FREE((*user_info)->wksta_name);
2127                 data_blob_free(&(*user_info)->lm_resp);
2128                 data_blob_free(&(*user_info)->nt_resp);
2129                 data_blob_clear_free(&(*user_info)->lm_interactive_pwd);
2130                 data_blob_clear_free(&(*user_info)->nt_interactive_pwd);
2131                 data_blob_clear_free(&(*user_info)->plaintext_password);
2132                 ZERO_STRUCT(**user_info);
2133         }
2134         SAFE_FREE(*user_info);
2135 }
2136
2137 /***************************************************************************
2138  Make an auth_methods struct
2139 ***************************************************************************/
2140
2141 bool make_auth_methods(struct auth_context *auth_context, auth_methods **auth_method) 
2142 {
2143         if (!auth_context) {
2144                 smb_panic("no auth_context supplied to "
2145                           "make_auth_methods()!\n");
2146         }
2147
2148         if (!auth_method) {
2149                 smb_panic("make_auth_methods: pointer to auth_method pointer "
2150                           "is NULL!\n");
2151         }
2152
2153         *auth_method = TALLOC_P(auth_context->mem_ctx, auth_methods);
2154         if (!*auth_method) {
2155                 DEBUG(0,("make_auth_method: malloc failed!\n"));
2156                 return False;
2157         }
2158         ZERO_STRUCTP(*auth_method);
2159         
2160         return True;
2161 }
2162
2163 /**
2164  * Verify whether or not given domain is trusted.
2165  *
2166  * @param domain_name name of the domain to be verified
2167  * @return true if domain is one of the trusted once or
2168  *         false if otherwise
2169  **/
2170
2171 bool is_trusted_domain(const char* dom_name)
2172 {
2173         DOM_SID trustdom_sid;
2174         bool ret;
2175
2176         /* no trusted domains for a standalone server */
2177
2178         if ( lp_server_role() == ROLE_STANDALONE )
2179                 return False;
2180
2181         /* if we are a DC, then check for a direct trust relationships */
2182
2183         if ( IS_DC ) {
2184                 become_root();
2185                 DEBUG (5,("is_trusted_domain: Checking for domain trust with "
2186                           "[%s]\n", dom_name ));
2187                 ret = pdb_get_trusteddom_pw(dom_name, NULL, NULL, NULL);
2188                 unbecome_root();
2189                 if (ret)
2190                         return True;
2191         }
2192         else {
2193                 wbcErr result;
2194
2195                 /* If winbind is around, ask it */
2196
2197                 result = wb_is_trusted_domain(dom_name);
2198
2199                 if (result == WBC_ERR_SUCCESS) {
2200                         return True;
2201                 }
2202
2203                 if (result == WBC_ERR_DOMAIN_NOT_FOUND) {
2204                         /* winbind could not find the domain */
2205                         return False;
2206                 }
2207
2208                 /* The only other possible result is that winbind is not up
2209                    and running. We need to update the trustdom_cache
2210                    ourselves */
2211                 
2212                 update_trustdom_cache();
2213         }
2214
2215         /* now the trustdom cache should be available a DC could still
2216          * have a transitive trust so fall back to the cache of trusted
2217          * domains (like a domain member would use  */
2218
2219         if ( trustdom_cache_fetch(dom_name, &trustdom_sid) ) {
2220                 return True;
2221         }
2222
2223         return False;
2224 }
2225