s3-auth: Added a function to get the server_info from the system user.
[amitay/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 "smbd/globals.h"
26 #include "../libcli/auth/libcli_auth.h"
27 #include "../lib/crypto/arcfour.h"
28
29 #undef DBGC_CLASS
30 #define DBGC_CLASS DBGC_AUTH
31
32 /****************************************************************************
33  Ensure primary group SID is always at position 0 in a 
34  auth_serversupplied_info struct.
35 ****************************************************************************/
36
37 static void sort_sid_array_for_smbd(struct auth_serversupplied_info *result,
38                                 const struct dom_sid *pgroup_sid)
39 {
40         unsigned int i;
41
42         if (!result->sids) {
43                 return;
44         }
45
46         if (sid_compare(&result->sids[0], pgroup_sid)==0) {
47                 return;
48         }
49
50         for (i = 1; i < result->num_sids; i++) {
51                 if (sid_compare(pgroup_sid,
52                                 &result->sids[i]) == 0) {
53                         sid_copy(&result->sids[i], &result->sids[0]);
54                         sid_copy(&result->sids[0], pgroup_sid);
55                         return;
56                 }
57         }
58 }
59
60 /****************************************************************************
61  Create a UNIX user on demand.
62 ****************************************************************************/
63
64 static int _smb_create_user(const char *domain, const char *unix_username, const char *homedir)
65 {
66         TALLOC_CTX *ctx = talloc_tos();
67         char *add_script;
68         int ret;
69
70         add_script = talloc_strdup(ctx, lp_adduser_script());
71         if (!add_script || !*add_script) {
72                 return -1;
73         }
74         add_script = talloc_all_string_sub(ctx,
75                                 add_script,
76                                 "%u",
77                                 unix_username);
78         if (!add_script) {
79                 return -1;
80         }
81         if (domain) {
82                 add_script = talloc_all_string_sub(ctx,
83                                         add_script,
84                                         "%D",
85                                         domain);
86                 if (!add_script) {
87                         return -1;
88                 }
89         }
90         if (homedir) {
91                 add_script = talloc_all_string_sub(ctx,
92                                 add_script,
93                                 "%H",
94                                 homedir);
95                 if (!add_script) {
96                         return -1;
97                 }
98         }
99         ret = smbrun(add_script,NULL);
100         flush_pwnam_cache();
101         DEBUG(ret ? 0 : 3,
102                 ("smb_create_user: Running the command `%s' gave %d\n",
103                  add_script,ret));
104         return ret;
105 }
106
107 /****************************************************************************
108  Create an auth_usersupplied_data structure after appropriate mapping.
109 ****************************************************************************/
110
111 NTSTATUS make_user_info_map(struct auth_usersupplied_info **user_info,
112                             const char *smb_name,
113                             const char *client_domain,
114                             const char *wksta_name,
115                             DATA_BLOB *lm_pwd,
116                             DATA_BLOB *nt_pwd,
117                             DATA_BLOB *lm_interactive_pwd,
118                             DATA_BLOB *nt_interactive_pwd,
119                             DATA_BLOB *plaintext,
120                             bool encrypted)
121 {
122         struct smbd_server_connection *sconn = smbd_server_conn;
123         const char *domain;
124         NTSTATUS result;
125         bool was_mapped;
126         fstring internal_username;
127         fstrcpy(internal_username, smb_name);
128         was_mapped = map_username(sconn, internal_username);
129
130         DEBUG(5, ("Mapping user [%s]\\[%s] from workstation [%s]\n",
131                  client_domain, smb_name, wksta_name));
132
133         domain = client_domain;
134
135         /* If you connect to a Windows domain member using a bogus domain name,
136          * the Windows box will map the BOGUS\user to SAMNAME\user.  Thus, if
137          * the Windows box is a DC the name will become DOMAIN\user and be
138          * authenticated against AD, if the Windows box is a member server but
139          * not a DC the name will become WORKSTATION\user.  A standalone
140          * non-domain member box will also map to WORKSTATION\user.
141          * This also deals with the client passing in a "" domain */
142
143         if (!is_trusted_domain(domain) &&
144             !strequal(domain, my_sam_name()))
145         {
146                 if (lp_map_untrusted_to_domain())
147                         domain = my_sam_name();
148                 else
149                         domain = get_global_sam_name();
150                 DEBUG(5, ("Mapped domain from [%s] to [%s] for user [%s] from "
151                           "workstation [%s]\n",
152                           client_domain, domain, smb_name, wksta_name));
153         }
154
155         /* We know that the given domain is trusted (and we are allowing them),
156          * it is our global SAM name, or for legacy behavior it is our
157          * primary domain name */
158
159         result = make_user_info(user_info, smb_name, internal_username,
160                               client_domain, domain, wksta_name,
161                               lm_pwd, nt_pwd,
162                               lm_interactive_pwd, nt_interactive_pwd,
163                               plaintext, encrypted);
164         if (NT_STATUS_IS_OK(result)) {
165                 (*user_info)->was_mapped = was_mapped;
166         }
167         return result;
168 }
169
170 /****************************************************************************
171  Create an auth_usersupplied_data, making the DATA_BLOBs here. 
172  Decrypt and encrypt the passwords.
173 ****************************************************************************/
174
175 bool make_user_info_netlogon_network(struct auth_usersupplied_info **user_info,
176                                      const char *smb_name, 
177                                      const char *client_domain, 
178                                      const char *wksta_name, 
179                                      uint32 logon_parameters,
180                                      const uchar *lm_network_pwd,
181                                      int lm_pwd_len,
182                                      const uchar *nt_network_pwd,
183                                      int nt_pwd_len)
184 {
185         bool ret;
186         NTSTATUS status;
187         DATA_BLOB lm_blob = data_blob(lm_network_pwd, lm_pwd_len);
188         DATA_BLOB nt_blob = data_blob(nt_network_pwd, nt_pwd_len);
189
190         status = make_user_info_map(user_info,
191                                     smb_name, client_domain, 
192                                     wksta_name, 
193                                     lm_pwd_len ? &lm_blob : NULL, 
194                                     nt_pwd_len ? &nt_blob : NULL,
195                                     NULL, NULL, NULL,
196                                     True);
197
198         if (NT_STATUS_IS_OK(status)) {
199                 (*user_info)->logon_parameters = logon_parameters;
200         }
201         ret = NT_STATUS_IS_OK(status) ? True : False;
202
203         data_blob_free(&lm_blob);
204         data_blob_free(&nt_blob);
205         return ret;
206 }
207
208 /****************************************************************************
209  Create an auth_usersupplied_data, making the DATA_BLOBs here. 
210  Decrypt and encrypt the passwords.
211 ****************************************************************************/
212
213 bool make_user_info_netlogon_interactive(struct auth_usersupplied_info **user_info,
214                                          const char *smb_name, 
215                                          const char *client_domain, 
216                                          const char *wksta_name, 
217                                          uint32 logon_parameters,
218                                          const uchar chal[8], 
219                                          const uchar lm_interactive_pwd[16], 
220                                          const uchar nt_interactive_pwd[16], 
221                                          const uchar *dc_sess_key)
222 {
223         unsigned char lm_pwd[16];
224         unsigned char nt_pwd[16];
225         unsigned char local_lm_response[24];
226         unsigned char local_nt_response[24];
227         unsigned char key[16];
228
229         memcpy(key, dc_sess_key, 16);
230
231         if (lm_interactive_pwd)
232                 memcpy(lm_pwd, lm_interactive_pwd, sizeof(lm_pwd));
233
234         if (nt_interactive_pwd)
235                 memcpy(nt_pwd, nt_interactive_pwd, sizeof(nt_pwd));
236
237 #ifdef DEBUG_PASSWORD
238         DEBUG(100,("key:"));
239         dump_data(100, key, sizeof(key));
240
241         DEBUG(100,("lm owf password:"));
242         dump_data(100, lm_pwd, sizeof(lm_pwd));
243
244         DEBUG(100,("nt owf password:"));
245         dump_data(100, nt_pwd, sizeof(nt_pwd));
246 #endif
247
248         if (lm_interactive_pwd)
249                 arcfour_crypt(lm_pwd, key, sizeof(lm_pwd));
250
251         if (nt_interactive_pwd)
252                 arcfour_crypt(nt_pwd, key, sizeof(nt_pwd));
253
254 #ifdef DEBUG_PASSWORD
255         DEBUG(100,("decrypt of lm owf password:"));
256         dump_data(100, lm_pwd, sizeof(lm_pwd));
257
258         DEBUG(100,("decrypt of nt owf password:"));
259         dump_data(100, nt_pwd, sizeof(nt_pwd));
260 #endif
261
262         if (lm_interactive_pwd)
263                 SMBOWFencrypt(lm_pwd, chal,
264                               local_lm_response);
265
266         if (nt_interactive_pwd)
267                 SMBOWFencrypt(nt_pwd, chal,
268                               local_nt_response);
269
270         /* Password info paranoia */
271         ZERO_STRUCT(key);
272
273         {
274                 bool ret;
275                 NTSTATUS nt_status;
276                 DATA_BLOB local_lm_blob;
277                 DATA_BLOB local_nt_blob;
278
279                 DATA_BLOB lm_interactive_blob;
280                 DATA_BLOB nt_interactive_blob;
281
282                 if (lm_interactive_pwd) {
283                         local_lm_blob = data_blob(local_lm_response,
284                                                   sizeof(local_lm_response));
285                         lm_interactive_blob = data_blob(lm_pwd,
286                                                         sizeof(lm_pwd));
287                         ZERO_STRUCT(lm_pwd);
288                 }
289
290                 if (nt_interactive_pwd) {
291                         local_nt_blob = data_blob(local_nt_response,
292                                                   sizeof(local_nt_response));
293                         nt_interactive_blob = data_blob(nt_pwd,
294                                                         sizeof(nt_pwd));
295                         ZERO_STRUCT(nt_pwd);
296                 }
297
298                 nt_status = make_user_info_map(
299                         user_info, 
300                         smb_name, client_domain, wksta_name, 
301                         lm_interactive_pwd ? &local_lm_blob : NULL,
302                         nt_interactive_pwd ? &local_nt_blob : NULL,
303                         lm_interactive_pwd ? &lm_interactive_blob : NULL,
304                         nt_interactive_pwd ? &nt_interactive_blob : NULL,
305                         NULL, True);
306
307                 if (NT_STATUS_IS_OK(nt_status)) {
308                         (*user_info)->logon_parameters = logon_parameters;
309                 }
310
311                 ret = NT_STATUS_IS_OK(nt_status) ? True : False;
312                 data_blob_free(&local_lm_blob);
313                 data_blob_free(&local_nt_blob);
314                 data_blob_free(&lm_interactive_blob);
315                 data_blob_free(&nt_interactive_blob);
316                 return ret;
317         }
318 }
319
320
321 /****************************************************************************
322  Create an auth_usersupplied_data structure
323 ****************************************************************************/
324
325 bool make_user_info_for_reply(struct auth_usersupplied_info **user_info,
326                               const char *smb_name, 
327                               const char *client_domain,
328                               const uint8 chal[8],
329                               DATA_BLOB plaintext_password)
330 {
331
332         DATA_BLOB local_lm_blob;
333         DATA_BLOB local_nt_blob;
334         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
335
336         /*
337          * Not encrypted - do so.
338          */
339
340         DEBUG(5,("make_user_info_for_reply: User passwords not in encrypted "
341                  "format.\n"));
342
343         if (plaintext_password.data && plaintext_password.length) {
344                 unsigned char local_lm_response[24];
345
346 #ifdef DEBUG_PASSWORD
347                 DEBUG(10,("Unencrypted password (len %d):\n",
348                           (int)plaintext_password.length));
349                 dump_data(100, plaintext_password.data,
350                           plaintext_password.length);
351 #endif
352
353                 SMBencrypt( (const char *)plaintext_password.data,
354                             (const uchar*)chal, local_lm_response);
355                 local_lm_blob = data_blob(local_lm_response, 24);
356
357                 /* We can't do an NT hash here, as the password needs to be
358                    case insensitive */
359                 local_nt_blob = data_blob_null; 
360         } else {
361                 local_lm_blob = data_blob_null; 
362                 local_nt_blob = data_blob_null; 
363         }
364
365         ret = make_user_info_map(
366                 user_info, smb_name, client_domain, 
367                 get_remote_machine_name(),
368                 local_lm_blob.data ? &local_lm_blob : NULL,
369                 local_nt_blob.data ? &local_nt_blob : NULL,
370                 NULL, NULL,
371                 plaintext_password.data && plaintext_password.length ? &plaintext_password : NULL, 
372                 False);
373
374         data_blob_free(&local_lm_blob);
375         return NT_STATUS_IS_OK(ret) ? True : False;
376 }
377
378 /****************************************************************************
379  Create an auth_usersupplied_data structure
380 ****************************************************************************/
381
382 NTSTATUS make_user_info_for_reply_enc(struct auth_usersupplied_info **user_info,
383                                       const char *smb_name,
384                                       const char *client_domain, 
385                                       DATA_BLOB lm_resp, DATA_BLOB nt_resp)
386 {
387         return make_user_info_map(user_info, smb_name, 
388                                   client_domain, 
389                                   get_remote_machine_name(), 
390                                   lm_resp.data ? &lm_resp : NULL, 
391                                   nt_resp.data ? &nt_resp : NULL, 
392                                   NULL, NULL, NULL,
393                                   True);
394 }
395
396 /****************************************************************************
397  Create a guest user_info blob, for anonymous authenticaion.
398 ****************************************************************************/
399
400 bool make_user_info_guest(struct auth_usersupplied_info **user_info)
401 {
402         NTSTATUS nt_status;
403
404         nt_status = make_user_info(user_info, 
405                                    "","", 
406                                    "","", 
407                                    "", 
408                                    NULL, NULL, 
409                                    NULL, NULL, 
410                                    NULL,
411                                    True);
412
413         return NT_STATUS_IS_OK(nt_status) ? True : False;
414 }
415
416 static NTSTATUS log_nt_token(NT_USER_TOKEN *token)
417 {
418         TALLOC_CTX *frame = talloc_stackframe();
419         char *command;
420         char *group_sidstr;
421         size_t i;
422
423         if ((lp_log_nt_token_command() == NULL) ||
424             (strlen(lp_log_nt_token_command()) == 0)) {
425                 TALLOC_FREE(frame);
426                 return NT_STATUS_OK;
427         }
428
429         group_sidstr = talloc_strdup(frame, "");
430         for (i=1; i<token->num_sids; i++) {
431                 group_sidstr = talloc_asprintf(
432                         frame, "%s %s", group_sidstr,
433                         sid_string_talloc(frame, &token->user_sids[i]));
434         }
435
436         command = talloc_string_sub(
437                 frame, lp_log_nt_token_command(),
438                 "%s", sid_string_talloc(frame, &token->user_sids[0]));
439         command = talloc_string_sub(frame, command, "%t", group_sidstr);
440
441         if (command == NULL) {
442                 TALLOC_FREE(frame);
443                 return NT_STATUS_NO_MEMORY;
444         }
445
446         DEBUG(8, ("running command: [%s]\n", command));
447         if (smbrun(command, NULL) != 0) {
448                 DEBUG(0, ("Could not log NT token\n"));
449                 TALLOC_FREE(frame);
450                 return NT_STATUS_ACCESS_DENIED;
451         }
452
453         TALLOC_FREE(frame);
454         return NT_STATUS_OK;
455 }
456
457 /*
458  * Create the token to use from server_info->info3 and
459  * server_info->sids (the info3/sam groups). Find the unix gids.
460  */
461
462 NTSTATUS create_local_token(struct auth_serversupplied_info *server_info)
463 {
464         NTSTATUS status;
465         size_t i;
466         struct dom_sid tmp_sid;
467         struct dom_sid user_sid;
468
469         /*
470          * If winbind is not around, we can not make much use of the SIDs the
471          * domain controller provided us with. Likewise if the user name was
472          * mapped to some local unix user.
473          */
474
475         if (((lp_server_role() == ROLE_DOMAIN_MEMBER) && !winbind_ping()) ||
476             (server_info->nss_token)) {
477                 status = create_token_from_username(server_info,
478                                                     server_info->unix_name,
479                                                     server_info->guest,
480                                                     &server_info->utok.uid,
481                                                     &server_info->utok.gid,
482                                                     &server_info->unix_name,
483                                                     &server_info->ptok);
484
485         } else {
486                 sid_compose(&user_sid,
487                             server_info->info3->base.domain_sid,
488                             server_info->info3->base.rid);
489
490                 server_info->ptok = create_local_nt_token(
491                         server_info,
492                         &user_sid,
493                         server_info->guest,
494                         server_info->num_sids, server_info->sids);
495                 status = server_info->ptok ?
496                         NT_STATUS_OK : NT_STATUS_NO_SUCH_USER;
497         }
498
499         if (!NT_STATUS_IS_OK(status)) {
500                 return status;
501         }
502
503         /* Convert the SIDs to gids. */
504
505         server_info->utok.ngroups = 0;
506         server_info->utok.groups = NULL;
507
508         /* Start at index 1, where the groups start. */
509
510         for (i=1; i<server_info->ptok->num_sids; i++) {
511                 gid_t gid;
512                 struct dom_sid *sid = &server_info->ptok->user_sids[i];
513
514                 if (!sid_to_gid(sid, &gid)) {
515                         DEBUG(10, ("Could not convert SID %s to gid, "
516                                    "ignoring it\n", sid_string_dbg(sid)));
517                         continue;
518                 }
519                 add_gid_to_array_unique(server_info, gid,
520                                         &server_info->utok.groups,
521                                         &server_info->utok.ngroups);
522         }
523
524         /*
525          * Add the "Unix Group" SID for each gid to catch mapped groups
526          * and their Unix equivalent.  This is to solve the backwards
527          * compatibility problem of 'valid users = +ntadmin' where
528          * ntadmin has been paired with "Domain Admins" in the group
529          * mapping table.  Otherwise smb.conf would need to be changed
530          * to 'valid user = "Domain Admins"'.  --jerry
531          *
532          * For consistency we also add the "Unix User" SID,
533          * so that the complete unix token is represented within
534          * the nt token.
535          */
536
537         if (!uid_to_unix_users_sid(server_info->utok.uid, &tmp_sid)) {
538                 DEBUG(1,("create_local_token: Failed to create SID "
539                         "for uid %u!\n", (unsigned int)server_info->utok.uid));
540         }
541         add_sid_to_array_unique(server_info->ptok, &tmp_sid,
542                                 &server_info->ptok->user_sids,
543                                 &server_info->ptok->num_sids);
544
545         for ( i=0; i<server_info->utok.ngroups; i++ ) {
546                 if (!gid_to_unix_groups_sid( server_info->utok.groups[i], &tmp_sid ) ) {
547                         DEBUG(1,("create_local_token: Failed to create SID "
548                                 "for gid %u!\n", (unsigned int)server_info->utok.groups[i]));
549                         continue;
550                 }
551                 add_sid_to_array_unique(server_info->ptok, &tmp_sid,
552                                         &server_info->ptok->user_sids,
553                                         &server_info->ptok->num_sids);
554         }
555
556         debug_nt_user_token(DBGC_AUTH, 10, server_info->ptok);
557         debug_unix_user_token(DBGC_AUTH, 10,
558                               server_info->utok.uid,
559                               server_info->utok.gid,
560                               server_info->utok.ngroups,
561                               server_info->utok.groups);
562
563         status = log_nt_token(server_info->ptok);
564         return status;
565 }
566
567 /***************************************************************************
568  Make (and fill) a server_info struct from a 'struct passwd' by conversion
569  to a struct samu
570 ***************************************************************************/
571
572 NTSTATUS make_server_info_pw(struct auth_serversupplied_info **server_info,
573                              char *unix_username,
574                              struct passwd *pwd)
575 {
576         NTSTATUS status;
577         struct samu *sampass = NULL;
578         gid_t *gids;
579         char *qualified_name = NULL;
580         TALLOC_CTX *mem_ctx = NULL;
581         struct dom_sid u_sid;
582         enum lsa_SidType type;
583         struct auth_serversupplied_info *result;
584
585         if ( !(sampass = samu_new( NULL )) ) {
586                 return NT_STATUS_NO_MEMORY;
587         }
588
589         status = samu_set_unix( sampass, pwd );
590         if (!NT_STATUS_IS_OK(status)) {
591                 return status;
592         }
593
594         result = make_server_info(NULL);
595         if (result == NULL) {
596                 TALLOC_FREE(sampass);
597                 return NT_STATUS_NO_MEMORY;
598         }
599
600         status = samu_to_SamInfo3(result, sampass,
601                                   global_myname(), &result->info3);
602         if (!NT_STATUS_IS_OK(status)) {
603                 DEBUG(10, ("Failed to convert samu to info3: %s\n",
604                            nt_errstr(status)));
605                 TALLOC_FREE(sampass);
606                 TALLOC_FREE(result);
607                 return status;
608         }
609
610
611         result->unix_name = talloc_strdup(result, unix_username);
612         result->sanitized_username = sanitize_username(result, unix_username);
613
614         if ((result->unix_name == NULL)
615             || (result->sanitized_username == NULL)) {
616                 TALLOC_FREE(sampass);
617                 TALLOC_FREE(result);
618                 return NT_STATUS_NO_MEMORY;
619         }
620
621         result->utok.uid = pwd->pw_uid;
622         result->utok.gid = pwd->pw_gid;
623
624         status = pdb_enum_group_memberships(result, sampass,
625                                             &result->sids, &gids,
626                                             &result->num_sids);
627
628         if (!NT_STATUS_IS_OK(status)) {
629                 DEBUG(10, ("pdb_enum_group_memberships failed: %s\n",
630                            nt_errstr(status)));
631                 TALLOC_FREE(sampass);
632                 TALLOC_FREE(result);
633                 return status;
634         }
635
636         TALLOC_FREE(sampass);
637
638         /*
639          * The SID returned in server_info->sam_account is based
640          * on our SAM sid even though for a pure UNIX account this should
641          * not be the case as it doesn't really exist in the SAM db.
642          * This causes lookups on "[in]valid users" to fail as they
643          * will lookup this name as a "Unix User" SID to check against
644          * the user token. Fix this by adding the "Unix User"\unix_username
645          * SID to the sid array. The correct fix should probably be
646          * changing the server_info->sam_account user SID to be a
647          * S-1-22 Unix SID, but this might break old configs where
648          * plaintext passwords were used with no SAM backend.
649          */
650
651         mem_ctx = talloc_init("make_server_info_pw_tmp");
652         if (!mem_ctx) {
653                 TALLOC_FREE(result);
654                 return NT_STATUS_NO_MEMORY;
655         }
656
657         qualified_name = talloc_asprintf(mem_ctx, "%s\\%s",
658                                         unix_users_domain_name(),
659                                         unix_username );
660         if (!qualified_name) {
661                 TALLOC_FREE(result);
662                 TALLOC_FREE(mem_ctx);
663                 return NT_STATUS_NO_MEMORY;
664         }
665
666         if (!lookup_name(mem_ctx, qualified_name, LOOKUP_NAME_ALL,
667                                                 NULL, NULL,
668                                                 &u_sid, &type)) {
669                 TALLOC_FREE(result);
670                 TALLOC_FREE(mem_ctx);
671                 return NT_STATUS_NO_SUCH_USER;
672         }
673
674         TALLOC_FREE(mem_ctx);
675
676         if (type != SID_NAME_USER) {
677                 TALLOC_FREE(result);
678                 return NT_STATUS_NO_SUCH_USER;
679         }
680
681         /* FIXME: add to info3 too ? */
682         status = add_sid_to_array_unique(result, &u_sid,
683                                          &result->sids,
684                                          &result->num_sids);
685         if (!NT_STATUS_IS_OK(status)) {
686                 TALLOC_FREE(result);
687                 return status;
688         }
689
690         /* For now we throw away the gids and convert via sid_to_gid
691          * later. This needs fixing, but I'd like to get the code straight and
692          * simple first. */
693         TALLOC_FREE(gids);
694
695         *server_info = result;
696
697         return NT_STATUS_OK;
698 }
699
700 /***************************************************************************
701  Make (and fill) a user_info struct for a guest login.
702  This *must* succeed for smbd to start. If there is no mapping entry for
703  the guest gid, then create one.
704 ***************************************************************************/
705
706 static NTSTATUS make_new_server_info_guest(struct auth_serversupplied_info **server_info)
707 {
708         NTSTATUS status;
709         struct samu *sampass = NULL;
710         struct dom_sid guest_sid;
711         bool ret;
712         static const char zeros[16] = {0, };
713         fstring tmp;
714
715         if ( !(sampass = samu_new( NULL )) ) {
716                 return NT_STATUS_NO_MEMORY;
717         }
718
719         sid_compose(&guest_sid, get_global_sam_sid(), DOMAIN_RID_GUEST);
720
721         become_root();
722         ret = pdb_getsampwsid(sampass, &guest_sid);
723         unbecome_root();
724
725         if (!ret) {
726                 TALLOC_FREE(sampass);
727                 return NT_STATUS_NO_SUCH_USER;
728         }
729
730         status = make_server_info_sam(server_info, sampass);
731         if (!NT_STATUS_IS_OK(status)) {
732                 TALLOC_FREE(sampass);
733                 return status;
734         }
735
736         TALLOC_FREE(sampass);
737
738         (*server_info)->guest = True;
739
740         status = create_local_token(*server_info);
741         if (!NT_STATUS_IS_OK(status)) {
742                 DEBUG(10, ("create_local_token failed: %s\n",
743                            nt_errstr(status)));
744                 return status;
745         }
746
747         /* annoying, but the Guest really does have a session key, and it is
748            all zeros! */
749         (*server_info)->user_session_key = data_blob(zeros, sizeof(zeros));
750         (*server_info)->lm_session_key = data_blob(zeros, sizeof(zeros));
751
752         alpha_strcpy(tmp, (*server_info)->info3->base.account_name.string,
753                      ". _-$", sizeof(tmp));
754         (*server_info)->sanitized_username = talloc_strdup(*server_info, tmp);
755
756         return NT_STATUS_OK;
757 }
758
759 /***************************************************************************
760  Make (and fill) a user_info struct for a system user login.
761  This *must* succeed for smbd to start.
762 ***************************************************************************/
763
764 static NTSTATUS make_new_server_info_system(TALLOC_CTX *mem_ctx,
765                                             struct auth_serversupplied_info **server_info)
766 {
767         struct passwd *pwd;
768
769         pwd = getpwuid_alloc(mem_ctx, sec_initial_uid());
770         if (pwd == NULL) {
771                 return NT_STATUS_NO_MEMORY;
772         }
773
774         return make_serverinfo_from_username(mem_ctx,
775                                              pwd->pw_name,
776                                              false,
777                                              server_info);
778 }
779
780 /****************************************************************************
781   Fake a auth_serversupplied_info just from a username
782 ****************************************************************************/
783
784 NTSTATUS make_serverinfo_from_username(TALLOC_CTX *mem_ctx,
785                                        const char *username,
786                                        bool is_guest,
787                                        struct auth_serversupplied_info **presult)
788 {
789         struct auth_serversupplied_info *result;
790         struct passwd *pwd;
791         NTSTATUS status;
792
793         pwd = getpwnam_alloc(talloc_tos(), username);
794         if (pwd == NULL) {
795                 return NT_STATUS_NO_SUCH_USER;
796         }
797
798         status = make_server_info_pw(&result, pwd->pw_name, pwd);
799
800         TALLOC_FREE(pwd);
801
802         if (!NT_STATUS_IS_OK(status)) {
803                 return status;
804         }
805
806         result->nss_token = true;
807         result->guest = is_guest;
808
809         status = create_local_token(result);
810
811         if (!NT_STATUS_IS_OK(status)) {
812                 TALLOC_FREE(result);
813                 return status;
814         }
815
816         *presult = result;
817         return NT_STATUS_OK;
818 }
819
820
821 struct auth_serversupplied_info *copy_serverinfo(TALLOC_CTX *mem_ctx,
822                                                  const struct auth_serversupplied_info *src)
823 {
824         struct auth_serversupplied_info *dst;
825
826         dst = make_server_info(mem_ctx);
827         if (dst == NULL) {
828                 return NULL;
829         }
830
831         dst->guest = src->guest;
832         dst->utok.uid = src->utok.uid;
833         dst->utok.gid = src->utok.gid;
834         dst->utok.ngroups = src->utok.ngroups;
835         if (src->utok.ngroups != 0) {
836                 dst->utok.groups = (gid_t *)TALLOC_MEMDUP(
837                         dst, src->utok.groups,
838                         sizeof(gid_t)*dst->utok.ngroups);
839         } else {
840                 dst->utok.groups = NULL;
841         }
842
843         if (src->ptok) {
844                 dst->ptok = dup_nt_token(dst, src->ptok);
845                 if (!dst->ptok) {
846                         TALLOC_FREE(dst);
847                         return NULL;
848                 }
849         }
850
851         dst->user_session_key = data_blob_talloc( dst, src->user_session_key.data,
852                                                 src->user_session_key.length);
853
854         dst->lm_session_key = data_blob_talloc(dst, src->lm_session_key.data,
855                                                 src->lm_session_key.length);
856
857         dst->info3 = copy_netr_SamInfo3(dst, src->info3);
858         if (!dst->info3) {
859                 TALLOC_FREE(dst);
860                 return NULL;
861         }
862
863         dst->pam_handle = NULL;
864         dst->unix_name = talloc_strdup(dst, src->unix_name);
865         if (!dst->unix_name) {
866                 TALLOC_FREE(dst);
867                 return NULL;
868         }
869
870         dst->sanitized_username = talloc_strdup(dst, src->sanitized_username);
871         if (!dst->sanitized_username) {
872                 TALLOC_FREE(dst);
873                 return NULL;
874         }
875
876         return dst;
877 }
878
879 /*
880  * Set a new session key. Used in the rpc server where we have to override the
881  * SMB level session key with SystemLibraryDTC
882  */
883
884 bool server_info_set_session_key(struct auth_serversupplied_info *info,
885                                  DATA_BLOB session_key)
886 {
887         TALLOC_FREE(info->user_session_key.data);
888
889         info->user_session_key = data_blob_talloc(
890                 info, session_key.data, session_key.length);
891
892         return (info->user_session_key.data != NULL);
893 }
894
895 static struct auth_serversupplied_info *guest_info = NULL;
896
897 bool init_guest_info(void)
898 {
899         if (guest_info != NULL)
900                 return True;
901
902         return NT_STATUS_IS_OK(make_new_server_info_guest(&guest_info));
903 }
904
905 NTSTATUS make_server_info_guest(TALLOC_CTX *mem_ctx,
906                                 struct auth_serversupplied_info **server_info)
907 {
908         *server_info = copy_serverinfo(mem_ctx, guest_info);
909         return (*server_info != NULL) ? NT_STATUS_OK : NT_STATUS_NO_MEMORY;
910 }
911
912 static struct auth_serversupplied_info *system_info = NULL;
913
914 bool init_system_info(void)
915 {
916         if (system_info != NULL)
917                 return True;
918
919         return NT_STATUS_IS_OK(make_new_server_info_system(talloc_autofree_context(), &system_info));
920 }
921
922 NTSTATUS make_server_info_system(TALLOC_CTX *mem_ctx,
923                                 struct auth_serversupplied_info **server_info)
924 {
925         if (system_info == NULL) return NT_STATUS_UNSUCCESSFUL;
926         *server_info = copy_serverinfo(mem_ctx, system_info);
927         return (*server_info != NULL) ? NT_STATUS_OK : NT_STATUS_NO_MEMORY;
928 }
929
930 bool copy_current_user(struct current_user *dst, struct current_user *src)
931 {
932         gid_t *groups;
933         NT_USER_TOKEN *nt_token;
934
935         groups = (gid_t *)memdup(src->ut.groups,
936                                  sizeof(gid_t) * src->ut.ngroups);
937         if ((src->ut.ngroups != 0) && (groups == NULL)) {
938                 return False;
939         }
940
941         nt_token = dup_nt_token(NULL, src->nt_user_token);
942         if (nt_token == NULL) {
943                 SAFE_FREE(groups);
944                 return False;
945         }
946
947         dst->conn = src->conn;
948         dst->vuid = src->vuid;
949         dst->ut.uid = src->ut.uid;
950         dst->ut.gid = src->ut.gid;
951         dst->ut.ngroups = src->ut.ngroups;
952         dst->ut.groups = groups;
953         dst->nt_user_token = nt_token;
954         return True;
955 }
956
957 /***************************************************************************
958  Purely internal function for make_server_info_info3
959 ***************************************************************************/
960
961 static NTSTATUS check_account(TALLOC_CTX *mem_ctx, const char *domain,
962                               const char *username, char **found_username,
963                               uid_t *uid, gid_t *gid,
964                               bool *username_was_mapped)
965 {
966         struct smbd_server_connection *sconn = smbd_server_conn;
967         NTSTATUS nt_status;
968         fstring dom_user, lower_username;
969         fstring real_username;
970         struct passwd *passwd;
971
972         fstrcpy( lower_username, username );
973         strlower_m( lower_username );
974
975         fstr_sprintf(dom_user, "%s%c%s", domain, *lp_winbind_separator(), 
976                 lower_username);
977
978         /* Get the passwd struct.  Try to create the account if necessary. */
979
980         *username_was_mapped = map_username(sconn, dom_user);
981
982         if ( !(passwd = smb_getpwnam( NULL, dom_user, real_username, True )) )
983                 return NT_STATUS_NO_SUCH_USER;
984
985         *uid = passwd->pw_uid;
986         *gid = passwd->pw_gid;
987
988         /* This is pointless -- there is no suport for differing 
989            unix and windows names.  Make sure to always store the 
990            one we actually looked up and succeeded. Have I mentioned
991            why I hate the 'winbind use default domain' parameter?   
992                                          --jerry              */
993
994         *found_username = talloc_strdup( mem_ctx, real_username );
995
996         TALLOC_FREE(passwd);
997
998         return nt_status;
999 }
1000
1001 /****************************************************************************
1002  Wrapper to allow the getpwnam() call to strip the domain name and 
1003  try again in case a local UNIX user is already there.  Also run through 
1004  the username if we fallback to the username only.
1005  ****************************************************************************/
1006
1007 struct passwd *smb_getpwnam( TALLOC_CTX *mem_ctx, char *domuser,
1008                              fstring save_username, bool create )
1009 {
1010         struct passwd *pw = NULL;
1011         char *p;
1012         fstring username;
1013
1014         /* we only save a copy of the username it has been mangled 
1015            by winbindd use default domain */
1016
1017         save_username[0] = '\0';
1018
1019         /* don't call map_username() here since it has to be done higher 
1020            up the stack so we don't call it multiple times */
1021
1022         fstrcpy( username, domuser );
1023
1024         p = strchr_m( username, *lp_winbind_separator() );
1025
1026         /* code for a DOMAIN\user string */
1027
1028         if ( p ) {
1029                 fstring strip_username;
1030
1031                 pw = Get_Pwnam_alloc( mem_ctx, domuser );
1032                 if ( pw ) {     
1033                         /* make sure we get the case of the username correct */
1034                         /* work around 'winbind use default domain = yes' */
1035
1036                         if ( !strchr_m( pw->pw_name, *lp_winbind_separator() ) ) {
1037                                 char *domain;
1038
1039                                 /* split the domain and username into 2 strings */
1040                                 *p = '\0';
1041                                 domain = username;
1042
1043                                 fstr_sprintf(save_username, "%s%c%s", domain, *lp_winbind_separator(), pw->pw_name);
1044                         }
1045                         else
1046                                 fstrcpy( save_username, pw->pw_name );
1047
1048                         /* whew -- done! */             
1049                         return pw;
1050                 }
1051
1052                 /* setup for lookup of just the username */
1053                 /* remember that p and username are overlapping memory */
1054
1055                 p++;
1056                 fstrcpy( strip_username, p );
1057                 fstrcpy( username, strip_username );
1058         }
1059
1060         /* just lookup a plain username */
1061
1062         pw = Get_Pwnam_alloc(mem_ctx, username);
1063
1064         /* Create local user if requested but only if winbindd
1065            is not running.  We need to protect against cases
1066            where winbindd is failing and then prematurely
1067            creating users in /etc/passwd */
1068
1069         if ( !pw && create && !winbind_ping() ) {
1070                 /* Don't add a machine account. */
1071                 if (username[strlen(username)-1] == '$')
1072                         return NULL;
1073
1074                 _smb_create_user(NULL, username, NULL);
1075                 pw = Get_Pwnam_alloc(mem_ctx, username);
1076         }
1077
1078         /* one last check for a valid passwd struct */
1079
1080         if ( pw )
1081                 fstrcpy( save_username, pw->pw_name );
1082
1083         return pw;
1084 }
1085
1086 /***************************************************************************
1087  Make a server_info struct from the info3 returned by a domain logon 
1088 ***************************************************************************/
1089
1090 NTSTATUS make_server_info_info3(TALLOC_CTX *mem_ctx, 
1091                                 const char *sent_nt_username,
1092                                 const char *domain,
1093                                 struct auth_serversupplied_info **server_info,
1094                                 struct netr_SamInfo3 *info3)
1095 {
1096         static const char zeros[16] = {0, };
1097
1098         NTSTATUS nt_status = NT_STATUS_OK;
1099         char *found_username = NULL;
1100         const char *nt_domain;
1101         const char *nt_username;
1102         struct dom_sid user_sid;
1103         struct dom_sid group_sid;
1104         bool username_was_mapped;
1105
1106         uid_t uid = (uid_t)-1;
1107         gid_t gid = (gid_t)-1;
1108
1109         struct auth_serversupplied_info *result;
1110
1111         /* 
1112            Here is where we should check the list of
1113            trusted domains, and verify that the SID 
1114            matches.
1115         */
1116
1117         if (!sid_compose(&user_sid, info3->base.domain_sid, info3->base.rid)) {
1118                 return NT_STATUS_INVALID_PARAMETER;
1119         }
1120
1121         if (!sid_compose(&group_sid, info3->base.domain_sid,
1122                          info3->base.primary_gid)) {
1123                 return NT_STATUS_INVALID_PARAMETER;
1124         }
1125
1126         nt_username = talloc_strdup(mem_ctx, info3->base.account_name.string);
1127         if (!nt_username) {
1128                 /* If the server didn't give us one, just use the one we sent
1129                  * them */
1130                 nt_username = sent_nt_username;
1131         }
1132
1133         nt_domain = talloc_strdup(mem_ctx, info3->base.domain.string);
1134         if (!nt_domain) {
1135                 /* If the server didn't give us one, just use the one we sent
1136                  * them */
1137                 nt_domain = domain;
1138         }
1139
1140         /* If getpwnam() fails try the add user script (2.2.x behavior).
1141
1142            We use the _unmapped_ username here in an attempt to provide
1143            consistent username mapping behavior between kerberos and NTLM[SSP]
1144            authentication in domain mode security.  I.E. Username mapping
1145            should be applied to the fully qualified username
1146            (e.g. DOMAIN\user) and not just the login name.  Yes this means we
1147            called map_username() unnecessarily in make_user_info_map() but
1148            that is how the current code is designed.  Making the change here
1149            is the least disruptive place.  -- jerry */
1150
1151         /* this call will try to create the user if necessary */
1152
1153         nt_status = check_account(mem_ctx, nt_domain, sent_nt_username,
1154                                      &found_username, &uid, &gid,
1155                                      &username_was_mapped);
1156
1157         result = make_server_info(NULL);
1158         if (result == NULL) {
1159                 DEBUG(4, ("make_server_info failed!\n"));
1160                 return NT_STATUS_NO_MEMORY;
1161         }
1162
1163         result->unix_name = talloc_strdup(result, found_username);
1164
1165         result->sanitized_username = sanitize_username(result,
1166                                                        result->unix_name);
1167         if (result->sanitized_username == NULL) {
1168                 TALLOC_FREE(result);
1169                 return NT_STATUS_NO_MEMORY;
1170         }
1171
1172         /* copy in the info3 */
1173         result->info3 = copy_netr_SamInfo3(result, info3);
1174
1175         /* Fill in the unix info we found on the way */
1176
1177         result->utok.uid = uid;
1178         result->utok.gid = gid;
1179
1180         /* Create a 'combined' list of all SIDs we might want in the SD */
1181
1182         result->num_sids = 0;
1183         result->sids = NULL;
1184
1185         nt_status = sid_array_from_info3(result, info3,
1186                                          &result->sids,
1187                                          &result->num_sids,
1188                                          false, false);
1189         if (!NT_STATUS_IS_OK(nt_status)) {
1190                 TALLOC_FREE(result);
1191                 return nt_status;
1192         }
1193
1194         /* Ensure the primary group sid is at position 0. */
1195         sort_sid_array_for_smbd(result, &group_sid);
1196
1197         /* ensure we are never given NULL session keys */
1198
1199         if (memcmp(info3->base.key.key, zeros, sizeof(zeros)) == 0) {
1200                 result->user_session_key = data_blob_null;
1201         } else {
1202                 result->user_session_key = data_blob_talloc(
1203                         result, info3->base.key.key,
1204                         sizeof(info3->base.key.key));
1205         }
1206
1207         if (memcmp(info3->base.LMSessKey.key, zeros, 8) == 0) {
1208                 result->lm_session_key = data_blob_null;
1209         } else {
1210                 result->lm_session_key = data_blob_talloc(
1211                         result, info3->base.LMSessKey.key,
1212                         sizeof(info3->base.LMSessKey.key));
1213         }
1214
1215         result->nss_token |= username_was_mapped;
1216
1217         *server_info = result;
1218
1219         return NT_STATUS_OK;
1220 }
1221
1222 /*****************************************************************************
1223  Make a server_info struct from the wbcAuthUserInfo returned by a domain logon
1224 ******************************************************************************/
1225
1226 NTSTATUS make_server_info_wbcAuthUserInfo(TALLOC_CTX *mem_ctx,
1227                                           const char *sent_nt_username,
1228                                           const char *domain,
1229                                           const struct wbcAuthUserInfo *info,
1230                                           struct auth_serversupplied_info **server_info)
1231 {
1232         struct netr_SamInfo3 *info3;
1233
1234         info3 = wbcAuthUserInfo_to_netr_SamInfo3(mem_ctx, info);
1235         if (!info3) {
1236                 return NT_STATUS_NO_MEMORY;
1237         }
1238
1239         return make_server_info_info3(mem_ctx,
1240                                       sent_nt_username, domain,
1241                                       server_info, info3);
1242 }
1243
1244 /**
1245  * Verify whether or not given domain is trusted.
1246  *
1247  * @param domain_name name of the domain to be verified
1248  * @return true if domain is one of the trusted ones or
1249  *         false if otherwise
1250  **/
1251
1252 bool is_trusted_domain(const char* dom_name)
1253 {
1254         struct dom_sid trustdom_sid;
1255         bool ret;
1256
1257         /* no trusted domains for a standalone server */
1258
1259         if ( lp_server_role() == ROLE_STANDALONE )
1260                 return False;
1261
1262         if (dom_name == NULL || dom_name[0] == '\0') {
1263                 return false;
1264         }
1265
1266         if (strequal(dom_name, get_global_sam_name())) {
1267                 return false;
1268         }
1269
1270         /* if we are a DC, then check for a direct trust relationships */
1271
1272         if ( IS_DC ) {
1273                 become_root();
1274                 DEBUG (5,("is_trusted_domain: Checking for domain trust with "
1275                           "[%s]\n", dom_name ));
1276                 ret = pdb_get_trusteddom_pw(dom_name, NULL, NULL, NULL);
1277                 unbecome_root();
1278                 if (ret)
1279                         return True;
1280         }
1281         else {
1282                 wbcErr result;
1283
1284                 /* If winbind is around, ask it */
1285
1286                 result = wb_is_trusted_domain(dom_name);
1287
1288                 if (result == WBC_ERR_SUCCESS) {
1289                         return True;
1290                 }
1291
1292                 if (result == WBC_ERR_DOMAIN_NOT_FOUND) {
1293                         /* winbind could not find the domain */
1294                         return False;
1295                 }
1296
1297                 /* The only other possible result is that winbind is not up
1298                    and running. We need to update the trustdom_cache
1299                    ourselves */
1300
1301                 update_trustdom_cache();
1302         }
1303
1304         /* now the trustdom cache should be available a DC could still
1305          * have a transitive trust so fall back to the cache of trusted
1306          * domains (like a domain member would use  */
1307
1308         if ( trustdom_cache_fetch(dom_name, &trustdom_sid) ) {
1309                 return True;
1310         }
1311
1312         return False;
1313 }
1314