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