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