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