libcli/security Provide a common, top level libcli/security/security.h
[kai/samba.git] / source3 / auth / token_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  *  Copyright (C) Michael Adam 2007
10  *
11  *  This program is free software; you can redistribute it and/or modify
12  *  it under the terms of the GNU General Public License as published by
13  *  the Free Software Foundation; either version 3 of the License, or
14  *  (at your option) any later version.
15  *
16  *  This program is distributed in the hope that it will be useful,
17  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
18  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  *  GNU General Public License for more details.
20  *
21  *  You should have received a copy of the GNU General Public License
22  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
23  */
24
25 /* functions moved from auth/auth_util.c to minimize linker deps */
26
27 #include "includes.h"
28 #include "secrets.h"
29 #include "memcache.h"
30 #include "../librpc/gen_ndr/netlogon.h"
31 #include "../libcli/security/security.h"
32
33 /****************************************************************************
34  Check for a SID in an struct security_token
35 ****************************************************************************/
36
37 bool nt_token_check_sid ( const struct dom_sid *sid, const struct security_token *token )
38 {
39         int i;
40
41         if ( !sid || !token )
42                 return False;
43
44         for ( i=0; i<token->num_sids; i++ ) {
45                 if ( dom_sid_equal( sid, &token->sids[i] ) )
46                         return True;
47         }
48
49         return False;
50 }
51
52 bool nt_token_check_domain_rid( struct security_token *token, uint32 rid )
53 {
54         struct dom_sid domain_sid;
55
56         /* if we are a domain member, the get the domain SID, else for
57            a DC or standalone server, use our own SID */
58
59         if ( lp_server_role() == ROLE_DOMAIN_MEMBER ) {
60                 if ( !secrets_fetch_domain_sid( lp_workgroup(),
61                                                 &domain_sid ) ) {
62                         DEBUG(1,("nt_token_check_domain_rid: Cannot lookup "
63                                  "SID for domain [%s]\n", lp_workgroup()));
64                         return False;
65                 }
66         }
67         else
68                 sid_copy( &domain_sid, get_global_sam_sid() );
69
70         sid_append_rid( &domain_sid, rid );
71
72         return nt_token_check_sid( &domain_sid, token );\
73 }
74
75 /******************************************************************************
76  Create a token for the root user to be used internally by smbd.
77  This is similar to running under the context of the LOCAL_SYSTEM account
78  in Windows.  This is a read-only token.  Do not modify it or free() it.
79  Create a copy if you need to change it.
80 ******************************************************************************/
81
82 struct security_token *get_root_nt_token( void )
83 {
84         struct security_token *token, *for_cache;
85         struct dom_sid u_sid, g_sid;
86         struct passwd *pw;
87         void *cache_data;
88
89         cache_data = memcache_lookup_talloc(
90                 NULL, SINGLETON_CACHE_TALLOC,
91                 data_blob_string_const_null("root_nt_token"));
92
93         if (cache_data != NULL) {
94                 return talloc_get_type_abort(
95                         cache_data, struct security_token);
96         }
97
98         if ( !(pw = sys_getpwuid(0)) ) {
99                 if ( !(pw = sys_getpwnam("root")) ) {
100                         DEBUG(0,("get_root_nt_token: both sys_getpwuid(0) "
101                                 "and sys_getpwnam(\"root\") failed!\n"));
102                         return NULL;
103                 }
104         }
105
106         /* get the user and primary group SIDs; although the
107            BUILTIN\Administrators SId is really the one that matters here */
108
109         uid_to_sid(&u_sid, pw->pw_uid);
110         gid_to_sid(&g_sid, pw->pw_gid);
111
112         token = create_local_nt_token(talloc_tos(), &u_sid, False,
113                                       1, &global_sid_Builtin_Administrators);
114
115         security_token_set_privilege(token, SEC_PRIV_DISK_OPERATOR);
116
117         for_cache = token;
118
119         memcache_add_talloc(
120                 NULL, SINGLETON_CACHE_TALLOC,
121                 data_blob_string_const_null("root_nt_token"), &for_cache);
122
123         return token;
124 }
125
126
127 /*
128  * Add alias SIDs from memberships within the partially created token SID list
129  */
130
131 NTSTATUS add_aliases(const struct dom_sid *domain_sid,
132                      struct security_token *token)
133 {
134         uint32 *aliases;
135         size_t i, num_aliases;
136         NTSTATUS status;
137         TALLOC_CTX *tmp_ctx;
138
139         if (!(tmp_ctx = talloc_init("add_aliases"))) {
140                 return NT_STATUS_NO_MEMORY;
141         }
142
143         aliases = NULL;
144         num_aliases = 0;
145
146         status = pdb_enum_alias_memberships(tmp_ctx, domain_sid,
147                                             token->sids,
148                                             token->num_sids,
149                                             &aliases, &num_aliases);
150
151         if (!NT_STATUS_IS_OK(status)) {
152                 DEBUG(10, ("pdb_enum_alias_memberships failed: %s\n",
153                            nt_errstr(status)));
154                 goto done;
155         }
156
157         for (i=0; i<num_aliases; i++) {
158                 struct dom_sid alias_sid;
159                 sid_compose(&alias_sid, domain_sid, aliases[i]);
160                 status = add_sid_to_array_unique(token, &alias_sid,
161                                                  &token->sids,
162                                                  &token->num_sids);
163                 if (!NT_STATUS_IS_OK(status)) {
164                         DEBUG(0, ("add_sid_to_array failed\n"));
165                         goto done;
166                 }
167         }
168
169 done:
170         TALLOC_FREE(tmp_ctx);
171         return NT_STATUS_OK;
172 }
173
174 /*******************************************************************
175 *******************************************************************/
176
177 static NTSTATUS add_builtin_administrators(struct security_token *token,
178                                            const struct dom_sid *dom_sid)
179 {
180         struct dom_sid domadm;
181         NTSTATUS status;
182
183         /* nothing to do if we aren't in a domain */
184
185         if ( !(IS_DC || lp_server_role()==ROLE_DOMAIN_MEMBER) ) {
186                 return NT_STATUS_OK;
187         }
188
189         /* Find the Domain Admins SID */
190
191         if ( IS_DC ) {
192                 sid_copy( &domadm, get_global_sam_sid() );
193         } else {
194                 sid_copy(&domadm, dom_sid);
195         }
196         sid_append_rid( &domadm, DOMAIN_RID_ADMINS );
197
198         /* Add Administrators if the user beloongs to Domain Admins */
199
200         if ( nt_token_check_sid( &domadm, token ) ) {
201                 status = add_sid_to_array(token,
202                                           &global_sid_Builtin_Administrators,
203                                           &token->sids, &token->num_sids);
204         if (!NT_STATUS_IS_OK(status)) {
205                         return status;
206                 }
207         }
208
209         return NT_STATUS_OK;
210 }
211
212 /**
213  * Create the requested BUILTIN if it doesn't already exist.  This requires
214  * winbindd to be running.
215  *
216  * @param[in] rid BUILTIN rid to create
217  * @return Normal NTSTATUS return.
218  */
219 static NTSTATUS create_builtin(uint32 rid)
220 {
221         NTSTATUS status = NT_STATUS_OK;
222         struct dom_sid sid;
223         gid_t gid;
224
225         if (!sid_compose(&sid, &global_sid_Builtin, rid)) {
226                 return NT_STATUS_NO_SUCH_ALIAS;
227         }
228
229         if (!sid_to_gid(&sid, &gid)) {
230                 if (!lp_winbind_nested_groups() || !winbind_ping()) {
231                         return NT_STATUS_PROTOCOL_UNREACHABLE;
232                 }
233                 status = pdb_create_builtin_alias(rid);
234         }
235         return status;
236 }
237
238 /**
239  * Add sid as a member of builtin_sid.
240  *
241  * @param[in] builtin_sid       An existing builtin group.
242  * @param[in] dom_sid           sid to add as a member of builtin_sid.
243  * @return Normal NTSTATUS return
244  */
245 static NTSTATUS add_sid_to_builtin(const struct dom_sid *builtin_sid,
246                                    const struct dom_sid *dom_sid)
247 {
248         NTSTATUS status = NT_STATUS_OK;
249
250         if (!dom_sid || !builtin_sid) {
251                 return NT_STATUS_INVALID_PARAMETER;
252         }
253
254         status = pdb_add_aliasmem(builtin_sid, dom_sid);
255
256         if (NT_STATUS_EQUAL(status, NT_STATUS_MEMBER_IN_ALIAS)) {
257                 DEBUG(5, ("add_sid_to_builtin %s is already a member of %s\n",
258                           sid_string_dbg(dom_sid),
259                           sid_string_dbg(builtin_sid)));
260                 return NT_STATUS_OK;
261         }
262
263         if (!NT_STATUS_IS_OK(status)) {
264                 DEBUG(4, ("add_sid_to_builtin %s could not be added to %s: "
265                           "%s\n", sid_string_dbg(dom_sid),
266                           sid_string_dbg(builtin_sid), nt_errstr(status)));
267         }
268         return status;
269 }
270
271 /*******************************************************************
272 *******************************************************************/
273
274 NTSTATUS create_builtin_users(const struct dom_sid *dom_sid)
275 {
276         NTSTATUS status;
277         struct dom_sid dom_users;
278
279         status = create_builtin(BUILTIN_RID_USERS);
280         if ( !NT_STATUS_IS_OK(status) ) {
281                 DEBUG(5,("create_builtin_users: Failed to create Users\n"));
282                 return status;
283         }
284
285         /* add domain users */
286         if ((IS_DC || (lp_server_role() == ROLE_DOMAIN_MEMBER))
287                 && sid_compose(&dom_users, dom_sid, DOMAIN_RID_USERS))
288         {
289                 status = add_sid_to_builtin(&global_sid_Builtin_Users,
290                                             &dom_users);
291         }
292
293         return status;
294 }
295
296 /*******************************************************************
297 *******************************************************************/
298
299 NTSTATUS create_builtin_administrators(const struct dom_sid *dom_sid)
300 {
301         NTSTATUS status;
302         struct dom_sid dom_admins, root_sid;
303         fstring root_name;
304         enum lsa_SidType type;
305         TALLOC_CTX *ctx;
306         bool ret;
307
308         status = create_builtin(BUILTIN_RID_ADMINISTRATORS);
309         if ( !NT_STATUS_IS_OK(status) ) {
310                 DEBUG(5,("create_builtin_administrators: Failed to create Administrators\n"));
311                 return status;
312         }
313
314         /* add domain admins */
315         if ((IS_DC || (lp_server_role() == ROLE_DOMAIN_MEMBER))
316                 && sid_compose(&dom_admins, dom_sid, DOMAIN_RID_ADMINS))
317         {
318                 status = add_sid_to_builtin(&global_sid_Builtin_Administrators,
319                                             &dom_admins);
320                 if (!NT_STATUS_IS_OK(status)) {
321                         return status;
322                 }
323         }
324
325         /* add root */
326         if ( (ctx = talloc_init("create_builtin_administrators")) == NULL ) {
327                 return NT_STATUS_NO_MEMORY;
328         }
329         fstr_sprintf( root_name, "%s\\root", get_global_sam_name() );
330         ret = lookup_name(ctx, root_name, LOOKUP_NAME_DOMAIN, NULL, NULL,
331                           &root_sid, &type);
332         TALLOC_FREE( ctx );
333
334         if ( ret ) {
335                 status = add_sid_to_builtin(&global_sid_Builtin_Administrators,
336                                             &root_sid);
337         }
338
339         return status;
340 }
341
342 static NTSTATUS finalize_local_nt_token(struct security_token *result,
343                                         bool is_guest);
344
345 NTSTATUS create_local_nt_token_from_info3(TALLOC_CTX *mem_ctx,
346                                           bool is_guest,
347                                           struct netr_SamInfo3 *info3,
348                                           struct extra_auth_info *extra,
349                                           struct security_token **ntok)
350 {
351         struct security_token *usrtok = NULL;
352         NTSTATUS status;
353         int i;
354
355         DEBUG(10, ("Create local NT token for %s\n",
356                    info3->base.account_name.string));
357
358         usrtok = talloc_zero(mem_ctx, struct security_token);
359         if (!usrtok) {
360                 DEBUG(0, ("talloc failed\n"));
361                 return NT_STATUS_NO_MEMORY;
362         }
363
364         /* Add the user and primary group sid FIRST */
365         /* check if the user rid is the special "Domain Guests" rid.
366          * If so pick the first sid for the extra sids instead as it
367          * is a local fake account */
368         usrtok->sids = talloc_array(usrtok, struct dom_sid, 2);
369         if (!usrtok->sids) {
370                 TALLOC_FREE(usrtok);
371                 return NT_STATUS_NO_MEMORY;
372         }
373         usrtok->num_sids = 2;
374
375         /* USER SID */
376         if (info3->base.rid == (uint32_t)(-1)) {
377                 /* this is a signal the user was fake and generated,
378                  * the actual SID we want to use is stored in the extra
379                  * sids */
380                 if (is_null_sid(&extra->user_sid)) {
381                         /* we couldn't find the user sid, bail out */
382                         DEBUG(3, ("Invalid user SID\n"));
383                         TALLOC_FREE(usrtok);
384                         return NT_STATUS_UNSUCCESSFUL;
385                 }
386                 sid_copy(&usrtok->sids[0], &extra->user_sid);
387         } else {
388                 sid_copy(&usrtok->sids[0], info3->base.domain_sid);
389                 sid_append_rid(&usrtok->sids[0], info3->base.rid);
390         }
391
392         /* GROUP SID */
393         if (info3->base.primary_gid == (uint32_t)(-1)) {
394                 /* this is a signal the user was fake and generated,
395                  * the actual SID we want to use is stored in the extra
396                  * sids */
397                 if (is_null_sid(&extra->pgid_sid)) {
398                         /* we couldn't find the user sid, bail out */
399                         DEBUG(3, ("Invalid group SID\n"));
400                         TALLOC_FREE(usrtok);
401                         return NT_STATUS_UNSUCCESSFUL;
402                 }
403                 sid_copy(&usrtok->sids[1], &extra->pgid_sid);
404         } else {
405                 sid_copy(&usrtok->sids[1], info3->base.domain_sid);
406                 sid_append_rid(&usrtok->sids[1],
407                                 info3->base.primary_gid);
408         }
409
410         /* Now the SIDs we got from authentication. These are the ones from
411          * the info3 struct or from the pdb_enum_group_memberships, depending
412          * on who authenticated the user.
413          * Note that we start the for loop at "1" here, we already added the
414          * first group sid as primary above. */
415
416         for (i = 0; i < info3->base.groups.count; i++) {
417                 struct dom_sid tmp_sid;
418
419                 sid_copy(&tmp_sid, info3->base.domain_sid);
420                 sid_append_rid(&tmp_sid, info3->base.groups.rids[i].rid);
421
422                 status = add_sid_to_array_unique(usrtok, &tmp_sid,
423                                                  &usrtok->sids,
424                                                  &usrtok->num_sids);
425                 if (!NT_STATUS_IS_OK(status)) {
426                         DEBUG(3, ("Failed to add SID to nt token\n"));
427                         TALLOC_FREE(usrtok);
428                         return status;
429                 }
430         }
431
432         /* now also add extra sids if they are not the special user/group
433          * sids */
434         for (i = 0; i < info3->sidcount; i++) {
435                 status = add_sid_to_array_unique(usrtok,
436                                                  info3->sids[i].sid,
437                                                  &usrtok->sids,
438                                                  &usrtok->num_sids);
439                 if (!NT_STATUS_IS_OK(status)) {
440                         DEBUG(3, ("Failed to add SID to nt token\n"));
441                         TALLOC_FREE(usrtok);
442                         return status;
443                 }
444         }
445
446         status = finalize_local_nt_token(usrtok, is_guest);
447         if (!NT_STATUS_IS_OK(status)) {
448                 DEBUG(3, ("Failed to finalize nt token\n"));
449                 TALLOC_FREE(usrtok);
450                 return status;
451         }
452
453         *ntok = usrtok;
454         return NT_STATUS_OK;
455 }
456
457 /*******************************************************************
458  Create a NT token for the user, expanding local aliases
459 *******************************************************************/
460
461 struct security_token *create_local_nt_token(TALLOC_CTX *mem_ctx,
462                                             const struct dom_sid *user_sid,
463                                             bool is_guest,
464                                             int num_groupsids,
465                                             const struct dom_sid *groupsids)
466 {
467         struct security_token *result = NULL;
468         int i;
469         NTSTATUS status;
470
471         DEBUG(10, ("Create local NT token for %s\n",
472                    sid_string_dbg(user_sid)));
473
474         if (!(result = TALLOC_ZERO_P(mem_ctx, struct security_token))) {
475                 DEBUG(0, ("talloc failed\n"));
476                 return NULL;
477         }
478
479         /* Add the user and primary group sid */
480
481         status = add_sid_to_array(result, user_sid,
482                                   &result->sids, &result->num_sids);
483         if (!NT_STATUS_IS_OK(status)) {
484                 TALLOC_FREE(result);
485                 return NULL;
486         }
487
488         /* For guest, num_groupsids may be zero. */
489         if (num_groupsids) {
490                 status = add_sid_to_array(result, &groupsids[0],
491                                           &result->sids,
492                                           &result->num_sids);
493                 if (!NT_STATUS_IS_OK(status)) {
494                         TALLOC_FREE(result);
495                         return NULL;
496                 }
497         }
498
499         /* Now the SIDs we got from authentication. These are the ones from
500          * the info3 struct or from the pdb_enum_group_memberships, depending
501          * on who authenticated the user.
502          * Note that we start the for loop at "1" here, we already added the
503          * first group sid as primary above. */
504
505         for (i=1; i<num_groupsids; i++) {
506                 status = add_sid_to_array_unique(result, &groupsids[i],
507                                                  &result->sids,
508                                                  &result->num_sids);
509                 if (!NT_STATUS_IS_OK(status)) {
510                         TALLOC_FREE(result);
511                         return NULL;
512                 }
513         }
514
515         status = finalize_local_nt_token(result, is_guest);
516         if (!NT_STATUS_IS_OK(status)) {
517                 TALLOC_FREE(result);
518                 return NULL;
519         }
520
521         return result;
522 }
523
524 static NTSTATUS finalize_local_nt_token(struct security_token *result,
525                                         bool is_guest)
526 {
527         struct dom_sid dom_sid;
528         gid_t gid;
529         NTSTATUS status;
530
531         /* Add in BUILTIN sids */
532
533         status = add_sid_to_array(result, &global_sid_World,
534                                   &result->sids, &result->num_sids);
535         if (!NT_STATUS_IS_OK(status)) {
536                 return status;
537         }
538         status = add_sid_to_array(result, &global_sid_Network,
539                                   &result->sids, &result->num_sids);
540         if (!NT_STATUS_IS_OK(status)) {
541                 return status;
542         }
543
544         if (is_guest) {
545                 status = add_sid_to_array(result, &global_sid_Builtin_Guests,
546                                           &result->sids,
547                                           &result->num_sids);
548                 if (!NT_STATUS_IS_OK(status)) {
549                         return status;
550                 }
551         } else {
552                 status = add_sid_to_array(result,
553                                           &global_sid_Authenticated_Users,
554                                           &result->sids,
555                                           &result->num_sids);
556                 if (!NT_STATUS_IS_OK(status)) {
557                         return status;
558                 }
559         }
560
561         /* Deal with the BUILTIN\Administrators group.  If the SID can
562            be resolved then assume that the add_aliasmem( S-1-5-32 )
563            handled it. */
564
565         if (!sid_to_gid(&global_sid_Builtin_Administrators, &gid)) {
566
567                 become_root();
568                 if (!secrets_fetch_domain_sid(lp_workgroup(), &dom_sid)) {
569                         status = NT_STATUS_OK;
570                         DEBUG(3, ("Failed to fetch domain sid for %s\n",
571                                   lp_workgroup()));
572                 } else {
573                         status = create_builtin_administrators(&dom_sid);
574                 }
575                 unbecome_root();
576
577                 if (NT_STATUS_EQUAL(status, NT_STATUS_PROTOCOL_UNREACHABLE)) {
578                         /* Add BUILTIN\Administrators directly to token. */
579                         status = add_builtin_administrators(result, &dom_sid);
580                         if ( !NT_STATUS_IS_OK(status) ) {
581                                 DEBUG(3, ("Failed to check for local "
582                                           "Administrators membership (%s)\n",
583                                           nt_errstr(status)));
584                         }
585                 } else if (!NT_STATUS_IS_OK(status)) {
586                         DEBUG(2, ("WARNING: Failed to create "
587                                   "BUILTIN\\Administrators group!  Can "
588                                   "Winbind allocate gids?\n"));
589                 }
590         }
591
592         /* Deal with the BUILTIN\Users group.  If the SID can
593            be resolved then assume that the add_aliasmem( S-1-5-32 )
594            handled it. */
595
596         if (!sid_to_gid(&global_sid_Builtin_Users, &gid)) {
597
598                 become_root();
599                 if (!secrets_fetch_domain_sid(lp_workgroup(), &dom_sid)) {
600                         status = NT_STATUS_OK;
601                         DEBUG(3, ("Failed to fetch domain sid for %s\n",
602                                   lp_workgroup()));
603                 } else {
604                         status = create_builtin_users(&dom_sid);
605                 }
606                 unbecome_root();
607
608                 if (!NT_STATUS_EQUAL(status, NT_STATUS_PROTOCOL_UNREACHABLE) &&
609                     !NT_STATUS_IS_OK(status))
610                 {
611                         DEBUG(2, ("WARNING: Failed to create BUILTIN\\Users group! "
612                                   "Can Winbind allocate gids?\n"));
613                 }
614         }
615
616         /* Deal with local groups */
617
618         if (lp_winbind_nested_groups()) {
619
620                 become_root();
621
622                 /* Now add the aliases. First the one from our local SAM */
623
624                 status = add_aliases(get_global_sam_sid(), result);
625
626                 if (!NT_STATUS_IS_OK(status)) {
627                         unbecome_root();
628                         return status;
629                 }
630
631                 /* Finally the builtin ones */
632
633                 status = add_aliases(&global_sid_Builtin, result);
634
635                 if (!NT_STATUS_IS_OK(status)) {
636                         unbecome_root();
637                         return status;
638                 }
639
640                 unbecome_root();
641         }
642
643         /* Add privileges based on current user sids */
644
645         get_privileges_for_sids(&result->privilege_mask, result->sids,
646                                 result->num_sids);
647
648         return NT_STATUS_OK;
649 }
650
651 /****************************************************************************
652  prints a struct security_token to debug output.
653 ****************************************************************************/
654
655 void debug_nt_user_token(int dbg_class, int dbg_lev, struct security_token *token)
656 {
657         size_t     i;
658
659         if (!token) {
660                 DEBUGC(dbg_class, dbg_lev, ("NT user token: (NULL)\n"));
661                 return;
662         }
663
664         DEBUGC(dbg_class, dbg_lev,
665                ("NT user token of user %s\n",
666                 sid_string_dbg(&token->sids[0]) ));
667         DEBUGADDC(dbg_class, dbg_lev,
668                   ("contains %lu SIDs\n", (unsigned long)token->num_sids));
669         for (i = 0; i < token->num_sids; i++)
670                 DEBUGADDC(dbg_class, dbg_lev,
671                           ("SID[%3lu]: %s\n", (unsigned long)i,
672                            sid_string_dbg(&token->sids[i])));
673
674         DEBUGADDC(dbg_class, dbg_lev,("Privilege mask: 0x%llx\n", (unsigned long long)token->privilege_mask));
675 }
676
677 /****************************************************************************
678  prints a UNIX 'token' to debug output.
679 ****************************************************************************/
680
681 void debug_unix_user_token(int dbg_class, int dbg_lev, uid_t uid, gid_t gid,
682                            int n_groups, gid_t *groups)
683 {
684         int     i;
685         DEBUGC(dbg_class, dbg_lev,
686                ("UNIX token of user %ld\n", (long int)uid));
687
688         DEBUGADDC(dbg_class, dbg_lev,
689                   ("Primary group is %ld and contains %i supplementary "
690                    "groups\n", (long int)gid, n_groups));
691         for (i = 0; i < n_groups; i++)
692                 DEBUGADDC(dbg_class, dbg_lev, ("Group[%3i]: %ld\n", i,
693                         (long int)groups[i]));
694 }
695
696 /*
697  * Create an artificial NT token given just a username. (Initially intended
698  * for force user)
699  *
700  * We go through lookup_name() to avoid problems we had with 'winbind use
701  * default domain'.
702  *
703  * We have 3 cases:
704  *
705  * unmapped unix users: Go directly to nss to find the user's group.
706  *
707  * A passdb user: The list of groups is provided by pdb_enum_group_memberships.
708  *
709  * If the user is provided by winbind, the primary gid is set to "domain
710  * users" of the user's domain. For an explanation why this is necessary, see
711  * the thread starting at
712  * http://lists.samba.org/archive/samba-technical/2006-January/044803.html.
713  */
714
715 NTSTATUS create_token_from_username(TALLOC_CTX *mem_ctx, const char *username,
716                                     bool is_guest,
717                                     uid_t *uid, gid_t *gid,
718                                     char **found_username,
719                                     struct security_token **token)
720 {
721         NTSTATUS result = NT_STATUS_NO_SUCH_USER;
722         TALLOC_CTX *tmp_ctx = talloc_stackframe();
723         struct dom_sid user_sid;
724         enum lsa_SidType type;
725         gid_t *gids;
726         struct dom_sid *group_sids;
727         struct dom_sid unix_group_sid;
728         uint32_t num_group_sids;
729         size_t num_gids;
730         size_t i;
731
732         if (!lookup_name_smbconf(tmp_ctx, username, LOOKUP_NAME_ALL,
733                          NULL, NULL, &user_sid, &type)) {
734                 DEBUG(1, ("lookup_name_smbconf for %s failed\n", username));
735                 goto done;
736         }
737
738         if (type != SID_NAME_USER) {
739                 DEBUG(1, ("%s is a %s, not a user\n", username,
740                           sid_type_lookup(type)));
741                 goto done;
742         }
743
744         if (sid_check_is_in_our_domain(&user_sid)) {
745                 bool ret;
746                 size_t pdb_num_group_sids;
747                 /* This is a passdb user, so ask passdb */
748
749                 struct samu *sam_acct = NULL;
750
751                 if ( !(sam_acct = samu_new( tmp_ctx )) ) {
752                         result = NT_STATUS_NO_MEMORY;
753                         goto done;
754                 }
755
756                 become_root();
757                 ret = pdb_getsampwsid(sam_acct, &user_sid);
758                 unbecome_root();
759
760                 if (!ret) {
761                         DEBUG(1, ("pdb_getsampwsid(%s) for user %s failed\n",
762                                   sid_string_dbg(&user_sid), username));
763                         DEBUGADD(1, ("Fall back to unix user %s\n", username));
764                         goto unix_user;
765                 }
766
767                 result = pdb_enum_group_memberships(tmp_ctx, sam_acct,
768                                                     &group_sids, &gids,
769                                                     &pdb_num_group_sids);
770                 if (!NT_STATUS_IS_OK(result)) {
771                         DEBUG(1, ("enum_group_memberships failed for %s (%s): "
772                                   "%s\n", username, sid_string_dbg(&user_sid),
773                                   nt_errstr(result)));
774                         DEBUGADD(1, ("Fall back to unix user %s\n", username));
775                         goto unix_user;
776                 }
777                 num_group_sids = pdb_num_group_sids;
778
779                 /* see the smb_panic() in pdb_default_enum_group_memberships */
780                 SMB_ASSERT(num_group_sids > 0);
781
782                 *gid = gids[0];
783
784                 /* Ensure we're returning the found_username on the right context. */
785                 *found_username = talloc_strdup(mem_ctx,
786                                                 pdb_get_username(sam_acct));
787
788                 /*
789                  * If the SID from lookup_name() was the guest sid, passdb knows
790                  * about the mapping of guest sid to lp_guestaccount()
791                  * username and will return the unix_pw info for a guest
792                  * user. Use it if it's there, else lookup the *uid details
793                  * using getpwnam_alloc(). See bug #6291 for details. JRA.
794                  */
795
796                 /* We must always assign the *uid. */
797                 if (sam_acct->unix_pw == NULL) {
798                         struct passwd *pwd = getpwnam_alloc(sam_acct, *found_username );
799                         if (!pwd) {
800                                 DEBUG(10, ("getpwnam_alloc failed for %s\n",
801                                         *found_username));
802                                 result = NT_STATUS_NO_SUCH_USER;
803                                 goto done;
804                         }
805                         result = samu_set_unix(sam_acct, pwd );
806                         if (!NT_STATUS_IS_OK(result)) {
807                                 DEBUG(10, ("samu_set_unix failed for %s\n",
808                                         *found_username));
809                                 result = NT_STATUS_NO_SUCH_USER;
810                                 goto done;
811                         }
812                 }
813                 *uid = sam_acct->unix_pw->pw_uid;
814
815         } else  if (sid_check_is_in_unix_users(&user_sid)) {
816                 size_t getgroups_num_group_sids;
817                 /* This is a unix user not in passdb. We need to ask nss
818                  * directly, without consulting passdb */
819
820                 struct passwd *pass;
821
822                 /*
823                  * This goto target is used as a fallback for the passdb
824                  * case. The concrete bug report is when passdb gave us an
825                  * unmapped gid.
826                  */
827
828         unix_user:
829
830                 if (!sid_to_uid(&user_sid, uid)) {
831                         DEBUG(1, ("unix_user case, sid_to_uid for %s (%s) failed\n",
832                                   username, sid_string_dbg(&user_sid)));
833                         result = NT_STATUS_NO_SUCH_USER;
834                         goto done;
835                 }
836
837                 uid_to_unix_users_sid(*uid, &user_sid);
838
839                 pass = getpwuid_alloc(tmp_ctx, *uid);
840                 if (pass == NULL) {
841                         DEBUG(1, ("getpwuid(%u) for user %s failed\n",
842                                   (unsigned int)*uid, username));
843                         goto done;
844                 }
845
846                 if (!getgroups_unix_user(tmp_ctx, username, pass->pw_gid,
847                                          &gids, &getgroups_num_group_sids)) {
848                         DEBUG(1, ("getgroups_unix_user for user %s failed\n",
849                                   username));
850                         goto done;
851                 }
852                 num_group_sids = getgroups_num_group_sids;
853
854                 if (num_group_sids) {
855                         group_sids = TALLOC_ARRAY(tmp_ctx, struct dom_sid, num_group_sids);
856                         if (group_sids == NULL) {
857                                 DEBUG(1, ("TALLOC_ARRAY failed\n"));
858                                 result = NT_STATUS_NO_MEMORY;
859                                 goto done;
860                         }
861                 } else {
862                         group_sids = NULL;
863                 }
864
865                 for (i=0; i<num_group_sids; i++) {
866                         gid_to_sid(&group_sids[i], gids[i]);
867                 }
868
869                 /* In getgroups_unix_user we always set the primary gid */
870                 SMB_ASSERT(num_group_sids > 0);
871
872                 *gid = gids[0];
873
874                 /* Ensure we're returning the found_username on the right context. */
875                 *found_username = talloc_strdup(mem_ctx, pass->pw_name);
876         } else {
877
878                 /* This user is from winbind, force the primary gid to the
879                  * user's "domain users" group. Under certain circumstances
880                  * (user comes from NT4), this might be a loss of
881                  * information. But we can not rely on winbind getting the
882                  * correct info. AD might prohibit winbind looking up that
883                  * information. */
884
885                 uint32 dummy;
886
887                 /* We must always assign the *uid. */
888                 if (!sid_to_uid(&user_sid, uid)) {
889                         DEBUG(1, ("winbindd case, sid_to_uid for %s (%s) failed\n",
890                                   username, sid_string_dbg(&user_sid)));
891                         result = NT_STATUS_NO_SUCH_USER;
892                         goto done;
893                 }
894
895                 num_group_sids = 1;
896                 group_sids = TALLOC_ARRAY(tmp_ctx, struct dom_sid, num_group_sids);
897                 if (group_sids == NULL) {
898                         DEBUG(1, ("TALLOC_ARRAY failed\n"));
899                         result = NT_STATUS_NO_MEMORY;
900                         goto done;
901                 }
902
903                 sid_copy(&group_sids[0], &user_sid);
904                 sid_split_rid(&group_sids[0], &dummy);
905                 sid_append_rid(&group_sids[0], DOMAIN_RID_USERS);
906
907                 if (!sid_to_gid(&group_sids[0], gid)) {
908                         DEBUG(1, ("sid_to_gid(%s) failed\n",
909                                   sid_string_dbg(&group_sids[0])));
910                         goto done;
911                 }
912
913                 gids = gid;
914
915                 /* Ensure we're returning the found_username on the right context. */
916                 *found_username = talloc_strdup(mem_ctx, username);
917         }
918
919         /* Add the "Unix Group" SID for each gid to catch mapped groups
920            and their Unix equivalent.  This is to solve the backwards
921            compatibility problem of 'valid users = +ntadmin' where
922            ntadmin has been paired with "Domain Admins" in the group
923            mapping table.  Otherwise smb.conf would need to be changed
924            to 'valid user = "Domain Admins"'.  --jerry */
925
926         num_gids = num_group_sids;
927         for ( i=0; i<num_gids; i++ ) {
928                 gid_t high, low;
929
930                 /* don't pickup anything managed by Winbind */
931
932                 if ( lp_idmap_gid(&low, &high) && (gids[i] >= low) && (gids[i] <= high) )
933                         continue;
934
935                 gid_to_unix_groups_sid(gids[i], &unix_group_sid);
936
937                 result = add_sid_to_array_unique(tmp_ctx, &unix_group_sid,
938                                                  &group_sids, &num_group_sids);
939                 if (!NT_STATUS_IS_OK(result)) {
940                         goto done;
941                 }
942         }
943
944         /* Ensure we're creating the nt_token on the right context. */
945         *token = create_local_nt_token(mem_ctx, &user_sid,
946                                        is_guest, num_group_sids, group_sids);
947
948         if ((*token == NULL) || (*found_username == NULL)) {
949                 result = NT_STATUS_NO_MEMORY;
950                 goto done;
951         }
952
953         result = NT_STATUS_OK;
954  done:
955         TALLOC_FREE(tmp_ctx);
956         return result;
957 }
958
959 /***************************************************************************
960  Build upon create_token_from_username:
961
962  Expensive helper function to figure out whether a user given its name is
963  member of a particular group.
964 ***************************************************************************/
965
966 bool user_in_group_sid(const char *username, const struct dom_sid *group_sid)
967 {
968         NTSTATUS status;
969         uid_t uid;
970         gid_t gid;
971         char *found_username;
972         struct security_token *token;
973         bool result;
974         TALLOC_CTX *mem_ctx = talloc_stackframe();
975
976         status = create_token_from_username(mem_ctx, username, False,
977                                             &uid, &gid, &found_username,
978                                             &token);
979
980         if (!NT_STATUS_IS_OK(status)) {
981                 DEBUG(10, ("could not create token for %s\n", username));
982                 TALLOC_FREE(mem_ctx);
983                 return False;
984         }
985
986         result = nt_token_check_sid(group_sid, token);
987
988         TALLOC_FREE(mem_ctx);
989         return result;
990 }
991
992 bool user_in_group(const char *username, const char *groupname)
993 {
994         TALLOC_CTX *mem_ctx = talloc_stackframe();
995         struct dom_sid group_sid;
996         bool ret;
997
998         ret = lookup_name(mem_ctx, groupname, LOOKUP_NAME_ALL,
999                           NULL, NULL, &group_sid, NULL);
1000         TALLOC_FREE(mem_ctx);
1001
1002         if (!ret) {
1003                 DEBUG(10, ("lookup_name for (%s) failed.\n", groupname));
1004                 return False;
1005         }
1006
1007         return user_in_group_sid(username, &group_sid);
1008 }
1009
1010 /* END */