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