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