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