Add name_lookup function in object_ops.
[wine] / server / token.c
1 /*
2  * Tokens
3  *
4  * Copyright (C) 1998 Alexandre Julliard
5  * Copyright (C) 2003 Mike McCormack
6  * Copyright (C) 2005 Robert Shearman
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include "config.h"
24
25 #include <assert.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28
29 #include "windef.h"
30
31 #include "handle.h"
32 #include "thread.h"
33 #include "process.h"
34 #include "request.h"
35 #include "security.h"
36
37 #include "wine/unicode.h"
38
39 #define MAX_SUBAUTH_COUNT 1
40
41 const LUID SeIncreaseQuotaPrivilege        = {  5, 0 };
42 const LUID SeSecurityPrivilege             = {  8, 0 };
43 const LUID SeTakeOwnershipPrivilege        = {  9, 0 };
44 const LUID SeLoadDriverPrivilege           = { 10, 0 };
45 const LUID SeSystemProfilePrivilege        = { 11, 0 };
46 const LUID SeSystemtimePrivilege           = { 12, 0 };
47 const LUID SeProfileSingleProcessPrivilege = { 13, 0 };
48 const LUID SeIncreaseBasePriorityPrivilege = { 14, 0 };
49 const LUID SeCreatePagefilePrivilege       = { 15, 0 };
50 const LUID SeBackupPrivilege               = { 17, 0 };
51 const LUID SeRestorePrivilege              = { 18, 0 };
52 const LUID SeShutdownPrivilege             = { 19, 0 };
53 const LUID SeDebugPrivilege                = { 20, 0 };
54 const LUID SeSystemEnvironmentPrivilege    = { 22, 0 };
55 const LUID SeChangeNotifyPrivilege         = { 23, 0 };
56 const LUID SeRemoteShutdownPrivilege       = { 24, 0 };
57 const LUID SeUndockPrivilege               = { 25, 0 };
58 const LUID SeManageVolumePrivilege         = { 28, 0 };
59 const LUID SeImpersonatePrivilege          = { 29, 0 };
60 const LUID SeCreateGlobalPrivilege         = { 30, 0 };
61
62 static const SID world_sid = { SID_REVISION, 1, { SECURITY_WORLD_SID_AUTHORITY }, { SECURITY_WORLD_RID } };
63 static const SID local_sid = { SID_REVISION, 1, { SECURITY_LOCAL_SID_AUTHORITY }, { SECURITY_LOCAL_RID } };
64 static const SID interactive_sid = { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_INTERACTIVE_RID } };
65 static const SID authenticated_user_sid = { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_AUTHENTICATED_USER_RID } };
66 static const SID local_system_sid = { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_LOCAL_SYSTEM_RID } };
67 static const PSID security_world_sid = (PSID)&world_sid;
68 static const PSID security_local_sid = (PSID)&local_sid;
69 const PSID security_interactive_sid = (PSID)&interactive_sid;
70 static const PSID security_authenticated_user_sid = (PSID)&authenticated_user_sid;
71 static const PSID security_local_system_sid = (PSID)&local_system_sid;
72
73 struct token
74 {
75     struct object  obj;             /* object header */
76     struct list    privileges;      /* privileges available to the token */
77     struct list    groups;          /* groups that the user of this token belongs to (sid_and_attributes) */
78     SID           *user;            /* SID of user this token represents */
79     unsigned       primary;         /* is this a primary or impersonation token? */
80     ACL           *default_dacl;    /* the default DACL to assign to objects created by this user */
81 };
82
83 struct privilege
84 {
85     struct list entry;
86     LUID        luid;
87     unsigned    enabled  : 1; /* is the privilege currently enabled? */
88     unsigned    def      : 1; /* is the privilege enabled by default? */
89 };
90
91 struct sid_and_attributes
92 {
93     struct list entry;
94     unsigned    enabled  : 1; /* is the sid currently enabled? */
95     unsigned    def      : 1; /* is the sid enabled by default? */
96     unsigned    logon    : 1; /* is this a logon sid? */
97     unsigned    mandatory: 1; /* is this sid always enabled? */
98     unsigned    owner    : 1; /* can this sid be an owner of an object? */
99     unsigned    resource : 1; /* is this a domain-local group? */
100     unsigned    deny_only: 1; /* is this a sid that should be use for denying only? */
101     SID         sid;
102 };
103
104 static void token_dump( struct object *obj, int verbose );
105 static void token_destroy( struct object *obj );
106
107 static const struct object_ops token_ops =
108 {
109     sizeof(struct token),      /* size */
110     token_dump,                /* dump */
111     no_add_queue,              /* add_queue */
112     NULL,                      /* remove_queue */
113     NULL,                      /* signaled */
114     NULL,                      /* satisfied */
115     no_signal,                 /* signal */
116     no_get_fd,                 /* get_fd */
117     no_lookup_name,            /* lookup_name */
118     no_close_handle,           /* close_handle */
119     token_destroy              /* destroy */
120 };
121
122
123 static void token_dump( struct object *obj, int verbose )
124 {
125     fprintf( stderr, "Security token\n" );
126     /* FIXME: dump token members */
127 }
128
129 static SID *security_sid_alloc( const SID_IDENTIFIER_AUTHORITY *idauthority, int subauthcount, const unsigned int subauth[] )
130 {
131     int i;
132     SID *sid = mem_alloc( FIELD_OFFSET(SID, SubAuthority[subauthcount]) );
133     if (!sid) return NULL;
134     sid->Revision = SID_REVISION;
135     sid->SubAuthorityCount = subauthcount;
136     sid->IdentifierAuthority = *idauthority;
137     for (i = 0; i < subauthcount; i++)
138         sid->SubAuthority[i] = subauth[i];
139     return sid;
140 }
141
142 static inline int security_equal_sid( const SID *sid1, const SID *sid2 )
143 {
144     return ((sid1->SubAuthorityCount == sid2->SubAuthorityCount) &&
145         !memcmp( sid1, sid2, FIELD_OFFSET(SID, SubAuthority[sid1->SubAuthorityCount]) ));
146 }
147
148 void security_set_thread_token( struct thread *thread, obj_handle_t handle )
149 {
150     if (!handle)
151     {
152         if (thread->token)
153             release_object( thread->token );
154         thread->token = NULL;
155     }
156     else
157     {
158         struct token *token = (struct token *)get_handle_obj( current->process,
159                                                               handle,
160                                                               TOKEN_IMPERSONATE,
161                                                               &token_ops );
162         if (token)
163         {
164             if (thread->token)
165                 release_object( thread->token );
166             thread->token = token;
167         }
168     }
169 }
170
171 static const ACE_HEADER *ace_next( const ACE_HEADER *ace )
172 {
173     return (const ACE_HEADER *)((const char *)ace + ace->AceSize);
174 }
175
176 static int acl_is_valid( const ACL *acl, size_t size )
177 {
178     ULONG i;
179     const ACE_HEADER *ace;
180
181     if (size < sizeof(ACL))
182         return FALSE;
183
184     size = min(size, MAX_ACL_LEN);
185
186     size -= sizeof(ACL);
187
188     ace = (const ACE_HEADER *)(acl + 1);
189     for (i = 0; i < acl->AceCount; i++)
190     {
191         const SID *sid;
192         size_t sid_size;
193
194         if (size < sizeof(ACE_HEADER))
195             return FALSE;
196         if (size < ace->AceSize)
197             return FALSE;
198         size -= ace->AceSize;
199         switch (ace->AceType)
200         {
201         case ACCESS_DENIED_ACE_TYPE:
202             sid = (const SID *)&((const ACCESS_DENIED_ACE *)ace)->SidStart;
203             sid_size = ace->AceSize - FIELD_OFFSET(ACCESS_DENIED_ACE, SidStart);
204             break;
205         case ACCESS_ALLOWED_ACE_TYPE:
206             sid = (const SID *)&((const ACCESS_ALLOWED_ACE *)ace)->SidStart;
207             sid_size = ace->AceSize - FIELD_OFFSET(ACCESS_ALLOWED_ACE, SidStart);
208             break;
209         case SYSTEM_AUDIT_ACE_TYPE:
210             sid = (const SID *)&((const SYSTEM_AUDIT_ACE *)ace)->SidStart;
211             sid_size = ace->AceSize - FIELD_OFFSET(SYSTEM_AUDIT_ACE, SidStart);
212             break;
213         case SYSTEM_ALARM_ACE_TYPE:
214             sid = (const SID *)&((const SYSTEM_ALARM_ACE *)ace)->SidStart;
215             sid_size = ace->AceSize - FIELD_OFFSET(SYSTEM_ALARM_ACE, SidStart);
216             break;
217         default:
218             return FALSE;
219         }
220         if (sid_size < FIELD_OFFSET(SID, SubAuthority[0]) ||
221             sid_size < FIELD_OFFSET(SID, SubAuthority[sid->SubAuthorityCount]))
222             return FALSE;
223         ace = ace_next( ace );
224     }
225     return TRUE;
226 }
227
228 /* gets the discretionary access control list from a security descriptor */
229 static inline const ACL *sd_get_dacl( const struct security_descriptor *sd, int *present )
230 {
231     *present = (sd->control & SE_DACL_PRESENT ? TRUE : FALSE);
232
233     if (sd->dacl_len)
234         return (const ACL *)((const char *)(sd + 1) +
235             sd->owner_len + sd->group_len + sd->sacl_len);
236     else
237         return NULL;
238 }
239
240 /* gets the system access control list from a security descriptor */
241 static inline const ACL *sd_get_sacl( const struct security_descriptor *sd, int *present )
242 {
243     *present = (sd->control & SE_SACL_PRESENT ? TRUE : FALSE);
244
245     if (sd->sacl_len)
246         return (const ACL *)((const char *)(sd + 1) +
247             sd->owner_len + sd->group_len);
248     else
249         return NULL;
250 }
251
252 /* gets the owner from a security descriptor */
253 static inline const SID *sd_get_owner( const struct security_descriptor *sd )
254 {
255     if (sd->owner_len)
256         return (const SID *)(sd + 1);
257     else
258         return NULL;
259 }
260
261 /* gets the primary group from a security descriptor */
262 static inline const SID *sd_get_group( const struct security_descriptor *sd )
263 {
264     if (sd->group_len)
265         return (const SID *)((const char *)(sd + 1) + sd->owner_len);
266     else
267         return NULL;
268 }
269
270 /* checks whether all members of a security descriptor fit inside the size
271  * of memory specified */
272 static int sd_is_valid( const struct security_descriptor *sd, size_t size )
273 {
274     size_t offset = sizeof(struct security_descriptor);
275     const SID *group;
276     const SID *owner;
277     const ACL *sacl;
278     const ACL *dacl;
279     int dummy;
280
281     if (size < offset)
282         return FALSE;
283
284     if ((sd->owner_len >= FIELD_OFFSET(SID, SubAuthority[255])) ||
285         (offset + sd->owner_len > size))
286         return FALSE;
287     owner = sd_get_owner( sd );
288     if (owner)
289     {
290         size_t needed_size = FIELD_OFFSET(SID, SubAuthority[owner->SubAuthorityCount]);
291         if ((sd->owner_len < sizeof(SID)) || (needed_size > sd->owner_len))
292             return FALSE;
293     }
294     offset += sd->owner_len;
295
296     if ((sd->group_len >= FIELD_OFFSET(SID, SubAuthority[255])) ||
297         (offset + sd->group_len > size))
298         return FALSE;
299     group = sd_get_group( sd );
300     if (group)
301     {
302         size_t needed_size = FIELD_OFFSET(SID, SubAuthority[group->SubAuthorityCount]);
303         if ((sd->owner_len < sizeof(SID)) || (needed_size > sd->owner_len))
304             return FALSE;
305     }
306     offset += sd->group_len;
307
308     if ((sd->sacl_len >= MAX_ACL_LEN) || (offset + sd->sacl_len > size))
309         return FALSE;
310     sacl = sd_get_sacl( sd, &dummy );
311     if (sacl && !acl_is_valid( sacl, sd->sacl_len ))
312         return FALSE;
313     offset += sd->sacl_len;
314
315     if ((sd->dacl_len >= MAX_ACL_LEN) || (offset + sd->dacl_len > size))
316         return FALSE;
317     dacl = sd_get_dacl( sd, &dummy );
318     if (dacl && !acl_is_valid( dacl, sd->dacl_len ))
319         return FALSE;
320     offset += sd->dacl_len;
321
322     return TRUE;
323 }
324
325 /* maps from generic rights to specific rights as given by a mapping */
326 static inline void map_generic_mask(unsigned int *mask, const GENERIC_MAPPING *mapping)
327 {
328     if (*mask & GENERIC_READ) *mask |= mapping->GenericRead;
329     if (*mask & GENERIC_WRITE) *mask |= mapping->GenericWrite;
330     if (*mask & GENERIC_EXECUTE) *mask |= mapping->GenericExecute;
331     if (*mask & GENERIC_ALL) *mask |= mapping->GenericAll;
332     *mask &= 0x0FFFFFFF;
333 }
334
335 static inline int is_equal_luid( const LUID *luid1, const LUID *luid2 )
336 {
337     return (luid1->LowPart == luid2->LowPart && luid1->HighPart == luid2->HighPart);
338 }
339
340 static inline void luid_and_attr_from_privilege( LUID_AND_ATTRIBUTES *out, const struct privilege *in)
341 {
342     out->Luid = in->luid;
343     out->Attributes =
344         (in->enabled ? SE_PRIVILEGE_ENABLED : 0) |
345         (in->def ? SE_PRIVILEGE_ENABLED_BY_DEFAULT : 0);
346 }
347
348 static struct privilege *privilege_add( struct token *token, const LUID *luid, int enabled )
349 {
350     struct privilege *privilege = mem_alloc( sizeof(*privilege) );
351     if (privilege)
352     {
353         privilege->luid = *luid;
354         privilege->def = privilege->enabled = (enabled != 0);
355         list_add_tail( &token->privileges, &privilege->entry );
356     }
357     return privilege;
358 }
359
360 static inline void privilege_remove( struct privilege *privilege )
361 {
362     list_remove( &privilege->entry );
363     free( privilege );
364 }
365
366 static void token_destroy( struct object *obj )
367 {
368     struct token* token;
369     struct list *cursor, *cursor_next;
370
371     assert( obj->ops == &token_ops );
372     token = (struct token *)obj;
373
374     free( token->user );
375
376     LIST_FOR_EACH_SAFE( cursor, cursor_next, &token->privileges )
377     {
378         struct privilege *privilege = LIST_ENTRY( cursor, struct privilege, entry );
379         privilege_remove( privilege );
380     }
381
382     LIST_FOR_EACH_SAFE( cursor, cursor_next, &token->groups )
383     {
384         struct sid_and_attributes *group = LIST_ENTRY( cursor, struct sid_and_attributes, entry );
385         list_remove( &group->entry );
386         free( group );
387     }
388
389     free( token->default_dacl );
390 }
391
392 /* creates a new token.
393  *  groups may be NULL if group_count is 0.
394  *  privs may be NULL if priv_count is 0.
395  *  default_dacl may be NULL, indicating that all objects created by the user
396  *   are unsecured.
397  */
398 static struct token *create_token( unsigned primary, const SID *user,
399                                    const SID_AND_ATTRIBUTES *groups, unsigned int group_count,
400                                    const LUID_AND_ATTRIBUTES *privs, unsigned int priv_count,
401                                    const ACL *default_dacl )
402 {
403     struct token *token = alloc_object( &token_ops );
404     if (token)
405     {
406         int i;
407
408         list_init( &token->privileges );
409         list_init( &token->groups );
410         token->primary = primary;
411
412         /* copy user */
413         token->user = memdup( user, FIELD_OFFSET(SID, SubAuthority[user->SubAuthorityCount]) );
414         if (!token->user)
415         {
416             release_object( token );
417             return NULL;
418         }
419
420         /* copy groups */
421         for (i = 0; i < group_count; i++)
422         {
423             size_t size = FIELD_OFFSET( struct sid_and_attributes, sid.SubAuthority[((const SID *)groups[i].Sid)->SubAuthorityCount] );
424             struct sid_and_attributes *group = mem_alloc( size );
425             memcpy( &group->sid, groups[i].Sid, FIELD_OFFSET( SID, SubAuthority[((const SID *)groups[i].Sid)->SubAuthorityCount] ) );
426             group->enabled = TRUE;
427             group->def = TRUE;
428             group->logon = FALSE;
429             group->mandatory = (groups[i].Attributes & SE_GROUP_MANDATORY) ? TRUE : FALSE;
430             group->owner = FALSE;
431             group->resource = FALSE;
432             group->deny_only = FALSE;
433             list_add_tail( &token->groups, &group->entry );
434         }
435
436         /* copy privileges */
437         for (i = 0; i < priv_count; i++)
438         {
439             /* note: we don't check uniqueness: the caller must make sure
440              * privs doesn't contain any duplicate luids */
441             if (!privilege_add( token, &privs[i].Luid,
442                                 privs[i].Attributes & SE_PRIVILEGE_ENABLED ))
443             {
444                 release_object( token );
445                 return NULL;
446             }
447         }
448
449         if (default_dacl)
450         {
451             token->default_dacl = memdup( default_dacl, default_dacl->AclSize );
452             if (!token->default_dacl)
453             {
454                 release_object( token );
455                 return NULL;
456             }
457         }
458         else
459             token->default_dacl = NULL;
460     }
461     return token;
462 }
463
464 static ACL *create_default_dacl( const SID *user )
465 {
466     ACCESS_ALLOWED_ACE *aaa;
467     ACL *default_dacl;
468     SID *sid;
469     size_t default_dacl_size = sizeof(ACL) +
470                                2*(sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) +
471                                sizeof(local_system_sid) +
472                                FIELD_OFFSET(SID, SubAuthority[user->SubAuthorityCount]);
473
474     default_dacl = mem_alloc( default_dacl_size );
475     if (!default_dacl) return NULL;
476
477     default_dacl->AclRevision = MAX_ACL_REVISION;
478     default_dacl->Sbz1 = 0;
479     default_dacl->AclSize = default_dacl_size;
480     default_dacl->AceCount = 2;
481     default_dacl->Sbz2 = 0;
482
483     /* GENERIC_ALL for Local System */
484     aaa = (ACCESS_ALLOWED_ACE *)(default_dacl + 1);
485     aaa->Header.AceType = ACCESS_ALLOWED_ACE_TYPE;
486     aaa->Header.AceFlags = 0;
487     aaa->Header.AceSize = (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) +
488                           sizeof(local_system_sid);
489     aaa->Mask = GENERIC_ALL;
490     sid = (SID *)&aaa->SidStart;
491     memcpy( sid, &local_system_sid, sizeof(local_system_sid) );
492
493     /* GENERIC_ALL for specified user */
494     aaa = (ACCESS_ALLOWED_ACE *)((const char *)aaa + aaa->Header.AceSize);
495     aaa->Header.AceType = ACCESS_ALLOWED_ACE_TYPE;
496     aaa->Header.AceFlags = 0;
497     aaa->Header.AceSize = (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) +
498                           FIELD_OFFSET( SID, SubAuthority[user->SubAuthorityCount] );
499     aaa->Mask = GENERIC_ALL;
500     sid = (SID *)&aaa->SidStart;
501     memcpy( sid, user, FIELD_OFFSET(SID, SubAuthority[user->SubAuthorityCount]) );
502
503     return default_dacl;
504 }
505
506 struct sid_data
507 {
508     SID_IDENTIFIER_AUTHORITY idauth;
509     int count;
510     unsigned int subauth[MAX_SUBAUTH_COUNT];
511 };
512
513 struct token *token_create_admin( void )
514 {
515     struct token *token = NULL;
516     static const SID_IDENTIFIER_AUTHORITY nt_authority = { SECURITY_NT_AUTHORITY };
517     static const unsigned int alias_admins_subauth[] = { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS };
518     static const unsigned int alias_users_subauth[] = { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_USERS };
519     PSID alias_admins_sid;
520     PSID alias_users_sid;
521     ACL *default_dacl = create_default_dacl( &local_system_sid );
522
523     alias_admins_sid = security_sid_alloc( &nt_authority, sizeof(alias_admins_subauth)/sizeof(alias_admins_subauth[0]),
524                                            alias_admins_subauth );
525     alias_users_sid = security_sid_alloc( &nt_authority, sizeof(alias_users_subauth)/sizeof(alias_users_subauth[0]),
526                                           alias_users_subauth );
527
528     if (alias_admins_sid && alias_users_sid && default_dacl)
529     {
530         const LUID_AND_ATTRIBUTES admin_privs[] =
531         {
532             { SeChangeNotifyPrivilege        , SE_PRIVILEGE_ENABLED },
533             { SeSecurityPrivilege            , 0                    },
534             { SeBackupPrivilege              , 0                    },
535             { SeRestorePrivilege             , 0                    },
536             { SeSystemtimePrivilege          , 0                    },
537             { SeShutdownPrivilege            , 0                    },
538             { SeRemoteShutdownPrivilege      , 0                    },
539             { SeTakeOwnershipPrivilege       , 0                    },
540             { SeDebugPrivilege               , 0                    },
541             { SeSystemEnvironmentPrivilege   , 0                    },
542             { SeSystemProfilePrivilege       , 0                    },
543             { SeProfileSingleProcessPrivilege, 0                    },
544             { SeIncreaseBasePriorityPrivilege, 0                    },
545             { SeLoadDriverPrivilege          , 0                    },
546             { SeCreatePagefilePrivilege      , 0                    },
547             { SeIncreaseQuotaPrivilege       , 0                    },
548             { SeUndockPrivilege              , 0                    },
549             { SeManageVolumePrivilege        , 0                    },
550             { SeImpersonatePrivilege         , SE_PRIVILEGE_ENABLED },
551             { SeCreateGlobalPrivilege        , SE_PRIVILEGE_ENABLED },
552         };
553         /* note: we don't include non-builtin groups here for the user -
554          * telling us these is the job of a client-side program */
555         const SID_AND_ATTRIBUTES admin_groups[] =
556         {
557             { security_world_sid, SE_GROUP_ENABLED|SE_GROUP_ENABLED_BY_DEFAULT|SE_GROUP_MANDATORY },
558             { security_local_sid, SE_GROUP_ENABLED|SE_GROUP_ENABLED_BY_DEFAULT|SE_GROUP_MANDATORY },
559             { security_interactive_sid, SE_GROUP_ENABLED|SE_GROUP_ENABLED_BY_DEFAULT|SE_GROUP_MANDATORY },
560             { security_authenticated_user_sid, SE_GROUP_ENABLED|SE_GROUP_ENABLED_BY_DEFAULT|SE_GROUP_MANDATORY },
561             { alias_admins_sid, SE_GROUP_ENABLED|SE_GROUP_ENABLED_BY_DEFAULT|SE_GROUP_MANDATORY },
562             { alias_users_sid, SE_GROUP_ENABLED|SE_GROUP_ENABLED_BY_DEFAULT|SE_GROUP_MANDATORY },
563         };
564         /* note: we just set the user sid to be the interactive builtin sid -
565          * we should really translate the UNIX user id to a sid */
566         token = create_token( TRUE, &interactive_sid,
567                             admin_groups, sizeof(admin_groups)/sizeof(admin_groups[0]),
568                             admin_privs, sizeof(admin_privs)/sizeof(admin_privs[0]),
569                             default_dacl );
570     }
571
572     if (alias_admins_sid)
573         free( alias_admins_sid );
574     if (alias_users_sid)
575         free( alias_users_sid );
576     if (default_dacl)
577         free( default_dacl );
578
579     return token;
580 }
581
582 static struct privilege *token_find_privilege( struct token *token, const LUID *luid, int enabled_only )
583 {
584     struct privilege *privilege;
585     LIST_FOR_EACH_ENTRY( privilege, &token->privileges, struct privilege, entry )
586     {
587         if (is_equal_luid( luid, &privilege->luid ))
588         {
589             if (enabled_only && !privilege->enabled)
590                 return NULL;
591             return privilege;
592         }
593     }
594     return NULL;
595 }
596
597 static unsigned int token_adjust_privileges( struct token *token, const LUID_AND_ATTRIBUTES *privs,
598                                              unsigned int count, LUID_AND_ATTRIBUTES *mod_privs,
599                                              unsigned int mod_privs_count )
600 {
601     int i;
602     unsigned int modified_count = 0;
603
604     for (i = 0; i < count; i++)
605     {
606         struct privilege *privilege =
607             token_find_privilege( token, &privs[i].Luid, FALSE );
608         if (!privilege)
609         {
610             set_error( STATUS_NOT_ALL_ASSIGNED );
611             continue;
612         }
613
614         if (privs[i].Attributes & SE_PRIVILEGE_REMOVE)
615             privilege_remove( privilege );
616         else
617         {
618             /* save previous state for caller */
619             if (mod_privs_count)
620             {
621                 luid_and_attr_from_privilege(mod_privs, privilege);
622                 mod_privs++;
623                 mod_privs_count--;
624                 modified_count++;
625             }
626
627             if (privs[i].Attributes & SE_PRIVILEGE_ENABLED)
628                 privilege->enabled = TRUE;
629             else
630                 privilege->enabled = FALSE;
631         }
632     }
633     return modified_count;
634 }
635
636 static void token_disable_privileges( struct token *token )
637 {
638     struct privilege *privilege;
639     LIST_FOR_EACH_ENTRY( privilege, &token->privileges, struct privilege, entry )
640         privilege->enabled = FALSE;
641 }
642
643 int token_check_privileges( struct token *token, int all_required,
644                             const LUID_AND_ATTRIBUTES *reqprivs,
645                             unsigned int count, LUID_AND_ATTRIBUTES *usedprivs)
646 {
647     int i;
648     unsigned int enabled_count = 0;
649
650     for (i = 0; i < count; i++)
651     {
652         struct privilege *privilege = 
653             token_find_privilege( token, &reqprivs[i].Luid, TRUE );
654
655         if (usedprivs)
656             usedprivs[i] = reqprivs[i];
657
658         if (privilege && privilege->enabled)
659         {
660             enabled_count++;
661             if (usedprivs)
662                 usedprivs[i].Attributes |= SE_PRIVILEGE_USED_FOR_ACCESS;
663         }
664     }
665
666     if (all_required)
667         return (enabled_count == count);
668     else
669         return (enabled_count > 0);
670 }
671
672 static int token_sid_present( struct token *token, const SID *sid, int deny )
673 {
674     struct sid_and_attributes *group;
675
676     if (security_equal_sid( token->user, sid )) return TRUE;
677
678     LIST_FOR_EACH_ENTRY( group, &token->groups, struct sid_and_attributes, entry )
679     {
680         if (!group->enabled) continue;
681         if (group->deny_only && !deny) continue;
682
683         if (security_equal_sid( &group->sid, sid )) return TRUE;
684     }
685
686     return FALSE;
687 }
688
689 /* checks access to a security descriptor. sd must have been validated by caller.
690  * it returns STATUS_SUCCESS if access was granted to the object, or an error
691  * status code if not, giving the reason. errors not relating to giving access
692  * to the object are returned in the status parameter. granted_access and
693  * status always have a valid value stored in them on return. */
694 static unsigned int token_access_check( struct token *token,
695                                  const struct security_descriptor *sd,
696                                  unsigned int desired_access,
697                                  LUID_AND_ATTRIBUTES *privs,
698                                  unsigned int *priv_count,
699                                  const GENERIC_MAPPING *mapping,
700                                  unsigned int *granted_access,
701                                  unsigned int *status )
702 {
703     unsigned int current_access = 0;
704     unsigned int denied_access = 0;
705     ULONG i;
706     const ACL *dacl;
707     int dacl_present;
708     const ACE_HEADER *ace;
709     const SID *owner;
710
711     /* assume success, but no access rights */
712     *status = STATUS_SUCCESS;
713     *granted_access = 0;
714
715     /* fail if desired_access contains generic rights */
716     if (desired_access & (GENERIC_READ|GENERIC_WRITE|GENERIC_EXECUTE|GENERIC_ALL))
717     {
718         *priv_count = 0;
719         *status = STATUS_GENERIC_NOT_MAPPED;
720         return STATUS_ACCESS_DENIED;
721     }
722
723     dacl = sd_get_dacl( sd, &dacl_present );
724     owner = sd_get_owner( sd );
725     if (!owner || !sd_get_group( sd ))
726     {
727         *priv_count = 0;
728         *status = STATUS_INVALID_SECURITY_DESCR;
729         return STATUS_ACCESS_DENIED;
730     }
731
732     /* 1: Grant desired access if the object is unprotected */
733     if (!dacl_present)
734     {
735         *priv_count = 0;
736         *granted_access = desired_access;
737         return STATUS_SUCCESS;
738     }
739     if (!dacl)
740     {
741         *priv_count = 0;
742         return STATUS_ACCESS_DENIED;
743     }
744
745     /* 2: Check if caller wants access to system security part. Note: access
746      * is only granted if specifically asked for */
747     if (desired_access & ACCESS_SYSTEM_SECURITY)
748     {
749         const LUID_AND_ATTRIBUTES security_priv = { SeSecurityPrivilege, 0 };
750         LUID_AND_ATTRIBUTES retpriv = security_priv;
751         if (token_check_privileges( token, TRUE, &security_priv, 1, &retpriv ))
752         {
753             if (priv_count)
754             {
755                 /* assumes that there will only be one privilege to return */
756                 if (*priv_count >= 1)
757                 {
758                     *priv_count = 1;
759                     *privs = retpriv;
760                 }
761                 else
762                 {
763                     *priv_count = 1;
764                     return STATUS_BUFFER_TOO_SMALL;
765                 }
766             }
767             current_access |= ACCESS_SYSTEM_SECURITY;
768             if (desired_access == current_access)
769             {
770                 *granted_access = current_access;
771                 return STATUS_SUCCESS;
772             }
773         }
774         else
775         {
776             *priv_count = 0;
777             return STATUS_PRIVILEGE_NOT_HELD;
778         }
779     }
780     else if (priv_count) *priv_count = 0;
781
782     /* 3: Check whether the token is the owner */
783     /* NOTE: SeTakeOwnershipPrivilege is not checked for here - it is instead
784      * checked when a "set owner" call is made, overriding the access rights
785      * determined here. */
786     if (token_sid_present( token, owner, FALSE ))
787     {
788         current_access |= (READ_CONTROL | WRITE_DAC);
789         if (desired_access == current_access)
790         {
791             *granted_access = current_access;
792             return STATUS_SUCCESS;
793         }
794     }
795
796     /* 4: Grant rights according to the DACL */
797     ace = (const ACE_HEADER *)(dacl + 1);
798     for (i = 0; i < dacl->AceCount; i++)
799     {
800         const ACCESS_ALLOWED_ACE *aa_ace;
801         const ACCESS_DENIED_ACE *ad_ace;
802         const SID *sid;
803         switch (ace->AceType)
804         {
805         case ACCESS_DENIED_ACE_TYPE:
806             ad_ace = (const ACCESS_DENIED_ACE *)ace;
807             sid = (const SID *)&ad_ace->SidStart;
808             if (token_sid_present( token, sid, TRUE ))
809             {
810                 unsigned int access = ad_ace->Mask;
811                 map_generic_mask(&access, mapping);
812                 if (desired_access & MAXIMUM_ALLOWED)
813                     denied_access |= access;
814                 else
815                 {
816                     denied_access |= (access & ~current_access);
817                     if (desired_access & access)
818                     {
819                         *granted_access = 0;
820                         return STATUS_SUCCESS;
821                     }
822                 }
823             }
824             break;
825         case ACCESS_ALLOWED_ACE_TYPE:
826             aa_ace = (const ACCESS_ALLOWED_ACE *)ace;
827             sid = (const SID *)&aa_ace->SidStart;
828             if (token_sid_present( token, sid, FALSE ))
829             {
830                 unsigned int access = aa_ace->Mask;
831                 map_generic_mask(&access, mapping);
832                 if (desired_access & MAXIMUM_ALLOWED)
833                     current_access |= access;
834                 else
835                     current_access |= (access & ~denied_access);
836             }
837             break;
838         }
839
840         /* don't bother carrying on checking if we've already got all of
841             * rights we need */
842         if (desired_access == *granted_access)
843             break;
844
845         ace = ace_next( ace );
846     }
847
848     if (desired_access & MAXIMUM_ALLOWED)
849     {
850         *granted_access = current_access & ~denied_access;
851         if (*granted_access)
852             return STATUS_SUCCESS;
853         else
854             return STATUS_ACCESS_DENIED;
855     }
856     else
857     {
858         if ((current_access & desired_access) == desired_access)
859         {
860             *granted_access = current_access & desired_access;
861             return STATUS_SUCCESS;
862         }
863         else
864             return STATUS_ACCESS_DENIED;
865     }
866 }
867
868 const ACL *token_get_default_dacl( struct token *token )
869 {
870     return token->default_dacl;
871 }
872
873 /* open a security token */
874 DECL_HANDLER(open_token)
875 {
876     if (req->flags & OPEN_TOKEN_THREAD)
877     {
878         struct thread *thread = get_thread_from_handle( req->handle, 0 );
879         if (thread)
880         {
881             if (thread->token)
882                 reply->token = alloc_handle( current->process, thread->token, TOKEN_ALL_ACCESS, 0);
883             else
884                 set_error(STATUS_NO_TOKEN);
885             release_object( thread );
886         }
887     }
888     else
889     {
890         struct process *process = get_process_from_handle( req->handle, 0 );
891         if (process)
892         {
893             if (process->token)
894                 reply->token = alloc_handle( current->process, process->token, TOKEN_ALL_ACCESS, 0);
895             else
896                 set_error(STATUS_NO_TOKEN);
897             release_object( process );
898         }
899     }
900 }
901
902 /* adjust the privileges held by a token */
903 DECL_HANDLER(adjust_token_privileges)
904 {
905     struct token *token;
906     unsigned int access = TOKEN_ADJUST_PRIVILEGES;
907
908     if (req->get_modified_state) access |= TOKEN_QUERY;
909
910     if ((token = (struct token *)get_handle_obj( current->process, req->handle,
911                                                  access, &token_ops )))
912     {
913         const LUID_AND_ATTRIBUTES *privs = get_req_data();
914         LUID_AND_ATTRIBUTES *modified_privs = NULL;
915         unsigned int priv_count = get_req_data_size() / sizeof(LUID_AND_ATTRIBUTES);
916         unsigned int modified_priv_count = 0;
917
918         if (req->get_modified_state && !req->disable_all)
919         {
920             int i;
921             /* count modified privs */
922             for (i = 0; i < priv_count; i++)
923             {
924                 struct privilege *privilege =
925                     token_find_privilege( token, &privs[i].Luid, FALSE );
926                 if (privilege && req->get_modified_state)
927                     modified_priv_count++;
928             }
929             reply->len = modified_priv_count;
930             modified_priv_count = min( modified_priv_count, get_reply_max_size() / sizeof(*modified_privs) );
931             if (modified_priv_count)
932                 modified_privs = set_reply_data_size( modified_priv_count * sizeof(*modified_privs) );
933         }
934         reply->len = modified_priv_count * sizeof(*modified_privs);
935
936         if (req->disable_all)
937             token_disable_privileges( token );
938         else
939             modified_priv_count = token_adjust_privileges( token, privs,
940                 priv_count, modified_privs, modified_priv_count );
941
942         release_object( token );
943     }
944 }
945
946 /* retrieves the list of privileges that may be held be the token */
947 DECL_HANDLER(get_token_privileges)
948 {
949     struct token *token;
950
951     if ((token = (struct token *)get_handle_obj( current->process, req->handle,
952                                                  TOKEN_QUERY,
953                                                  &token_ops )))
954     {
955         int priv_count = 0;
956         LUID_AND_ATTRIBUTES *privs;
957         struct privilege *privilege;
958
959         LIST_FOR_EACH_ENTRY( privilege, &token->privileges, struct privilege, entry )
960             priv_count++;
961
962         reply->len = priv_count * sizeof(*privs);
963         if (reply->len <= get_reply_max_size())
964         {
965             privs = set_reply_data_size( priv_count * sizeof(*privs) );
966             if (privs)
967             {
968                 int i = 0;
969                 LIST_FOR_EACH_ENTRY( privilege, &token->privileges, struct privilege, entry )
970                 {
971                     luid_and_attr_from_privilege( &privs[i], privilege );
972                     i++;
973                 }
974             }
975         }
976         else
977             set_error(STATUS_BUFFER_TOO_SMALL);
978
979         release_object( token );
980     }
981 }
982
983 /* creates a duplicate of the token */
984 DECL_HANDLER(duplicate_token)
985 {
986     struct token *src_token;
987     if ((src_token = (struct token *)get_handle_obj( current->process, req->handle,
988                                                      TOKEN_DUPLICATE,
989                                                      &token_ops )))
990     {
991         /* FIXME: use req->impersonation_level */
992         struct token *token = create_token( req->primary, src_token->user, NULL, 0, NULL, 0, src_token->default_dacl );
993         if (token)
994         {
995             struct privilege *privilege;
996             struct sid_and_attributes *group;
997             unsigned int access;
998
999             /* copy groups */
1000             LIST_FOR_EACH_ENTRY( group, &src_token->groups, struct sid_and_attributes, entry )
1001             {
1002                 size_t size = FIELD_OFFSET( struct sid_and_attributes, sid.SubAuthority[group->sid.SubAuthorityCount] );
1003                 struct sid_and_attributes *newgroup = mem_alloc( size );
1004                 memcpy( newgroup, group, size );
1005                 list_add_tail( &token->groups, &newgroup->entry );
1006             }
1007
1008             /* copy privileges */
1009             LIST_FOR_EACH_ENTRY( privilege, &src_token->privileges, struct privilege, entry )
1010                 privilege_add( token, &privilege->luid, privilege->enabled );
1011
1012             access = req->access;
1013             if (access & MAXIMUM_ALLOWED) access = TOKEN_ALL_ACCESS; /* FIXME: needs general solution */
1014             reply->new_handle = alloc_handle( current->process, token, access, req->inherit);
1015             release_object( token );
1016         }
1017         release_object( src_token );
1018     }
1019 }
1020
1021 /* checks the specified privileges are held by the token */
1022 DECL_HANDLER(check_token_privileges)
1023 {
1024     struct token *token;
1025
1026     if ((token = (struct token *)get_handle_obj( current->process, req->handle,
1027                                                  TOKEN_QUERY,
1028                                                  &token_ops )))
1029     {
1030         unsigned int count = get_req_data_size() / sizeof(LUID_AND_ATTRIBUTES);
1031         if (get_reply_max_size() >= count * sizeof(LUID_AND_ATTRIBUTES))
1032         {
1033             LUID_AND_ATTRIBUTES *usedprivs = set_reply_data_size( count * sizeof(*usedprivs) );
1034             reply->has_privileges = token_check_privileges( token, req->all_required, get_req_data(), count, usedprivs );
1035         }
1036         else
1037             set_error( STATUS_BUFFER_OVERFLOW );
1038         release_object( token );
1039     }
1040 }
1041
1042 /* checks that a user represented by a token is allowed to access an object
1043  * represented by a security descriptor */
1044 DECL_HANDLER(access_check)
1045 {
1046     size_t sd_size = get_req_data_size();
1047     const struct security_descriptor *sd = get_req_data();
1048     struct token *token;
1049
1050     if (!sd_is_valid( sd, sd_size ))
1051     {
1052         set_error( STATUS_ACCESS_VIOLATION );
1053         return;
1054     }
1055
1056     if ((token = (struct token *)get_handle_obj( current->process, req->handle,
1057                                                  TOKEN_QUERY,
1058                                                  &token_ops )))
1059     {
1060         GENERIC_MAPPING mapping;
1061         unsigned int status;
1062         LUID_AND_ATTRIBUTES priv;
1063         unsigned int priv_count = 1;
1064
1065         memset(&priv, 0, sizeof(priv));
1066
1067         /* only impersonation tokens may be used with this function */
1068         if (token->primary)
1069         {
1070             set_error( STATUS_NO_IMPERSONATION_TOKEN );
1071             release_object( token );
1072             return;
1073         }
1074
1075         mapping.GenericRead = req->mapping_read;
1076         mapping.GenericWrite = req->mapping_write;
1077         mapping.GenericExecute = req->mapping_execute;
1078         mapping.GenericAll = req->mapping_all;
1079
1080         reply->access_status = token_access_check(
1081             token, sd, req->desired_access, &priv, &priv_count, &mapping,
1082             &reply->access_granted, &status );
1083
1084         reply->privileges_len = priv_count*sizeof(LUID_AND_ATTRIBUTES);
1085
1086         if ((priv_count > 0) && (reply->privileges_len <= get_reply_max_size()))
1087         {
1088             LUID_AND_ATTRIBUTES *privs = set_reply_data_size( priv_count * sizeof(*privs) );
1089             memcpy( privs, &priv, sizeof(priv) );
1090         }
1091
1092         if (status != STATUS_SUCCESS)
1093             set_error( status );
1094
1095         release_object( token );
1096     }
1097 }
1098
1099 /* */
1100 DECL_HANDLER(get_token_user)
1101 {
1102     struct token *token;
1103
1104     reply->user_len = 0;
1105
1106     if ((token = (struct token *)get_handle_obj( current->process, req->handle,
1107                                                  TOKEN_QUERY,
1108                                                  &token_ops )))
1109     {
1110         const SID *user = token->user;
1111
1112         reply->user_len = FIELD_OFFSET(SID, SubAuthority[user->SubAuthorityCount]);
1113         if (reply->user_len <= get_reply_max_size())
1114         {
1115             SID *user_reply = set_reply_data_size( reply->user_len );
1116             if (user_reply)
1117                 memcpy( user_reply, user, reply->user_len );
1118         }
1119         else set_error( STATUS_BUFFER_TOO_SMALL );
1120
1121         release_object( token );
1122     }
1123 }