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