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