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